Compare commits

..

3 Commits

Author SHA1 Message Date
姚章浩 0cc3cac837 feat(release): 发布管理显示真实测试库名
build / build (push) Successful in 1m47s
业务名「对内知识库」在 WeKnora 里叫 wiki-demo,两边对不上号。
页面从测试知识库绑定读取库名并拼在业务名后,读不到就只显示业务名,
不影响发布状态判定。
2026-11-17 14:42:04 +08:00
姚章浩 e4342fa05b style(release): 移除旧封存关联与文档级发布区域
build / build (push) Successful in 1m58s
2026-11-17 14:12:00 +08:00
姚章浩 040b7285d7 style(release): 收敛发布主流程并折叠诊断明细
build / build (push) Successful in 2m7s
根据封存、授权和作业状态切换唯一主动作,保留独立签发与执行确认。
收起变更、完整性、恢复验证和历史;维护占用及失败作业保持可见。
补充挂载交互回归和流程说明,保持原有 API 与恢复所有者约束。

验证:make verify 退出 0,本地全部必需门禁通过;前端 574 项通过,
Go 1536 项通过、487 项声明的可选集成跳过。候选构建经只读代理
接入测试 API,核验切库、折叠与快照入口;未执行真实发布/恢复。
2026-11-17 13:38:25 +08:00
37 changed files with 1245 additions and 1599 deletions
+2 -27
View File
@@ -1,35 +1,10 @@
# Changelog
## 开发快照 0.1.384(系统设置审查修复:能力心跳、封存源对照、分区合并)
### Added
- `GET /api/v1/system/worker-capabilities`:读取 worker 认领记录里的 job_types,
页面据此显示“执行器已启用/已停用/无认领”,不再把 readiness 当成可接单。
- 测试知识库绑定接口返回整库封存源与一致性状态,设置页同屏对照“入库目标 / 封存源”。
## [Unreleased]
### Changed
- 系统设置分区合并为“知识库映射”(测试入库 + 生产目标 + 封存源对照)。
- 服务卡片分三行:地址可达、凭据与库读取、执行器能力。
## 开发快照 0.1.383(发布管理精简 + 系统设置审查修复)
### Changed
- 发布管理:顶部改为「状态卡 + 下一步」,一个主按钮(启动同步/查看任务)+ 一个准备按钮
(封存/基线/签发授权);启动条件、检查清单、恢复验证收进「发布前检查」;
目标维护、差异明细、来源身份收进「高级与历史」。去掉重复的版本入口与说明。
### Fixed
- 服务配置与刷新策略各自保存边界:保存一方不再夹带另一方未保存的草稿(F03)。
- 系统设置分区独立加载:监控/目录失败不再挡住成员与备份入口;保存后重新探测服务状态(F09)。
- 解析停滞阈值接入活动配置(worker 60 秒内生效),收尾超时仍只保存并在页面标注未接入(F02)。
- 重置密码改为受控遮罩对话框,不再用浏览器 prompt(F11)。
- 生产绑定:文档级旧配置收进折叠区,凭据缺失时说明不影响整库执行器(F05/F06)。
- 备份:主机未接通时明确「当前计划不会执行」,无运行记录时失败库显示未知(F07)。
- 文案统一:生产租户 ID、备份执行主机、收尾超时告警;技术细节不再占据主视图(F10)。
- 发布管理按封存、授权、同步与查看任务切换主操作,合并重复入口;变更明细、完整性和恢复验证按需展开,维护占用与失败作业保持可见。流程说明见 [发布管理流程与页面精简](docs/release-ui-flow.md)。
## 开发快照 0.1.382(采集 agent 允许显式 peer uid)
-20
View File
@@ -3434,26 +3434,6 @@
}
}
},
"/api/v1/system/worker-capabilities": {
"get": {
"tags": [
"Settings"
],
"operationId": "getWorkerCapabilities",
"summary": "读取 worker 能力心跳(执行器是否注册上传/解析链)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/routing-bindings": {
"get": {
"tags": [
-32
View File
@@ -10,7 +10,6 @@ import (
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
@@ -562,11 +561,6 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
Client: client,
PollDelay: config.TestWeKnoraPollInitial,
StallAfter: config.TestWeKnoraStalledAfter,
// 页面保存的停滞阈值在这里生效;每 60 秒重读一次活动配置,
// 读失败保留上一次值,再失败才回落到启动参数。
StallAfterSource: func() time.Duration {
return activeStalledAfter(context.Background(), store, config.TestWeKnoraStalledAfter)
},
})
if err != nil {
return nil, fmt.Errorf("create test poll handler: %w", err)
@@ -598,29 +592,3 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
handlers["test.remove"] = remove.Handle
return handlers, nil
}
// activeStalledAfter 读取活动 UI 配置里的解析停滞阈值(带 60 秒缓存)。
// 页面保存后无需重启 worker 即可生效;“保存即生效”不是文案,而是这里的读取。
var stalledAfterCache struct {
mu sync.Mutex
value time.Duration
fetchedAt time.Time
}
func activeStalledAfter(ctx context.Context, store *postgresstore.Store, fallback time.Duration) time.Duration {
stalledAfterCache.mu.Lock()
defer stalledAfterCache.mu.Unlock()
if time.Since(stalledAfterCache.fetchedAt) < time.Minute && stalledAfterCache.value > 0 {
return stalledAfterCache.value
}
settings, err := store.GetActiveUISettings(ctx)
if err != nil || settings.StalledAfterSeconds <= 0 {
if stalledAfterCache.value > 0 {
return stalledAfterCache.value
}
return fallback
}
stalledAfterCache.value = time.Duration(settings.StalledAfterSeconds) * time.Second
stalledAfterCache.fetchedAt = time.Now()
return stalledAfterCache.value
}
+45
View File
@@ -0,0 +1,45 @@
# 发布管理流程与页面精简
## 目标与边界
现有整库发布页面同时呈现日常发布、维护诊断、恢复演练与历史快照,且封存操作位于页面底部,版本入口重复。此次优化聚焦 `ReleaseTargets` 的信息层级和操作位置,沿用现有 API、权限、授权绑定、维护所有者与恢复确认。
基线采用云测试站当前前端对应的工作树 `cbc6b98`;该提交的 web 与部署版本 `0b753e5` 相同。并行主干及其他工作树不合并、不覆盖。
## 操作者主流程
| 顺序 | 页面操作 | 后台行为 | 完成边界 |
| --- | --- | --- | --- |
| 1 | 选择对内或对外知识库 | 读取该范围 overview、快照、作业及维护窗口 | 目标身份与版本来自所选范围;读取失败不当作空库 |
| 2 | 封存测试版本 | POST `/api/v1/library/captures`,由队列及执行器捕获测试整库版本 | 投递不等于完成,以作业与登记快照为准;此步不发布生产 |
| 3 | 查看变更及发布条件 | 展开变更、备份与恢复验证;若缺基线或恢复证据,沿用对应管理员入口 | 逐条呈现服务端阻塞原因,不删除发布门槛 |
| 4 | 签发同步授权 | 管理员调用 `/api/v1/library/authorizations`,绑定目标与当前快照 | 有效期内仍需单独点击启动;不自动执行同步 |
| 5 | 启动同步 | 沿用现有同步请求与执行链:固定版本、生产预备份、同步、校验及收尾 | 只在接口条件允许时可执行;运行中主按钮改为查看任务 |
| 6 | 查看结果 | 自动刷新作业进度,终态按真实记录呈现 | 失败显示原始原因;维护占用不被其他作业成功覆盖 |
| 异常 | 从版本与快照选择恢复点 | 继续执行独立恢复授权、影响确认和恢复条件校验 | 恢复整套目标知识状态,不回退测试知识库 |
封存、签发授权、启动同步三个动作保持独立,不将其合并为一键生产写入。
## 页面保留规则
- 顶栏:唯一的「版本与快照」入口和刷新。
- 主工作区:实际目标身份、当前生产版本、候选测试版本、紧凑变更统计、当前主动作与一份阻塞原因。
- 已有封存时提供次级「重新封存」;运行时不提供重复封存、授权或同步入口。
- 「查看变更明细」「发布准备与恢复验证」「封存完整性」默认折叠;原有详情和验证回调继续存在。
- 目标维护正常时折叠,持有维护窗口时自动展开;仍按窗口持有作业展示恢复信息。
- 最近作业仅在有记录时展示,正常完成默认折叠,失败默认展开;运行中保留主进度,分项明细按需展开。
- 版本抽屉保留历史筛选、分页、校验记录、恢复授权和影响确认,移除重复的封存按钮。
- 发布管理页面移除旧文档级发布及历史来源关联区域,只展示整库发布流程。
## 验收清单
- [x] 前端生产构建通过。
- [x] 原发布、恢复、维护所有者和刷新/切库回归通过。
- [x] 同一挂载下依次切换封存、授权、同步,点击只调用对应动作。
- [x] 折叠与展开、打开历史不触发业务写入。
- [x] 运行时主操作只查看任务,不调用封存、授权或同步。
- [x] 正常维护折叠、持有时展开、释放后折叠;切库重置明细展开状态。
- [x] 无作业不画空进度;失败原因默认可见。
- [x] 只读角色和读取失败时禁止主动作。
浏览器验收使用本地候选构建,GET/HEAD 通过已有 SSH 通道读取云测试 API;代理拒绝所有写请求。界面验收与真实封存、生产同步及恢复演练分开记录;本任务不执行这些业务写入。完整仓库门禁和云端部署结论以实际运行结果为准,不用上述前端检查替代。
+1 -23
View File
@@ -41,24 +41,6 @@ type routingBindingView struct {
// that had not been uploaded yet. A plain read reports zeros.
Replanned int `json:"replanned"`
RetiredDuplicates int `json:"retired_duplicates"`
// 整库封存源(LIBRARY_SOURCE_KB_*)与“测试入库绑定”是两套配置:
// 页面必须同时给出两者,并标明是否一致,避免改绑后名字变了、封存还是旧库。
LibrarySourceInternalKB string `json:"library_source_internal_kb"`
LibrarySourceExternalKB string `json:"library_source_external_kb"`
InternalSourceState string `json:"internal_source_state"`
ExternalSourceState string `json:"external_source_state"`
}
// sourceState 只回答“入库目标与封存源是不是同一个库”。
func sourceState(binding, source string) string {
switch {
case source == "":
return "unconfigured"
case binding == source:
return "consistent"
default:
return "mismatch"
}
}
type routingKnowledgeBaseOption struct {
@@ -119,11 +101,7 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
LibrarySourceInternalKB: config.LibrarySourceInternalKB,
LibrarySourceExternalKB: config.LibrarySourceExternalKB,
InternalSourceState: sourceState(internal, config.LibrarySourceInternalKB),
ExternalSourceState: sourceState(external, config.LibrarySourceExternalKB),
UpdatedBy: updatedBy, WeKnoraConnected: connected,
UpdatedBy: updatedBy, WeKnoraConnected: connected,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
}
-3
View File
@@ -377,9 +377,6 @@ func NewHandler(config Config) (http.Handler, error) {
internal, external := config.effectiveRoutingTargets(r.Context())
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": internal != "", "external_enabled": external != ""}})
})
mux.HandleFunc("GET /api/v1/system/worker-capabilities", func(w http.ResponseWriter, r *http.Request) {
config.handleWorkerCapabilities(w, r)
})
mux.HandleFunc("GET /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
if config.RoutingBindings == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
-91
View File
@@ -1,91 +0,0 @@
package httpapi
import (
"context"
"net/http"
"slices"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// workerHeartbeatStore 是队列存活记录的只读视图。页面要回答“执行器在不在”,
// 只能看 worker 认领任务时自己写下的 job_types;readiness 只证明接口可达。
type workerHeartbeatStore interface {
ListWorkerHeartbeats(context.Context) ([]postgresstore.WorkerHeartbeat, error)
}
type workerCapabilityView struct {
WorkerID string `json:"worker_id"`
JobTypes []string `json:"job_types"`
Alive bool `json:"alive"`
LastSeenAt string `json:"last_seen_at"`
}
type testUploadCapability struct {
State string `json:"state"`
Consumers int `json:"consumers"`
Detail string `json:"detail"`
}
// 与 qaopsmirror 的工作就绪判定同一个窗口:2 分钟没有认领记录就当作不在线。
const workerHeartbeatTTL = 2 * time.Minute
const testUploadJobType = "test.upload"
func testUploadCapabilityOf(workers []postgresstore.WorkerHeartbeat, now time.Time) testUploadCapability {
alive, consumers := 0, 0
for _, worker := range workers {
if now.Sub(worker.LastSeenAt) > workerHeartbeatTTL {
continue
}
alive++
if slices.Contains(worker.JobTypes, testUploadJobType) {
consumers++
}
}
switch {
case consumers > 0:
return testUploadCapability{State: "enabled", Consumers: consumers,
Detail: "上传/解析执行器已注册(认领过 test.upload)"}
case alive > 0:
return testUploadCapability{State: "disabled", Consumers: 0,
Detail: "worker 在线但没有注册 test.upload:上传/解析任务不会被消费"}
default:
return testUploadCapability{State: "stale", Consumers: 0,
Detail: "没有有效的 worker 认领记录:执行器未运行,或从未接单"}
}
}
func (config Config) handleWorkerCapabilities(w http.ResponseWriter, r *http.Request) {
store, ok := config.Store.(workerHeartbeatStore)
if !ok || store == nil {
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"test_upload": testUploadCapability{State: "unknown", Detail: "worker 存活记录不可用"},
"workers": []workerCapabilityView{},
}})
return
}
workers, err := store.ListWorkerHeartbeats(r.Context())
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"test_upload": testUploadCapability{State: "unknown", Detail: "读取 worker 存活记录失败"},
"workers": []workerCapabilityView{},
}})
return
}
now := time.Now().UTC()
views := make([]workerCapabilityView, 0, len(workers))
for _, worker := range workers {
views = append(views, workerCapabilityView{
WorkerID: worker.WorkerID,
JobTypes: worker.JobTypes,
Alive: now.Sub(worker.LastSeenAt) <= workerHeartbeatTTL,
LastSeenAt: worker.LastSeenAt.UTC().Format(time.RFC3339),
})
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"test_upload": testUploadCapabilityOf(workers, now),
"workers": views,
}})
}
@@ -1,35 +0,0 @@
package httpapi
import (
"testing"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
)
func TestTestUploadCapabilityReflectsWorkerHeartbeats(t *testing.T) {
now := time.Date(2026, time.November, 17, 7, 0, 0, 0, time.UTC)
fresh := now.Add(-10 * time.Second)
stale := now.Add(-5 * time.Minute)
cases := []struct {
name string
workers []postgresstore.WorkerHeartbeat
state string
consume int
}{
{"no heartbeats", nil, "stale", 0},
{"heartbeat too old", []postgresstore.WorkerHeartbeat{{LastSeenAt: stale, JobTypes: []string{"test.upload"}}}, "stale", 0},
{"worker online without upload chain", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"source.scan.dingtalk"}}}, "disabled", 0},
{"enabled consumer", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"test.upload", "test.poll"}}}, "enabled", 1},
}
for _, tc := range cases {
got := testUploadCapabilityOf(tc.workers, now)
if got.State != tc.state || got.Consumers != tc.consume {
t.Fatalf("%s: got state=%s consumers=%d, want %s/%d", tc.name, got.State, got.Consumers, tc.state, tc.consume)
}
if got.Detail == "" {
t.Fatalf("%s: detail must explain the state", tc.name)
}
}
}
@@ -1,40 +0,0 @@
package postgres
import (
"context"
"strings"
"time"
)
// WorkerHeartbeat 是队列认领时顺手写下的存活记录(P10)。
// 它本来就带 job_types:页面用它判断“这个 worker 有没有注册上传/解析链”,
// 不需要再开一张表,也不该拿 readiness 或 env 去猜。
type WorkerHeartbeat struct {
WorkerID string
JobTypes []string
StartedAt time.Time
LastSeenAt time.Time
}
func (s *Store) ListWorkerHeartbeats(ctx context.Context) ([]WorkerHeartbeat, error) {
rows, err := s.db.Query(ctx, `
SELECT worker_id, job_types, started_at, last_seen_at
FROM worker_heartbeats ORDER BY last_seen_at DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []WorkerHeartbeat
for rows.Next() {
var hb WorkerHeartbeat
var types string
if err := rows.Scan(&hb.WorkerID, &types, &hb.StartedAt, &hb.LastSeenAt); err != nil {
return nil, err
}
if types != "" {
hb.JobTypes = strings.Split(types, ",")
}
out = append(out, hb)
}
return out, rows.Err()
}
+4 -15
View File
@@ -35,9 +35,7 @@ type PollHandlerConfig struct {
Client PollClient
PollDelay time.Duration
StallAfter time.Duration
// StallAfterSource 可选:返回当前生效的停滞阈值(来自活动 UI 配置)。
StallAfterSource func() time.Duration
Now func() time.Time
Now func() time.Time
}
type PollHandler struct {
@@ -45,10 +43,7 @@ type PollHandler struct {
client PollClient
pollDelay time.Duration
stallAfter time.Duration
// stallAfterSource 存在时优先于 stallAfter:页面保存的“解析停滞阈值”
// 必须真的决定判定,而不是只写进数据库。
stallAfterSource func() time.Duration
now func() time.Time
now func() time.Time
}
type pollPayload struct {
@@ -65,7 +60,7 @@ func NewPollHandler(config PollHandlerConfig) (*PollHandler, error) {
}
return &PollHandler{
store: config.Store, client: config.Client, pollDelay: config.PollDelay,
stallAfter: config.StallAfter, stallAfterSource: config.StallAfterSource, now: config.Now,
stallAfter: config.StallAfter, now: config.Now,
}, nil
}
@@ -108,13 +103,7 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
}
return nil
}
stall := handler.stallAfter
if handler.stallAfterSource != nil {
if fromSettings := handler.stallAfterSource(); fromSettings > 0 {
stall = fromSettings
}
}
cutoff := now.Add(-stall)
cutoff := now.Add(-handler.stallAfter)
lastProgress := publication.LastProgressAt
if lastProgress == nil {
lastProgress = publication.ProcessingStartedAt
@@ -186,61 +186,3 @@ func (store *pollStoreStub) MarkStalled(_ context.Context, _ string, _ int, cuto
store.stalledCutoff = cutoff
return nil
}
// F02 验收:停滞判定必须用“活动配置”的阈值,而不是启动时的常量。
// 同一条已经停在同一进度上的解析任务:阈值 30 分钟判停,阈值 2 小时不判停。
func TestPollHandlerStallThresholdFollowsActiveSettings(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"processing","updated_at":"2026-09-04T03:00:00Z"}}`))
}))
defer server.Close()
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: server.URL, APIKey: "test-key", Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, time.September, 4, 4, 0, 0, 0, time.UTC)
progressAt := now.Add(-45 * time.Minute)
makeStore := func() *pollStoreStub {
return &pollStoreStub{publication: postgresstore.PublicationForPoll{
ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
ProcessingState: governance.ProcessingProcessing, PollSequence: 3,
LastProgressAt: &progressAt, ProcessingStartedAt: &progressAt,
}}
}
payload := jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":3}`)}
// 启动常量 30 分钟、活动配置也是 30 分钟:45 分钟没进度 → 判停。
store := makeStore()
handler, err := NewPollHandler(PollHandlerConfig{
Store: store, Client: client, PollDelay: 15 * time.Second,
StallAfter: 30 * time.Minute, Now: func() time.Time { return now },
})
if err != nil {
t.Fatal(err)
}
if err := handler.Handle(context.Background(), payload); err != nil {
t.Fatalf("Handle() error = %v", err)
}
if !store.stalledMarked {
t.Fatal("30 分钟阈值下 45 分钟无进度应判停")
}
// 活动配置改成 2 小时:同一条任务不应再判停。
store = makeStore()
handler, err = NewPollHandler(PollHandlerConfig{
Store: store, Client: client, PollDelay: 15 * time.Second,
StallAfter: 30 * time.Minute,
StallAfterSource: func() time.Duration { return 2 * time.Hour },
Now: func() time.Time { return now },
})
if err != nil {
t.Fatal(err)
}
if err := handler.Handle(context.Background(), payload); err != nil {
t.Fatalf("Handle() error = %v", err)
}
if store.stalledMarked {
t.Fatal("活动配置 2 小时阈值下不应判停:阈值没有接入实际判定")
}
}
File diff suppressed because one or more lines are too long
-47
View File
@@ -410,53 +410,6 @@ export function ModulePage({
return (
<div className="release-module">
<ReleaseTargets />
<details className="release-legacy">
<summary>文档级发布(旧流程,折叠保留):单篇文档发布成功不等于整库发布成功</summary>
<ReleaseManagement
reviewPage={reviewPage}
reviewLoading={reviewLoading}
reviewError={reviewError}
reviewingId={reviewingId}
batchPage={batchPage}
batchDetail={batchDetail}
batchLoading={batchLoading}
batchError={batchError}
mutatingBatchId={mutatingBatchId}
onReview={onReview}
onBatchReview={onBatchReview}
reviewBatchMessage={reviewBatchMessage}
onReviewRefresh={onReviewRefresh}
onCreateBatch={onCreateBatch}
onSealBatch={onSealBatch}
onSelectBatch={onSelectBatch}
onBatchRefresh={onBatchRefresh}
releaseCapabilities={releaseCapabilities}
releasePlan={releasePlan}
releaseChangeSet={releaseChangeSet}
changeSetBusy={changeSetBusy}
changeSetError={changeSetError}
onGenerateChangeSet={onGenerateChangeSet}
onConfirmChangeSet={onConfirmChangeSet}
selectedDeleteIDs={selectedDeleteIDs}
onToggleDelete={onToggleDelete}
executionPage={executionPage}
executionDetail={executionDetail}
executionChain={executionChain}
executionLoading={executionLoading}
executionError={executionError}
onSelectExecution={onSelectExecution}
onExecutionRefresh={onExecutionRefresh}
pendingReleaseAction={pendingReleaseAction}
releaseActionPhrase={releaseActionPhrase}
releaseActionBusy={releaseActionBusy}
releaseActionError={releaseActionError}
releaseActionMessage={releaseActionMessage}
onStartReleaseAction={onStartReleaseAction}
onReleaseActionPhrase={onReleaseActionPhrase}
onSubmitReleaseAction={onSubmitReleaseAction}
onCancelReleaseAction={onCancelReleaseAction}
/>
</details>
</div>
)
}
+1 -1
View File
@@ -81,7 +81,7 @@ describe('BackupScheduleView', () => {
const html = view()
for (const text of [
'存储与备份',
'备份执行主机',
'目标库所在主机',
'定时时间',
'储存天数',
'每月归档保留',
+6 -14
View File
@@ -104,7 +104,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<div>
<h2>存储与备份</h2>
<p>
整库逻辑备份(pg_dump 目录格式)在<strong>备份执行主机</strong>(同 VPC 直连 RDS)
整库逻辑备份(pg_dump 目录格式)在<strong>目标库所在主机</strong>
上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。
</p>
</div>
@@ -136,11 +136,9 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<dd>
{schedule.host_next_run
? schedule.host_next_run
: !schedule.host_configured
? '未接通备份执行主机:当前计划不会执行'
: schedule.host_schedule_enabled
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
: '未启用定时或未从主机读到计划'}
: schedule.host_schedule_enabled
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
: '未启用定时或未从主机读到计划'}
</dd>
<dt>最近一次运行</dt>
<dd>
@@ -165,13 +163,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<dt>覆盖的库</dt>
<dd>{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}</dd>
<dt>失败的库</dt>
<dd>
{schedule.last_run_failed_databases.length
? schedule.last_run_failed_databases.join('、')
: schedule.last_run_stamp
? '无'
: '未知(还没有读到运行记录,不能据此判断没有失败)'}
</dd>
<dd>{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}</dd>
<dt>主机上生效的计划</dt>
<dd>
{schedule.host_schedule_enabled
@@ -276,7 +268,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
)
}
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是备份执行主机(同 VPC 直连 RDS)。
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。
export function BackupScheduleSection() {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
+67 -71
View File
@@ -89,82 +89,78 @@ export function LibraryStorageSection() {
)}
</div>
<details className="settings-details" open={!policyConfigured}>
<summary>保留策略与清理预览(未设置时按“全部保留”处理)</summary>
<div className="library-storage-panel">
<h4>保留与依赖保护</h4>
<p>
{policyConfigured
? `策略:${[
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
]
.filter(Boolean)
.join(' + ')}`
: '策略:未设置(不生成清理候选)'}
</p>
<p>
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用,
不论多久都不会进入候选。
</p>
{data.versions.filter((item) => item.protected).length > 0 ? (
<ul className="library-storage-versions">
{data.versions
.filter((item) => item.protected)
.map((item) => (
<div className="library-storage-panel">
<h4>保留与依赖保护</h4>
<p>
{policyConfigured
? `策略:${[
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
]
.filter(Boolean)
.join(' + ')}`
: '策略:未设置(不生成清理候选)'}
</p>
<p>
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、在飞作业引用,
不论多久都不会进入候选。
</p>
{data.versions.filter((item) => item.protected).length > 0 ? (
<ul className="library-storage-versions">
{data.versions
.filter((item) => item.protected)
.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
</li>
))}
</ul>
) : null}
</div>
<div className="library-storage-panel">
<h4>清理预览</h4>
{policyConfigured ? (
plan && plan.candidates.length > 0 ? (
<>
<p>
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
{formatBytes(plan.reclaim_preview_bytes)}(共享 blob 不会因此释放,这不是可回收空间)。
</p>
<ul className="library-storage-versions">
{plan.candidates.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
{formatBytes(item.exclusive_bytes)}
</li>
))}
</ul>
) : null}
</div>
<div className="library-storage-panel">
<h4>清理预览</h4>
{policyConfigured ? (
plan && plan.candidates.length > 0 ? (
<>
<p>
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
{formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。
</p>
<ul className="library-storage-versions">
{plan.candidates.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
{formatBytes(item.exclusive_bytes)}
</li>
))}
</ul>
</>
) : (
<p>按当前策略没有可清理的候选版本。</p>
)
</ul>
</>
) : (
<p className="library-storage-warn">
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
</p>
)}
{plan?.blocked.length ? (
<ul className="library-storage-blocked-list">
{plan.blocked.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
) : null}
</div>
<p>按当前策略没有可清理的候选版本。</p>
)
) : (
<p className="library-storage-warn">
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
</p>
)}
{plan?.blocked.length ? (
<ul className="library-storage-blocked-list">
{plan.blocked.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
) : null}
</div>
<ul className="library-storage-limits">
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
<li>实际删除需要单独授权,本页只给预览</li>
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
{data.notes.map((note) => (
// 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。
<li key={note}>{note.replace(/blob/gi, '归档文件')}</li>
))}
</ul>
</details>
<ul className="library-storage-limits">
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
<li>实际删除需要单独授权,本页只给预览</li>
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
{data.notes.map((note) => (
<li key={note}>{note}</li>
))}
</ul>
</>
) : null}
</section>
+9 -46
View File
@@ -23,9 +23,6 @@ export function MembersSection() {
const [busy, setBusy] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [message, setMessage] = useState<string | null>(null)
// 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。
const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null)
const [resetValue, setResetValue] = useState('')
const [form, setForm] = useState({
username: '',
display_name: '',
@@ -157,8 +154,15 @@ export function MembersSection() {
className="secondary-action"
disabled={busy === user.id}
onClick={() => {
setResetTarget({ id: user.id, username: user.username })
setResetValue('')
const temporary = window.prompt(
`为 ${user.username} 生成一个临时密码(至少 8 位,对方首次登录必须更换)`
)
if (temporary)
void run(
user.id,
() => resetManagedUserPassword(user.id, temporary),
`${user.username} 的临时密码已生效`
)
}}
>
重置密码
@@ -234,47 +238,6 @@ export function MembersSection() {
</button>
</div>
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
{resetTarget ? (
<div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码">
<h3>重置 {resetTarget.username} 的临时密码</h3>
<p>至少 8 位;对方首次登录必须更换,旧会话会立即失效。</p>
<PasswordInput
value={resetValue}
autoFocus
autoComplete="new-password"
onChange={(event) => setResetValue(event.target.value)}
/>
<div className="row-actions">
<button
type="button"
disabled={resetValue.length < 8 || busy === resetTarget.id}
onClick={() => {
const target = resetTarget
const value = resetValue
setResetTarget(null)
setResetValue('')
void run(
target.id,
() => resetManagedUserPassword(target.id, value),
`${target.username} 的临时密码已生效`
)
}}
>
确认重置
</button>
<button
type="button"
className="secondary-action"
onClick={() => {
setResetTarget(null)
setResetValue('')
}}
>
取消
</button>
</div>
</div>
) : null}
</section>
)
}
+1 -1
View File
@@ -65,7 +65,7 @@ describe('ProductionBindingsView', () => {
it('旧文档级绑定标成旧路径,不再声称"发布写入此库"', () => {
const html = view(bindings())
expect(html).toContain('文档级发布(单篇文档写生产)· 旧路径')
expect(html).toContain('整库封存/同步/恢复不读取这组配置')
expect(html).toContain('仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。')
expect(html).toContain('对内文档级目标')
expect(html).not.toContain('发布写入此库')
})
+14 -17
View File
@@ -103,9 +103,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
</div>
{error ? (
<p className="error-message" role="alert">
{/api key file/i.test(error)
? '生产 API 读取凭据未配置:无法在此列出生产知识库。整库同步走独立执行器通道,不受这条读取凭据影响。'
: error}
{error}
</p>
) : null}
{bindings ? (
@@ -135,24 +133,19 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
</div>
) : null}
{bindings ? (
<details className="stack legacy-bindings">
<summary>
{bindings.legacy_scope || '文档级发布(单篇文档写生产)· 旧路径'}
<span className="hint"> · 展开编辑;整库封存/同步/恢复不读取这组配置</span>
</summary>
<div className="stack">
<h3>{bindings.legacy_scope || '文档级绑定(旧路径)'}</h3>
<p className="hint">仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。</p>
<div className="kb-binding-grid">
{renderSide('对内文档级目标', bindings.internal_kb_id, bindings.internal_kb_name)}
{renderSide('对外文档级目标', bindings.external_kb_id, bindings.external_kb_name)}
</div>
</details>
</div>
) : null}
{bindings && !bindings.production_connected ? (
<p className="hint">
生产端核对不可用:
{/api key file/i.test(bindings.production_message)
? '生产 API 读取凭据未配置(不影响整库执行器;整库同步走独立数据库/索引/存储通道)'
: bindings.production_message}
。{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}
生产端核对不可用:{bindings.production_message}。
{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}
</p>
) : null}
{bindings && bindings.production_connected && bindings.production_base_url ? (
@@ -163,8 +156,12 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
) : null}
{isAdmin && bindings ? (
<div className="kb-binding-editor">
<label>对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}</label>
<label>对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}</label>
<label>
对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}
</label>
<label>
对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}
</label>
<p className="hint">保存时只改文档级绑定;整库发布目标由部署配置决定,本页不改它。</p>
<p className="hint">保存时会向生产端核对所选的库是否真实存在;对不上会拒收,生产端不可达则只提示。</p>
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的生产知识库</p> : null}
@@ -262,4 +259,4 @@ export function ProductionBindingsSection() {
onReload={() => void load()}
/>
)
}
}
+258
View File
@@ -0,0 +1,258 @@
// @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 { ReleaseTargetsView } from './ReleaseTargets'
import type { LibraryJobRecord, LibraryOverview, LibrarySnapshot } from './librarySnapshots'
// The existing mounted suite exercises transport races and owner-bound recovery.
// This suite exercises the visible flow without authorizing any real operation.
vi.mock('./RestoreVerificationSection', () => ({
RestoreVerificationSection: () => <section aria-label="恢复验证">恢复验证入口</section>,
}))
type Props = Parameters<typeof ReleaseTargetsView>[0]
const snapshot: LibrarySnapshot = {
snapshot_id: 'a'.repeat(64),
scope: 'internal',
knowledge_base_id: 'test-kb',
tenant_id: 1,
created_at: '2026-11-17T01:00:00Z',
validation_policy: 'artifact-acceptance-v1',
format: 'weknora-library-snapshot/v1',
compatibility: {
weknora_version: 'v0.9.0',
schema_version: 134,
retriever_engine: 'elasticsearch_v8',
embedding_model: 'test-model',
embedding_dimension: 1024,
index_mapping_sha256: 'b'.repeat(64),
},
parts: [],
logical_bytes: 0,
unique_bytes: 0,
shared_bytes: 0,
totals: {},
}
const overview: LibraryOverview = {
scope: 'internal',
production: { state: 'unknown', empty_baseline: true },
prebackup: { state: 'unknown' },
diff: { state: 'computed', added: [], updated: [], removed: [] },
gate: { sync_allowed: false, reasons: ['没有与目标快照匹配的有效发布授权'] },
authorization: { state: 'none' },
capture_available: true,
jobs: [],
now: '2026-11-17T01:00:00Z',
}
let props: Props
let container: HTMLDivElement
let root: Root
const draw = async (next: Partial<Props> = {}) => {
props = { ...props, ...next }
await act(async () => root.render(<ReleaseTargetsView {...props} />))
}
const primary = () => container.querySelector<HTMLButtonElement>('.rel-primary')!
const details = (label: string) =>
Array.from(container.querySelectorAll('details')).find((item) =>
item.querySelector('summary')?.textContent?.startsWith(label)
)!
const click = async (element: HTMLElement) => {
await act(async () => element.click())
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
props = {
page: null,
jobs: [],
overview,
loading: false,
error: null,
notice: null,
scope: 'internal',
onScope: vi.fn(),
drawerOpen: false,
onDrawer: vi.fn(),
expandedSnapshot: null,
onExpandSnapshot: vi.fn(),
pendingCapture: false,
canCapture: true,
canWrite: true,
canReconcileCapture: false,
pendingReconcileCapture: '',
onReconcileCapture: vi.fn(),
sync: { canSign: true, pendingGrant: false, onGrant: vi.fn(), canStart: false, pending: false, onStart: vi.fn() },
baseline: { canStart: false, pending: false, onStart: vi.fn() },
verification: { onAccepted: vi.fn(), onComplete: vi.fn() },
canRestore: false,
restore: null,
restoreNotice: null,
pendingRestore: false,
pendingGrant: false,
onGrantRestore: vi.fn(),
onRestore: vi.fn(),
maintenance: null,
now: 0,
onRefresh: vi.fn(),
onCapture: vi.fn(),
onRecover: vi.fn(),
}
})
afterEach(async () => {
await act(async () => root.unmount())
container.remove()
vi.restoreAllMocks()
})
describe('发布管理精简主流程', () => {
it('同一挂载依次封存、授权、同步,每次点击只调用当前动作', async () => {
await draw()
expect(primary().textContent).toBe('封存测试版本')
await click(primary())
expect(props.onCapture).toHaveBeenCalledOnce()
expect(props.sync.onGrant).not.toHaveBeenCalled()
expect(props.sync.onStart).not.toHaveBeenCalled()
await draw({ overview: { ...overview, test_sealed: snapshot } })
expect(primary().textContent).toBe('签发同步授权(30 分钟)')
await click(primary())
expect(props.sync.onGrant).toHaveBeenCalledOnce()
expect(props.sync.onStart).not.toHaveBeenCalled()
await draw({
overview: {
...overview,
test_sealed: snapshot,
authorization: { state: 'active' },
gate: { sync_allowed: true, reasons: [] },
},
sync: { ...props.sync, canStart: true },
})
expect(primary().textContent).toBe('▶ 启动同步')
expect(primary().disabled).toBe(false)
await click(primary())
expect(props.sync.onStart).toHaveBeenCalledOnce()
})
it('默认收起明细,展开和收起均不调用业务写入;历史只保留一个入口', async () => {
await draw({ overview: { ...overview, test_sealed: snapshot } })
expect(container.querySelectorAll('button').length).toBeGreaterThan(0)
const history = Array.from(container.querySelectorAll('button')).filter((b) =>
b.textContent?.includes('版本与快照')
)
expect(history).toHaveLength(1)
for (const label of ['查看变更明细', '发布准备与恢复验证', '目标维护', '封存完整性']) {
const panel = details(label)
expect(panel.open).toBe(false)
await click(panel.querySelector('summary')!)
expect(panel.open).toBe(true)
await click(panel.querySelector('summary')!)
expect(panel.open).toBe(false)
}
await click(history[0])
expect(props.onDrawer).toHaveBeenCalledWith(true)
expect(props.onCapture).not.toHaveBeenCalled()
expect(props.sync.onGrant).not.toHaveBeenCalled()
expect(props.sync.onStart).not.toHaveBeenCalled()
expect(props.onRestore).not.toHaveBeenCalled()
})
it('运行时只查看进度,不能再封存、授权或同步', async () => {
const job: LibraryJobRecord = {
id: 'job-1',
scope: 'internal',
kind: 'sync',
state: 'running',
stage: 'database',
request_digest: '',
queue_job_id: '',
snapshot_id: '',
target_snapshot_id: snapshot.snapshot_id,
actor: 'test',
error: '',
recovery: '',
created_at: overview.now,
updated_at: overview.now,
finished_at: null,
stages: [],
}
await draw({
overview: { ...overview, test_sealed: snapshot, job, jobs: [job] },
sync: { ...props.sync, canStart: true },
})
expect(primary().textContent).toBe('查看当前任务')
expect(container.textContent).not.toContain('重新封存')
await click(primary())
expect(props.onCapture).not.toHaveBeenCalled()
expect(props.sync.onGrant).not.toHaveBeenCalled()
expect(props.sync.onStart).not.toHaveBeenCalled()
expect(details('查看执行明细').open).toBe(false)
})
it('无作业不展示空进度,失败作业展开显示原始原因', async () => {
await draw()
expect(container.textContent).not.toContain('最近作业')
const job: LibraryJobRecord = {
id: 'job-failed',
scope: 'internal',
kind: 'sync',
state: 'failed',
stage: 'database',
request_digest: '',
queue_job_id: '',
snapshot_id: '',
target_snapshot_id: '',
actor: 'test',
error: '目标连接失败',
recovery: '',
created_at: overview.now,
updated_at: overview.now,
finished_at: overview.now,
stages: [],
}
await draw({ overview: { ...overview, job, jobs: [job] } })
expect(details('最近作业').open).toBe(true)
expect(details('最近作业').textContent).toContain('目标连接失败')
})
it('维护占用时自动展开,释放后恢复折叠;切库不沿用展开状态', async () => {
await draw({ maintenance: { held: false } })
expect(details('目标维护').open).toBe(false)
await draw({ maintenance: { held: true } })
expect(details('目标维护').open).toBe(true)
await draw({ maintenance: { held: false } })
expect(details('目标维护').open).toBe(false)
await click(details('查看变更明细').querySelector('summary')!)
expect(details('查看变更明细').open).toBe(true)
const external = Array.from(container.querySelectorAll<HTMLButtonElement>('[role="tab"]'))[1]
await click(external)
expect(props.onScope).toHaveBeenCalledWith('external')
await draw({ scope: 'external', overview: { ...overview, scope: 'external' } })
expect(details('查看变更明细').open).toBe(false)
expect(container.querySelector('[aria-selected="true"]')?.textContent).toContain('对外知识库')
})
it('只读权限与刷新失败均不提供可执行主动作', async () => {
await draw({ canWrite: false, canCapture: false })
expect(primary().disabled).toBe(true)
await click(primary())
expect(props.onCapture).not.toHaveBeenCalled()
await draw({ overview: { ...overview, test_sealed: snapshot }, sync: { ...props.sync, canSign: false } })
expect(primary().textContent).toBe('等待管理员授权')
expect(primary().disabled).toBe(true)
await draw({ error: '网络中断', sync: { ...props.sync, canSign: true } })
expect(primary().disabled).toBe(true)
expect(container.textContent).toContain('网络中断')
await click(primary())
expect(props.sync.onGrant).not.toHaveBeenCalled()
await draw({ canWrite: true, canCapture: true })
const recapture = Array.from(container.querySelectorAll('button')).find(
(button) => button.textContent === '重新封存'
)!
expect(recapture.disabled).toBe(true)
await click(recapture)
expect(props.onCapture).not.toHaveBeenCalled()
})
})
+8 -9
View File
@@ -228,12 +228,10 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
it('没有当前作业时不把历史封存当成阶段完成', () => {
const html = render()
// 阶段条第一段必须是 idle(○),"✓" 只允许出现在准备清单,不出现在阶段条
const stageBar = html.slice(html.indexOf('aria-label="作业阶段"'), html.indexOf('rel-steps-note'))
expect(stageBar).not.toContain('✓')
expect(stageBar).toContain('本次作业尚未开始')
expect(html).toContain('已有测试封存')
expect(html).toContain('没有当前作业证据时不会把历史封存当作阶段完成')
// 没有作业就不展示空进度,更不能将历史封存伪装成当前作业完成。
expect(html).not.toContain('aria-label="作业阶段"')
expect(html).not.toContain('启动后的作业进度')
expect(html).toContain('尚未启动,不修改生产')
})
it('差异已计算时按文档身份列增改撤销,并标注比对的两个版本', () => {
@@ -895,7 +893,7 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
it('闸口全满足时“启动同步”真的可点,并给出执行说明', () => {
const html = render({
sync: { canSign: false, pendingGrant: false, onGrant: vi.fn(), canStart: true, pending: false, onStart: vi.fn() },
overview: { ...overview, gate: { sync_allowed: true, reasons: [] } },
overview: { ...overview, authorization: { state: 'active' }, gate: { sync_allowed: true, reasons: [] } },
})
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*>▶ 启动同步/)
expect(html).not.toMatch(/class="rel-primary"[^>]*disabled/)
@@ -1060,7 +1058,7 @@ describe('生产目标四类状态:known / 空 / 非空 / 不可读', () => {
expect(html).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/)
})
it('空目标但没有测试封存:启动同步保持禁用并说明缺候选', () => {
it('空目标但没有测试封存:主动作是封存,不提供启动同步', () => {
const html = render({
baseline,
overview: {
@@ -1070,7 +1068,8 @@ describe('生产目标四类状态:known / 空 / 非空 / 不可读', () => {
test_sealed_reason: '还没有该目标的测试封存',
},
})
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*disabled/)
expect(html).toMatch(/<button[^>]*class="rel-primary"[^>]*>封存测试版本/)
expect(html).not.toContain('▶ 启动同步')
expect(html).toContain('尚无测试封存')
})
})
+420 -426
View File
File diff suppressed because it is too large Load Diff
+16 -40
View File
@@ -124,46 +124,22 @@ export function RoutingBindingsSection() {
</p>
) : null}
{bindings ? (
<>
<div className="source-consistency" role="status" aria-label="入库目标与封存源对照">
{(['internal', 'external'] as const).map((scope) => {
const binding = scope === 'internal' ? bindings.internal_kb_id : bindings.external_kb_id
const source =
scope === 'internal' ? bindings.library_source_internal_kb : bindings.library_source_external_kb
const state = scope === 'internal' ? bindings.internal_source_state : bindings.external_source_state
return (
<div key={scope} className={`source-consistency-row ${state}`}>
<b>{scope === 'internal' ? '对内' : '对外'}</b>
<span>入库目标 {binding ? `${binding.slice(0, 8)}…` : '未绑定'}</span>
<span>封存源 {source ? `${source.slice(0, 8)}…` : '未配置(LIBRARY_SOURCE_KB_*)'}</span>
<em>
{state === 'consistent'
? '一致'
: state === 'mismatch'
? '不一致:改绑定不会改封存源,封存仍导出旧库'
: '未配置:整库封存无法定位来源'}
</em>
</div>
)
})}
</div>
<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>
</>
<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>
-8
View File
@@ -118,14 +118,6 @@ export function SourceSettingsCard({
? '自动刷新中'
: '仅手动刷新'}
</span>
{/* 刷新方式之外还要能判断“最近有没有真的跑过、下一次什么时候跑”。 */}
<small className="source-timing">
{`上次更新 ${connection.updated_at ? new Date(connection.updated_at).toLocaleString('zh-CN', { hour12: false }) : '未知'}`}
{manual
? ' · 手工导入无自动计划'
: ` · 下次计划 ${connection.next_refresh_at ? new Date(connection.next_refresh_at).toLocaleString('zh-CN', { hour12: false }) : '无(仅手动)'}`}
{` · ${connection.item_count} 条`}
</small>
</div>
{!manual || isAdmin ? (
<button
+7 -53
View File
@@ -1,12 +1,6 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import {
SystemSettingsView,
ppSourceConnections,
refreshSettingsInput,
serviceSettingsInput,
visibleSaveMessage,
} from './SystemSettings'
import { SystemSettingsView, ppSourceConnections, visibleSaveMessage } from './SystemSettings'
import { AuthContext } from './auth'
import type { MonitorOverview } from './monitor'
import type { CatalogSource } from './sourceCatalog'
@@ -153,7 +147,7 @@ describe('SystemSettingsView service configuration', () => {
for (const text of [
'测试地址',
'生产地址',
'生产租户 ID',
'生产 ID',
'知识库 ID',
'保存并启用服务配置',
'https://weknora.test.example',
@@ -279,9 +273,9 @@ describe('SystemSettingsView', () => {
'finalizing 2小时',
'文档状态刷新间隔',
'15秒',
'解析停滞阈值',
'解析停滞判定',
'30分钟',
'保存刷新与告警参数',
'保存并应用刷新与告警参数',
])
expect(refreshHtml).toContain(text)
expect(visibleSaveMessage('已保存', true)).toBeNull()
@@ -328,8 +322,8 @@ describe('SystemSettingsView', () => {
/>
</AuthContext.Provider>
)
// 测试绑定与生产目标已合并为「知识库映射」:入库目标、封存源、生产目标同屏。
expect(view('sources')).toContain('知识库映射')
expect(view('sources')).toContain('测试知识库绑定')
expect(view('sources')).toContain('生产知识库绑定')
const bound = view('bindings')
expect(bound).toContain('id="settings-routing-bindings"')
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
@@ -429,7 +423,7 @@ describe('SystemSettingsView', () => {
)
const on = view(true, true)
expect(on).toContain('测试 WeKnora')
expect(on).toContain('接口可达 · 执行器未验证')
expect(on).toContain('可达 · 可接单')
expect(on).toContain('延迟 86ms')
expect(on).toContain('已启用 · 可提交生产请求')
expect(on).toContain('生产写入:开启')
@@ -647,43 +641,3 @@ describe('ppSourceConnections(数据源配置的清单规则)', () => {
expect(ppSourceConnections([])).toEqual([])
})
})
// F03 回归:分区保存不能夹带另一分区未保存的草稿。
describe('保存边界(F03)', () => {
const server = {
document_refresh_seconds: 15,
resource_refresh_seconds: 30,
stalled_after_seconds: 1800,
finalizing_after_seconds: 7200,
ingestion_concurrency: 2,
test_weknora_base_url: 'https://server.test',
production_weknora_base_url: 'https://server.prod',
production_tenant_id: '10000',
production_knowledge_base_id: 'kb-server',
} as unknown as UISettings
it('保存刷新策略时忽略服务分区里未保存的地址', () => {
const input = refreshSettingsInput(server, {
documentRefresh: 60,
resourceRefresh: 60,
stalled: 3600,
finalizing: 14400,
concurrency: 4,
})
expect(input.test_weknora_base_url).toBe('https://server.test')
expect(input.production_weknora_base_url).toBe('https://server.prod')
expect(input.document_refresh_seconds).toBe(60)
})
it('保存服务配置时忽略刷新分区里未保存的参数', () => {
const input = serviceSettingsInput(server, {
testEndpoint: 'https://draft.test',
endpoint: 'https://draft.prod',
productionTenantID: '20000',
productionKnowledgeBaseID: 'kb-draft',
})
expect(input.document_refresh_seconds).toBe(15)
expect(input.ingestion_concurrency).toBe(2)
expect(input.test_weknora_base_url).toBe('https://draft.test')
})
})
+63 -155
View File
@@ -12,8 +12,6 @@ import { useOptionalAuth } from './auth'
import { fetchMonitorOverview } from './monitor'
import type { MonitorOverview } from './monitor'
import { fetchReleaseCapabilities } from './reviewRelease'
import { fetchWorkerCapabilities, testUploadLabel } from './systemCapabilities'
import type { WorkerCapabilities } from './systemCapabilities'
import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCatalog'
import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog'
import { archiveSourceConnection, fetchSourceConnectionList } from './sourceConnections'
@@ -37,7 +35,6 @@ interface Props {
productionEnabled: boolean
productionBackupRestoreVerified?: boolean
routingCapabilities: CatalogRoutingCapabilities
workerCapabilities?: WorkerCapabilities | null
loading: boolean
saving: boolean
error: string | null
@@ -45,16 +42,16 @@ interface Props {
onSave: (input: UISettingsCandidateInput) => void
onSourcesChanged: () => void
onRefresh: () => void
// 兼容旧入口:'bindings'/'production-bindings' 已合并为“知识库映射”。
initialSection?: SectionKey | 'bindings' | 'production-bindings'
initialSection?: SectionKey
}
type SectionKey = 'sources' | 'services' | 'knowledge-map' | 'storage' | 'refresh' | 'members'
type SectionKey = 'sources' | 'services' | 'bindings' | 'production-bindings' | 'storage' | 'refresh' | 'members'
const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
{ key: 'sources', label: '数据源配置' },
{ key: 'services', label: '服务配置' },
{ key: 'knowledge-map', label: '知识库映射' },
{ key: 'bindings', label: '测试知识库绑定' },
{ key: 'production-bindings', label: '生产知识库绑定' },
{ key: 'storage', label: '存储与备份' },
{ key: 'refresh', label: '刷新策略' },
{ key: 'members', label: '成员与角色', adminOnly: true },
@@ -78,44 +75,6 @@ const secondsLabel = (value: number) =>
value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时`
export const visibleSaveMessage = (message: string | null, dirty: boolean) => (dirty ? null : message)
// 保存边界是纯函数:服务分区只取服务草稿,刷新分区只取刷新草稿,
// 另一侧一律用服务器当前值。组件与测试共用同一实现。
export interface ServiceDrafts {
testEndpoint: string
endpoint: string
productionTenantID: string
productionKnowledgeBaseID: string
}
export interface RefreshDrafts {
documentRefresh: 15 | 30 | 60
resourceRefresh: 30 | 60
stalled: 1800 | 3600
finalizing: 7200 | 14400
concurrency: number
}
export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts): UISettingsCandidateInput => ({
document_refresh_seconds: settings.document_refresh_seconds,
resource_refresh_seconds: settings.resource_refresh_seconds,
stalled_after_seconds: settings.stalled_after_seconds,
finalizing_after_seconds: settings.finalizing_after_seconds,
ingestion_concurrency: settings.ingestion_concurrency,
test_weknora_base_url: drafts.testEndpoint.trim(),
production_weknora_base_url: drafts.endpoint.trim(),
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,
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,
production_knowledge_base_id: settings.production_knowledge_base_id,
})
type ServiceHealthView = MonitorOverview['health'][number]
type ServiceView = MonitorOverview['services'][number]
@@ -133,14 +92,6 @@ export const healthStateLabel = (health: ServiceHealthView | undefined, service:
if (health.readiness === 'not_applicable') return '未部署'
return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单'
}
// 测试 WeKnora 卡片只证明“接口就绪”:readiness 不覆盖上传/解析执行器,
// 所以不能沿用“可接单”这种承诺式措辞。
export const testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
const label = healthStateLabel(health, service)
return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label
}
export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
if (!health) return service?.detail || '真实 Provider 未接入'
const success = health.last_success_at
@@ -176,7 +127,6 @@ export function SystemSettingsView({
productionEnabled,
productionBackupRestoreVerified = false,
routingCapabilities,
workerCapabilities = null,
loading,
saving,
error,
@@ -187,11 +137,7 @@ export function SystemSettingsView({
}: Props) {
const auth = useOptionalAuth()
const identity = auth?.identity ?? null
const [section, setSection] = useState<SectionKey>(
initialSection === 'bindings' || initialSection === 'production-bindings'
? 'knowledge-map'
: (initialSection as SectionKey)
)
const [section, setSection] = useState<SectionKey>(initialSection)
const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15)
const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30)
const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800)
@@ -237,28 +183,21 @@ export function SystemSettingsView({
productionTenantID.trim() !== settings.production_tenant_id ||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id)
)
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)
)
// 保存边界:服务分区只带上自己这一组的输入,另一组一律用服务器当前值。
// 否则“改了地址没保存、切到刷新策略保存”会把未确认的地址一起写进去。
// 两个分区都有独立草稿;缺 settings 时按钮本就不可点,这里只防一手。
const serviceInput = (): UISettingsCandidateInput =>
settings
? serviceSettingsInput(settings, { testEndpoint, endpoint, productionTenantID, productionKnowledgeBaseID })
: ({} as UISettingsCandidateInput)
const refreshInput = (): UISettingsCandidateInput =>
settings
? refreshSettingsInput(settings, { documentRefresh, resourceRefresh, stalled, finalizing, concurrency })
: ({} as UISettingsCandidateInput)
const candidateInput = (overrides: Partial<UISettingsCandidateInput> = {}): UISettingsCandidateInput => ({
document_refresh_seconds: documentRefresh,
resource_refresh_seconds: resourceRefresh,
stalled_after_seconds: stalled,
finalizing_after_seconds: finalizing,
ingestion_concurrency: concurrency,
test_weknora_base_url: testEndpoint.trim(),
production_weknora_base_url: endpoint.trim(),
production_tenant_id: productionTenantID.trim(),
production_knowledge_base_id: productionKnowledgeBaseID.trim(),
...overrides,
})
const saveEndpoint = () => {
setDirty(false)
onSave(serviceInput())
onSave(candidateInput())
}
return (
<main className="page-shell system-settings">
@@ -272,7 +211,7 @@ export function SystemSettingsView({
{error}
</div>
) : null}
{settings || monitor ? (
{monitor && settings ? (
<div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">
{sections
@@ -319,13 +258,14 @@ export function SystemSettingsView({
<SourceManagementDetails connections={listedConnections} onSourcesChanged={onSourcesChanged} />
</section>
) : null}
{section === 'services' && settings ? (
{section === 'services' ? (
<section className="settings-panel wide" id="settings-services">
<div className="settings-section-heading">
<div>
<h2>服务配置</h2>
<p>
四项可写:测试地址、生产地址、生产租户、生产知识库。保存前会做真实探活与列库核验,凭据只写不读。
只配四项:测试地址、生产地址、生产 ID、知识库
ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。
</p>
</div>
</div>
@@ -333,12 +273,8 @@ export function SystemSettingsView({
<div className="environment-cards">
<article>
<b>测试 WeKnora</b>
<span>{testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
<small className={`worker-capability ${workerCapabilities?.test_upload.state ?? 'unknown'}`}>
{testUploadLabel(workerCapabilities)}
{workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''}
</small>
</article>
<article className="production">
<b>生产 WeKnora</b>
@@ -380,7 +316,7 @@ export function SystemSettingsView({
/>
</label>
<label>
生产租户 ID
生产 ID
<input
value={productionTenantID}
onChange={(event) => {
@@ -433,15 +369,13 @@ export function SystemSettingsView({
>
{saving ? '正在验证并启用…' : '保存并启用服务配置'}
</button>
<details className="settings-details">
<summary>保存规则与核验说明</summary>
<small>
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,
凭据一律走文件引用);生产租户 ID 为十进制数字;知识库 ID 粘贴 URL 不会通过。
保存会生成修订、真实验证后原子启用;端点回答“没有这个知识库”或租户不符会拒收,
端点抖动、鉴权失败或未配置生产凭据只警告不拦。
</small>
</details>
<small>
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 #
片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID
是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 +
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
</small>
{serviceSettingsValid ? null : (
<p className="error-message" role="alert">
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
@@ -459,17 +393,8 @@ export function SystemSettingsView({
)}
</section>
) : null}
{section === 'knowledge-map' ? (
<>
<p className="settings-hint-wide">
一张图看清三件事:<strong>入库目标</strong>(来源打标分发到此库)、
<strong>封存源</strong>(整库封存实际导出的库)、<strong>生产目标</strong>(同步写入的库)。
前两者不一致时,发布页显示的名字与封存出来的内容会对不上。
</p>
<RoutingBindingsSection />
<ProductionBindingsSection />
</>
) : null}
{section === 'bindings' ? <RoutingBindingsSection /> : null}
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
{section === 'storage' ? (
<>
<LibraryStorageSection />
@@ -477,12 +402,12 @@ export function SystemSettingsView({
</>
) : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' && settings ? (
{section === 'refresh' ? (
<section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading">
<div>
<h2>刷新策略</h2>
<p>保存只改这一组参数,不会带上服务配置里未保存的地址。</p>
<p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p>
</div>
<span className="safe-badge">当前活动版本</span>
</div>
@@ -515,7 +440,7 @@ export function SystemSettingsView({
</select>
</label>
<label>
解析停滞阈值
解析停滞判定
<select
value={stalled}
onChange={(event) => {
@@ -528,7 +453,7 @@ export function SystemSettingsView({
</select>
</label>
<label>
收尾超时告警
finalizing 告警
<select
value={finalizing}
onChange={(event) => {
@@ -561,20 +486,17 @@ export function SystemSettingsView({
<button
onClick={() => {
setDirty(false)
onSave(refreshInput())
onSave(candidateInput())
}}
disabled={!canSave || !refreshSettingsDirty}
disabled={!canSave}
>
{saving ? '正在验证并应用…' : '保存刷新与告警参数'}
{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}
</button>
{visibleSaveMessage(saveMessage, dirty) ? (
<p className="success-message" role="status">
{saveMessage}
</p>
) : null}
<p className="settings-warn">
解析停滞阈值保存后由 worker 在 1 分钟内生效;收尾超时告警目前只保存配置,判定尚未接入。
</p>
<small>
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
@@ -601,48 +523,41 @@ export function SystemSettings() {
internal_enabled: false,
external_enabled: false,
})
// 执行器能力单独加载:读不到只是这一行显示未知,不影响其它分区。
const [workerCapabilities, setWorkerCapabilities] = useState<WorkerCapabilities | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [saveMessage, setSaveMessage] = useState<string | null>(null)
const [revision, setRevision] = useState(0)
// 六个请求彼此独立:任何一块失败只影响它自己,不能让成员、备份这些
// 互不相干的入口一起消失。设置本身读不到才阻断“设置”相关分区。
useEffect(() => {
const controller = new AbortController()
const failures: string[] = []
const track = <T,>(promise: Promise<T>, apply: (value: T) => void, label: string) =>
promise
.then((value) => {
if (!controller.signal.aborted) apply(value)
})
.catch((cause) => {
failures.push(`${label}:${cause instanceof Error ? cause.message : '读取失败'}`)
})
setLoading(true)
void Promise.all([
track(fetchCatalogSources(controller.signal), setSources, '数据源'),
track(fetchSourceConnectionList(controller.signal), setConnections, '来源连接'),
track(fetchMonitorOverview(controller.signal), setMonitor, '监控'),
track(
fetchReleaseCapabilities(controller.signal),
(capabilities) => {
fetchCatalogSources(controller.signal),
fetchSourceConnectionList(controller.signal),
fetchMonitorOverview(controller.signal),
fetchReleaseCapabilities(controller.signal),
fetchCatalogRoutingCapabilities(controller.signal),
fetchActiveUISettings(controller.signal),
])
.then(([nextSources, nextConnections, overview, capabilities, routing, active]) => {
if (!controller.signal.aborted) {
setSources(nextSources)
setConnections(nextConnections)
setMonitor(overview)
setProductionEnabled(capabilities.production_release_requests_enabled)
setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified)
},
'发布能力'
),
track(fetchCatalogRoutingCapabilities(controller.signal), setRoutingCapabilities, '路由能力'),
track(fetchWorkerCapabilities(controller.signal), setWorkerCapabilities, '执行器能力'),
track(fetchActiveUISettings(controller.signal), setSettings, '系统设置'),
]).finally(() => {
if (controller.signal.aborted) return
setError(failures.length ? failures.join(';') : null)
setLoading(false)
})
setRoutingCapabilities(routing)
setSettings(active)
setError(null)
}
})
.catch((cause) => {
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败')
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [revision])
@@ -656,12 +571,6 @@ export function SystemSettings() {
const active = activated.settings
const verification = activated.verification ?? candidate.verification
setSettings(active)
// 保存成功后重新探测一次,卡片上的“最近检查”才不会停在旧结果。
try {
setMonitor(await fetchMonitorOverview())
} catch {
// 探测失败不影响保存结果,页面保留上一次观测。
}
setSaveMessage(
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
)
@@ -684,7 +593,6 @@ export function SystemSettings() {
productionEnabled={productionEnabled}
productionBackupRestoreVerified={productionBackupRestoreVerified}
routingCapabilities={routingCapabilities}
workerCapabilities={workerCapabilities}
loading={loading}
saving={saving}
error={error}
+35 -31
View File
@@ -43,27 +43,29 @@ describe('monitor API', () => {
expect((await fetchMonitorOverview()).simulated).toBe(true)
})
it('filters files by real WeKnora status contract', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
items: [
{
name: '[模拟] 文件.pdf',
directory: '02 产品资料',
visibility: 'internal',
status: 'finalizing',
stage_detail: 'Wiki生成中',
elapsed_seconds: 120,
error_code: '',
},
],
total: 1,
limit: 20,
offset: 0,
sample_only: true,
})
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
items: [
{
name: '[模拟] 文件.pdf',
directory: '02 产品资料',
visibility: 'internal',
status: 'finalizing',
stage_detail: 'Wiki生成中',
elapsed_seconds: 120,
error_code: '',
},
],
total: 1,
limit: 20,
offset: 0,
sample_only: true,
})
)
)
)
vi.stubGlobal('fetch', fetchMock)
const page = await fetchMonitorFiles('kb-sim', 'finalizing', 20, 0)
expect(page.sample_only).toBe(true)
@@ -112,18 +114,20 @@ describe('monitor API', () => {
it('rejects metrics without a worker source or with a fake zero rate', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
observed_at: '',
queue: { pending: 0 },
short_window: { window_seconds: 3600 },
long_window: { window_seconds: 86400 },
},
})
vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
observed_at: '',
queue: { pending: 0 },
short_window: { window_seconds: 3600 },
long_window: { window_seconds: 86400 },
},
})
)
)
)
)
await expect(fetchRunMetrics()).rejects.toThrow()
})
+13 -11
View File
@@ -67,18 +67,20 @@ describe('production bindings API', () => {
it('reports an unverified save honestly instead of pretending it was checked', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
...binding,
production_connected: false,
production_message: '生产 WeKnora 不可用:dial tcp: timeout',
},
}),
{ status: 200 }
vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
...binding,
production_connected: false,
production_message: '生产 WeKnora 不可用:dial tcp: timeout',
},
}),
{ status: 200 }
)
)
)
)
const result = await saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })
expect(result.production_connected).toBe(false)
+85 -64
View File
@@ -712,79 +712,100 @@
padding: 8px;
}
/* 发布管理精简版:一个状态卡 + 一个主按钮,其余收进折叠区。 */
.rel-status {
display: grid;
gap: 14px;
padding: 18px 20px;
/* 主流程保持展开;诊断共享一组轻量折叠行,避免面板套面板。 */
.rel-disclosure {
min-width: 0;
border: 1px solid var(--rel-line);
border-radius: 8px;
background: #fff;
}
.rel-status-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 14px;
margin: 0;
}
.rel-status-grid div {
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 12px;
background: var(--card);
}
.rel-status-grid dt {
font-size: 12px;
color: var(--muted-foreground);
margin-bottom: 4px;
}
.rel-status-grid dd {
margin: 0;
.rel-disclosure > summary {
padding: 13px 16px;
color: var(--rel-ink);
font-size: 14px;
font-weight: 600;
font-size: 15px;
word-break: break-all;
cursor: pointer;
overflow-wrap: anywhere;
}
.rel-status-grid small {
display: block;
margin-top: 4px;
color: var(--muted-foreground);
.rel-disclosure > summary > span {
margin-left: 12px;
color: #586c7b;
font-size: 12px;
font-weight: 400;
}
.rel-status-actions {
.rel-disclosure[open] > summary {
border-bottom: 1px solid var(--rel-line);
}
.rel-disclosure > .rel-panel {
border: 0;
border-radius: 0;
background: transparent;
overflow-x: auto;
}
.rel-integrity {
margin-top: 12px;
background: #f8fbfa;
}
.rel-integrity .rel-checklist {
margin: 0;
background: transparent;
}
.rel-next-step {
margin: 14px 0 0;
color: #41596b;
font-size: 13px;
line-height: 1.6;
}
.release-targets .rel-primary:disabled {
background: #e9eef1 !important;
border-color: #d6e2e8 !important;
color: #657786 !important;
opacity: 1;
box-shadow: none;
}
.release-targets button:focus-visible,
.rel-disclosure > summary:focus-visible {
outline: 2px solid var(--rel-teal);
outline-offset: 3px;
}
.rel-metrics {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
gap: 12px 24px;
padding: 12px 0;
border-bottom: 1px solid var(--rel-line);
}
.rel-next {
flex: 1 1 320px;
.rel-metrics div {
display: flex;
align-items: baseline;
gap: 8px;
border: 0;
padding: 0;
}
.rel-metrics dd {
margin: 0;
color: var(--muted-foreground);
font-size: 13px;
font-size: 16px;
}
.rel-next span {
display: inline-block;
margin-right: 8px;
padding: 1px 8px;
border-radius: 999px;
background: var(--accent);
color: var(--foreground);
font-size: 12px;
@media (max-width: 640px) {
.release-targets {
padding: 16px 12px 24px;
}
.rel-panel {
padding: 16px;
}
.rel-tab {
width: 100%;
}
.rel-disclosure > summary > span {
display: block;
margin: 6px 0 0 16px;
}
.rel-maintenance-rows {
grid-template-columns: 1fr;
}
}
.rel-check,
.rel-advanced {
border: 1px solid var(--border);
border-radius: 12px;
padding: 4px 16px 12px;
background: var(--card);
}
.rel-check summary,
.rel-advanced summary {
cursor: pointer;
padding: 10px 0;
font-weight: 600;
}
.rel-check .rel-gate,
.rel-check .rel-checklist {
margin: 6px 0 10px;
}
.rel-advanced > * + * {
margin-top: 10px;
@media (prefers-reduced-motion: reduce) {
.release-targets * {
scroll-behavior: auto !important;
}
}
+42 -32
View File
@@ -400,20 +400,22 @@ describe('release change set (R1)', () => {
await expect(generateReleaseChangeSet('x')).rejects.toThrow('发布计划集响应缺少标识或清单摘要')
})
it('confirms via scoped endpoint and loads latest detail tolerating 404', async () => {
const confirmMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
...changeSetPayload,
state: 'confirmed',
confirmed_by: 'boss',
confirmed_at: '2026-09-12T08:00:00Z',
},
operation: 'created',
}),
{ status: 200 }
const confirmMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
...changeSetPayload,
state: 'confirmed',
confirmed_by: 'boss',
confirmed_at: '2026-09-12T08:00:00Z',
},
operation: 'created',
}),
{ status: 200 }
)
)
)
vi.stubGlobal('fetch', confirmMock)
const confirmed = await confirmReleaseChangeSet('rcs-1')
expect(confirmed.state).toBe('confirmed')
@@ -617,10 +619,12 @@ describe('审核策略的只读展示', () => {
describe('批量审核与建批即锁定', () => {
it('批量审核发送选中的条目与同一决定', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }),
})
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }),
})
vi.stubGlobal('fetch', fetchMock)
const result = await reviewPublicationsBatch(['tp-a', 'tp-b'], 'approved', 'internal', 'approved_for_release')
expect(result).toEqual({ selected: 2, decided: 2, skipped: 0, skipped_ids: [] })
@@ -635,10 +639,12 @@ describe('批量审核与建批即锁定', () => {
})
it('如实回报被跳过的条目', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }),
})
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }),
})
vi.stubGlobal('fetch', fetchMock)
const result = await reviewPublicationsBatch(
['tp-a', 'tp-b', 'tp-c'],
@@ -663,12 +669,14 @@ describe('批量审核与建批即锁定', () => {
describe('发布到生产(建批+锁定+授权合成一个动作)', () => {
it('提交条目与固定确认语句,回传批次与执行', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } },
}),
})
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: true,
json: async () => ({
data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } },
}),
})
vi.stubGlobal('fetch', fetchMock)
const result = await runPublishNow(['tp-a', 'tp-b'], [], '立即发布 · 2026/10/10', 'publish-to-production')
expect(result).toEqual({ batch_id: 'rb-now', batch_name: '立即发布 · 2026/10/10', execution_id: 'rx-now' })
@@ -683,11 +691,13 @@ describe('发布到生产(建批+锁定+授权合成一个动作)', () => {
})
it('服务端拒绝时把原因带出来', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 412,
json: async () => ({ error: 'production backup restore verification is required' }),
})
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: false,
status: 412,
json: async () => ({ error: 'production backup restore verification is required' }),
})
vi.stubGlobal('fetch', fetchMock)
await expect(runPublishNow(['tp-a'], [], 'x', 'publish-to-production')).rejects.toThrow(
'production backup restore verification is required'
-17
View File
@@ -14,11 +14,6 @@ export interface RoutingBindings {
// 本次保存把多少条「还没上传」的待入库项重新指向了新库(读取时为 0)。
replanned: number
retired_duplicates: number
// 整库封存源与“测试入库绑定”是两套配置:这里给出封存源 ID 与一致性判定。
library_source_internal_kb: string
library_source_external_kb: string
internal_source_state: 'consistent' | 'mismatch' | 'unconfigured'
external_source_state: 'consistent' | 'mismatch' | 'unconfigured'
}
export interface KnowledgeBaseOption {
@@ -43,18 +38,6 @@ function bindingProjection(item: Record<string, unknown>): RoutingBindings {
updated_by: typeof item.updated_by === 'string' ? item.updated_by : '',
weknora_connected: item.weknora_connected === true,
replanned: typeof item.replanned === 'number' ? item.replanned : 0,
library_source_internal_kb:
typeof item.library_source_internal_kb === 'string' ? item.library_source_internal_kb : '',
library_source_external_kb:
typeof item.library_source_external_kb === 'string' ? item.library_source_external_kb : '',
internal_source_state:
item.internal_source_state === 'consistent' || item.internal_source_state === 'mismatch'
? item.internal_source_state
: 'unconfigured',
external_source_state:
item.external_source_state === 'consistent' || item.external_source_state === 'mismatch'
? item.external_source_state
: 'unconfigured',
retired_duplicates: typeof item.retired_duplicates === 'number' ? item.retired_duplicates : 0,
}
}
+33 -29
View File
@@ -5,24 +5,26 @@ afterEach(() => vi.unstubAllGlobals())
describe('scope rule API', () => {
it('lists rules for exactly one configured connection', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
target_type: 'directory',
connection_id: 'conn-1',
directory_path: '产品',
visibility: 'internal',
updated_by: 'engineer',
reason: '内部资料',
updated_at: '2026-09-08T00:00:00Z',
},
],
summary: { total: 1 },
})
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
target_type: 'directory',
connection_id: 'conn-1',
directory_path: '产品',
visibility: 'internal',
updated_by: 'engineer',
reason: '内部资料',
updated_at: '2026-09-08T00:00:00Z',
},
],
summary: { total: 1 },
})
)
)
)
vi.stubGlobal('fetch', fetchMock)
const rules = await fetchScopeRules('conn-1')
expect(rules).toHaveLength(1)
@@ -32,20 +34,22 @@ describe('scope rule API', () => {
)
})
it('sets and clears rules with explicit audited payloads', async () => {
const fetchMock = vi.fn().mockImplementation(() =>
Promise.resolve(
new Response(
JSON.stringify({
data: {
target_type: 'directory',
connection_id: 'conn-1',
directory_path: '产品',
visibility: 'internal',
},
})
const fetchMock = vi
.fn()
.mockImplementation(() =>
Promise.resolve(
new Response(
JSON.stringify({
data: {
target_type: 'directory',
connection_id: 'conn-1',
directory_path: '产品',
visibility: 'internal',
},
})
)
)
)
)
vi.stubGlobal('fetch', fetchMock)
const target = {
target_type: 'directory' as const,
+93 -85
View File
@@ -59,53 +59,57 @@ describe('source catalog API', () => {
})
it('rejects a scanning source without progress instead of rendering a fake 0%', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
connection_id: 'conn-scan',
source_type: 'dingtalk',
name: 'X',
root_node_id: '',
folder_count: 0,
file_count: 0,
observed_at: '2026-10-10T08:51:44Z',
snapshot_only: true,
snapshot_status: 'scanning',
last_refresh_duration_ms: 0,
},
],
summary: { total: 1 },
})
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
connection_id: 'conn-scan',
source_type: 'dingtalk',
name: 'X',
root_node_id: '',
folder_count: 0,
file_count: 0,
observed_at: '2026-10-10T08:51:44Z',
snapshot_only: true,
snapshot_status: 'scanning',
last_refresh_duration_ms: 0,
},
],
summary: { total: 1 },
})
)
)
)
vi.stubGlobal('fetch', fetchMock)
await expect(fetchCatalogSources()).rejects.toThrow(/来源目录响应无效/)
})
it('loads safe source roots', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
connection_id: 'conn-1',
source_type: 'dingtalk',
name: '公司级技术支持知识库',
root_node_id: 'root-1',
folder_count: 8,
file_count: 3468,
observed_at: '2026-09-08T00:00:00Z',
snapshot_only: true,
snapshot_status: 'ready',
last_refresh_duration_ms: 12000,
secret: 'drop',
},
],
summary: { total: 1 },
})
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
connection_id: 'conn-1',
source_type: 'dingtalk',
name: '公司级技术支持知识库',
root_node_id: 'root-1',
folder_count: 8,
file_count: 3468,
observed_at: '2026-09-08T00:00:00Z',
snapshot_only: true,
snapshot_status: 'ready',
last_refresh_duration_ms: 12000,
secret: 'drop',
},
],
summary: { total: 1 },
})
)
)
)
vi.stubGlobal('fetch', fetchMock)
const sources = await fetchCatalogSources()
expect(sources[0].name).toBe('公司级技术支持知识库')
@@ -244,20 +248,22 @@ describe('source catalog API', () => {
expect(fetchMock.mock.calls[1][1].headers['Idempotency-Key']).not.toBe('')
})
it('reports blocked items without planning anything', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
selected_files: 2,
intents_recorded: 2,
fetch_queued: 0,
planned_publications: 0,
blocked_items: 2,
unbound_files: 0,
},
})
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
selected_files: 2,
intents_recorded: 2,
fetch_queued: 0,
planned_publications: 0,
blocked_items: 2,
unbound_files: 0,
},
})
)
)
)
vi.stubGlobal('fetch', fetchMock)
const result = await routeCatalogFiles({
connection_id: 'conn-1',
@@ -295,38 +301,40 @@ describe('source catalog API', () => {
expect(JSON.stringify(result.payload)).not.toContain('token')
})
it('loads the latest persisted snapshot change set without internal hashes', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
id: 'cs-1',
connection_id: 'conn-1',
source_name: '国内工业',
state: 'planned',
add_count: 2,
update_count: 1,
move_count: 0,
move_scope_count: 1,
delete_count: 1,
no_change_count: 10,
created_at: '2026-09-10T00:00:00Z',
items: [
{
action: 'delete',
title: '旧手册.pdf',
old_path: '旧目录/旧手册.pdf',
reason_code: 'source_missing',
seq: 7,
},
],
total: 1,
limit: 20,
offset: 0,
source_locator_hash: 'drop',
},
})
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
id: 'cs-1',
connection_id: 'conn-1',
source_name: '国内工业',
state: 'planned',
add_count: 2,
update_count: 1,
move_count: 0,
move_scope_count: 1,
delete_count: 1,
no_change_count: 10,
created_at: '2026-09-10T00:00:00Z',
items: [
{
action: 'delete',
title: '旧手册.pdf',
old_path: '旧目录/旧手册.pdf',
reason_code: 'source_missing',
seq: 7,
},
],
total: 1,
limit: 20,
offset: 0,
source_locator_hash: 'drop',
},
})
)
)
)
vi.stubGlobal('fetch', fetchMock)
const result = await fetchLatestCatalogChangeSet('conn-1', 'delete', 20, 0)
expect(result.add_count).toBe(2)
-56
View File
@@ -1,56 +0,0 @@
// Worker 能力心跳:页面的“执行器能力”只信 worker 自己上报的记录。
export interface WorkerCapability {
worker_id: string
job_types: string[]
alive: boolean
last_seen_at: string
}
export interface WorkerCapabilities {
test_upload: { state: 'enabled' | 'disabled' | 'stale' | 'unknown'; consumers: number; detail: string }
workers: WorkerCapability[]
}
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
export async function fetchWorkerCapabilities(signal?: AbortSignal): Promise<WorkerCapabilities> {
const response = await fetch('/api/v1/system/worker-capabilities', { credentials: 'include', signal })
if (!response.ok) throw new Error(`读取执行器能力失败(${response.status})`)
const body = (await response.json()) as { data?: unknown }
const data = record(body.data) ? body.data : {}
const upload = record(data.test_upload) ? data.test_upload : {}
const state = upload.state
const workers = Array.isArray(data.workers)
? data.workers.filter(record).map((item) => ({
worker_id: typeof item.worker_id === 'string' ? item.worker_id : '',
job_types: Array.isArray(item.job_types)
? item.job_types.filter((t): t is string => typeof t === 'string')
: [],
alive: item.alive === true,
last_seen_at: typeof item.last_seen_at === 'string' ? item.last_seen_at : '',
}))
: []
return {
test_upload: {
state: state === 'enabled' || state === 'disabled' || state === 'stale' ? state : 'unknown',
consumers: typeof upload.consumers === 'number' ? upload.consumers : 0,
detail: typeof upload.detail === 'string' ? upload.detail : '能力心跳不可用',
},
workers,
}
}
export const testUploadLabel = (capabilities: WorkerCapabilities | null): string => {
if (!capabilities) return '执行器:未知'
switch (capabilities.test_upload.state) {
case 'enabled':
return `执行器:已启用(${capabilities.test_upload.consumers} 个 worker)`
case 'disabled':
return '执行器:已停用(不会消费上传/解析)'
case 'stale':
return '执行器:无心跳(worker 未运行)'
default:
return '执行器:未知'
}
}
-25
View File
@@ -882,28 +882,3 @@ button.link {
font-size: 0.8rem;
line-height: 1.5;
}
.settings-warn {
margin: 8px 0 0;
color: #b45309;
font-size: 12px;
}
.member-reset-dialog {
margin-top: 16px;
border: 1px solid var(--border);
border-radius: 12px;
padding: 14px 16px;
background: var(--card);
display: grid;
gap: 8px;
}
.member-reset-dialog h3 {
margin: 0;
font-size: 15px;
}
.member-reset-dialog p {
margin: 0;
color: var(--muted-foreground);
font-size: 12px;
}
+14 -10
View File
@@ -127,11 +127,13 @@ describe('需下架条目的移除入口', () => {
})
it('带幂等键触发下架并回传任务号', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ publication_id: 'tp-1', job_id: 'job-remove-1', state: 'disabling' }), {
status: 202,
})
)
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ publication_id: 'tp-1', job_id: 'job-remove-1', state: 'disabling' }), {
status: 202,
})
)
vi.stubGlobal('fetch', fetchMock)
await expect(startPublicationRemoval('tp-1')).resolves.toEqual({ job_id: 'job-remove-1' })
@@ -153,11 +155,13 @@ describe('需下架条目的移除入口', () => {
describe('startTestPublications', () => {
it('starts only the explicitly confirmed processing plans', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ data: { selected: 2, started: 1, already_started: 1, unavailable: 0 } }), {
status: 202,
})
)
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ data: { selected: 2, started: 1, already_started: 1, unavailable: 0 } }), {
status: 202,
})
)
vi.stubGlobal('fetch', fetchMock)
await expect(startTestPublications(['pub-a', 'pub-b'], '已核对差异')).resolves.toEqual({
+8 -6
View File
@@ -205,13 +205,15 @@ describe('UI settings API', () => {
}
vi.stubGlobal(
'fetch',
vi.fn().mockImplementation(() =>
Promise.resolve(
new Response(JSON.stringify({ error: '未通过:生产地址上找不到知识库 ID「kb-prod-1」', verification }), {
status: 400,
})
vi
.fn()
.mockImplementation(() =>
Promise.resolve(
new Response(JSON.stringify({ error: '未通过:生产地址上找不到知识库 ID「kb-prod-1」', verification }), {
status: 400,
})
)
)
)
)
await expect(createUISettingsCandidate(candidateInput)).rejects.toThrow('找不到知识库 ID')
const failure = await createUISettingsCandidate(candidateInput).catch((cause: unknown) => cause)