feat(settings): 知识库绑定按环境一次保存连接与内外库

原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥,
也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址
与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与
绑定,回读真实生效值。

服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件
凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥
不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储
解析当前连接,避免只保存了页面数据。

验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错;
make verify 在本提交上执行(结果见交付说明)。
This commit is contained in:
姚章浩
2026-11-19 14:43:51 +08:00
parent df69b278ce
commit ce2a155ebc
53 changed files with 3367 additions and 601 deletions
+1 -1
View File
@@ -125,7 +125,7 @@ describe('ModulePage', () => {
expect(html).toContain('P2 · 知识治理总览')
expect(html).toContain('PP历史来源清单已接管')
expect(html).toContain('生产写入:关闭')
expect(html).toContain('以「系统设置 → 知识库映射」的实时探测为准')
expect(html).toContain('以「系统设置 → 知识库绑定」的实时探测为准')
expect(html).not.toContain('本地测试WeKnora已连接')
expect(html).not.toContain('生产WeKnora仍未连接')
expect(html).not.toContain('尚未连接测试或生产WeKnora')
+1 -1
View File
@@ -505,7 +505,7 @@ export function ModulePage({
? '已开启'
: '已开启(快照恢复未验证,仍被阻断)'
: '关闭'}
;测试 / 生产 WeKnora 连接状态以「系统设置 → 知识库映射」的实时探测为准。
;测试 / 生产 WeKnora 连接状态以「系统设置 → 知识库绑定」的实时探测为准。
</span>
</div>
<span className="safe-badge">Release Worker 默认关闭</span>
+213
View File
@@ -0,0 +1,213 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AuthContext } from './auth'
import { KnowledgeBaseBinding } from './KnowledgeBaseBinding'
import type { KBEnvironmentBinding } from './knowledgeBaseBindings'
const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
environment,
revision: 1,
base_url: `https://${environment}.weknora.example`,
key_configured: true,
key_source: 'sealed',
internal_kb_id: `kb-${environment}-in-0001`,
internal_kb_name: `${environment} 内部资料`,
external_kb_id: `kb-${environment}-out-0001`,
external_kb_name: `${environment} 对外资料`,
verification: 'verified',
checked_at: null,
updated_by: 'admin',
updated_at: null,
source: 'web',
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
})
const snapshot = {
data: { environments: [binding('test'), binding('production')], storage_ready: true },
}
const catalog = {
data: {
status: 'ok',
message: '已读取 2 个知识库',
page: 1,
page_size: 20,
total: 2,
options: [
{ id: 'kb-new-in-0001', name: '新内部库', knowledge_count: 3 },
{ id: 'kb-new-out-0001', name: '新对外库', knowledge_count: 4 },
],
},
}
const json = (value: unknown, status = 200) => ({
ok: status >= 200 && status < 300,
status,
json: async () => value,
})
const auth = (role: 'admin' | 'viewer') => ({
identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false },
ready: true,
login: async () => null,
logout: async () => {},
changePassword: async () => null,
signedOut: 0,
notifySignedOut: () => {},
})
let root: Root
let host: HTMLDivElement
const flush = async () => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
const click = async (label: string) => {
const button = [...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === label)
expect(button, label).toBeTruthy()
await act(async () => button!.click())
await flush()
}
const choose = async (label: string, value: string) => {
const select = [...host.querySelectorAll('label')]
.find((item) => item.textContent?.startsWith(label))
?.querySelector('select')
expect(select, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(select, value)
select!.dispatchEvent(new Event('change', { bubbles: true }))
})
}
const type = async (label: string, value: string) => {
const input = [...host.querySelectorAll('label')]
.find((item) => item.textContent?.startsWith(label))
?.querySelector('input')
expect(input, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
input!.dispatchEvent(new Event('input', { bubbles: true }))
})
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
host = document.createElement('div')
document.body.append(host)
root = createRoot(host)
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
vi.unstubAllGlobals()
})
const render = async (role: 'admin' | 'viewer' = 'admin') => {
await act(async () => {
root.render(
<AuthContext.Provider value={auth(role)}>
<KnowledgeBaseBinding />
</AuthContext.Provider>
)
})
await flush()
}
describe('KnowledgeBaseBinding', () => {
it('switches environments without letting a late catalog response cross over', async () => {
let resolveCatalog: ((value: unknown) => void) | null = null
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) {
return new Promise((resolve) => {
resolveCatalog = resolve
})
}
return Promise.resolve(json({ data: binding('test') }))
})
)
await render()
expect(host.textContent).toContain('当前生效 · 测试 090')
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
await click('验证并读取知识库')
await click('生产 090')
expect(host.textContent).toContain('当前生效 · 生产 090')
expect(host.textContent).toContain('production 内部资料')
await act(async () => {
resolveCatalog?.(json(catalog))
})
await flush()
// 迟到的测试环境列库结果不得出现在生产工作区。
expect(host.textContent).not.toContain('新内部库')
expect(host.textContent).toContain('production 内部资料')
})
it('keeps the old binding visible when a save fails and never applies an unsaved draft', async () => {
const fetchMock = vi.fn((url: string, init?: { method?: string }) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return Promise.resolve(json({ error: '候选实例拒绝保存' }, 400))
return Promise.resolve(json({ data: binding('test') }))
})
vi.stubGlobal('fetch', fetchMock)
await render()
await click('验证并读取知识库')
await choose('对内知识库', 'kb-new-in-0001')
await choose('对外知识库', 'kb-new-out-0001')
expect(host.textContent).toContain('有未保存的修改')
await click('保存测试绑定')
expect(host.textContent).toContain('候选实例拒绝保存')
// 顶部当前生效仍是旧值;草稿只存在于下方。
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
expect(host.textContent).not.toContain('当前生效 · 测试 090新内部库')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
const body = JSON.parse(String((put![1] as { body: string }).body))
expect(body).toMatchObject({
base_revision: 1,
base_url: 'https://test.weknora.example',
key_action: 'keep',
internal_kb_id: 'kb-new-in-0001',
external_kb_id: 'kb-new-out-0001',
})
expect(body.api_key).toBeUndefined()
})
it('gives viewers a read-only summary with no editing inputs', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
await render('viewer')
expect(host.textContent).toContain('普通用户只读')
expect(host.textContent).toContain('当前生效 · 测试 090')
expect(host.querySelectorAll('input')).toHaveLength(0)
expect(
[...host.querySelectorAll('button')].every((button) =>
['测试 090', '生产 090'].includes(button.textContent?.trim() ?? '')
)
).toBe(true)
})
it('requires a new key after the address changes and clears the previous selection', async () => {
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
return Promise.resolve(json(catalog))
})
)
await render()
await type('服务地址', 'https://new.weknora.example')
expect(host.textContent).toContain('已更换服务地址:必须为新地址重新录入 API Key')
const selects = [...host.querySelectorAll('select')]
expect(selects.every((select) => select.value === '')).toBe(true)
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
expect(save?.hasAttribute('disabled')).toBe(true)
})
})
+570
View File
@@ -0,0 +1,570 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useOptionalAuth } from './auth'
import { secretEntryAllowed } from './secureEntry'
import {
KBBindingError,
duplicateSelection,
fetchKBBindings,
fetchKBCatalog,
keyActionFor,
knowledgeBaseLabel,
saveKBBinding,
shortKnowledgeBaseID,
} from './knowledgeBaseBindings'
import type {
KBEnvironment,
KBEnvironmentBinding,
KBBindingSnapshot,
KBCatalog,
KBCatalogOption,
} from './knowledgeBaseBindings'
import { validServiceEndpoint } from './uiSettings'
const environments: { key: KBEnvironment; label: string; short: string }[] = [
{ key: 'test', label: '测试 090', short: '测试' },
{ key: 'production', label: '生产 090', short: '生产' },
]
type Busy = '' | 'catalog' | 'saving'
type Notice = { tone: 'ok' | 'error'; text: string }
interface Draft {
baseURL: string
replaceKey: boolean
apiKey: string
internalID: string
internalName: string
externalID: string
externalName: string
catalog: KBCatalog | null
verifiedBaseURL: string
}
type Drafts = Record<KBEnvironment, Draft>
type BusyMap = Record<KBEnvironment, Busy>
type NoticeMap = Record<KBEnvironment, Notice | null>
function draftFrom(saved: KBEnvironmentBinding): Draft {
return {
baseURL: saved.base_url,
replaceKey: !saved.key_configured,
apiKey: '',
internalID: saved.internal_kb_id,
internalName: saved.internal_kb_name,
externalID: saved.external_kb_id,
externalName: saved.external_kb_name,
catalog: null,
verifiedBaseURL: '',
}
}
function emptyDrafts(snapshot: KBBindingSnapshot): Drafts {
return { test: draftFrom(snapshot.test), production: draftFrom(snapshot.production) }
}
const sameDraft = (draft: Draft, saved: KBEnvironmentBinding): boolean =>
draft.baseURL.trim() === saved.base_url &&
!draft.replaceKey &&
draft.apiKey === '' &&
draft.internalID === saved.internal_kb_id &&
draft.externalID === saved.external_kb_id
const statusTone = (status: KBCatalog['status']): string =>
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
export function KnowledgeBaseBinding() {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null)
const [env, setEnv] = useState<KBEnvironment>('test')
const [drafts, setDrafts] = useState<Drafts | null>(null)
const [busy, setBusy] = useState<BusyMap>({ test: '', production: '' })
const [notices, setNotices] = useState<NoticeMap>({ test: null, production: null })
const [loadError, setLoadError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const catalogSeq = useRef(0)
const saveSeq = useRef(0)
const envRef = useRef<KBEnvironment>(env)
const loadAbort = useRef<AbortController | null>(null)
const catalogAbort = useRef<AbortController | null>(null)
const saveAbort = useRef<AbortController | null>(null)
envRef.current = env
const load = async () => {
const controller = new AbortController()
loadAbort.current?.abort()
loadAbort.current = controller
setLoading(true)
setLoadError(null)
try {
const next = await fetchKBBindings(controller.signal)
if (controller.signal.aborted) return
setSnapshot(next)
setDrafts((current) => current ?? emptyDrafts(next))
} catch (cause) {
if (!controller.signal.aborted) {
setLoadError(cause instanceof Error ? cause.message : '读取知识库绑定失败')
}
} finally {
if (!controller.signal.aborted) setLoading(false)
}
}
useEffect(() => {
void load()
return () => {
loadAbort.current?.abort()
catalogAbort.current?.abort()
saveAbort.current?.abort()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const saved = snapshot?.[env] ?? null
const draft = drafts?.[env] ?? null
const busyNow = busy[env]
const notice = notices[env]
const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location)
const storageReady = Boolean(snapshot?.storage_ready)
const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
const keyEntryBlocked = !secure || !storageReady
const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false
const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false
const catalogReady = Boolean(
draft?.catalog &&
draft.verifiedBaseURL === draft.baseURL &&
(draft.catalog.status === 'ok' || draft.catalog.status === 'empty')
)
const dirty = Boolean(saved && draft && !sameDraft(draft, saved))
const canSave = Boolean(
isAdmin &&
saved &&
draft &&
dirty &&
!busyNow &&
storageReady &&
endpointValid &&
keyReady &&
!duplicate &&
catalogReady
)
const patchDraft = (patch: Partial<Draft>) => {
setDrafts((current) => (current ? { ...current, [env]: { ...current[env], ...patch } } : current))
setNotices((current) => ({ ...current, [env]: null }))
}
const switchEnvironment = (next: KBEnvironment) => {
if (next === env) return
// 切换只作废在途列库:迟到结果不得写进另一个环境的工作区。
// 保存按目标环境落库,响应也只更新该环境的状态,切回来仍是真实结果。
catalogSeq.current++
catalogAbort.current?.abort()
setEnv(next)
}
const onBaseURLChange = (value: string) => {
if (!saved) return
const changed = value.trim() !== saved.base_url
patchDraft({
baseURL: value,
replaceKey: changed ? true : !saved.key_configured,
internalID: '',
internalName: '',
externalID: '',
externalName: '',
catalog: null,
verifiedBaseURL: '',
})
}
const runCatalog = async (page: number) => {
if (!saved || !draft) return
if (!endpointValid) {
setNotices((current) => ({
...current,
[env]: { tone: 'error', text: '请填写有效的 http(s) 服务地址(不能带用户名、? 查询串或 #)' },
}))
return
}
if (keyAction === 'replace' && draft.apiKey.trim() === '') {
setNotices((current) => ({ ...current, [env]: { tone: 'error', text: '请先填入这个地址的 API Key' } }))
return
}
if (keyAction === 'keep' && !saved.key_configured) {
setNotices((current) => ({ ...current, [env]: { tone: 'error', text: '当前连接还没有可用密钥,请先录入' } }))
return
}
const targetEnv = env
const seq = ++catalogSeq.current
const controller = new AbortController()
catalogAbort.current = controller
setBusy((current) => ({ ...current, [targetEnv]: 'catalog' }))
setNotices((current) => ({ ...current, [targetEnv]: null }))
try {
const catalog = await fetchKBCatalog(
targetEnv,
{
base_revision: saved.revision,
base_url: draft.baseURL.trim(),
key_action: keyAction,
...(keyAction === 'replace' ? { api_key: draft.apiKey } : {}),
page,
page_size: 20,
},
controller.signal
)
if (controller.signal.aborted || seq !== catalogSeq.current || envRef.current !== targetEnv) return
setDrafts((current) => {
if (!current) return current
return {
...current,
[targetEnv]: { ...current[targetEnv], catalog, verifiedBaseURL: draft.baseURL.trim() },
}
})
} catch (cause) {
if (controller.signal.aborted || seq !== catalogSeq.current || envRef.current !== targetEnv) return
setNotices((current) => ({
...current,
[targetEnv]: { tone: 'error', text: cause instanceof Error ? cause.message : '读取知识库列表失败' },
}))
} finally {
setBusy((current) => ({ ...current, [targetEnv]: '' }))
}
}
const runSave = async () => {
if (!saved || !draft || !canSave) return
const targetEnv = env
const seq = ++saveSeq.current
const controller = new AbortController()
saveAbort.current = controller
setBusy((current) => ({ ...current, [targetEnv]: 'saving' }))
setNotices((current) => ({ ...current, [targetEnv]: null }))
try {
const view = await saveKBBinding(
targetEnv,
{
base_revision: saved.revision,
base_url: draft.baseURL.trim(),
key_action: keyAction,
...(keyAction === 'replace' ? { api_key: draft.apiKey } : {}),
internal_kb_id: draft.internalID,
external_kb_id: draft.externalID,
},
controller.signal
)
if (controller.signal.aborted || seq !== saveSeq.current) return
setSnapshot((current) => (current ? { ...current, [targetEnv]: view } : current))
setDrafts((current) => (current ? { ...current, [targetEnv]: draftFrom(view) } : current))
const replan =
view.replanned || view.retired_duplicates
? `;同时把 ${view.replanned} 项未上传的待入库重新指向新库${view.retired_duplicates ? `,${view.retired_duplicates} 项因新库已有同篇而退休` : ''}`
: ''
setNotices((current) => ({
...current,
[targetEnv]: {
tone: 'ok',
text: `已保存${environments.find((item) => item.key === targetEnv)?.short}绑定:对内 ${
view.internal_kb_name || shortKnowledgeBaseID(view.internal_kb_id) || '未绑定'
} · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${replan}`,
},
}))
} catch (cause) {
if (controller.signal.aborted || seq !== saveSeq.current) return
const message = cause instanceof Error ? cause.message : '保存知识库绑定失败'
setNotices((current) => ({ ...current, [targetEnv]: { tone: 'error', text: message } }))
if (cause instanceof KBBindingError && cause.status === 409) {
// 冲突:重新读取服务器生效值,保留草稿但作废这次列库结论,必须按新版本重验。
try {
const fresh = await fetchKBBindings()
if (seq !== saveSeq.current) return
setSnapshot(fresh)
setDrafts((current) =>
current
? { ...current, [targetEnv]: { ...current[targetEnv], catalog: null, verifiedBaseURL: '' } }
: current
)
} catch {
/* 读取失败时保留现有显示,错误信息已经可见 */
}
}
} finally {
setBusy((current) => ({ ...current, [targetEnv]: '' }))
}
}
const currentOptions = useMemo<{ internal: KBCatalogOption[]; external: KBCatalogOption[] }>(() => {
const base = draft?.catalog?.options ?? []
const withSelection = (id: string, name: string): KBCatalogOption[] => {
if (!id || base.some((option) => option.id === id)) return base
return [{ id, name: name || shortKnowledgeBaseID(id), knowledge_count: 0 }, ...base]
}
return {
internal: draft ? withSelection(draft.internalID, draft.internalName) : [],
external: draft ? withSelection(draft.externalID, draft.externalName) : [],
}
}, [draft])
const renderCurrent = (binding: KBEnvironmentBinding) => (
<div className="kb-current">
<strong>当前生效 · {environments.find((item) => item.key === binding.environment)?.label}</strong>
<div className="kb-current-targets">
<span>
对内 <b>{knowledgeBaseLabel(binding.internal_kb_id, binding.internal_kb_name)}</b>
</span>
<span>
对外 <b>{knowledgeBaseLabel(binding.external_kb_id, binding.external_kb_name)}</b>
</span>
</div>
<small>
{binding.base_url || '未配置服务地址'} ·{' '}
{binding.key_configured
? binding.key_source === 'file'
? 'API Key 来自服务器文件'
: 'API Key 已配置(不回显)'
: 'API Key 未配置'}
{binding.source === 'legacy' ? ' · 旧部署配置' : ` · 版本 ${binding.revision}`}
</small>
</div>
)
if (!isAdmin) {
return (
<section className="settings-panel wide" id="settings-kb-bindings">
<div className="settings-section-heading">
<div>
<h2>知识库绑定</h2>
<p>普通用户只读:这里显示当前生效的连接与内外库绑定。</p>
</div>
</div>
<nav className="kb-env-switch" aria-label="选择环境">
{environments.map((item) => (
<button
key={item.key}
type="button"
aria-pressed={env === item.key}
onClick={() => switchEnvironment(item.key)}
>
{item.label}
</button>
))}
</nav>
{saved ? renderCurrent(saved) : loading ? <p role="status">正在读取知识库绑定…</p> : null}
{loadError ? (
<p className="error-message" role="alert">
{loadError}
</p>
) : null}
</section>
)
}
return (
<section className="settings-panel wide" id="settings-kb-bindings">
<div className="settings-section-heading">
<div>
<h2>知识库绑定</h2>
<p>
一次保存当前环境的连接与对内/对外绑定。地址与密钥由服务器真实列库核验;顶部始终是已生效的值,
下面的修改只是草稿。
</p>
</div>
</div>
<nav className="kb-env-switch" aria-label="选择环境">
{environments.map((item) => (
<button
key={item.key}
type="button"
aria-pressed={env === item.key}
onClick={() => switchEnvironment(item.key)}
>
{item.label}
</button>
))}
</nav>
{saved ? renderCurrent(saved) : loading ? <p role="status">正在读取知识库绑定…</p> : null}
{loadError ? (
<p className="error-message" role="alert">
{loadError}
</p>
) : null}
{!storageReady && snapshot ? (
<p className="settings-warn">
独立安全存储未就绪(服务器未配置 WEKNORA_BINDING_MASTER_KEY_FILE):可以查看旧绑定,但不能保存新连接。
</p>
) : null}
{saved && draft ? (
<>
<section className="kb-block" aria-label="WeKnora 连接">
<h3>WeKnora 连接 · {environments.find((item) => item.key === env)?.label}</h3>
{env === 'production' ? (
<p className="hint">
生产连接用于候选列库与探活;文档级/整库发布实际写入目标仍由部署配置决定(见下方诊断)。
</p>
) : null}
<div className="kb-fields">
<label>
服务地址
<input
value={draft.baseURL}
onChange={(event) => onBaseURLChange(event.target.value)}
placeholder="https://weknora.example"
autoComplete="off"
spellCheck={false}
disabled={busyNow !== ''}
aria-invalid={!endpointValid}
/>
</label>
<div className="kb-key">
<span className="label">API Key</span>
{saved.key_configured && !draft.replaceKey ? (
<div className="kb-key-line">
<span>已配置(不回显){saved.key_source === 'file' ? ' · 服务器文件' : ''}</span>
<button
type="button"
className="link"
onClick={() => patchDraft({ replaceKey: true, apiKey: '' })}
disabled={busyNow !== ''}
>
更换密钥
</button>
</div>
) : (
<div className="kb-key-line">
<input
type="password"
name={`kb_key_${env}`}
value={draft.apiKey}
onChange={(event) =>
patchDraft({ apiKey: event.target.value, catalog: null, verifiedBaseURL: '' })
}
autoComplete="new-password"
spellCheck={false}
placeholder={saved.key_configured ? '输入新密钥;保存后才生效' : '仅用于此治理平台'}
disabled={busyNow !== '' || keyEntryBlocked}
aria-invalid={keyEntryBlocked}
/>
{saved.key_configured && draft.baseURL.trim() === saved.base_url ? (
<button
type="button"
className="link"
onClick={() => patchDraft({ replaceKey: false, apiKey: '' })}
disabled={busyNow !== ''}
>
取消更换
</button>
) : null}
</div>
)}
</div>
</div>
{!secure ? (
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
) : null}
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
) : null}
<div className="kb-actions">
<button
type="button"
onClick={() => void runCatalog(draft.catalog?.page ?? 1)}
disabled={busyNow !== '' || !endpointValid || (keyAction === 'replace' && draft.apiKey.trim() === '')}
>
{busyNow === 'catalog' ? '正在验证并读取…' : '验证并读取知识库'}
</button>
<small>服务器会用这份地址与密钥真实列库,只读,不写入。</small>
</div>
{draft.catalog ? (
<div className={`kb-catalog-status ${statusTone(draft.catalog.status)}`} role="status">
{draft.catalog.message}
{draft.catalog.total > 0
? ` · 第 ${draft.catalog.page} / ${Math.max(1, Math.ceil(draft.catalog.total / draft.catalog.page_size))} 页`
: ''}
{draft.catalog.total > draft.catalog.page_size ? (
<span className="kb-pager">
<button
type="button"
onClick={() => void runCatalog(Math.max(1, draft.catalog!.page - 1))}
disabled={busyNow !== '' || draft.catalog.page <= 1}
>
上一页
</button>
<button
type="button"
onClick={() => void runCatalog(draft.catalog!.page + 1)}
disabled={busyNow !== '' || draft.catalog.page * draft.catalog.page_size >= draft.catalog.total}
>
下一页
</button>
</span>
) : null}
</div>
) : (
<p className="hint">验证并读取后,才能从这份连接可读的库里选择。</p>
)}
</section>
<section className="kb-block" aria-label="选择已有知识库">
<h3>选择已有知识库</h3>
<div className="kb-targets">
<label>
对内知识库
<select
value={draft.internalID}
onChange={(event) => {
const option = currentOptions.internal.find((item) => item.id === event.target.value)
patchDraft({ internalID: event.target.value, internalName: option?.name ?? '' })
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
<option value="">暂不绑定</option>
{currentOptions.internal.map((option) => (
<option key={option.id} value={option.id}>
{option.name}({shortKnowledgeBaseID(option.id)})
</option>
))}
</select>
</label>
<label>
对外知识库
<select
value={draft.externalID}
onChange={(event) => {
const option = currentOptions.external.find((item) => item.id === event.target.value)
patchDraft({ externalID: event.target.value, externalName: option?.name ?? '' })
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
<option value="">暂不绑定</option>
{currentOptions.external.map((option) => (
<option key={option.id} value={option.id}>
{option.name}({shortKnowledgeBaseID(option.id)})
</option>
))}
</select>
</label>
</div>
<small>名称相同很常见,括号里的短 ID 才是区分依据;对内与对外不能选同一个库。</small>
{duplicate ? <p className="error-message">对内和对外不能绑定同一个知识库。</p> : null}
</section>
<div className="kb-footer">
<span
className={notice?.tone === 'error' ? 'error-message' : 'muted'}
role={notice?.tone === 'error' ? 'alert' : 'status'}
>
{notice?.text || (dirty ? '有未保存的修改;当前生效值未改变' : '草稿与当前生效值一致')}
</span>
<button type="button" className="primary" onClick={() => void runSave()} disabled={!canSave}>
{busyNow === 'saving'
? '正在校验并保存…'
: `保存${environments.find((item) => item.key === env)?.short}绑定`}
</button>
</div>
</>
) : null}
</section>
)
}
+6 -3
View File
@@ -22,6 +22,7 @@ export interface ProductionBindingsViewProps {
message: string
dirty: boolean
sameSelection: boolean
diagnosticsOnly?: boolean
onInternalChange: (next: string) => void
onExternalChange: (next: string) => void
onSave: () => void
@@ -41,6 +42,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
message,
dirty,
sameSelection,
diagnosticsOnly = false,
onInternalChange,
onExternalChange,
onSave,
@@ -161,7 +163,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
{bindings.updated_by ? ` · 最近修改:${bindings.updated_by}` : ''}
</p>
) : null}
{isAdmin && bindings ? (
{!diagnosticsOnly && isAdmin && bindings ? (
<div className="kb-binding-editor">
<label>对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}</label>
<label>对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}</label>
@@ -178,13 +180,13 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
) : null}
</div>
) : null}
{!isAdmin ? <p className="hint">仅管理员可修改文档级发布目标。</p> : null}
{!diagnosticsOnly && !isAdmin ? <p className="hint">仅管理员可修改文档级发布目标。</p> : null}
</section>
)
}
// 容器:读取 + 保存。整库目标只读展示,保存动作只写文档级绑定。
export function ProductionBindingsSection() {
export function ProductionBindingsSection({ diagnosticsOnly = false }: { diagnosticsOnly?: boolean } = {}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [bindings, setBindings] = useState<ProductionBindings | null>(null)
@@ -256,6 +258,7 @@ export function ProductionBindingsSection() {
message={message}
dirty={dirty}
sameSelection={sameSelection}
diagnosticsOnly={diagnosticsOnly}
onInternalChange={setInternalDraft}
onExternalChange={setExternalDraft}
onSave={() => void save()}
+3 -3
View File
@@ -3,9 +3,9 @@ import type { AISettings } from './qaAITypes'
import type { AISettingsInput } from './qaAI'
import { fetchAISettings, saveAISettings, testAISettings } from './qaAI'
import { QARequestError } from './qaOps'
export function qaAIKeyEntryAllowed(location: { protocol: string; hostname: string }) {
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
}
import { secretEntryAllowed } from './secureEntry'
// 兼容既有导入:密钥录入的安全判定只有一份,实现已移到 secureEntry。
export const qaAIKeyEntryAllowed = secretEntryAllowed
const verificationLabels: Record<AISettings['verification'], string> = {
not_configured: '未配置可用密钥',
verified: '已通过真实连接测试',
+3 -3
View File
@@ -4,7 +4,7 @@ import { useOptionalAuth } from './auth'
import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings'
import type { KnowledgeBaseOption, RoutingBindings } from './routingBindings'
export function RoutingBindingsSection() {
export function RoutingBindingsSection({ diagnosticsOnly = false }: { diagnosticsOnly?: boolean } = {}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [bindings, setBindings] = useState<RoutingBindings | null>(null)
@@ -168,7 +168,7 @@ export function RoutingBindingsSection() {
{bindings && !bindings.weknora_connected ? (
<p className="hint">当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。</p>
) : null}
{isAdmin && bindings ? (
{!diagnosticsOnly && isAdmin && bindings ? (
<div className="kb-binding-editor">
<label>对内绑定 {editorFor(internalDraft, setInternalDraft, '选择对内知识库')}</label>
<label>对外绑定 {editorFor(externalDraft, setExternalDraft, '选择对外知识库')}</label>
@@ -184,7 +184,7 @@ export function RoutingBindingsSection() {
) : null}
</div>
) : null}
{!isAdmin ? <p className="hint">仅管理员可修改测试知识库绑定。</p> : null}
{!diagnosticsOnly && !isAdmin ? <p className="hint">仅管理员可修改测试知识库绑定。</p> : null}
</section>
)
}
+21 -18
View File
@@ -141,13 +141,13 @@ describe('SystemSettingsView AI 模型连接', () => {
/>
</AuthContext.Provider>
)
it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库映射', () => {
it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库绑定', () => {
const adminHtml = view('admin')
for (const text of [
'AI 模型连接',
'正在读取已保存的模型连接',
'问答四字段分析与中文问题翻译共用此连接',
'WeKnora 的知识库连接已移到「知识库映射」',
'WeKnora 的知识库连接已移到「知识库绑定」',
]) {
expect(adminHtml).toContain(text)
}
@@ -179,7 +179,7 @@ describe('SystemSettingsView', () => {
onRefresh={vi.fn()}
/>
)
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库映射', '存储与备份', '刷新策略'])
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '刷新策略'])
expect(html).toContain(text)
// 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。
for (const removed of [
@@ -202,7 +202,7 @@ describe('SystemSettingsView', () => {
expect(html).not.toContain(removed)
// 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。
for (const removed of ['+ 新增钉钉知识库', '新增钉钉知识库']) expect(html).not.toContain(removed)
// WeKnora 连接已迁到「知识库映射」:地址与核验参数跟入库/封存/生产目标同屏。
// WeKnora 连接已迁到「知识库绑定」:主表单保存连接+绑定,诊断折叠保留。
const mapHtml = renderToStaticMarkup(
<AuthContext.Provider value={authValue('admin')}>
<SystemSettingsView
@@ -224,18 +224,19 @@ describe('SystemSettingsView', () => {
</AuthContext.Provider>
)
for (const text of [
'WeKnora 连接',
'知识库绑定',
'测试 090',
'生产 090',
'正在读取知识库绑定…',
'连接与绑定诊断',
'测试 WeKnora',
'生产 WeKnora',
'测试地址',
'生产地址',
'生产租户 ID',
'知识库 ID',
'保存并校验连接',
'生产核验参数',
'整库发布目标',
])
expect(mapHtml).toContain(text)
// 凭据是服务器文件引用:连接卡只报状态,页面不提供 API Key 录入。
// 旧连接表单已被单一保存入口取代;SSR 尚未读到绑定时不渲染密钥输入。
for (const removed of ['保存并校验连接', '测试地址', '生产租户 ID', '生产核验参数'])
expect(mapHtml).not.toContain(removed)
expect(mapHtml).not.toContain('API Key')
const storageHtml = renderToStaticMarkup(
<SystemSettingsView
@@ -332,14 +333,16 @@ describe('SystemSettingsView', () => {
/>
</AuthContext.Provider>
)
// 测试绑定与生产目标已合并为「知识库映射」:入库目标、封存源、生产目标同屏。
expect(view('sources')).toContain('知识库映射')
// 旧入口(bindings / production-bindings)都落到「知识库绑定」:新主表单 + 折叠诊断。
expect(view('sources')).toContain('知识库绑定')
const bound = view('bindings')
expect(bound).toContain('id="settings-kb-bindings"')
expect(bound).toContain('知识库绑定')
expect(bound).toContain('正在读取知识库绑定…')
expect(bound).toContain('连接与绑定诊断')
// 诊断区保留原链路:测试入库绑定与生产目标入口仍在,但不再提供第二个保存路径。
expect(bound).toContain('id="settings-routing-bindings"')
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
// 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。
expect(bound).toContain('读取中…')
// 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。
const target = view('production-bindings')
expect(target).toContain('id="settings-production-bindings"')
expect(target).toContain('整库发布目标')
@@ -437,7 +440,7 @@ describe('SystemSettingsView', () => {
expect(on).toContain('延迟 86ms')
expect(on).toContain('已启用 · 可提交生产请求')
expect(on).toContain('生产写入:开启')
expect(on).toContain('凭据:服务器文件引用,页面不回读')
expect(on).toContain('凭据:服务器文件/加密存储,页面不回读')
const off = view(false, false)
expect(off).toContain('未启用')
expect(off).toContain('生产写入:关闭')
+33 -33
View File
@@ -9,6 +9,8 @@ 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'
@@ -22,10 +24,9 @@ import type { SourceConnectionListItem } from './sourceConnections'
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings'
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
import { refreshSettingsInput } from './settingsInputs'
import { WeKnoraConnections } from './WeKnoraConnections'
import './systemSettings.css'
// 连接配置已从「服务配置」迁到「知识库映射」。这两个纯函数仍从本模块导出,
// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出,
// 既有调用与回归测试的导入路径不变。
export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs'
export type { RefreshDrafts, ServiceDrafts } from './settingsInputs'
@@ -46,16 +47,16 @@ interface Props {
onSave: (input: UISettingsCandidateInput) => void
onSourcesChanged: () => void
onRefresh: () => void
// 兼容旧入口:'bindings'/'production-bindings' 已合并为“知识库映射”。
initialSection?: SectionKey | 'bindings' | 'production-bindings'
// 兼容旧入口:'bindings'/'production-bindings'/'knowledge-map' 都落到「知识库绑定」。
initialSection?: SectionKey | 'bindings' | 'production-bindings' | 'knowledge-map'
}
type SectionKey = 'sources' | 'services' | 'knowledge-map' | 'storage' | 'refresh' | 'members'
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-map', label: '知识库映射' },
{ key: 'knowledge-bindings', label: '知识库绑定' },
{ key: 'storage', label: '存储与备份' },
{ key: 'refresh', label: '刷新策略' },
{ key: 'members', label: '成员与角色', adminOnly: true },
@@ -99,8 +100,8 @@ export function SystemSettingsView({
const auth = useOptionalAuth()
const identity = auth?.identity ?? null
const [section, setSection] = useState<SectionKey>(
initialSection === 'bindings' || initialSection === 'production-bindings'
? 'knowledge-map'
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)
@@ -133,7 +134,7 @@ export function SystemSettingsView({
finalizing !== settings.finalizing_after_seconds ||
concurrency !== settings.ingestion_concurrency)
)
// 保存边界:刷新分区只带刷新草稿;WeKnora 连接草稿在 WeKnoraConnections 内独立保存,
// 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
// 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。
const refreshInput = (): UISettingsCandidateInput =>
settings
@@ -210,36 +211,35 @@ export function SystemSettingsView({
<h2>AI 模型连接</h2>
<p>
问答四字段分析与中文问题翻译共用此连接;保存只更新这份连接,不会自动开启自动分析或自动翻译。
WeKnora 的知识库连接已移到「知识库映射」。
WeKnora 的知识库连接已移到「知识库绑定」。
</p>
</div>
</div>
{isAdmin ? <QAModelSettings /> : <small>仅管理员可修改模型连接;密钥不回显。</small>}
</section>
) : null}
{section === 'knowledge-map' ? (
{section === 'knowledge-bindings' ? (
<>
{settings ? (
<WeKnoraConnections
settings={settings}
monitor={monitor}
routingCapabilities={routingCapabilities}
workerCapabilities={workerCapabilities}
productionEnabled={productionEnabled}
productionBackupRestoreVerified={productionBackupRestoreVerified}
isAdmin={Boolean(isAdmin)}
saving={saving}
saveMessage={visibleSaveMessage(saveMessage, dirty)}
onSave={onSave}
/>
) : null}
<p className="settings-hint-wide">
一张图看清三件事:<strong>入库目标</strong>(来源打标分发到此库)、
<strong>封存源</strong>(整库封存实际导出的库)、<strong>生产目标</strong>(同步写入的库)。
前两者不一致时,发布页显示的名字与封存出来的内容会对不上。
</p>
<RoutingBindingsSection />
<ProductionBindingsSection />
<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' ? (
@@ -254,7 +254,7 @@ export function SystemSettingsView({
<div className="settings-section-heading">
<div>
<h2>刷新策略</h2>
<p>保存只改这一组参数,不会带上「知识库映射」里未保存的连接地址。</p>
<p>保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
</div>
<span className="safe-badge">当前活动版本</span>
</div>
-130
View File
@@ -1,130 +0,0 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { WeKnoraConnections } from './WeKnoraConnections'
import type { UISettings } from './uiSettings'
const settings: UISettings = {
id: 'settings-live',
state: 'active',
document_refresh_seconds: 30,
resource_refresh_seconds: 60,
stalled_after_seconds: 3600,
finalizing_after_seconds: 14400,
ingestion_concurrency: 4,
test_weknora_base_url: 'https://server.test',
production_weknora_base_url: 'https://server.prod',
production_tenant_id: '10000',
production_knowledge_base_id: 'kb-server',
updated_by: 'admin-1',
created_at: '2026-11-18T08:00:00Z',
activated_at: '2026-11-18T08:00:00Z',
retired_at: null,
error_code: '',
}
let root: Root
let host: HTMLDivElement
const click = async (label: string) => {
const button = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label)
expect(button, label).toBeTruthy()
await act(async () => button!.click())
}
const type = async (label: string, value: string) => {
const input = [...host.querySelectorAll('label')]
.find((x) => x.textContent?.startsWith(label))
?.querySelector('input')
expect(input, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
input!.dispatchEvent(new Event('input', { bubbles: true }))
})
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
host = document.createElement('div')
document.body.append(host)
root = createRoot(host)
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
})
describe('WeKnoraConnections', () => {
it('保存只带连接草稿,刷新参数取服务器当前值', async () => {
const onSave = vi.fn()
await act(async () =>
root.render(
<WeKnoraConnections
settings={settings}
monitor={null}
routingCapabilities={{ internal_enabled: true, external_enabled: false }}
productionEnabled={false}
isAdmin
saving={false}
saveMessage={null}
onSave={onSave}
/>
)
)
await type('测试地址', 'https://draft.test')
await click('保存并校验连接')
expect(onSave).toHaveBeenCalledTimes(1)
expect(onSave.mock.calls[0][0]).toMatchObject({
test_weknora_base_url: 'https://draft.test',
production_weknora_base_url: 'https://server.prod',
production_tenant_id: '10000',
production_knowledge_base_id: 'kb-server',
document_refresh_seconds: 30,
ingestion_concurrency: 4,
})
})
it('未修改时保存按钮不可点,非法地址也不允许提交', async () => {
const onSave = vi.fn()
await act(async () =>
root.render(
<WeKnoraConnections
settings={settings}
monitor={null}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
productionEnabled={false}
isAdmin
saving={false}
saveMessage={null}
onSave={onSave}
/>
)
)
const saveButton = () =>
[...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === '保存并校验连接') as
HTMLButtonElement | undefined
expect(saveButton()?.disabled).toBe(true)
await type('生产地址', 'https://draft.prod/?token=x')
expect(saveButton()?.disabled).toBe(true)
expect(host.textContent).toContain('格式不合法')
await click('保存并校验连接')
expect(onSave).not.toHaveBeenCalled()
})
it('工程师只看到只读摘要,没有保存入口', async () => {
await act(async () =>
root.render(
<WeKnoraConnections
settings={settings}
monitor={null}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
productionEnabled={false}
isAdmin={false}
saving={false}
saveMessage={null}
onSave={vi.fn()}
/>
)
)
expect(host.textContent).toContain('仅管理员可修改 WeKnora 连接')
expect(host.textContent).toContain('https://server.test')
expect([...host.querySelectorAll('button')]).toHaveLength(0)
})
})
-242
View File
@@ -1,242 +0,0 @@
import { useEffect, useState } from 'react'
import type { MonitorOverview } from './monitor'
import { serviceSettingsInput } from './settingsInputs'
import type { CatalogRoutingCapabilities } from './sourceCatalog'
import type { WorkerCapabilities } from './systemCapabilities'
import { testUploadLabel } from './systemCapabilities'
import { validKnowledgeBaseID, validProductionTenantID, validServiceEndpoint } from './uiSettings'
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
type ServiceHealthView = MonitorOverview['health'][number]
type ServiceView = MonitorOverview['services'][number]
// 连接分区只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID),
// 依赖与解析队列的状态仍按真实探测呈现,不写死。
export 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' ? '可达 · 不可接单' : '不可达 · 不可接单'
}
// 测试 WeKnora 卡片只证明“接口就绪”:readiness 不覆盖上传/解析执行器,
// 所以不能沿用“可接单”这种承诺式措辞。
export const testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
const label = healthStateLabel(health, service)
return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label
}
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 interface WeKnoraConnectionsProps {
settings: UISettings
monitor: MonitorOverview | null
routingCapabilities: CatalogRoutingCapabilities
workerCapabilities?: WorkerCapabilities | null
productionEnabled: boolean
productionBackupRestoreVerified?: boolean
isAdmin: boolean
saving: boolean
saveMessage: string | null
onSave: (input: UISettingsCandidateInput) => void
}
// 「知识库映射 → WeKnora 连接」:地址由管理员在页面维护,保存前后端会真做一次
// 探活与列库核验;凭据仍是服务器文件引用,页面只显示状态、不回读也不接受录入。
export function WeKnoraConnections({
settings,
monitor,
routingCapabilities,
workerCapabilities = null,
productionEnabled,
productionBackupRestoreVerified = false,
isAdmin,
saving,
saveMessage,
onSave,
}: WeKnoraConnectionsProps) {
const [endpoint, setEndpoint] = useState<string>(settings.production_weknora_base_url ?? '')
const [testEndpoint, setTestEndpoint] = useState<string>(settings.test_weknora_base_url ?? '')
const [productionTenantID, setProductionTenantID] = useState<string>(settings.production_tenant_id ?? '')
const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState<string>(
settings.production_knowledge_base_id ?? ''
)
useEffect(() => {
setEndpoint(settings.production_weknora_base_url)
setTestEndpoint(settings.test_weknora_base_url)
setProductionTenantID(settings.production_tenant_id)
setProductionKnowledgeBaseID(settings.production_knowledge_base_id)
}, [settings])
const endpointValid = validServiceEndpoint(endpoint)
const testEndpointValid = validServiceEndpoint(testEndpoint)
const productionTenantIDValid = validProductionTenantID(productionTenantID)
const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID)
const valid = endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid
const dirty =
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
return (
<section className="settings-panel wide" id="settings-weknora-connections">
<div className="settings-section-heading">
<div>
<h2>WeKnora 连接</h2>
<p>
测试与生产各自的地址在这里维护;保存前后端会真做一次探活与列库核验。凭据由服务器文件引用提供,
页面只显示是否已配置,不回读、也不能在这里录入。
</p>
</div>
</div>
<div className="environment-cards">
<article>
<b>测试 WeKnora</b>
<span>{testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
<small className={`worker-capability ${workerCapabilities?.test_upload.state ?? 'unknown'}`}>
{testUploadLabel(workerCapabilities)}
{workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''}
</small>
</article>
<article className="production">
<b>生产 WeKnora</b>
<span>
{!productionEnabled
? '未启用'
: productionBackupRestoreVerified
? '已启用 · 可提交生产请求'
: '已启用 · 被阻断'}
</span>
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};凭据:服务器文件引用,页面不回读`}</small>
</article>
</div>
{isAdmin ? (
<>
<div className="safe-setting-grid production-endpoint-form">
<label>
测试地址
<input
value={testEndpoint}
onChange={(event) => setTestEndpoint(event.target.value)}
placeholder="https://weknora.test.example"
aria-invalid={!testEndpointValid}
/>
</label>
<label>
生产地址
<input
value={endpoint}
onChange={(event) => setEndpoint(event.target.value)}
placeholder="https://weknora.prod.example"
aria-invalid={!endpointValid}
/>
</label>
</div>
<details className="settings-details">
<summary>生产核验参数(仅用于核验,不决定发布写入目标)</summary>
<div className="safe-setting-grid">
<label>
生产租户 ID
<input
value={productionTenantID}
onChange={(event) => setProductionTenantID(event.target.value)}
placeholder="10000"
aria-invalid={!productionTenantIDValid}
/>
</label>
<label>
知识库 ID
<input
value={productionKnowledgeBaseID}
onChange={(event) => setProductionKnowledgeBaseID(event.target.value)}
placeholder="生产知识库 ID"
aria-invalid={!productionKnowledgeBaseIDValid}
/>
</label>
</div>
<small>
这两项用于确认生产端确实存在目标库、租户归属正确;整库发布的实际写入目标见下方「生产知识库绑定」,
由部署配置决定,不在本页修改。
</small>
</details>
<button
onClick={() =>
onSave(
serviceSettingsInput(settings, {
testEndpoint,
endpoint,
productionTenantID,
productionKnowledgeBaseID,
})
)
}
disabled={saving || !valid || !dirty}
>
{saving ? '正在验证并启用…' : '保存并校验连接'}
</button>
<details className="settings-details">
<summary>保存规则与核验说明</summary>
<small>
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,
凭据一律走文件引用);生产租户 ID 为十进制数字;知识库 ID 粘贴 URL 不会通过。
保存会生成修订、真实验证后原子启用;端点回答“没有这个知识库”或租户不符会拒收,
端点抖动、鉴权失败或未配置生产凭据只警告不拦。
</small>
</details>
{valid ? null : (
<p className="error-message" role="alert">
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产 ID
需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。
</p>
)}
{saveMessage ? (
<p className="success-message" role="status">
{saveMessage}
</p>
) : null}
</>
) : (
<small>
仅管理员可修改 WeKnora 连接;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址{' '}
{settings.production_weknora_base_url || '未配置'} · 生产 ID {settings.production_tenant_id || '未配置'} ·
知识库 ID {settings.production_knowledge_base_id || '未配置'}。
</small>
)}
</section>
)
}
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest'
import {
duplicateSelection,
keyActionFor,
knowledgeBaseLabel,
parseKBBindingSnapshot,
shortKnowledgeBaseID,
} from './knowledgeBaseBindings'
import type { KBEnvironmentBinding } from './knowledgeBaseBindings'
const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
environment,
revision: 1,
base_url: `https://${environment}.example`,
key_configured: true,
key_source: 'sealed',
internal_kb_id: `${environment}-in`,
internal_kb_name: '内部资料',
external_kb_id: `${environment}-out`,
external_kb_name: '对外资料',
verification: 'verified',
checked_at: null,
updated_by: 'admin',
updated_at: null,
source: 'web',
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
})
describe('knowledgeBaseBindings', () => {
it('parses both environments and never projects a key field', () => {
const parsed = parseKBBindingSnapshot({
data: {
environments: [binding('test'), binding('production')],
storage_ready: true,
},
})
expect(parsed.test.base_url).toBe('https://test.example')
expect(parsed.production.internal_kb_name).toBe('内部资料')
expect(parsed.storage_ready).toBe(true)
const asRecord = parsed.test as unknown as Record<string, unknown>
expect(asRecord.api_key).toBeUndefined()
expect(asRecord.key_ciphertext).toBeUndefined()
})
it('rejects a snapshot missing an environment instead of inventing one', () => {
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
})
it('shows a short id next to the name so same-name bases are distinguishable', () => {
expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…')
expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)')
expect(knowledgeBaseLabel('', '')).toBe('未绑定')
})
it('rejects using one base for both sides', () => {
expect(duplicateSelection('kb-1', 'kb-1')).toBe(true)
expect(duplicateSelection('kb-1', 'kb-2')).toBe(false)
expect(duplicateSelection('', '')).toBe(false)
})
it('forces a new key for any address other than the saved one', () => {
const saved = binding('test')
expect(keyActionFor(saved, 'https://test.example', false)).toBe('keep')
expect(keyActionFor(saved, 'https://other.example', false)).toBe('replace')
expect(keyActionFor({ ...saved, key_configured: false }, 'https://test.example', false)).toBe('replace')
expect(keyActionFor(saved, 'https://test.example', true)).toBe('replace')
})
})
+225
View File
@@ -0,0 +1,225 @@
import { newOperationID } from './operationKey'
export type KBEnvironment = 'test' | 'production'
export interface KBEnvironmentBinding {
environment: KBEnvironment
revision: number
base_url: string
key_configured: boolean
key_source: string
internal_kb_id: string
internal_kb_name: string
external_kb_id: string
external_kb_name: string
verification: string
checked_at: string | null
updated_by: string
updated_at: string | null
source: 'web' | 'legacy'
storage_ready: boolean
replanned: number
retired_duplicates: number
}
export interface KBBindingSnapshot {
test: KBEnvironmentBinding
production: KBEnvironmentBinding
storage_ready: boolean
}
export interface KBCatalogOption {
id: string
name: string
knowledge_count: number
}
export type KBCatalogStatus = 'ok' | 'empty' | 'unauthorized' | 'unreachable' | 'unsupported'
export interface KBCatalog {
status: KBCatalogStatus
message: string
page: number
page_size: number
total: number
options: KBCatalogOption[]
}
export interface KBCatalogInput {
base_revision: number
base_url: string
key_action: 'keep' | 'replace'
api_key?: string
page: number
page_size: number
}
export interface KBBindingSaveInput {
base_revision: number
base_url: string
key_action: 'keep' | 'replace'
api_key?: string
internal_kb_id: string
external_kb_id: string
}
export class KBBindingError extends Error {
readonly status: number
constructor(message: string, status: number) {
super(message)
this.name = 'KBBindingError'
this.status = status
}
}
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
const bool = (value: unknown): boolean => value === true
const count = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
function parseBinding(value: unknown): KBEnvironmentBinding {
if (!record(value) || (value.environment !== 'test' && value.environment !== 'production')) {
throw new Error('知识库绑定响应无效')
}
return {
environment: value.environment,
revision: count(value.revision),
base_url: text(value.base_url),
key_configured: bool(value.key_configured),
key_source: text(value.key_source),
internal_kb_id: text(value.internal_kb_id),
internal_kb_name: text(value.internal_kb_name),
external_kb_id: text(value.external_kb_id),
external_kb_name: text(value.external_kb_name),
verification: text(value.verification),
checked_at: typeof value.checked_at === 'string' ? value.checked_at : null,
updated_by: text(value.updated_by),
updated_at: typeof value.updated_at === 'string' ? value.updated_at : null,
source: value.source === 'web' ? 'web' : 'legacy',
storage_ready: bool(value.storage_ready),
replanned: count(value.replanned),
retired_duplicates: count(value.retired_duplicates),
}
}
export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
if (!record(value) || !record(value.data) || !Array.isArray(value.data.environments)) {
throw new Error('知识库绑定响应无效')
}
const byEnvironment = new Map<KBEnvironment, KBEnvironmentBinding>()
for (const item of value.data.environments) {
const binding = parseBinding(item)
byEnvironment.set(binding.environment, binding)
}
const test = byEnvironment.get('test')
const production = byEnvironment.get('production')
if (!test || !production) throw new Error('知识库绑定响应缺少环境')
return { test, production, storage_ready: bool(value.data.storage_ready) }
}
// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。
export function shortKnowledgeBaseID(value: string): string {
return value.length > 8 ? `${value.slice(0, 8)}…` : value
}
export function knowledgeBaseLabel(id: string, name: string): string {
if (!id) return '未绑定'
return name ? `${name}(${shortKnowledgeBaseID(id)})` : shortKnowledgeBaseID(id)
}
export function duplicateSelection(internal: string, external: string): boolean {
return internal !== '' && internal === external
}
// Keep is only legal for exactly the saved address; any other draft address
// needs a freshly typed key. This mirrors the server rule so the button state
// cannot promise something the server will refuse.
export function keyActionFor(saved: KBEnvironmentBinding, baseURL: string, replace: boolean): 'keep' | 'replace' {
if (replace || !saved.key_configured) return 'replace'
return baseURL.trim() === saved.base_url ? 'keep' : 'replace'
}
function failureMessage(value: unknown, fallback: string): string {
if (record(value) && typeof value.error === 'string' && value.error.trim() !== '') return value.error
return fallback
}
async function readResponse(response: Response): Promise<Record<string, unknown>> {
if (response.ok) {
const payload: unknown = await response.json()
return record(payload) ? payload : {}
}
const failure: unknown = await response.json().catch(() => null)
throw new KBBindingError(failureMessage(failure, `知识库绑定请求失败(HTTP ${response.status})`), response.status)
}
export async function fetchKBBindings(signal?: AbortSignal): Promise<KBBindingSnapshot> {
const response = await fetch('/api/v1/kb-bindings', { signal, headers: { Accept: 'application/json' } })
return parseKBBindingSnapshot(await readResponse(response))
}
export async function fetchKBCatalog(
environment: KBEnvironment,
input: KBCatalogInput,
signal?: AbortSignal
): Promise<KBCatalog> {
const response = await fetch(`/api/v1/kb-bindings/${environment}/catalog`, {
method: 'POST',
signal,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-Governance-Action': 'kb-bindings',
'Idempotency-Key': newOperationID(),
},
body: JSON.stringify(input),
})
const payload = await readResponse(response)
if (!record(payload.data)) throw new Error('知识库列表响应无效')
const item = payload.data
const status = text(item.status)
if (!['ok', 'empty', 'unauthorized', 'unreachable', 'unsupported'].includes(status)) {
throw new Error('知识库列表响应无效')
}
const options = Array.isArray(item.options)
? item.options
.filter(record)
.map((option) => ({
id: text(option.id),
name: text(option.name),
knowledge_count: count(option.knowledge_count),
}))
.filter((option) => option.id)
: []
return {
status: status as KBCatalogStatus,
message: text(item.message),
page: count(item.page) || 1,
page_size: count(item.page_size) || 20,
total: count(item.total),
options,
}
}
export async function saveKBBinding(
environment: KBEnvironment,
input: KBBindingSaveInput,
signal?: AbortSignal
): Promise<KBEnvironmentBinding> {
const response = await fetch(`/api/v1/kb-bindings/${environment}`, {
method: 'PUT',
signal,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-Governance-Action': 'kb-bindings',
'Idempotency-Key': newOperationID(),
},
body: JSON.stringify(input),
})
const payload = await readResponse(response)
return parseBinding(payload.data)
}
+5
View File
@@ -0,0 +1,5 @@
// Secret entry is only allowed on a real HTTPS origin or loopback. Plain LAN
// HTTP must not receive a key that would then cross the network in the clear.
export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
}
+170
View File
@@ -997,3 +997,173 @@ button.link {
grid-template-columns: 1fr;
}
}
/* ── 知识库绑定(按环境一次保存连接 + 内外库)────────────────────────── */
.kb-env-switch {
display: inline-flex;
gap: 4px;
margin: 0 0 14px;
padding: 3px;
border: 1px solid var(--border-base);
border-radius: 9px;
background: var(--bg-soft);
}
.kb-env-switch button {
border: 0;
background: transparent;
padding: 6px 14px;
border-radius: 6px;
color: var(--ink-mute);
cursor: pointer;
font: inherit;
}
.kb-env-switch button[aria-pressed='true'] {
background: var(--bg-panel);
color: var(--ink-base);
font-weight: 700;
box-shadow: 0 1px 2px rgb(0 0 0 / 8%);
}
.kb-current {
display: grid;
gap: 6px;
padding: 11px 14px;
margin-bottom: 14px;
border-inline-start: 3px solid var(--c-run, #318184);
border-radius: 8px;
background: var(--bg-soft);
}
.kb-current strong {
font-size: 12px;
color: var(--ink-mute);
}
.kb-current-targets {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
}
.kb-current-targets span {
color: var(--ink-mute);
font-size: 12px;
}
.kb-current-targets b {
color: var(--ink-base);
font-weight: 700;
}
.kb-current small,
.kb-block small,
.kb-footer .muted {
color: var(--ink-mute);
}
.kb-block {
padding: 14px 0;
border-bottom: 1px solid var(--border-base);
}
.kb-block h3 {
margin: 0 0 10px;
color: var(--ink-base);
font-size: 13px;
}
.kb-fields,
.kb-targets {
display: grid;
grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr);
gap: 14px;
}
.kb-targets {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.kb-fields label,
.kb-targets label,
.kb-key {
display: grid;
gap: 5px;
color: var(--ink-base);
font-size: 11px;
font-weight: 600;
}
.kb-key .label {
font-size: 11px;
}
.kb-key-line {
display: flex;
align-items: center;
gap: 8px;
min-height: 34px;
}
.kb-key-line input {
flex: 1;
}
.kb-key-line button.link {
border: 0;
background: transparent;
color: var(--c-run, #135e77);
cursor: pointer;
text-decoration: underline;
white-space: nowrap;
}
.kb-fields input,
.kb-targets select,
.kb-key-line input {
width: 100%;
min-height: 34px;
padding: 6px 9px;
border: 1px solid var(--border-base);
border-radius: 6px;
background: var(--bg-panel);
color: var(--ink-base);
font: inherit;
}
.kb-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin-top: 10px;
}
.kb-catalog-status {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 10px;
padding: 8px 10px;
border-radius: 7px;
background: var(--bg-soft);
font-size: 11px;
}
.kb-catalog-status.ok {
color: var(--c-done, #1f7a4d);
}
.kb-catalog-status.empty {
color: var(--ink-mute);
}
.kb-catalog-status.error {
color: var(--c-fail, #a63b32);
}
.kb-pager {
display: inline-flex;
gap: 6px;
}
.kb-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px;
padding-top: 14px;
}
.kb-binding-diagnostics {
margin-top: 14px;
}
.kb-binding-diagnostics > summary {
cursor: pointer;
color: var(--ink-mute);
font-size: 11px;
}
@media (max-width: 720px) {
.kb-fields,
.kb-targets {
grid-template-columns: 1fr;
}
}
+101
View File
@@ -0,0 +1,101 @@
import type { MonitorOverview } from './monitor'
import type { CatalogRoutingCapabilities } from './sourceCatalog'
import type { WorkerCapabilities } from './systemCapabilities'
import { testUploadLabel } from './systemCapabilities'
import type { UISettings } from './uiSettings'
type ServiceHealthView = MonitorOverview['health'][number]
type ServiceView = MonitorOverview['services'][number]
// 连接卡只读诊断:知识库绑定的保存入口已收敛到「知识库绑定」主表单,
// 这里保留原链路需要的探活/执行器状态,不再提供第二个保存路径。
export 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 testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
const label = healthStateLabel(health, service)
return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label
}
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(';')
}
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 interface WeKnoraConnectionDiagnosticsProps {
settings: UISettings
monitor: MonitorOverview | null
routingCapabilities: CatalogRoutingCapabilities
workerCapabilities?: WorkerCapabilities | null
productionEnabled: boolean
productionBackupRestoreVerified?: boolean
}
export function WeKnoraConnectionDiagnostics({
settings,
monitor,
routingCapabilities,
workerCapabilities = null,
productionEnabled,
productionBackupRestoreVerified = false,
}: WeKnoraConnectionDiagnosticsProps) {
return (
<div className="environment-cards" id="settings-weknora-diagnostics">
<article>
<b>测试 WeKnora</b>
<span>{testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${
routingCapabilities.internal_enabled ? '已配置' : '未配置'
} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
<small className={`worker-capability ${workerCapabilities?.test_upload.state ?? 'unknown'}`}>
{testUploadLabel(workerCapabilities)}
{workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''}
</small>
<small>{settings.test_weknora_base_url || '未配置地址'} · 凭据:服务器文件/加密存储,页面不回读</small>
</article>
<article className="production">
<b>生产 WeKnora</b>
<span>
{!productionEnabled
? '未启用'
: productionBackupRestoreVerified
? '已启用 · 可提交生产请求'
: '已启用 · 被阻断'}
</span>
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'}`}</small>
<small>{settings.production_weknora_base_url || '未配置地址'} · 凭据:服务器文件/加密存储,页面不回读</small>
</article>
</div>
)
}