Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d3c435183e | |||
| aa75dc6d44 | |||
| c96189db1b | |||
| d76363c117 | |||
| 8c84c9c601 |
@@ -28,6 +28,8 @@ QA_AI_MASTER_KEY_FILE=
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。
|
||||
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
||||
QA_AI_DNS_OVER_TLS=
|
||||
|
||||
@@ -1,5 +1,34 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.415(系统设置:刷新策略改为按模块分组的参数设置)
|
||||
|
||||
### Changed
|
||||
|
||||
- **入口改为「参数设置」**:系统设置左侧子导航与页面标题由「刷新策略」替换为「参数设置」,
|
||||
旧入口不再出现。
|
||||
- **参数按模块分组**:按产品归属固定为「来源与目录」(文档状态刷新间隔 15/30/60 秒、
|
||||
资源刷新间隔 30/60 秒)与「解析监控」(解析停滞阈值 30/60 分钟、入库并发上限 1..16);
|
||||
分组标题下不叠加说明段。
|
||||
- **数值输入与就地校验**:四个下拉改为文本数值输入;空值、非整数、`+15`/`1e1`、全角数字
|
||||
与越界值当场红字提示并禁用保存,不发请求;并发不再受旧下拉六档限制。
|
||||
- **保留现状说明与保存边界**:每项保留单位与调大/调小后果;解析停滞阈值保留 worker 1 分钟
|
||||
内生效说明;保存仍只提交参数分区,且原样回传未展示的 `finalizing_after_seconds` 与连接字段。
|
||||
- **去掉无消费者的收尾超时展示**:本页不再展示「收尾超时告警」,成功消息与底部摘要也不再
|
||||
播报它;API/DB/worker 与 `finalizing` 处理状态均未改动。
|
||||
|
||||
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **私网 http 控制台无法录入 API Key**:页面过去只看浏览器 URL 决定能否录入,而服务端写侧
|
||||
已按 `WEKNORA_ALLOW_PRIVATE_HTTP` 放行私网 http,导致「开关开着、输入框仍禁用」。GET
|
||||
`/api/v1/kb-bindings` 现在返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
|
||||
开关与受信反代判定;API 未返回该字段时前端按不可录入处理(失败关闭)。写侧判定不变。
|
||||
- **明文录入没有风险提示**:能力位开启且页面经非回环 http 打开时,Key 输入下方常驻提示密钥
|
||||
将明文传输;HTTPS 反代未配置 `QA_AI_TRUST_TLS_PROXY` 时改为提示该配置,不再笼统要求 HTTPS。
|
||||
- **`Host: [::1]`(无端口)被误判为非回环**:地址规范化统一去掉 IPv6 方括号与可选端口,
|
||||
回环写入不再被拒;受信反代能力位对 GET 只依赖 `X-Forwarded-Proto`(浏览器无法伪造该头)。
|
||||
|
||||
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -70,6 +70,14 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
|
||||
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
|
||||
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
|
||||
|
||||
**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET
|
||||
`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
|
||||
`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以
|
||||
录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台
|
||||
自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传
|
||||
`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。
|
||||
先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
|
||||
|
||||
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
|
||||
@@ -176,7 +184,7 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
|
||||
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
|
||||
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
|
||||
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
|
||||
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
|
||||
| 参数设置 | 文档工程师 | 「来源与目录」文档/资源刷新间隔;「解析监控」停滞阈值、入库并发上限(1..16,版本化 + 原子切换);finalizing 设置仅在 API/DB 保留,页面不展示 |
|
||||
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
|
||||
|
||||
## 9. 备份与恢复运维 **【新】**
|
||||
|
||||
@@ -284,10 +284,14 @@
|
||||
- 立即备份:按钮变"备份进行中…"→ 约 50 秒后自动刷出新结果(异步 202 + 在途单飞,重复点击不会跑两次)
|
||||
- 状态:✅ 2026-10-09 面板实测(写操作仅管理员:`PUT/POST /api/v1/backup-schedule*`)
|
||||
|
||||
### D5 刷新策略
|
||||
- 入口:**系统设置 → 刷新策略**(文档工程师可改)
|
||||
- 期望:文档/资源刷新间隔、停滞判定、finalizing 时长;保存先验证再原子启用、旧版本留审计
|
||||
- 状态:✅(`ui_settings` 版本化激活测试)
|
||||
### D5 参数设置
|
||||
- 入口:**系统设置 → 参数设置**(文档工程师可改)
|
||||
- 期望:按「来源与目录」「解析监控」两组呈现。来源与目录:文档状态刷新间隔(15/30/60 秒)、
|
||||
资源刷新间隔(30/60 秒);解析监控:解析停滞阈值(30/60 分钟)、入库并发上限(1..16)。
|
||||
四项以数值输入呈现,单位与调大/调小后果常驻,越界就地提示并禁用保存;保存先验证再原子
|
||||
启用、旧版本留审计。收尾超时告警不再在页面任何位置出现;API/DB 的
|
||||
`finalizing_after_seconds` 与 `finalizing` 处理状态不变。
|
||||
- 状态:✅(`ui_settings` 版本化激活测试;本任务补数值校验与浏览器实测)
|
||||
|
||||
### D6 成员与角色
|
||||
- 入口:**系统设置 → 成员与角色**(管理员)
|
||||
|
||||
@@ -34,7 +34,13 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
for _, view := range views {
|
||||
storageReady = storageReady || view.StorageReady
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"environments": views,
|
||||
"storage_ready": storageReady,
|
||||
// The page cannot test the server's transport rule from the browser URL
|
||||
// alone (a TLS proxy and an untrusted proxy look identical there).
|
||||
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
|
||||
}})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -128,3 +128,96 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
host string
|
||||
allow bool
|
||||
want bool
|
||||
}{
|
||||
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true},
|
||||
{name: "private console without toggle", host: "172.29.151.11:28188", want: false},
|
||||
{name: "loopback console", host: "127.0.0.1:8080", want: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
config := kbBindingHandler(t, store)
|
||||
config.WeKnoraAllowPrivateHTTP = tc.allow
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
|
||||
request.Host = tc.host
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Data struct {
|
||||
SecretEntryAllowed bool `json:"secret_entry_allowed"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Data.SecretEntryAllowed != tc.want {
|
||||
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
|
||||
const (
|
||||
privateHost = "172.29.151.11:28188"
|
||||
origin = "http://172.29.151.11:28188"
|
||||
)
|
||||
store := &fakeKBBindings{
|
||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
|
||||
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
|
||||
}
|
||||
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
||||
|
||||
save := func(config *Config) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
|
||||
request.Host = privateHost
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
request.Header.Set("Origin", origin)
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
return response
|
||||
}
|
||||
catalog := func(config *Config) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog",
|
||||
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`))
|
||||
request.Host = privateHost
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
request.Header.Set("Origin", origin)
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
return response
|
||||
}
|
||||
|
||||
enabled := kbBindingHandler(t, store)
|
||||
enabled.WeKnoraAllowPrivateHTTP = true
|
||||
if response := save(enabled); response.Code != http.StatusOK {
|
||||
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if store.lastSave.APIKey != "typed-key" {
|
||||
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
|
||||
}
|
||||
if response := catalog(enabled); response.Code != http.StatusOK {
|
||||
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
disabled := kbBindingHandler(t, store)
|
||||
if response := save(disabled); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if response := catalog(disabled); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,7 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = parsedHost
|
||||
}
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
if loopbackHost(r.Host) {
|
||||
return true
|
||||
}
|
||||
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
@@ -36,12 +29,14 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
|
||||
// fetch from the operator console itself when it is served over plain http on a
|
||||
// private address. That is the only non-TLS shape this deployment needs, and it
|
||||
// still requires an exact Origin/Host match.
|
||||
// still requires an exact Origin/Host match. It deliberately does not require
|
||||
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
|
||||
// http console on a private address never carries that header.
|
||||
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
|
||||
if secretTransportAllowed(r, trustTLSProxy) {
|
||||
return true
|
||||
}
|
||||
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
if !allowPrivateHTTP {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
@@ -53,8 +48,70 @@ func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, all
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
return strings.EqualFold(host, "localhost")
|
||||
return privateAddressHost(host)
|
||||
}
|
||||
|
||||
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
|
||||
// it cannot simply call secretTransportAllowed: that gate guards a write and
|
||||
// therefore insists on a same-origin Origin header, which a GET navigation
|
||||
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
|
||||
// browsers cannot set it and the deployment already declares the proxy
|
||||
// trusted; a forged header still cannot make the write gate accept anything.
|
||||
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
|
||||
if r.TLS != nil || loopbackHost(r.Host) {
|
||||
return true
|
||||
}
|
||||
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
|
||||
return true
|
||||
}
|
||||
return allowPrivateHTTP && privateAddressHost(r.Host)
|
||||
}
|
||||
|
||||
// requestHostname strips the optional port and IPv6 brackets. Brackets come
|
||||
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
|
||||
// ported forms are not address spellings the server or a browser ever emits,
|
||||
// so they stay untouched and keep failing the address checks.
|
||||
func requestHostname(host string) string {
|
||||
host = strings.TrimSpace(host)
|
||||
if strings.HasPrefix(host, "[") {
|
||||
end := strings.Index(host, "]")
|
||||
if end <= 0 {
|
||||
return host
|
||||
}
|
||||
ip := net.ParseIP(host[1:end])
|
||||
if ip == nil || ip.To4() != nil {
|
||||
return host
|
||||
}
|
||||
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
|
||||
return host
|
||||
}
|
||||
return ip.String()
|
||||
}
|
||||
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
|
||||
return parsedHost
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// loopbackHost is the address-only part of the secret transport rule: a
|
||||
// request from this machine never crosses a network.
|
||||
func loopbackHost(host string) bool {
|
||||
host = requestHostname(host)
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
// privateAddressHost accepts loopback and private addresses. Names other than
|
||||
// localhost are rejected because the deployment toggle is about addresses,
|
||||
// not about trusting whatever DNS resolves to.
|
||||
func privateAddressHost(host string) bool {
|
||||
host = requestHostname(host)
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
host string
|
||||
tls bool
|
||||
xfp string
|
||||
trust bool
|
||||
allow bool
|
||||
want bool
|
||||
}{
|
||||
{name: "direct TLS", host: "console.example", tls: true, want: true},
|
||||
{name: "loopback name", host: "localhost:8080", want: true},
|
||||
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
|
||||
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
|
||||
{name: "loopback v6 without port", host: "[::1]", want: true},
|
||||
// Bracketed non-IPv6 hosts are not address spellings; they must not
|
||||
// borrow loopback trust from the bracket stripper.
|
||||
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
|
||||
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
|
||||
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
|
||||
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
|
||||
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
|
||||
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
|
||||
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
|
||||
{name: "public name with toggle", host: "console.example", allow: true, want: false},
|
||||
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
|
||||
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
|
||||
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
|
||||
// A forged header must not beat the address rule when the proxy is not trusted.
|
||||
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
|
||||
request.Host = tc.host
|
||||
if tc.tls {
|
||||
request.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if tc.xfp != "" {
|
||||
request.Header.Set("X-Forwarded-Proto", tc.xfp)
|
||||
}
|
||||
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
|
||||
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||
request.Host = "[::1]"
|
||||
if !secretTransportAllowed(request, false) {
|
||||
t.Fatal("bare [::1] Host was rejected as a loopback transport")
|
||||
}
|
||||
request.Host = "console.example"
|
||||
if secretTransportAllowed(request, false) {
|
||||
t.Fatal("public name without TLS was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// Plain-http consoles are not secure contexts, so Chrome never sends
|
||||
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
|
||||
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
|
||||
request.Host = "192.168.50.134:18093"
|
||||
request.Header.Set("Origin", "http://192.168.50.134:18093")
|
||||
if !secretTransportAllowedForPrivateConsole(request, false, true) {
|
||||
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
|
||||
}
|
||||
request.Header.Set("Origin", "http://evil.example")
|
||||
if secretTransportAllowedForPrivateConsole(request, false, true) {
|
||||
t.Fatal("cross-origin request was accepted as a private console")
|
||||
}
|
||||
request.Header.Set("Origin", "http://192.168.50.134:18093")
|
||||
if secretTransportAllowedForPrivateConsole(request, false, false) {
|
||||
t.Fatal("private console was accepted with the deployment toggle off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
|
||||
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||
request.Host = host
|
||||
if secretTransportAllowed(request, false) {
|
||||
t.Fatalf("Host %q was accepted as a loopback transport", host)
|
||||
}
|
||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
request.Header.Set("Origin", "http://"+host)
|
||||
if secretTransportAllowedForPrivateConsole(request, false, true) {
|
||||
t.Fatalf("Host %q was accepted as a private console", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
|
||||
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||
request.Host = host
|
||||
if secretTransportAllowed(request, false) {
|
||||
t.Fatalf("Host %q was accepted as a loopback transport", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,12 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
|
||||
})
|
||||
|
||||
const snapshot = {
|
||||
data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true },
|
||||
}
|
||||
const snapshotWith = (secretEntryAllowed: boolean) => ({
|
||||
data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed },
|
||||
})
|
||||
const snapshotWithoutCapability = {
|
||||
data: { environments: [binding('test'), binding('production')], storage_ready: true },
|
||||
}
|
||||
const catalog = {
|
||||
@@ -110,11 +116,11 @@ afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const render = async (role: 'admin' | 'viewer' = 'admin') => {
|
||||
const render = async (role: 'admin' | 'viewer' = 'admin', consoleLocation?: { protocol: string; hostname: string }) => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<AuthContext.Provider value={auth(role)}>
|
||||
<KnowledgeBaseBinding />
|
||||
<KnowledgeBaseBinding consoleLocation={consoleLocation} />
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
})
|
||||
@@ -272,4 +278,66 @@ describe('KnowledgeBaseBinding', () => {
|
||||
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
|
||||
expect(save?.hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('disables key entry when the server reports no accepted transport', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
|
||||
await render()
|
||||
await click('更换密钥')
|
||||
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
|
||||
expect(input?.disabled).toBe(true)
|
||||
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
|
||||
})
|
||||
|
||||
it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
|
||||
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
||||
expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true')
|
||||
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
|
||||
})
|
||||
|
||||
it('does not blame a proxy when an older API omits the capability', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability)))
|
||||
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
||||
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
|
||||
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
|
||||
})
|
||||
|
||||
it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
|
||||
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
|
||||
await click('更换密钥')
|
||||
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
|
||||
expect(input?.disabled).toBe(false)
|
||||
expect(host.textContent).toContain('密钥会以明文经过这段内网')
|
||||
expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true')
|
||||
})
|
||||
|
||||
it('does not warn on an HTTPS console the server already trusts', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
|
||||
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
||||
expect(host.textContent).not.toContain('密钥会以明文经过这段内网')
|
||||
})
|
||||
|
||||
it('keeps existing-key operations available while key entry is closed', async () => {
|
||||
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
|
||||
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false)))
|
||||
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
|
||||
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
|
||||
return Promise.resolve(json({ data: binding('test') }))
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await render()
|
||||
await click('验证并读取知识库')
|
||||
await choose('对内知识库', 'kb-new-in-0001')
|
||||
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
|
||||
// 没有新密钥也能改选库:keep 不经过密钥传输闸门。
|
||||
expect(save?.hasAttribute('disabled')).toBe(false)
|
||||
await click('保存测试绑定')
|
||||
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
|
||||
expect(put).toBeTruthy()
|
||||
const body = JSON.parse(String(put![1]?.body))
|
||||
expect(body.key_action).toBe('keep')
|
||||
expect(body.api_key).toBeUndefined()
|
||||
expect(host.textContent).toContain('已保存测试绑定')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { secretEntryAllowed } from './secureEntry'
|
||||
import { plaintextRemoteConsole } from './secureEntry'
|
||||
import {
|
||||
KBBindingError,
|
||||
duplicateSelection,
|
||||
@@ -82,7 +82,18 @@ const fallbackLabel = (fallback: string): string =>
|
||||
const statusTone = (status: KBCatalog['status']): string =>
|
||||
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
|
||||
|
||||
export function KnowledgeBaseBinding() {
|
||||
interface ConsoleLocation {
|
||||
protocol: string
|
||||
hostname: string
|
||||
}
|
||||
|
||||
// consoleLocation is injected by tests that need both console shapes; the app
|
||||
// always uses the real window.
|
||||
export function KnowledgeBaseBinding({
|
||||
consoleLocation,
|
||||
}: {
|
||||
consoleLocation?: ConsoleLocation
|
||||
} = {}) {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null)
|
||||
@@ -135,7 +146,13 @@ export function KnowledgeBaseBinding() {
|
||||
const busyNow = busy[env]
|
||||
const notice = notices[env]
|
||||
|
||||
const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location)
|
||||
const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
|
||||
// The server decides whether it will accept a key on this connection; the
|
||||
// browser URL cannot tell a trusted TLS proxy from an untrusted one.
|
||||
const secretEntryAllowed = snapshot?.secret_entry_allowed
|
||||
const secure = secretEntryAllowed === true
|
||||
const plaintext = secure && plaintextRemoteConsole(console)
|
||||
const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:'
|
||||
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() !== ''
|
||||
@@ -518,9 +535,20 @@ export function KnowledgeBaseBinding() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!secure ? (
|
||||
{untrustedProxy ? (
|
||||
<p className="settings-warn">
|
||||
服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递
|
||||
X-Forwarded-Proto。
|
||||
</p>
|
||||
) : !secure ? (
|
||||
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
|
||||
) : null}
|
||||
{plaintext ? (
|
||||
<p className="settings-warn">
|
||||
当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网
|
||||
HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。
|
||||
</p>
|
||||
) : null}
|
||||
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
|
||||
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// @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 { SystemSettingsView } from './SystemSettings'
|
||||
import type { UISettings } from './uiSettings'
|
||||
|
||||
let root: Root, host: HTMLDivElement
|
||||
|
||||
const settings: UISettings = {
|
||||
id: 'uis-active',
|
||||
state: 'active',
|
||||
document_refresh_seconds: 30,
|
||||
resource_refresh_seconds: 30,
|
||||
stalled_after_seconds: 1800,
|
||||
finalizing_after_seconds: 7200,
|
||||
ingestion_concurrency: 8,
|
||||
test_weknora_base_url: '',
|
||||
production_weknora_base_url: '',
|
||||
production_tenant_id: '',
|
||||
production_knowledge_base_id: '',
|
||||
updated_by: 'admin',
|
||||
created_at: '2026-11-24T04:15:00Z',
|
||||
activated_at: '2026-11-24T04:15:00Z',
|
||||
retired_at: null,
|
||||
error_code: '',
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
const renderView = async (onSave: (input: unknown) => void) => {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<SystemSettingsView
|
||||
sources={[]}
|
||||
connections={[]}
|
||||
monitor={null}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={onSave}
|
||||
onSourcesChanged={() => {}}
|
||||
onRefresh={() => {}}
|
||||
initialSection="refresh"
|
||||
/>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const input = (label: string) => {
|
||||
const found = [...host.querySelectorAll('label')]
|
||||
.find((item) => item.textContent?.startsWith(label))
|
||||
?.querySelector('input')
|
||||
expect(found, label).toBeTruthy()
|
||||
return found!
|
||||
}
|
||||
|
||||
const type = async (label: string, value: string) => {
|
||||
const target = input(label)
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(target, value)
|
||||
target.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
|
||||
const saveButton = () =>
|
||||
[...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === '保存参数设置')!
|
||||
|
||||
describe('参数设置保存边界', () => {
|
||||
it('keeps other inputs, blocks invalid saves and sends the hidden contract fields unchanged', async () => {
|
||||
const onSave = vi.fn()
|
||||
await renderView(onSave)
|
||||
expect(saveButton().disabled).toBe(true)
|
||||
|
||||
await type('解析停滞阈值', '45')
|
||||
expect(host.textContent).toContain('解析停滞阈值只能是 30/60 分钟;当前 45')
|
||||
expect(input('解析停滞阈值').getAttribute('aria-invalid')).toBe('true')
|
||||
expect(saveButton().disabled).toBe(true)
|
||||
// 直接点击禁用按钮也不能绕过校验触发保存。
|
||||
await act(async () => saveButton().click())
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
|
||||
// 同组和另一组的已填值都不因单个字段非法被清空。
|
||||
expect(input('文档状态刷新间隔').value).toBe('30')
|
||||
expect(input('资源刷新间隔').value).toBe('30')
|
||||
expect(input('入库并发上限').value).toBe('8')
|
||||
|
||||
await type('解析停滞阈值', '60')
|
||||
expect(input('解析停滞阈值').getAttribute('aria-invalid')).toBe('false')
|
||||
expect(saveButton().disabled).toBe(false)
|
||||
await act(async () => saveButton().click())
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
document_refresh_seconds: 30,
|
||||
resource_refresh_seconds: 30,
|
||||
stalled_after_seconds: 3600,
|
||||
finalizing_after_seconds: 7200,
|
||||
ingestion_concurrency: 8,
|
||||
test_weknora_base_url: '',
|
||||
production_weknora_base_url: '',
|
||||
production_tenant_id: '',
|
||||
production_knowledge_base_id: '',
|
||||
})
|
||||
})
|
||||
})
|
||||
+125
-13
@@ -3,7 +3,10 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
SystemSettingsView,
|
||||
ppSourceConnections,
|
||||
refreshDraftText,
|
||||
refreshSettingsDirty,
|
||||
refreshSettingsInput,
|
||||
parseRefreshDrafts,
|
||||
serviceSettingsInput,
|
||||
visibleSaveMessage,
|
||||
} from './SystemSettings'
|
||||
@@ -173,13 +176,13 @@ describe('SystemSettingsView', () => {
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
|
||||
saveMessage="设置已验证并启用:文档15秒、资源30秒、停滞30分钟、入库并发 2"
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
)
|
||||
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '刷新策略'])
|
||||
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '参数设置'])
|
||||
expect(html).toContain(text)
|
||||
// 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。
|
||||
for (const removed of [
|
||||
@@ -271,7 +274,7 @@ describe('SystemSettingsView', () => {
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
|
||||
saveMessage="设置已验证并启用:文档15秒、资源30秒、停滞30分钟、入库并发 2"
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
@@ -279,16 +282,38 @@ describe('SystemSettingsView', () => {
|
||||
/>
|
||||
)
|
||||
for (const text of [
|
||||
'刷新与告警参数已验证并启用',
|
||||
'停滞30分钟',
|
||||
'finalizing 2小时',
|
||||
'参数设置',
|
||||
'来源与目录',
|
||||
'解析监控',
|
||||
'文档状态刷新间隔',
|
||||
'15秒',
|
||||
'解析监控按此周期刷新文档状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
'资源刷新间隔',
|
||||
'解析监控按此周期刷新资源与服务状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
'解析停滞阈值',
|
||||
'30分钟',
|
||||
'保存刷新与告警参数',
|
||||
'超过此时长没有进展就标记停滞;调大更容忍长解析,调小更快标记停滞',
|
||||
'入库并发上限',
|
||||
'调大入库更快、写入压力更高;调小更稳,排队更久',
|
||||
'保存参数设置',
|
||||
'当前:文档 15 秒、资源 30 秒、停滞 30 分钟、入库并发 2。',
|
||||
])
|
||||
expect(refreshHtml).toContain(text)
|
||||
for (const removed of ['收尾超时告警', 'finalizing', '刷新与入库', '保存刷新与告警参数'])
|
||||
expect(refreshHtml).not.toContain(removed)
|
||||
const sourcesGroup = refreshHtml.slice(
|
||||
refreshHtml.indexOf('data-refresh-group="sources"'),
|
||||
refreshHtml.indexOf('data-refresh-group="parsing"')
|
||||
)
|
||||
const parsingGroup = refreshHtml.slice(refreshHtml.indexOf('data-refresh-group="parsing"'))
|
||||
expect(sourcesGroup).toContain('文档状态刷新间隔')
|
||||
expect(sourcesGroup).toContain('资源刷新间隔')
|
||||
expect(sourcesGroup).not.toContain('解析停滞阈值')
|
||||
expect(sourcesGroup).not.toContain('入库并发上限')
|
||||
expect(parsingGroup).toContain('解析停滞阈值')
|
||||
expect(parsingGroup).toContain('入库并发上限')
|
||||
expect(parsingGroup).not.toContain('文档状态刷新间隔')
|
||||
expect(parsingGroup).not.toContain('资源刷新间隔')
|
||||
expect(refreshHtml).toContain('aria-invalid="false"')
|
||||
expect(refreshHtml).toContain('inputMode="numeric"')
|
||||
expect(visibleSaveMessage('已保存', true)).toBeNull()
|
||||
expect(visibleSaveMessage('已保存', false)).toBe('已保存')
|
||||
expect(html).not.toContain('本地模拟')
|
||||
@@ -671,20 +696,24 @@ describe('保存边界(F03)', () => {
|
||||
production_knowledge_base_id: 'kb-server',
|
||||
} as unknown as UISettings
|
||||
|
||||
it('保存刷新策略时忽略服务分区里未保存的地址', () => {
|
||||
it('保存参数设置时忽略服务分区里未保存的地址,并原样回传 finalizing', () => {
|
||||
const input = refreshSettingsInput(server, {
|
||||
documentRefresh: 60,
|
||||
resourceRefresh: 60,
|
||||
stalled: 3600,
|
||||
finalizing: 14400,
|
||||
concurrency: 4,
|
||||
concurrency: 7,
|
||||
})
|
||||
expect(input.test_weknora_base_url).toBe('https://server.test')
|
||||
expect(input.production_weknora_base_url).toBe('https://server.prod')
|
||||
expect(input.production_tenant_id).toBe('10000')
|
||||
expect(input.production_knowledge_base_id).toBe('kb-server')
|
||||
expect(input.finalizing_after_seconds).toBe(server.finalizing_after_seconds)
|
||||
expect(input.document_refresh_seconds).toBe(60)
|
||||
expect(input.stalled_after_seconds).toBe(3600)
|
||||
expect(input.ingestion_concurrency).toBe(7)
|
||||
})
|
||||
|
||||
it('保存服务配置时忽略刷新分区里未保存的参数', () => {
|
||||
it('保存服务配置时忽略参数分区里未保存的参数', () => {
|
||||
const input = serviceSettingsInput(server, {
|
||||
testEndpoint: 'https://draft.test',
|
||||
endpoint: 'https://draft.prod',
|
||||
@@ -696,3 +725,86 @@ describe('保存边界(F03)', () => {
|
||||
expect(input.test_weknora_base_url).toBe('https://draft.test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('参数设置的文本草稿解析', () => {
|
||||
const drafts = (patch: Record<string, string> = {}) => ({ ...refreshDraftText(settings), ...patch })
|
||||
|
||||
it('把活动设置转成带单位的草稿(停滞用分钟)', () => {
|
||||
expect(refreshDraftText(settings)).toEqual({
|
||||
documentRefresh: '15',
|
||||
resourceRefresh: '30',
|
||||
stalled: '30',
|
||||
concurrency: '2',
|
||||
})
|
||||
})
|
||||
|
||||
it('接受白名单与 1..16 的整数,停滞分钟换算成秒', () => {
|
||||
const parsed = parseRefreshDrafts({
|
||||
documentRefresh: '60',
|
||||
resourceRefresh: '60',
|
||||
stalled: '60',
|
||||
concurrency: '16',
|
||||
})
|
||||
expect(parsed.errors).toEqual({
|
||||
documentRefresh: null,
|
||||
resourceRefresh: null,
|
||||
stalled: null,
|
||||
concurrency: null,
|
||||
})
|
||||
expect(parsed.values).toEqual({
|
||||
documentRefresh: 60,
|
||||
resourceRefresh: 60,
|
||||
stalled: 3600,
|
||||
concurrency: 16,
|
||||
})
|
||||
})
|
||||
|
||||
it('接受并发 5/7/9(后端范围 1..16,而不是旧下拉六档)', () => {
|
||||
for (const value of ['5', '7', '9']) {
|
||||
expect(parseRefreshDrafts(drafts({ concurrency: value })).values?.concurrency).toBe(Number(value))
|
||||
}
|
||||
})
|
||||
|
||||
it('拒绝空值、非整数、越界与全角数字,并给出字段级提示', () => {
|
||||
const cases: [Record<string, string>, string, string][] = [
|
||||
[{ documentRefresh: '' }, 'documentRefresh', '不能为空'],
|
||||
[{ documentRefresh: '1' }, 'documentRefresh', '15/30/60'],
|
||||
[{ documentRefresh: '2.5' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '+15' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '1e1' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '15' }, 'documentRefresh', '必须是整数'],
|
||||
[{ documentRefresh: '15abc' }, 'documentRefresh', '必须是整数'],
|
||||
[{ resourceRefresh: '15' }, 'resourceRefresh', '30/60'],
|
||||
[{ stalled: '45' }, 'stalled', '30/60'],
|
||||
[{ stalled: '0.5' }, 'stalled', '必须是整数'],
|
||||
[{ concurrency: '0' }, 'concurrency', '1~16'],
|
||||
[{ concurrency: '99' }, 'concurrency', '1~16'],
|
||||
[{ concurrency: '2.5' }, 'concurrency', '必须是整数'],
|
||||
]
|
||||
for (const [patch, field, message] of cases) {
|
||||
const parsed = parseRefreshDrafts(drafts(patch))
|
||||
expect(parsed.values, `${field} ${patch[field]}`).toBeNull()
|
||||
expect(parsed.errors[field as keyof typeof parsed.errors]).toContain(message)
|
||||
}
|
||||
})
|
||||
|
||||
it('错误文案使用完整字段名', () => {
|
||||
expect(parseRefreshDrafts(drafts({ documentRefresh: '1' })).errors.documentRefresh).toContain(
|
||||
'文档状态刷新间隔只能是 15/30/60 秒'
|
||||
)
|
||||
expect(parseRefreshDrafts(drafts({ stalled: '45' })).errors.stalled).toContain('解析停滞阈值只能是 30/60 分钟')
|
||||
})
|
||||
|
||||
it('任一字段非法时整体 values 为 null,避免夹带默认值保存', () => {
|
||||
const parsed = parseRefreshDrafts(drafts({ concurrency: '99' }))
|
||||
expect(parsed.values).toBeNull()
|
||||
expect(parsed.errors.documentRefresh).toBeNull()
|
||||
})
|
||||
|
||||
it('脏值按解析后的数值比较:015 等价 15,改值或非法值才变脏', () => {
|
||||
expect(refreshSettingsDirty(drafts(), settings)).toBe(false)
|
||||
expect(refreshSettingsDirty(drafts({ documentRefresh: '015' }), settings)).toBe(false)
|
||||
expect(refreshSettingsDirty(drafts({ concurrency: '7' }), settings)).toBe(true)
|
||||
expect(refreshSettingsDirty(drafts({ documentRefresh: '1' }), settings)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
+95
-120
@@ -22,13 +22,26 @@ import { archiveSourceConnection, fetchSourceConnectionList } from './sourceConn
|
||||
import type { SourceConnectionListItem } from './sourceConnections'
|
||||
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings'
|
||||
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
|
||||
import { refreshSettingsInput } from './settingsInputs'
|
||||
import {
|
||||
parseRefreshDrafts,
|
||||
REFRESH_FIELD_META,
|
||||
refreshDraftText,
|
||||
refreshSettingsDirty,
|
||||
refreshSettingsInput,
|
||||
} from './settingsInputs'
|
||||
import type { RefreshDrafts, RefreshField } from './settingsInputs'
|
||||
import './systemSettings.css'
|
||||
|
||||
// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出,
|
||||
// 连接配置已从「服务配置」迁到「知识库绑定」。这些纯函数仍从本模块导出,
|
||||
// 既有调用与回归测试的导入路径不变。
|
||||
export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs'
|
||||
export type { RefreshDrafts, ServiceDrafts } from './settingsInputs'
|
||||
export {
|
||||
parseRefreshDrafts,
|
||||
refreshDraftText,
|
||||
refreshSettingsDirty,
|
||||
refreshSettingsInput,
|
||||
serviceSettingsInput,
|
||||
} from './settingsInputs'
|
||||
export type { RefreshDrafts, RefreshValues, ServiceDrafts } from './settingsInputs'
|
||||
|
||||
interface Props {
|
||||
sources: CatalogSource[]
|
||||
@@ -57,10 +70,23 @@ const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
|
||||
{ key: 'services', label: 'AI 模型连接' },
|
||||
{ key: 'knowledge-bindings', label: '知识库绑定' },
|
||||
{ key: 'storage', label: '存储与备份' },
|
||||
{ key: 'refresh', label: '刷新策略' },
|
||||
{ key: 'refresh', label: '参数设置' },
|
||||
{ key: 'members', label: '成员与角色', adminOnly: true },
|
||||
] as { key: SectionKey; label: string; adminOnly?: boolean }[]
|
||||
|
||||
const refreshHints: Record<RefreshField, string> = {
|
||||
documentRefresh: '解析监控按此周期刷新文档状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
resourceRefresh: '解析监控按此周期刷新资源与服务状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
|
||||
stalled: '超过此时长没有进展就标记停滞;调大更容忍长解析,调小更快标记停滞',
|
||||
concurrency: '调大入库更快、写入压力更高;调小更稳,排队更久',
|
||||
}
|
||||
|
||||
// 产品定义的分组与归属,顺序即页面呈现顺序。
|
||||
const refreshGroups: { key: string; title: string; fields: RefreshField[] }[] = [
|
||||
{ key: 'sources', title: '来源与目录', fields: ['documentRefresh', 'resourceRefresh'] },
|
||||
{ key: 'parsing', title: '解析监控', fields: ['stalled', 'concurrency'] },
|
||||
]
|
||||
|
||||
const sourceTypeLabels: Record<string, string> = {
|
||||
dingtalk: '钉钉知识库',
|
||||
pp: 'PP 资料下载中心',
|
||||
@@ -103,41 +129,30 @@ export function SystemSettingsView({
|
||||
? 'knowledge-bindings'
|
||||
: (initialSection as SectionKey)
|
||||
)
|
||||
const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15)
|
||||
const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30)
|
||||
const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800)
|
||||
const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200)
|
||||
const [concurrency, setConcurrency] = useState<number>(settings?.ingestion_concurrency ?? 2)
|
||||
const [dirty, setDirty] = useState(false)
|
||||
// 输入框用文本草稿而不是 number:浏览器会吞掉 1e1/+15,无法展示「非法」提示。
|
||||
const [refreshDrafts, setRefreshDrafts] = useState<RefreshDrafts>(() =>
|
||||
settings
|
||||
? refreshDraftText(settings)
|
||||
: { documentRefresh: '15', resourceRefresh: '30', stalled: '30', concurrency: '2' }
|
||||
)
|
||||
|
||||
// 统一入口后,清单里列全部来源(钉钉知识库 / 钉盘 / PP),不再只显示 PP。
|
||||
const listedConnections = connections
|
||||
|
||||
useEffect(() => {
|
||||
if (!settings) return
|
||||
setDocumentRefresh(settings.document_refresh_seconds)
|
||||
setResourceRefresh(settings.resource_refresh_seconds)
|
||||
setStalled(settings.stalled_after_seconds)
|
||||
setFinalizing(settings.finalizing_after_seconds)
|
||||
setConcurrency(settings.ingestion_concurrency)
|
||||
setDirty(false)
|
||||
setRefreshDrafts(refreshDraftText(settings))
|
||||
}, [settings])
|
||||
|
||||
const canSave = Boolean(settings && !saving)
|
||||
const parsedRefresh = parseRefreshDrafts(refreshDrafts)
|
||||
const refreshDirty = settings ? refreshSettingsDirty(refreshDrafts, settings) : false
|
||||
const canSave = Boolean(settings && !saving && parsedRefresh.values)
|
||||
const isAdmin = identity?.role === 'admin'
|
||||
const refreshSettingsDirty = Boolean(
|
||||
settings &&
|
||||
(documentRefresh !== settings.document_refresh_seconds ||
|
||||
resourceRefresh !== settings.resource_refresh_seconds ||
|
||||
stalled !== settings.stalled_after_seconds ||
|
||||
finalizing !== settings.finalizing_after_seconds ||
|
||||
concurrency !== settings.ingestion_concurrency)
|
||||
)
|
||||
// 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
|
||||
// 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。
|
||||
// 保存边界:参数分区只带参数草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
|
||||
// 互不夹带(未保存的地址不会因为保存参数设置被写进去)。
|
||||
const refreshInput = (): UISettingsCandidateInput =>
|
||||
settings
|
||||
? refreshSettingsInput(settings, { documentRefresh, resourceRefresh, stalled, finalizing, concurrency })
|
||||
settings && parsedRefresh.values
|
||||
? refreshSettingsInput(settings, parsedRefresh.values)
|
||||
: ({} as UISettingsCandidateInput)
|
||||
return (
|
||||
<main className="page-shell system-settings">
|
||||
@@ -247,105 +262,65 @@ export function SystemSettingsView({
|
||||
<section className="settings-panel wide" id="settings-refresh">
|
||||
<div className="settings-section-heading">
|
||||
<div>
|
||||
<h2>刷新策略</h2>
|
||||
<p>保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
|
||||
<h2>参数设置</h2>
|
||||
</div>
|
||||
<span className="safe-badge">当前活动版本</span>
|
||||
</div>
|
||||
<div className="safe-setting-grid">
|
||||
<label>
|
||||
文档状态刷新间隔
|
||||
<select
|
||||
value={documentRefresh}
|
||||
onChange={(event) => {
|
||||
setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={15}>15秒</option>
|
||||
<option value={30}>30秒</option>
|
||||
<option value={60}>1分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
资源刷新间隔
|
||||
<select
|
||||
value={resourceRefresh}
|
||||
onChange={(event) => {
|
||||
setResourceRefresh(Number(event.target.value) as 30 | 60)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={30}>30秒</option>
|
||||
<option value={60}>1分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
解析停滞阈值
|
||||
<select
|
||||
value={stalled}
|
||||
onChange={(event) => {
|
||||
setStalled(Number(event.target.value) as 1800 | 3600)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={1800}>30分钟</option>
|
||||
<option value={3600}>1小时</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
收尾超时告警
|
||||
<select
|
||||
value={finalizing}
|
||||
onChange={(event) => {
|
||||
setFinalizing(Number(event.target.value) as 7200 | 14400)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={7200}>2小时</option>
|
||||
<option value={14400}>4小时</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
入库并发上限
|
||||
<select
|
||||
value={concurrency}
|
||||
onChange={(event) => {
|
||||
setConcurrency(Number(event.target.value))
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={1}>1(谨慎,MinerU 并发 1)</option>
|
||||
<option value={2}>2</option>
|
||||
<option value={3}>3</option>
|
||||
<option value={4}>4</option>
|
||||
<option value={6}>6</option>
|
||||
<option value={8}>8</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="settings-param-groups">
|
||||
{refreshGroups.map((group) => (
|
||||
<section className="settings-param-group" key={group.key} data-refresh-group={group.key}>
|
||||
<h3>{group.title}</h3>
|
||||
<div className="safe-setting-grid">
|
||||
{group.fields.map((key) => {
|
||||
const meta = REFRESH_FIELD_META[key]
|
||||
const hint = refreshHints[key]
|
||||
const error = parsedRefresh.errors[key]
|
||||
const hintID = `refresh-${key}-hint`
|
||||
const errorID = `refresh-${key}-error`
|
||||
return (
|
||||
<label key={key}>
|
||||
{meta.label}
|
||||
<span className="settings-field-control">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
value={refreshDrafts[key]}
|
||||
aria-invalid={error ? 'true' : 'false'}
|
||||
aria-describedby={error ? `${hintID} ${errorID}` : hintID}
|
||||
onChange={(event) =>
|
||||
setRefreshDrafts((drafts) => ({ ...drafts, [key]: event.target.value }))
|
||||
}
|
||||
/>
|
||||
<span className="settings-field-unit">{meta.unit}</span>
|
||||
</span>
|
||||
<small className="settings-field-hint" id={hintID}>
|
||||
{hint}
|
||||
</small>
|
||||
{error ? (
|
||||
<span className="settings-field-error" id={errorID} role="alert">
|
||||
{error}
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setDirty(false)
|
||||
onSave(refreshInput())
|
||||
}}
|
||||
disabled={!canSave || !refreshSettingsDirty}
|
||||
>
|
||||
{saving ? '正在验证并应用…' : '保存刷新与告警参数'}
|
||||
<button onClick={() => onSave(refreshInput())} disabled={!canSave || !refreshDirty}>
|
||||
{saving ? '正在验证并应用…' : '保存参数设置'}
|
||||
</button>
|
||||
{visibleSaveMessage(saveMessage, dirty) ? (
|
||||
{visibleSaveMessage(saveMessage, refreshDirty) ? (
|
||||
<p className="success-message" role="status">
|
||||
{saveMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="settings-warn">
|
||||
解析停滞阈值保存后由 worker 在 1 分钟内生效;收尾超时告警目前只保存配置,判定尚未接入。
|
||||
</p>
|
||||
<p className="settings-warn">解析停滞阈值保存后由 worker 在 1 分钟内生效。</p>
|
||||
<p className="settings-hint">保存只改这组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
|
||||
<small>
|
||||
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
|
||||
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
|
||||
、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '}
|
||||
{settings.ingestion_concurrency}。
|
||||
{`当前:文档 ${settings.document_refresh_seconds} 秒、资源 ${settings.resource_refresh_seconds} 秒、停滞 ${settings.stalled_after_seconds / 60} 分钟、入库并发 ${settings.ingestion_concurrency}。`}
|
||||
</small>
|
||||
</section>
|
||||
) : null}
|
||||
@@ -429,7 +404,7 @@ export function SystemSettings() {
|
||||
// 探测失败不影响保存结果,页面保留上一次观测。
|
||||
}
|
||||
setSaveMessage(
|
||||
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
|
||||
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${active.stalled_after_seconds / 60}分钟、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
|
||||
)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '保存系统设置失败')
|
||||
|
||||
@@ -39,11 +39,13 @@ describe('knowledgeBaseBindings', () => {
|
||||
data: {
|
||||
environments: [binding('test'), binding('production')],
|
||||
storage_ready: true,
|
||||
secret_entry_allowed: true,
|
||||
},
|
||||
})
|
||||
expect(parsed.test.base_url).toBe('https://test.example')
|
||||
expect(parsed.production.internal_kb_name).toBe('内部资料')
|
||||
expect(parsed.storage_ready).toBe(true)
|
||||
expect(parsed.secret_entry_allowed).toBe(true)
|
||||
const asRecord = parsed.test as unknown as Record<string, unknown>
|
||||
expect(asRecord.api_key).toBeUndefined()
|
||||
expect(asRecord.key_ciphertext).toBeUndefined()
|
||||
@@ -53,6 +55,24 @@ describe('knowledgeBaseBindings', () => {
|
||||
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
|
||||
})
|
||||
|
||||
it('leaves the capability absent when an older API does not report it', () => {
|
||||
const parsed = parseKBBindingSnapshot({
|
||||
data: { environments: [binding('test'), binding('production')], storage_ready: true },
|
||||
})
|
||||
expect(parsed.secret_entry_allowed).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps an explicit refusal distinguishable from a missing field', () => {
|
||||
const parsed = parseKBBindingSnapshot({
|
||||
data: {
|
||||
environments: [binding('test'), binding('production')],
|
||||
storage_ready: true,
|
||||
secret_entry_allowed: false,
|
||||
},
|
||||
})
|
||||
expect(parsed.secret_entry_allowed).toBe(false)
|
||||
})
|
||||
|
||||
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…)')
|
||||
|
||||
@@ -34,6 +34,9 @@ export interface KBBindingSnapshot {
|
||||
test: KBEnvironmentBinding
|
||||
production: KBEnvironmentBinding
|
||||
storage_ready: boolean
|
||||
// Absent stays absent: an older API must not be reported as an untrusted
|
||||
// proxy, and it must still fail closed for key entry.
|
||||
secret_entry_allowed?: boolean
|
||||
}
|
||||
|
||||
export interface KBCatalogOption {
|
||||
@@ -130,7 +133,13 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
|
||||
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) }
|
||||
return {
|
||||
test,
|
||||
production,
|
||||
storage_ready: bool(value.data.storage_ready),
|
||||
secret_entry_allowed:
|
||||
typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { plaintextRemoteConsole, secretEntryAllowed } from './secureEntry'
|
||||
|
||||
describe('secureEntry', () => {
|
||||
it('accepts HTTPS and loopback whatever the deployment toggle says', () => {
|
||||
for (const location of [
|
||||
{ protocol: 'https:', hostname: 'kb.example' },
|
||||
{ protocol: 'http:', hostname: 'localhost' },
|
||||
{ protocol: 'http:', hostname: '127.0.0.1' },
|
||||
{ protocol: 'http:', hostname: '[::1]' },
|
||||
{ protocol: 'http:', hostname: '::1' },
|
||||
]) {
|
||||
expect(secretEntryAllowed(location), JSON.stringify(location)).toBe(true)
|
||||
expect(plaintextRemoteConsole(location)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('treats plain HTTP from any other host as a plaintext network path', () => {
|
||||
for (const hostname of ['172.29.151.11', '10.0.0.5', 'kb.internal.example', '203.0.113.10']) {
|
||||
const location = { protocol: 'http:', hostname }
|
||||
expect(secretEntryAllowed(location), hostname).toBe(false)
|
||||
expect(plaintextRemoteConsole(location), hostname).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -3,3 +3,10 @@
|
||||
export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
|
||||
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
|
||||
}
|
||||
|
||||
// True when a key typed here would cross a network in the clear, even though
|
||||
// the server presently allows it. Drives the warning only, never the gate:
|
||||
// the gate is the server-reported capability.
|
||||
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
|
||||
return !secretEntryAllowed(location)
|
||||
}
|
||||
|
||||
+89
-13
@@ -1,6 +1,6 @@
|
||||
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
|
||||
|
||||
// 保存边界是纯函数:连接分区只取连接草稿,刷新分区只取刷新草稿,
|
||||
// 保存边界是纯函数:连接分区只取连接草稿,参数分区只取参数草稿,
|
||||
// 另一侧一律用服务器当前值。组件与测试共用同一实现。
|
||||
export interface ServiceDrafts {
|
||||
testEndpoint: string
|
||||
@@ -8,13 +8,87 @@ export interface ServiceDrafts {
|
||||
productionTenantID: string
|
||||
productionKnowledgeBaseID: string
|
||||
}
|
||||
export interface RefreshDrafts {
|
||||
documentRefresh: 15 | 30 | 60
|
||||
resourceRefresh: 30 | 60
|
||||
stalled: 1800 | 3600
|
||||
finalizing: 7200 | 14400
|
||||
concurrency: number
|
||||
export type RefreshField = 'documentRefresh' | 'resourceRefresh' | 'stalled' | 'concurrency'
|
||||
export type RefreshDrafts = Record<RefreshField, string>
|
||||
export type RefreshValues = Record<RefreshField, number>
|
||||
export type RefreshParseResult = {
|
||||
values: RefreshValues | null
|
||||
errors: Record<RefreshField, string | null>
|
||||
}
|
||||
|
||||
export interface RefreshFieldMeta {
|
||||
label: string
|
||||
unit: string
|
||||
}
|
||||
|
||||
interface RefreshRule extends RefreshFieldMeta {
|
||||
allowed?: number[]
|
||||
min?: number
|
||||
max?: number
|
||||
// 草稿单位与存储单位不同:停滞输入分钟、接口收秒。
|
||||
toStored: (value: number) => number
|
||||
}
|
||||
|
||||
// 展示与错误文案共用同一份字段名/单位,避免两处各写一遍后漂移。
|
||||
export const REFRESH_FIELD_META: Record<RefreshField, RefreshFieldMeta> = {
|
||||
documentRefresh: { label: '文档状态刷新间隔', unit: '秒' },
|
||||
resourceRefresh: { label: '资源刷新间隔', unit: '秒' },
|
||||
stalled: { label: '解析停滞阈值', unit: '分钟' },
|
||||
concurrency: { label: '入库并发上限', unit: '个' },
|
||||
}
|
||||
|
||||
const REFRESH_RULES: Record<RefreshField, RefreshRule> = {
|
||||
documentRefresh: { ...REFRESH_FIELD_META.documentRefresh, allowed: [15, 30, 60], toStored: (value) => value },
|
||||
resourceRefresh: { ...REFRESH_FIELD_META.resourceRefresh, allowed: [30, 60], toStored: (value) => value },
|
||||
stalled: { ...REFRESH_FIELD_META.stalled, allowed: [30, 60], toStored: (value) => value * 60 },
|
||||
concurrency: { ...REFRESH_FIELD_META.concurrency, min: 1, max: 16, toStored: (value) => value },
|
||||
}
|
||||
|
||||
const parseField = (field: RefreshField, rawDraft: string): { value: number | null; error: string | null } => {
|
||||
const rule = REFRESH_RULES[field]
|
||||
const raw = rawDraft.trim()
|
||||
if (!raw) return { value: null, error: `${rule.label}不能为空` }
|
||||
// 不用 Number()/parseInt():空串、全角数字、"15abc" 都会被静默转成数字。
|
||||
if (!/^\d+$/.test(raw)) return { value: null, error: `${rule.label}必须是整数` }
|
||||
const value = Number(raw)
|
||||
if (rule.allowed) {
|
||||
if (!rule.allowed.includes(value))
|
||||
return { value: null, error: `${rule.label}只能是 ${rule.allowed.join('/')} ${rule.unit};当前 ${raw}` }
|
||||
} else if (rule.min !== undefined && rule.max !== undefined && (value < rule.min || value > rule.max)) {
|
||||
return { value: null, error: `${rule.label}只能是 ${rule.min}~${rule.max} 的整数;当前 ${raw}` }
|
||||
}
|
||||
return { value: rule.toStored(value), error: null }
|
||||
}
|
||||
|
||||
export const refreshDraftText = (settings: UISettings): RefreshDrafts => ({
|
||||
documentRefresh: String(settings.document_refresh_seconds),
|
||||
resourceRefresh: String(settings.resource_refresh_seconds),
|
||||
stalled: String(settings.stalled_after_seconds / 60),
|
||||
concurrency: String(settings.ingestion_concurrency),
|
||||
})
|
||||
|
||||
export const parseRefreshDrafts = (drafts: RefreshDrafts): RefreshParseResult => {
|
||||
const errors = {} as Record<RefreshField, string | null>
|
||||
const values = {} as RefreshValues
|
||||
for (const field of Object.keys(REFRESH_RULES) as RefreshField[]) {
|
||||
const parsed = parseField(field, drafts[field])
|
||||
errors[field] = parsed.error
|
||||
if (parsed.value !== null) values[field] = parsed.value
|
||||
}
|
||||
return { values: Object.values(errors).every((error) => error === null) ? values : null, errors }
|
||||
}
|
||||
|
||||
export const refreshSettingsDirty = (drafts: RefreshDrafts, settings: UISettings): boolean => {
|
||||
const parsed = parseRefreshDrafts(drafts)
|
||||
if (!parsed.values) return true
|
||||
return (
|
||||
parsed.values.documentRefresh !== settings.document_refresh_seconds ||
|
||||
parsed.values.resourceRefresh !== settings.resource_refresh_seconds ||
|
||||
parsed.values.stalled !== settings.stalled_after_seconds ||
|
||||
parsed.values.concurrency !== settings.ingestion_concurrency
|
||||
)
|
||||
}
|
||||
|
||||
export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts): UISettingsCandidateInput => ({
|
||||
document_refresh_seconds: settings.document_refresh_seconds,
|
||||
resource_refresh_seconds: settings.resource_refresh_seconds,
|
||||
@@ -26,12 +100,14 @@ export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts
|
||||
production_tenant_id: drafts.productionTenantID.trim(),
|
||||
production_knowledge_base_id: drafts.productionKnowledgeBaseID.trim(),
|
||||
})
|
||||
export const refreshSettingsInput = (settings: UISettings, drafts: RefreshDrafts): UISettingsCandidateInput => ({
|
||||
document_refresh_seconds: drafts.documentRefresh,
|
||||
resource_refresh_seconds: drafts.resourceRefresh,
|
||||
stalled_after_seconds: drafts.stalled,
|
||||
finalizing_after_seconds: drafts.finalizing,
|
||||
ingestion_concurrency: drafts.concurrency,
|
||||
export const refreshSettingsInput = (settings: UISettings, values: RefreshValues): UISettingsCandidateInput => ({
|
||||
// 范围由 parseRefreshDrafts 白名单保证;这里只把 number 收回契约的枚举类型。
|
||||
document_refresh_seconds: values.documentRefresh as UISettings['document_refresh_seconds'],
|
||||
resource_refresh_seconds: values.resourceRefresh as UISettings['resource_refresh_seconds'],
|
||||
stalled_after_seconds: values.stalled as UISettings['stalled_after_seconds'],
|
||||
// 参数分区不展示收尾超时,但契约必填且写侧按服务器值判权限:原样回传,绝不置空。
|
||||
finalizing_after_seconds: settings.finalizing_after_seconds,
|
||||
ingestion_concurrency: values.concurrency,
|
||||
test_weknora_base_url: settings.test_weknora_base_url,
|
||||
production_weknora_base_url: settings.production_weknora_base_url,
|
||||
production_tenant_id: settings.production_tenant_id,
|
||||
|
||||
@@ -155,10 +155,28 @@
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
}
|
||||
.settings-param-groups {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
.settings-param-group + .settings-param-group {
|
||||
border-top: 1px solid var(--border-base);
|
||||
padding-top: 14px;
|
||||
}
|
||||
.settings-param-group h3 {
|
||||
margin: 0 0 10px;
|
||||
color: var(--ink-base);
|
||||
font-size: 12px;
|
||||
}
|
||||
.settings-hint {
|
||||
margin: 6px 0 0;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.safe-setting-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.safe-setting-grid label {
|
||||
display: grid;
|
||||
@@ -166,12 +184,39 @@
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.safe-setting-grid select {
|
||||
.safe-setting-grid input {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 7px;
|
||||
padding: 8px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.safe-setting-grid input[aria-invalid='true'] {
|
||||
border-color: var(--c-fail);
|
||||
}
|
||||
.settings-field-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.settings-field-control input {
|
||||
flex: 1;
|
||||
}
|
||||
.settings-field-unit {
|
||||
flex: none;
|
||||
font-size: 9px;
|
||||
}
|
||||
.settings-field-hint {
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.settings-field-error {
|
||||
color: var(--c-fail);
|
||||
font-size: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.locked-gates {
|
||||
display: flex;
|
||||
|
||||
Reference in New Issue
Block a user