feat(settings): 页面录入测试/生产 WeKnora 连接与密钥并收敛可达性判定
连接(地址 + 写-only 密钥)从文件引用搬进治理库:AES-GCM 密文 + 独立 0600 主密钥,
页面与接口只回显尾 4 位;测试连接真实列库并区分 地址不可达/密钥无效/无权限/成功,
换地址或换密钥必须测通才能保存(迁移 000083)。
可达性判定收敛为 weknora.HTTPAllowed,客户端与监控探活共用;新增
WEKNORA_ALLOW_PRIVATE_HTTP 只放行 RFC1918/回环/链路本地。生产绑定只保留下拉,
保存后回报冻结/未冻结条数,已冻结目标不被改写。
(cherry picked from commit ad02e8bb9c)
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { WeKnoraConnections } from './WeKnoraConnections'
|
||||
import { fetchProductionBindingOptions, fetchProductionBindings, saveProductionBindings } from './productionBindings'
|
||||
import type { ProductionBindings } from './productionBindings'
|
||||
import type { KnowledgeBaseOption } from './routingBindings'
|
||||
@@ -41,9 +42,12 @@ export function ProductionBindingsSection() {
|
||||
const next = await saveProductionBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
|
||||
setBindings(next)
|
||||
const where = `对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}`
|
||||
const frozen = next.frozen + next.retargetable > 0
|
||||
? `;已冻结目标 ${next.frozen} 条(不会被改写),仍可改指向 ${next.retargetable} 条`
|
||||
: ''
|
||||
setMessage(next.production_connected
|
||||
? `发布目标已更新:${where}。之后新发布的“对内/对外”内容会写入这两个生产库(已发布过的条目仍回到原目标)。`
|
||||
: `发布目标已保存:${where};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
|
||||
? `发布目标已更新:${where}${frozen}。之后新发布的“对内/对外”内容会写入这两个生产库。`
|
||||
: `发布目标已保存:${where}${frozen};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
@@ -62,11 +66,14 @@ export function ProductionBindingsSection() {
|
||||
<option value="">{placeholder}</option>
|
||||
{options.map((base) => <option key={base.id} value={base.id}>{optionLabel(base)}</option>)}
|
||||
</select>
|
||||
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入生产知识库 ID)`} aria-label={placeholder} />
|
||||
: <select value="" disabled aria-label={placeholder}>
|
||||
<option value="">读不到生产库列表:先在上方把生产连接测通</option>
|
||||
</select>
|
||||
)
|
||||
|
||||
return <section className="settings-panel wide" id="settings-production-bindings">
|
||||
<div className="settings-section-heading"><div><h2>生产知识库绑定</h2><p>发布链路的“源库 → 目标库”:新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库。留空表示未绑定,按同 ID 语义发布。</p></div><button onClick={() => void load()} disabled={loading}>{loading ? '读取中…' : '重新读取'}</button></div>
|
||||
<WeKnoraConnections environment="production" title="生产 WeKnora" placeholder="http://172.29.151.11:18093" onSaved={() => void load()} />
|
||||
{error ? <p className="error-message" role="alert">{error}</p> : null}
|
||||
{bindings ? <div className="kb-binding-grid">
|
||||
{renderSide('对内生产知识库', bindings.internal_kb_id, bindings.internal_kb_name)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { WeKnoraConnections } from './WeKnoraConnections'
|
||||
import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings'
|
||||
import type { KnowledgeBaseOption, RoutingBindings } from './routingBindings'
|
||||
|
||||
@@ -17,67 +18,171 @@ export function RoutingBindingsSection() {
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true); setError(null)
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const next = await fetchRoutingBindings()
|
||||
setBindings(next)
|
||||
setInternalDraft(next.internal_bound_by_ui ? next.internal_kb_id : '')
|
||||
setExternalDraft(next.external_bound_by_ui ? next.external_kb_id : '')
|
||||
try { setOptions(await fetchRoutingBindingOptions()) } catch { setOptions([]) }
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '读取测试知识库绑定失败') }
|
||||
finally { setLoading(false) }
|
||||
try {
|
||||
setOptions(await fetchRoutingBindingOptions())
|
||||
} catch {
|
||||
setOptions([])
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '读取测试知识库绑定失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => { void load() }, [load])
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const dirty = bindings !== null && (internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') || externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : ''))
|
||||
const dirty =
|
||||
bindings !== null &&
|
||||
(internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') ||
|
||||
externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : ''))
|
||||
const sameSelection = internalDraft !== '' && internalDraft === externalDraft
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true); setError(null); setMessage('')
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
setMessage('')
|
||||
try {
|
||||
const next = await saveRoutingBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
|
||||
setBindings(next)
|
||||
const replan = next.replanned || next.retired_duplicates
|
||||
? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}`
|
||||
: ''
|
||||
setMessage(`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由${replan}。`)
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存测试知识库绑定失败') }
|
||||
finally { setSaving(false) }
|
||||
const replan =
|
||||
next.replanned || next.retired_duplicates
|
||||
? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}`
|
||||
: ''
|
||||
const fallbacks: string[] = []
|
||||
if (!next.internal_bound_by_ui)
|
||||
fallbacks.push(
|
||||
`对内回退到部署默认库 ${next.internal_fallback_kb_id ? `${next.internal_fallback_kb_id.slice(0, 8)}…` : '(未设置)'}`
|
||||
)
|
||||
if (!next.external_bound_by_ui)
|
||||
fallbacks.push(
|
||||
`对外回退到部署默认库 ${next.external_fallback_kb_id ? `${next.external_fallback_kb_id.slice(0, 8)}…` : '(未设置)'}`
|
||||
)
|
||||
setMessage(
|
||||
`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}${fallbacks.length ? `;${fallbacks.join(';')}` : ''}。此后“来源与目录”的标记按新绑定路由${replan}。`
|
||||
)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '保存测试知识库绑定失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)`
|
||||
const renderSide = (label: string, boundID: string, boundName: string, fromEnv: boolean, boundByUI: boolean) => (
|
||||
const optionLabel = (base: KnowledgeBaseOption) =>
|
||||
`${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)`
|
||||
const renderSide = (
|
||||
label: string,
|
||||
boundID: string,
|
||||
boundName: string,
|
||||
fromEnv: boolean,
|
||||
boundByUI: boolean,
|
||||
fallbackID = ''
|
||||
) => (
|
||||
<div className={`kb-binding-side ${boundID ? 'bound' : 'warn'}`}>
|
||||
<b>{label}</b>
|
||||
<span>{boundID ? (boundName || `${boundID.slice(0, 8)}…`) : '未绑定 · 该方向的标记会被拒绝'}</span>
|
||||
<small>{boundID ? (boundByUI ? (boundName ? `UI 绑定 · ${boundID.slice(0, 8)}…` : 'UI 绑定') : fromEnv ? '来自部署默认值(env)' : '') : '请绑定一个测试知识库'}</small>
|
||||
<span>{boundID ? boundName || `${boundID.slice(0, 8)}…` : '未绑定 · 该方向的标记会被拒绝'}</span>
|
||||
<small>
|
||||
{boundID
|
||||
? boundByUI
|
||||
? boundName
|
||||
? `UI 绑定 · ${boundID.slice(0, 8)}…`
|
||||
: 'UI 绑定'
|
||||
: fromEnv
|
||||
? `回退到部署默认库 ${fallbackID ? `${fallbackID.slice(0, 8)}…` : '(未设置)'}`
|
||||
: ''
|
||||
: '请绑定一个测试知识库'}
|
||||
</small>
|
||||
</div>
|
||||
)
|
||||
const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => (
|
||||
options.length > 0
|
||||
? <select value={value} onChange={(event) => onChange(event.target.value)} aria-label={placeholder}>
|
||||
<option value="">{placeholder}</option>
|
||||
{options.map((base) => <option key={base.id} value={base.id}>{optionLabel(base)}</option>)}
|
||||
</select>
|
||||
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入知识库 ID)`} aria-label={placeholder} />
|
||||
)
|
||||
const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) =>
|
||||
options.length > 0 ? (
|
||||
<select value={value} onChange={(event) => onChange(event.target.value)} aria-label={placeholder}>
|
||||
<option value="">{placeholder}</option>
|
||||
{options.map((base) => (
|
||||
<option key={base.id} value={base.id}>
|
||||
{optionLabel(base)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<select value="" disabled aria-label={placeholder}>
|
||||
<option value="">读不到测试库列表:先在上方把测试连接测通</option>
|
||||
</select>
|
||||
)
|
||||
|
||||
return <section className="settings-panel wide" id="settings-routing-bindings">
|
||||
<div className="settings-section-heading"><div><h2>测试知识库绑定</h2><p>“来源与目录”里的对内 / 对外标记按这里的绑定分发到对应的测试 WeKnora 知识库;保存后立即生效,无需重启。发布写入的生产知识库见「生产知识库绑定」。</p></div><button onClick={() => void load()} disabled={loading}>{loading ? '读取中…' : '重新读取'}</button></div>
|
||||
{error ? <p className="error-message" role="alert">{error}</p> : null}
|
||||
{bindings ? <div className="kb-binding-grid">
|
||||
{renderSide('对内知识库', bindings.internal_kb_id, bindings.internal_kb_name, bindings.internal_env_fallback, bindings.internal_bound_by_ui)}
|
||||
{renderSide('对外知识库', bindings.external_kb_id, bindings.external_kb_name, bindings.external_env_fallback, bindings.external_bound_by_ui)}
|
||||
</div> : null}
|
||||
{bindings && !bindings.weknora_connected ? <p className="hint">当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。</p> : null}
|
||||
{isAdmin && bindings ? <div className="kb-binding-editor">
|
||||
<label>对内绑定 {editorFor(internalDraft, setInternalDraft, '选择对内知识库')}</label>
|
||||
<label>对外绑定 {editorFor(externalDraft, setExternalDraft, '选择对外知识库')}</label>
|
||||
<p className="hint">留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。</p>
|
||||
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的知识库</p> : null}
|
||||
<button onClick={() => void save()} disabled={saving || !dirty || sameSelection}>{saving ? '正在校验并保存…' : '保存绑定'}</button>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
</div> : null}
|
||||
{!isAdmin ? <p className="hint">仅管理员可修改测试知识库绑定。</p> : null}
|
||||
</section>
|
||||
return (
|
||||
<section className="settings-panel wide" id="settings-routing-bindings">
|
||||
<div className="settings-section-heading">
|
||||
<div>
|
||||
<h2>测试知识库绑定</h2>
|
||||
<p>
|
||||
“来源与目录”里的对内 / 对外标记按这里的绑定分发到对应的测试 WeKnora
|
||||
知识库;保存后立即生效,无需重启。发布写入的生产知识库见「生产知识库绑定」。
|
||||
</p>
|
||||
</div>
|
||||
<button onClick={() => void load()} disabled={loading}>
|
||||
{loading ? '读取中…' : '重新读取'}
|
||||
</button>
|
||||
</div>
|
||||
<WeKnoraConnections
|
||||
environment="test"
|
||||
title="测试 WeKnora"
|
||||
placeholder="http://127.0.0.1:8092"
|
||||
onSaved={() => void load()}
|
||||
/>
|
||||
{error ? (
|
||||
<p className="error-message" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{bindings ? (
|
||||
<div className="kb-binding-grid">
|
||||
{renderSide(
|
||||
'对内知识库',
|
||||
bindings.internal_kb_id,
|
||||
bindings.internal_kb_name,
|
||||
bindings.internal_env_fallback,
|
||||
bindings.internal_bound_by_ui,
|
||||
bindings.internal_fallback_kb_id
|
||||
)}
|
||||
{renderSide(
|
||||
'对外知识库',
|
||||
bindings.external_kb_id,
|
||||
bindings.external_kb_name,
|
||||
bindings.external_env_fallback,
|
||||
bindings.external_bound_by_ui,
|
||||
bindings.external_fallback_kb_id
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
{bindings && !bindings.weknora_connected ? (
|
||||
<p className="hint">当前读不到 WeKnora 的库列表:先在上面的连接卡把地址与密钥配好并测通,再回来选库。</p>
|
||||
) : null}
|
||||
{isAdmin && bindings ? (
|
||||
<div className="kb-binding-editor">
|
||||
<label>对内绑定 {editorFor(internalDraft, setInternalDraft, '选择对内知识库')}</label>
|
||||
<label>对外绑定 {editorFor(externalDraft, setExternalDraft, '选择对外知识库')}</label>
|
||||
<p className="hint">留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。</p>
|
||||
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的知识库</p> : null}
|
||||
<button onClick={() => void save()} disabled={saving || !dirty || sameSelection}>
|
||||
{saving ? '正在校验并保存…' : '保存绑定'}
|
||||
</button>
|
||||
{message ? (
|
||||
<p className="success-message" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{!isAdmin ? <p className="hint">仅管理员可修改测试知识库绑定。</p> : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -424,12 +424,14 @@ describe('SystemSettingsView', () => {
|
||||
expect(on).toContain('测试 WeKnora')
|
||||
expect(on).toContain('可达 · 可接单')
|
||||
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('连接:可达')
|
||||
expect(off).toContain('生产写入:关闭')
|
||||
expect(off).not.toContain('被阻断')
|
||||
// 卡片状态由真实探测/门禁驱动,写死的“已连接 / 未连接 / 生产映射:未配置”必须消失。
|
||||
for (const removed of ['本地真实连接', '生产映射:未配置']) expect(off).not.toContain(removed)
|
||||
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
|
||||
@@ -453,7 +455,7 @@ describe('SystemSettingsView', () => {
|
||||
initialSection="services"
|
||||
/>
|
||||
)
|
||||
expect(blocked).toContain('已启用 · 被阻断')
|
||||
expect(blocked).toContain('生产写入:开启 · 恢复演练未核验')
|
||||
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
|
||||
expect(blocked).toContain('端点探测:暂无真实探测结果')
|
||||
const unconfigured = renderToStaticMarkup(
|
||||
|
||||
+23
-26
@@ -119,6 +119,15 @@ export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string
|
||||
return `端点探测:${label}${detail ? `(${detail})` : ''}`
|
||||
}
|
||||
|
||||
// 生产卡片拆两行:连接是否可达,与生产写入是否开启是两件事 —— 以前把
|
||||
// 「被阻断」混进连接状态,页面会自相矛盾(端点明明可达却显示被阻断)。
|
||||
const productionConnectionLine = (monitor: MonitorOverview | null): string => {
|
||||
const health = findHealth(monitor, '生产 WeKnora')
|
||||
if (!health) return '连接:暂无探测结果'
|
||||
if (!health.configured) return '连接:未配置'
|
||||
return health.liveness === 'up' ? '连接:可达' : '连接:不可达'
|
||||
}
|
||||
|
||||
export function SystemSettingsView({
|
||||
sources,
|
||||
connections,
|
||||
@@ -199,6 +208,12 @@ export function SystemSettingsView({
|
||||
setDirty(false)
|
||||
onSave(candidateInput())
|
||||
}
|
||||
const productionConnectionLineText = productionConnectionLine(monitor)
|
||||
const productionWriteLine = !productionEnabled
|
||||
? '生产写入:关闭'
|
||||
: productionBackupRestoreVerified
|
||||
? '生产写入:开启 · 可提交生产请求'
|
||||
: '生产写入:开启 · 恢复演练未核验'
|
||||
return (
|
||||
<main className="page-shell system-settings">
|
||||
<header className="hero compact">
|
||||
@@ -278,14 +293,8 @@ export function SystemSettingsView({
|
||||
</article>
|
||||
<article className="production">
|
||||
<b>生产 WeKnora</b>
|
||||
<span>
|
||||
{!productionEnabled
|
||||
? '未启用'
|
||||
: productionBackupRestoreVerified
|
||||
? '已启用 · 可提交生产请求'
|
||||
: '已启用 · 被阻断'}
|
||||
</span>
|
||||
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
|
||||
<span>{productionConnectionLineText}</span>
|
||||
<small>{`${productionWeKnoraProbe(monitor)};${productionWriteLine};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
|
||||
</article>
|
||||
</div>
|
||||
<div className="safe-setting-grid production-endpoint-form">
|
||||
@@ -293,27 +302,11 @@ export function SystemSettingsView({
|
||||
<>
|
||||
<label>
|
||||
测试地址
|
||||
<input
|
||||
value={testEndpoint}
|
||||
onChange={(event) => {
|
||||
setTestEndpoint(event.target.value)
|
||||
setDirty(true)
|
||||
}}
|
||||
placeholder="https://weknora.test.example"
|
||||
aria-invalid={!testEndpointValid}
|
||||
/>
|
||||
<input value={testEndpoint || '未配置'} readOnly disabled />
|
||||
</label>
|
||||
<label>
|
||||
生产地址
|
||||
<input
|
||||
value={endpoint}
|
||||
onChange={(event) => {
|
||||
setEndpoint(event.target.value)
|
||||
setDirty(true)
|
||||
}}
|
||||
placeholder="https://weknora.prod.example"
|
||||
aria-invalid={!endpointValid}
|
||||
/>
|
||||
<input value={endpoint || '未配置'} readOnly disabled />
|
||||
</label>
|
||||
<label>
|
||||
生产 ID
|
||||
@@ -376,6 +369,10 @@ export function SystemSettingsView({
|
||||
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
|
||||
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
|
||||
</small>
|
||||
<p className="hint">
|
||||
地址已移到「测试知识库绑定 /
|
||||
生产知识库绑定」分区顶部的连接卡维护(可在那里测试连接);这里是回退值,只读。
|
||||
</p>
|
||||
{serviceSettingsValid ? null : (
|
||||
<p className="error-message" role="alert">
|
||||
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { PasswordInput } from './PasswordInput'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import {
|
||||
fetchWeKnoraConnections,
|
||||
keyLabel,
|
||||
saveWeKnoraConnection,
|
||||
testWeKnoraConnection,
|
||||
verificationLabel,
|
||||
} from './weknoraConnections'
|
||||
import type { WeKnoraConnection, WeKnoraEnvironment } from './weknoraConnections'
|
||||
|
||||
interface Props {
|
||||
environment: WeKnoraEnvironment
|
||||
title: string
|
||||
placeholder: string
|
||||
onSaved?: () => void
|
||||
}
|
||||
|
||||
// 连接卡:地址 + 写-only 密钥 + 真实列库测试。它只改「连哪台实例、用哪把钥匙」,
|
||||
// 不碰绑定,也不触发任何同步或发布。
|
||||
export function WeKnoraConnections({ environment, title, placeholder, onSaved }: Props) {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
const [connection, setConnection] = useState<WeKnoraConnection | null>(null)
|
||||
const [endpointDraft, setEndpointDraft] = useState('')
|
||||
const [keyDraft, setKeyDraft] = useState('')
|
||||
const [testing, setTesting] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState('')
|
||||
const [testedEndpoint, setTestedEndpoint] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const all = await fetchWeKnoraConnections()
|
||||
const found = all.find((item) => item.environment === environment) ?? null
|
||||
setConnection(found)
|
||||
setEndpointDraft(found?.endpoint ?? '')
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '读取连接失败')
|
||||
}
|
||||
}, [environment])
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const endpoint = endpointDraft.trim()
|
||||
const keyEntered = keyDraft.trim() !== ''
|
||||
const endpointChanged = connection !== null && endpoint !== connection.endpoint
|
||||
const canTest = endpoint !== '' && !testing && !saving
|
||||
const tested = testedEndpoint !== '' && testedEndpoint === endpoint
|
||||
const canSave = endpoint !== '' && !saving && !testing && (keyEntered || endpointChanged ? tested : true)
|
||||
|
||||
const test = async () => {
|
||||
setTesting(true)
|
||||
setError(null)
|
||||
setMessage('')
|
||||
try {
|
||||
const result = await testWeKnoraConnection(environment, {
|
||||
endpoint,
|
||||
...(keyEntered
|
||||
? { api_key: keyDraft.trim(), key_action: 'replace' as const }
|
||||
: { key_action: 'keep' as const }),
|
||||
})
|
||||
setMessage(result.message)
|
||||
setTestedEndpoint(result.outcome === 'ok' ? endpoint : '')
|
||||
if (result.outcome !== 'ok') setError(result.message)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '测试连接失败')
|
||||
} finally {
|
||||
setTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const save = async (action: 'keep' | 'replace' | 'clear') => {
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
try {
|
||||
const next = await saveWeKnoraConnection(environment, {
|
||||
endpoint,
|
||||
...(action === 'replace' ? { api_key: keyDraft.trim() } : {}),
|
||||
key_action: action,
|
||||
base_revision: connection?.revision ?? 0,
|
||||
})
|
||||
setConnection(next)
|
||||
setEndpointDraft(next.endpoint)
|
||||
setKeyDraft('')
|
||||
setTestedEndpoint('')
|
||||
setMessage(`已保存:${keyLabel(next)};最近一次测试:${verificationLabel(next)}。保存未触发任何同步或发布。`)
|
||||
onSaved?.()
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '保存连接失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const clearKey = () => {
|
||||
if (!window.confirm('清除后该侧将没有任何可用密钥,发布与列库都会失败。确定清除?')) return
|
||||
void save('clear')
|
||||
}
|
||||
|
||||
const saveAction = keyEntered ? 'replace' : 'keep'
|
||||
|
||||
return (
|
||||
<div className="weknora-connection-card" id={`settings-weknora-connection-${environment}`}>
|
||||
<div className="kb-binding-grid">
|
||||
<div className={`kb-binding-side ${connection?.verification === 'ok' ? 'bound' : 'warn'}`}>
|
||||
<b>{title}</b>
|
||||
<span>连接:{verificationLabel(connection)}</span>
|
||||
<small>
|
||||
{connection?.endpoint
|
||||
? `地址:${connection.endpoint} · 密钥:${keyLabel(connection)}`
|
||||
: '还没有配置地址与密钥'}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
{connection && !connection.storage_ready ? (
|
||||
<p className="hint">密钥存储不可用(主密钥文件缺失或权限不是 0600):可以读取当前状态,但保存会被拒绝。</p>
|
||||
) : null}
|
||||
{isAdmin ? (
|
||||
<div className="kb-binding-editor">
|
||||
<label>
|
||||
{title}地址
|
||||
<input
|
||||
value={endpointDraft}
|
||||
onChange={(event) => {
|
||||
setEndpointDraft(event.target.value)
|
||||
setTestedEndpoint('')
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
aria-label={`${title}地址`}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
API Key
|
||||
<PasswordInput
|
||||
autoComplete="new-password"
|
||||
value={keyDraft}
|
||||
onChange={(event) => {
|
||||
setKeyDraft(event.target.value)
|
||||
setTestedEndpoint('')
|
||||
}}
|
||||
placeholder={connection?.key_configured ? '留空 = 保留原密钥' : '粘贴 API Key'}
|
||||
aria-label={`${title} API Key`}
|
||||
/>
|
||||
</label>
|
||||
<p className="hint">
|
||||
「测试连接」会真实请求该实例的知识库列表,并区分地址不可达 / 密钥无效 / 无权限 /
|
||||
成功;换了地址或密钥必须先测通才能保存。撤销绑定请把下方目标库留空。
|
||||
</p>
|
||||
<div className="kb-binding-actions">
|
||||
<button onClick={() => void test()} disabled={!canTest}>
|
||||
{testing ? '正在测试…' : '测试连接'}
|
||||
</button>
|
||||
<button onClick={() => void save(saveAction)} disabled={!canSave}>
|
||||
{saving ? '正在保存…' : '保存连接'}
|
||||
</button>
|
||||
{connection?.key_configured ? (
|
||||
<button className="danger" onClick={clearKey} disabled={saving || testing}>
|
||||
清除密钥
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
{error ? (
|
||||
<p className="error-message" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{message ? (
|
||||
<p className="success-message" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<p className="hint">仅管理员可修改连接与密钥;当前密钥只显示尾 4 位,任何接口都不会回读明文。</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,8 @@ export interface ProductionBindings {
|
||||
production_base_url: string
|
||||
production_connected: boolean
|
||||
production_message: string
|
||||
frozen: number
|
||||
retargetable: number
|
||||
}
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
@@ -25,6 +27,8 @@ function projection(item: Record<string, unknown>): ProductionBindings {
|
||||
production_base_url: typeof item.production_base_url === 'string' ? item.production_base_url : '',
|
||||
production_connected: item.production_connected === true,
|
||||
production_message: typeof item.production_message === 'string' ? item.production_message : '',
|
||||
frozen: typeof item.frozen === 'number' ? item.frozen : 0,
|
||||
retargetable: typeof item.retargetable === 'number' ? item.retargetable : 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ export interface RoutingBindings {
|
||||
external_kb_id: string
|
||||
internal_env_fallback: boolean
|
||||
external_env_fallback: boolean
|
||||
internal_fallback_kb_id: string
|
||||
external_fallback_kb_id: string
|
||||
internal_bound_by_ui: boolean
|
||||
external_bound_by_ui: boolean
|
||||
internal_kb_name: string
|
||||
@@ -30,6 +32,8 @@ function bindingProjection(item: Record<string, unknown>): RoutingBindings {
|
||||
external_kb_id: typeof item.external_kb_id === 'string' ? item.external_kb_id : '',
|
||||
internal_env_fallback: item.internal_env_fallback === true,
|
||||
external_env_fallback: item.external_env_fallback === true,
|
||||
internal_fallback_kb_id: typeof item.internal_fallback_kb_id === 'string' ? item.internal_fallback_kb_id : '',
|
||||
external_fallback_kb_id: typeof item.external_fallback_kb_id === 'string' ? item.external_fallback_kb_id : '',
|
||||
internal_bound_by_ui: item.internal_bound_by_ui === true,
|
||||
external_bound_by_ui: item.external_bound_by_ui === true,
|
||||
internal_kb_name: typeof item.internal_kb_name === 'string' ? item.internal_kb_name : '',
|
||||
|
||||
@@ -882,3 +882,29 @@ button.link {
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* 连接卡:地址 + 写-only 密钥 + 真实列库测试。它嵌在既有的「测试/生产知识库绑定」
|
||||
分区里,所以只做一个轻量内框,不另起一套分区样式。 */
|
||||
.weknora-connection-card {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 10px 0 16px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.weknora-connection-card .kb-binding-grid {
|
||||
margin: 0;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.kb-binding-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.kb-binding-actions button.danger {
|
||||
border-color: var(--c-fail);
|
||||
background: #fff;
|
||||
color: var(--c-fail);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
fetchWeKnoraConnections,
|
||||
keyLabel,
|
||||
saveWeKnoraConnection,
|
||||
testWeKnoraConnection,
|
||||
verificationLabel,
|
||||
} from './weknoraConnections'
|
||||
import type { WeKnoraConnection, WeKnoraVerification } from './weknoraConnections'
|
||||
|
||||
const connection: WeKnoraConnection = {
|
||||
environment: 'production',
|
||||
endpoint: 'http://172.29.151.11:18093',
|
||||
key_configured: true,
|
||||
key_tail: '9f2c',
|
||||
verification: 'ok',
|
||||
library_count: 4,
|
||||
checked_at: '2026-11-22T07:00:00Z',
|
||||
updated_by: 'admin',
|
||||
revision: 3,
|
||||
storage_ready: true,
|
||||
}
|
||||
|
||||
describe('WeKnora connection API', () => {
|
||||
it('projects only the safe fields and never surfaces a key', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [{ ...connection, api_key: 'placeholder-key-value', key_ciphertext: 'AAAA' }],
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
)
|
||||
const [projected] = await fetchWeKnoraConnections()
|
||||
expect(projected.key_tail).toBe('9f2c')
|
||||
expect(projected).not.toHaveProperty('api_key')
|
||||
expect(projected).not.toHaveProperty('key_ciphertext')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('renders the four answers distinctly', () => {
|
||||
const withVerification = (verification: WeKnoraVerification): WeKnoraConnection => ({ ...connection, verification })
|
||||
expect(verificationLabel({ ...connection, library_count: 4 })).toBe('可达 · 已读到 4 个知识库')
|
||||
expect(verificationLabel(withVerification('key_invalid'))).toBe('密钥无效')
|
||||
expect(verificationLabel(withVerification('key_forbidden'))).toBe('密钥无权限读取知识库列表')
|
||||
expect(verificationLabel(withVerification('unreachable'))).toBe('地址不可达')
|
||||
expect(verificationLabel(null)).toBe('未配置')
|
||||
expect(keyLabel(connection)).toBe('已配置 · 尾9f2c')
|
||||
expect(keyLabel({ ...connection, key_configured: false, key_tail: '' })).toBe('未配置')
|
||||
})
|
||||
|
||||
it('tests through the environment route and keeps the outcome', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
environment: 'production',
|
||||
endpoint: connection.endpoint,
|
||||
outcome: 'key_forbidden',
|
||||
library_count: 0,
|
||||
message: '密钥无权限读取知识库列表(403)',
|
||||
checked_at: '2026-11-22T07:00:00Z',
|
||||
},
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const result = await testWeKnoraConnection('production', {
|
||||
endpoint: connection.endpoint,
|
||||
api_key: 'sk-live-x',
|
||||
key_action: 'replace',
|
||||
})
|
||||
expect(result.outcome).toBe('key_forbidden')
|
||||
expect(result.message).toContain('无权限')
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/weknora-connections/production/test')
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ key_action: 'replace' })
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('saves with the revision and an idempotency key', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: connection }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const saved = await saveWeKnoraConnection('production', {
|
||||
endpoint: connection.endpoint,
|
||||
key_action: 'keep',
|
||||
base_revision: 2,
|
||||
})
|
||||
expect(saved.revision).toBe(3)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('/api/v1/weknora-connections/production')
|
||||
expect(init.method).toBe('PUT')
|
||||
expect(init.headers['Idempotency-Key']).toBeTruthy()
|
||||
expect(JSON.parse(init.body)).toMatchObject({ key_action: 'keep', base_revision: 2 })
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('surfaces the server reason when a save is refused', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: '请先点「测试连接」并成功,才能保存这一侧的配置' }), { status: 400 })
|
||||
)
|
||||
)
|
||||
await expect(
|
||||
saveWeKnoraConnection('test', { endpoint: 'http://127.0.0.1:8092', key_action: 'keep', base_revision: 0 })
|
||||
).rejects.toThrow('测试连接')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
|
||||
// 连接状态:地址 + 「有没有配过密钥」+ 上一次真实列库的结论。密钥本身永远不回到
|
||||
// 页面,只回显尾 4 位。
|
||||
export type WeKnoraVerification = 'not_configured' | 'ok' | 'unreachable' | 'key_invalid' | 'key_forbidden'
|
||||
export type WeKnoraTestOutcome = 'ok' | 'unreachable' | 'key_invalid' | 'key_forbidden'
|
||||
export type WeKnoraEnvironment = 'test' | 'production'
|
||||
|
||||
export interface WeKnoraConnection {
|
||||
environment: WeKnoraEnvironment
|
||||
endpoint: string
|
||||
key_configured: boolean
|
||||
key_tail: string
|
||||
verification: WeKnoraVerification
|
||||
library_count: number
|
||||
checked_at: string | null
|
||||
updated_by: string
|
||||
revision: number
|
||||
storage_ready: boolean
|
||||
}
|
||||
|
||||
export interface WeKnoraConnectionTestResult {
|
||||
environment: WeKnoraEnvironment
|
||||
endpoint: string
|
||||
outcome: WeKnoraTestOutcome
|
||||
library_count: number
|
||||
message: string
|
||||
checked_at: string
|
||||
}
|
||||
|
||||
type KeyAction = 'keep' | 'replace' | 'clear'
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> =>
|
||||
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
|
||||
const verificationOf = (value: unknown): WeKnoraVerification =>
|
||||
value === 'ok' ||
|
||||
value === 'unreachable' ||
|
||||
value === 'key_invalid' ||
|
||||
value === 'key_forbidden' ||
|
||||
value === 'not_configured'
|
||||
? value
|
||||
: 'not_configured'
|
||||
|
||||
function projection(item: Record<string, unknown>): WeKnoraConnection {
|
||||
const environment = item.environment === 'production' ? 'production' : 'test'
|
||||
return {
|
||||
environment,
|
||||
endpoint: typeof item.endpoint === 'string' ? item.endpoint : '',
|
||||
key_configured: item.key_configured === true,
|
||||
key_tail: typeof item.key_tail === 'string' ? item.key_tail : '',
|
||||
verification: verificationOf(item.verification),
|
||||
library_count: typeof item.library_count === 'number' ? item.library_count : 0,
|
||||
checked_at: typeof item.checked_at === 'string' ? item.checked_at : null,
|
||||
updated_by: typeof item.updated_by === 'string' ? item.updated_by : '',
|
||||
revision: typeof item.revision === 'number' ? item.revision : 0,
|
||||
storage_ready: item.storage_ready === true,
|
||||
}
|
||||
}
|
||||
|
||||
async function reason(response: Response, fallback: string): Promise<string> {
|
||||
try {
|
||||
const body = (await response.json()) as unknown
|
||||
if (record(body) && typeof body.error === 'string' && body.error) return body.error
|
||||
} catch {
|
||||
/* keep the status text */
|
||||
}
|
||||
return `${fallback}(HTTP ${response.status})`
|
||||
}
|
||||
|
||||
export async function fetchWeKnoraConnections(signal?: AbortSignal): Promise<WeKnoraConnection[]> {
|
||||
const response = await fetch('/api/v1/weknora-connections', { signal, headers: { Accept: 'application/json' } })
|
||||
if (!response.ok) throw new Error(await reason(response, '读取 WeKnora 连接失败'))
|
||||
const value = (await response.json()) as unknown
|
||||
if (!record(value) || !Array.isArray(value.data)) throw new Error('WeKnora 连接响应无效')
|
||||
return value.data.filter(record).map(projection)
|
||||
}
|
||||
|
||||
export async function testWeKnoraConnection(
|
||||
environment: WeKnoraEnvironment,
|
||||
input: { endpoint: string; api_key?: string; key_action?: KeyAction },
|
||||
signal?: AbortSignal
|
||||
): Promise<WeKnoraConnectionTestResult> {
|
||||
const response = await fetch(`/api/v1/weknora-connections/${environment}/test`, {
|
||||
method: 'POST',
|
||||
signal,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
if (!response.ok) throw new Error(await reason(response, '测试连接失败'))
|
||||
const value = (await response.json()) as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('测试连接响应无效')
|
||||
const data = value.data
|
||||
return {
|
||||
environment: data.environment === 'production' ? 'production' : 'test',
|
||||
endpoint: typeof data.endpoint === 'string' ? data.endpoint : input.endpoint,
|
||||
outcome:
|
||||
data.outcome === 'key_invalid' || data.outcome === 'key_forbidden' || data.outcome === 'unreachable'
|
||||
? data.outcome
|
||||
: 'ok',
|
||||
library_count: typeof data.library_count === 'number' ? data.library_count : 0,
|
||||
message: typeof data.message === 'string' ? data.message : '',
|
||||
checked_at: typeof data.checked_at === 'string' ? data.checked_at : '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveWeKnoraConnection(
|
||||
environment: WeKnoraEnvironment,
|
||||
input: { endpoint: string; api_key?: string; key_action: KeyAction; base_revision: number },
|
||||
signal?: AbortSignal
|
||||
): Promise<WeKnoraConnection> {
|
||||
const response = await fetch(`/api/v1/weknora-connections/${environment}`, {
|
||||
method: 'PUT',
|
||||
signal,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
if (!response.ok) throw new Error(await reason(response, '保存连接失败'))
|
||||
const value = (await response.json()) as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('保存连接响应无效')
|
||||
return projection(value.data)
|
||||
}
|
||||
|
||||
// verificationLabel 是页面唯一的口径:四态说清「哪里不通」,成功时带库数量。
|
||||
export function verificationLabel(connection: WeKnoraConnection | null): string {
|
||||
if (!connection || !connection.endpoint) return '未配置'
|
||||
switch (connection.verification) {
|
||||
case 'ok':
|
||||
return `可达 · 已读到 ${connection.library_count} 个知识库`
|
||||
case 'key_invalid':
|
||||
return '密钥无效'
|
||||
case 'key_forbidden':
|
||||
return '密钥无权限读取知识库列表'
|
||||
case 'unreachable':
|
||||
return '地址不可达'
|
||||
default:
|
||||
// 填了地址但还没测过:说「尚未验证」,不要谎报不可达。
|
||||
return '尚未验证'
|
||||
}
|
||||
}
|
||||
|
||||
export function keyLabel(connection: WeKnoraConnection | null): string {
|
||||
if (!connection || !connection.key_configured) return '未配置'
|
||||
return `已配置 · 尾${connection.key_tail || '—'}`
|
||||
}
|
||||
Reference in New Issue
Block a user