Compare commits

...

6 Commits

Author SHA1 Message Date
dev 6c10f71c28 fix(settings): 数据源显示上次更新/下次计划;归档注记统一术语
build / build (push) Successful in 1m54s
2026-11-17 16:14:05 +08:00
dev cf65d3f363 fix(settings): 生产凭据缺失说明准确化;存储页保留策略收进折叠并统一术语
build / build (push) Successful in 1m49s
2026-11-17 16:08:54 +08:00
dev 8e6094e9e5 feat(settings): worker 能力心跳读取 + 封存源对照 + 知识库映射合并
build / build (push) Successful in 2m6s
F01:新增 /api/v1/system/worker-capabilities,按 job_types 判定 test.upload 执行器是否注册,
服务卡片分「地址可达 / 凭据与库读取 / 执行器能力」三行。
F04:routing-bindings 返回 LIBRARY_SOURCE_KB_* 与一致性,设置页同屏显示入库目标与封存源。
结构:测试绑定与生产目标合并为「知识库映射」。
2026-11-17 16:04:00 +08:00
dev 33afdb9f11 test(web): 保存边界回归(F03):分区提交载荷互不夹带
build / build (push) Successful in 1m51s
2026-11-17 15:34:31 +08:00
dev 8a574903a1 fix(web): 测试 WeKnora 卡片不承诺可接单,技术说明折叠
build / build (push) Successful in 1m49s
2026-11-17 15:30:13 +08:00
dev 0fb78cfe26 feat(web): 发布管理界面精简 + 系统设置审查修复
build / build (push) Successful in 1m51s
发布管理:状态卡 + 一个主按钮,准备动作与检查项分层次收纳,去掉重复入口。
系统设置:F02 停滞阈值接入活动配置;F03 分区保存边界;F05/F06 生产绑定分层与凭据说明;
F07 备份未接主机/未知证据如实显示;F09 分区独立加载与保存后重探;F10 文案精简;F11 重置密码对话框。
2026-11-17 15:23:29 +08:00
33 changed files with 1338 additions and 603 deletions
+31
View File
@@ -1,5 +1,36 @@
# Changelog
## 开发快照 0.1.384(系统设置审查修复:能力心跳、封存源对照、分区合并)
### Added
- `GET /api/v1/system/worker-capabilities`:读取 worker 认领记录里的 job_types,
页面据此显示“执行器已启用/已停用/无认领”,不再把 readiness 当成可接单。
- 测试知识库绑定接口返回整库封存源与一致性状态,设置页同屏对照“入库目标 / 封存源”。
### Changed
- 系统设置分区合并为“知识库映射”(测试入库 + 生产目标 + 封存源对照)。
- 服务卡片分三行:地址可达、凭据与库读取、执行器能力。
## 开发快照 0.1.383(发布管理精简 + 系统设置审查修复)
### Changed
- 发布管理:顶部改为「状态卡 + 下一步」,一个主按钮(启动同步/查看任务)+ 一个准备按钮
(封存/基线/签发授权);启动条件、检查清单、恢复验证收进「发布前检查」;
目标维护、差异明细、来源身份收进「高级与历史」。去掉重复的版本入口与说明。
### Fixed
- 服务配置与刷新策略各自保存边界:保存一方不再夹带另一方未保存的草稿(F03)。
- 系统设置分区独立加载:监控/目录失败不再挡住成员与备份入口;保存后重新探测服务状态(F09)。
- 解析停滞阈值接入活动配置(worker 60 秒内生效),收尾超时仍只保存并在页面标注未接入(F02)。
- 重置密码改为受控遮罩对话框,不再用浏览器 prompt(F11)。
- 生产绑定:文档级旧配置收进折叠区,凭据缺失时说明不影响整库执行器(F05/F06)。
- 备份:主机未接通时明确「当前计划不会执行」,无运行记录时失败库显示未知(F07)。
- 文案统一:生产租户 ID、备份执行主机、收尾超时告警;技术细节不再占据主视图(F10)。
## 开发快照 0.1.382(采集 agent 允许显式 peer uid)
### Added
+20
View File
@@ -3434,6 +3434,26 @@
}
}
},
"/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,6 +10,7 @@ import (
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
@@ -561,6 +562,11 @@ 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)
@@ -592,3 +598,29 @@ 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
}
+23 -1
View File
@@ -41,6 +41,24 @@ 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 {
@@ -101,7 +119,11 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
UpdatedBy: updatedBy, WeKnoraConnected: connected,
LibrarySourceInternalKB: config.LibrarySourceInternalKB,
LibrarySourceExternalKB: config.LibrarySourceExternalKB,
InternalSourceState: sourceState(internal, config.LibrarySourceInternalKB),
ExternalSourceState: sourceState(external, config.LibrarySourceExternalKB),
UpdatedBy: updatedBy, WeKnoraConnected: connected,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
}
+3
View File
@@ -377,6 +377,9 @@ 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
@@ -0,0 +1,91 @@
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,
}})
}
@@ -0,0 +1,35 @@
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)
}
}
}
@@ -0,0 +1,40 @@
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()
}
+15 -4
View File
@@ -35,7 +35,9 @@ type PollHandlerConfig struct {
Client PollClient
PollDelay time.Duration
StallAfter time.Duration
Now func() time.Time
// StallAfterSource 可选:返回当前生效的停滞阈值(来自活动 UI 配置)。
StallAfterSource func() time.Duration
Now func() time.Time
}
type PollHandler struct {
@@ -43,7 +45,10 @@ type PollHandler struct {
client PollClient
pollDelay time.Duration
stallAfter time.Duration
now func() time.Time
// stallAfterSource 存在时优先于 stallAfter:页面保存的“解析停滞阈值”
// 必须真的决定判定,而不是只写进数据库。
stallAfterSource func() time.Duration
now func() time.Time
}
type pollPayload struct {
@@ -60,7 +65,7 @@ func NewPollHandler(config PollHandlerConfig) (*PollHandler, error) {
}
return &PollHandler{
store: config.Store, client: config.Client, pollDelay: config.PollDelay,
stallAfter: config.StallAfter, now: config.Now,
stallAfter: config.StallAfter, stallAfterSource: config.StallAfterSource, now: config.Now,
}, nil
}
@@ -103,7 +108,13 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
}
return nil
}
cutoff := now.Add(-handler.stallAfter)
stall := handler.stallAfter
if handler.stallAfterSource != nil {
if fromSettings := handler.stallAfterSource(); fromSettings > 0 {
stall = fromSettings
}
}
cutoff := now.Add(-stall)
lastProgress := publication.LastProgressAt
if lastProgress == nil {
lastProgress = publication.ProcessingStartedAt
@@ -186,3 +186,61 @@ 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
+1 -1
View File
@@ -81,7 +81,7 @@ describe('BackupScheduleView', () => {
const html = view()
for (const text of [
'存储与备份',
'目标库所在主机',
'备份执行主机',
'定时时间',
'储存天数',
'每月归档保留',
+14 -6
View File
@@ -104,7 +104,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<div>
<h2>存储与备份</h2>
<p>
整库逻辑备份(pg_dump 目录格式)在<strong>目标库所在主机</strong>
整库逻辑备份(pg_dump 目录格式)在<strong>备份执行主机</strong>(同 VPC 直连 RDS)
上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。
</p>
</div>
@@ -136,9 +136,11 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<dd>
{schedule.host_next_run
? schedule.host_next_run
: schedule.host_schedule_enabled
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
: '未启用定时或未从主机读到计划'}
: !schedule.host_configured
? '未接通备份执行主机:当前计划不会执行'
: schedule.host_schedule_enabled
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
: '未启用定时或未从主机读到计划'}
</dd>
<dt>最近一次运行</dt>
<dd>
@@ -163,7 +165,13 @@ 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('、') : '无'}</dd>
<dd>
{schedule.last_run_failed_databases.length
? schedule.last_run_failed_databases.join('、')
: schedule.last_run_stamp
? '无'
: '未知(还没有读到运行记录,不能据此判断没有失败)'}
</dd>
<dt>主机上生效的计划</dt>
<dd>
{schedule.host_schedule_enabled
@@ -268,7 +276,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
)
}
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是备份执行主机(同 VPC 直连 RDS)。
export function BackupScheduleSection() {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
+72 -68
View File
@@ -89,78 +89,82 @@ export function LibraryStorageSection() {
)}
</div>
<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) => (
<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) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
{formatBytes(item.exclusive_bytes)}
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
</li>
))}
</ul>
</>
) : (
<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>
) : null}
</div>
<ul className="library-storage-limits">
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
<li>实际删除需要单独授权,本页只给预览</li>
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
{data.notes.map((note) => (
<li key={note}>{note}</li>
))}
</ul>
<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>
)
) : (
<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>
</>
) : null}
</section>
+46 -9
View File
@@ -23,6 +23,9 @@ 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: '',
@@ -154,15 +157,8 @@ export function MembersSection() {
className="secondary-action"
disabled={busy === user.id}
onClick={() => {
const temporary = window.prompt(
`为 ${user.username} 生成一个临时密码(至少 8 位,对方首次登录必须更换)`
)
if (temporary)
void run(
user.id,
() => resetManagedUserPassword(user.id, temporary),
`${user.username} 的临时密码已生效`
)
setResetTarget({ id: user.id, username: user.username })
setResetValue('')
}}
>
重置密码
@@ -238,6 +234,47 @@ 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('发布写入此库')
})
+17 -14
View File
@@ -103,7 +103,9 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
</div>
{error ? (
<p className="error-message" role="alert">
{error}
{/api key file/i.test(error)
? '生产 API 读取凭据未配置:无法在此列出生产知识库。整库同步走独立执行器通道,不受这条读取凭据影响。'
: error}
</p>
) : null}
{bindings ? (
@@ -133,19 +135,24 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
</div>
) : null}
{bindings ? (
<div className="stack">
<h3>{bindings.legacy_scope || '文档级绑定(旧路径)'}</h3>
<p className="hint">仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。</p>
<details className="stack legacy-bindings">
<summary>
{bindings.legacy_scope || '文档级发布(单篇文档写生产)· 旧路径'}
<span className="hint"> · 展开编辑;整库封存/同步/恢复不读取这组配置</span>
</summary>
<div className="kb-binding-grid">
{renderSide('对内文档级目标', bindings.internal_kb_id, bindings.internal_kb_name)}
{renderSide('对外文档级目标', bindings.external_kb_id, bindings.external_kb_name)}
</div>
</div>
</details>
) : null}
{bindings && !bindings.production_connected ? (
<p className="hint">
生产端核对不可用:{bindings.production_message}。
{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}
生产端核对不可用:
{/api key file/i.test(bindings.production_message)
? '生产 API 读取凭据未配置(不影响整库执行器;整库同步走独立数据库/索引/存储通道)'
: bindings.production_message}
。{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}
</p>
) : null}
{bindings && bindings.production_connected && bindings.production_base_url ? (
@@ -156,12 +163,8 @@ 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}
@@ -259,4 +262,4 @@ export function ProductionBindingsSection() {
onReload={() => void load()}
/>
)
}
}
+203 -175
View File
@@ -958,39 +958,15 @@ function ProtectionCard({
<dt>恢复条件</dt>
<dd>{gate.reasons.length === 0 ? '已满足' : `缺 ${gate.reasons.length} 项`}</dd>
</dl>
<RestoreVerificationSection
scope={scope}
isAdmin={sync.canSign}
onAccepted={verification.onAccepted}
onComplete={verification.onComplete}
/>
{gate.reasons.length > 0 ? (
<ul className="rel-gate" aria-label="恢复与启动条件">
{gate.reasons.map((reason) => (
<li key={reason}>{reason}</li>
))}
</ul>
) : null}
<div className="rel-drawer-actions">
{sync.canSign && authorization.state !== 'active' && targetSealed ? (
<button type="button" className="rel-secondary" onClick={sync.onGrant} disabled={sync.pendingGrant}>
{sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)'}
</button>
) : null}
{baseline.canStart && baselineNeeded ? (
<button type="button" className="rel-secondary" onClick={baseline.onStart} disabled={baseline.pending}>
{baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)'}
</button>
) : null}
</div>
<p className="rel-hint">
{gate.reasons.length > 0
? `启动与恢复条件还有 ${gate.reasons.length} 项未满足,见上方“发布前检查”。`
: '启动与恢复条件已满足。'}
</p>
{authorization.state !== 'active' && !sync.canSign ? (
<p className="rel-hint">同步授权只能由管理员按目标+快照签发;工程师看不到签发入口。</p>
) : null}
<p className="rel-hint">同步启动后,这里显示本次生产恢复点及备份进度,可直接查看对应快照。</p>
<button type="button" className="rel-secondary" onClick={onOpen}>
查看已有版本与快照 ›
</button>
<p className="rel-warn">恢复版本会恢复一整套生产知识状态,不回退测试知识库。</p>
<p className="rel-warn">恢复会回退整套生产知识状态,不回退测试知识库。</p>
</aside>
)
}
@@ -1040,7 +1016,6 @@ function ReadyBody({
return (
<>
<div className="rel-grid">
<ChangeTable diff={diff} />
<ProtectionCard
production={production}
productionNote={productionNote}
@@ -1077,18 +1052,7 @@ function ReadyBody({
: '还没有测试库封存。封存会短暂停住测试写入者,导出完整版本后恢复。'}
</p>
</div>
{canCapture ? (
<button
type="button"
className="rel-secondary"
onClick={onCapture}
disabled={pendingCapture || Boolean(view.activeJob)}
>
{pendingCapture ? '投递中…' : '封存测试版本'}
</button>
) : (
<span className="rel-hint">{captureHint(view, canWrite)}</span>
)}
<span className="rel-hint">{canCapture ? '封存入口在页面顶部“下一步”。' : captureHint(view, canWrite)}</span>
</div>
</>
)
@@ -1918,17 +1882,69 @@ export function ReleaseTargetsView(props: ViewProps) {
const gate = view.overview?.gate ?? { sync_allowed: false, reasons: ['整库状态接口不可用'] }
const authorization = view.overview?.authorization ?? { state: 'none' as const, reason: '整库状态接口不可用' }
const sealed = Boolean(view.snapshot)
const authorizationActive = authorization.state === 'active'
// 主按钮永远是"同步"或"查看当前任务";准备动作(封存/基线/恢复验证/授权)
// 作为次要按钮按状态出现,页面因此只有一个前进方向。
const primaryAction = runningJob
? {
label: '查看当前任务',
hint: `${jobKindText(runningJob.kind)}正在执行,不要重复启动。`,
disabled: false,
run: () => document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }),
}
: {
label: sync.pending ? '投递中…' : '▶ 启动同步',
hint: sync.canStart
? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。'
: `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`,
disabled: !sync.canStart || sync.pending,
run: sync.onStart,
}
const prepAction = !sealed
? canCapture
? {
label: pendingCapture ? '封存中…' : '封存测试版本',
hint: '只读导出测试库,生成一份可发布的整库版本。',
disabled: pendingCapture,
run: onCapture,
}
: { label: '尚无封存', hint: captureHint(view, canWrite), disabled: true, run: () => {} }
: productionClass === 'nonempty' && baseline.canStart
? {
label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)',
hint: '生产目标非空但还没有权威版本,先登记一份基线。',
disabled: baseline.pending,
run: baseline.onStart,
}
: !authorizationActive && sync.canSign
? {
label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)',
hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。',
disabled: sync.pendingGrant,
run: sync.onGrant,
}
: null
const productionText =
productionClass === 'known' && production?.version
? production.version.version_label || `生效 ${production.version.snapshot_id.slice(0, 12)}`
: productionClass === 'empty'
? '目标已读且为空'
: productionClass === 'unreachable'
? '读取失败'
: productionClass === 'nonempty'
? '目标非空,尚无权威版本'
: '未读取'
return (
<section className="release-targets" aria-label="发布管理">
<header className="rel-head page-header">
<div>
<h1 className="page-title">发布管理</h1>
<p className="page-subtitle">测试维护与验证,生产按知识库版本同步。</p>
<p className="page-subtitle">测试封存 → 生产同步:每一步只保留一个入口。</p>
</div>
<div className="rel-head-actions page-header-actions">
<button type="button" className="rel-secondary" onClick={() => onDrawer(true)}>
▣ 版本与快照
</button>
<button type="button" className="rel-secondary" onClick={onRefresh} disabled={loading}>
{loading ? '刷新中…' : '刷新'}
</button>
@@ -1969,128 +1985,87 @@ export function ReleaseTargetsView(props: ViewProps) {
) : null}
{notice ? <p className="rel-notice">{notice}</p> : null}
<div className="rel-panel rel-jobhead">
<div className="rel-between">
<h2>
{scopeName(scope)} ·{' '}
{active
? `${jobKindText(view.job?.kind)}进行中`
: view.snapshot
? '已封存,同步按条件放行'
: '尚无测试封存'}
</h2>
<div className="rel-head-actions">
<button type="button" className="rel-secondary" onClick={() => onDrawer(true)}>
版本与快照
</button>
<button
type="button"
className="rel-primary"
onClick={() => {
if (runningJob) {
document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' })
return
}
sync.onStart()
}}
disabled={Boolean(runningJob) ? false : !sync.canStart || sync.pending}
title={
runningJob
? `${jobKindText(runningJob.kind)}正在执行;请查看当前任务,不要重复启动`
: sync.canStart
? '按已签发的同步授权启动:先固定测试版本,再备份目标并写入'
: `暂不能启动同步:${gate.reasons.join(';')}`
}
>
{runningJob ? '查看当前任务' : sync.pending ? '投递中…' : '▶ 启动同步'}
</button>
</div>
</div>
<p className="rel-target-identity" aria-label="实际目标实例">
目标实例 {view.overview?.target_instance || view.overview?.executor?.instance || '未读取'} · 项目{' '}
{view.overview?.target_project || view.overview?.executor?.project || '未读取'} · 知识库{' '}
{view.overview?.target_knowledge_base_id || target?.knowledge_base_id || '未读取'}({scopeName(scope)})
<div className="rel-panel rel-status">
<p className="rel-scope-state">
{scopeName(scope)} ·{' '}
{active ? `${jobKindText(view.job?.kind)}进行中` : sealed ? '已封存,同步按条件放行' : '尚无测试封存'}
{sealed ? '(需要新版本时点上方“封存测试版本”)' : ''}
</p>
<p className="rel-versionline">
目标当前{' '}
{productionClass === 'known' && production?.version ? (
<b>
{production.version.version_label || `生效 ${production.version.snapshot_id.slice(0, 12)}`}
{' · '}
快照 {production.version.snapshot_id.slice(0, 12)}
</b>
) : productionClass === 'empty' ? (
<b>目标已读且为空(首次发布)</b>
) : productionClass === 'unreachable' ? (
<b className="rel-unknown">读取失败:{production?.reason || '无法读取目标整库状态'}</b>
) : productionClass === 'nonempty' ? (
<b className="rel-unknown">目标非空,尚无权威版本</b>
) : (
<b className="rel-unknown">{productionNote}</b>
)}
{productionStale ? <em className="rel-scope">({STALE_NOTE})</em> : null} → 拟发布{' '}
<b>{target ? `封存 ${target.snapshot_id.slice(0, 12)} · ${stamp(target.created_at)}` : '还没有测试封存'}</b> ·{' '}
{publishStateText(view.job)}
</p>
<dl className="rel-metrics">
<dl className="rel-status-grid">
<div>
<dt>新增文档</dt>
<dd className={diff.state === 'computed' ? '' : 'rel-unknown'}>
{diff.state === 'computed' ? diff.added.length : '未接入'}
<dt>测试封存</dt>
<dd className={sealed ? '' : 'rel-unknown'}>
{sealed ? `快照 ${view.snapshot!.snapshot_id.slice(0, 12)}` : '尚无'}
</dd>
<small>{sealed ? stamp(view.snapshot!.created_at) : '先封存测试版本'}</small>
</div>
<div>
<dt>更新文档</dt>
<dd className={diff.state === 'computed' ? '' : 'rel-unknown'}>
{diff.state === 'computed' ? diff.updated.length : '未接入'}
</dd>
<dt>生产当前</dt>
<dd className={productionClass === 'known' ? '' : 'rel-unknown'}>{productionText}</dd>
<small>{publishStateText(view.job)}</small>
</div>
<div>
<dt>删除文档</dt>
<dd className={diff.state === 'computed' ? '' : 'rel-unknown'}>
{diff.state === 'computed' ? diff.removed.length : '未接入'}
</dd>
<dt>发布授权</dt>
<dd className={authorizationActive ? '' : 'rel-unknown'}>{authorizationActive ? '已签发' : '未签发'}</dd>
<small>
{authorizationActive
? `有效至 ${stamp(authorization.expires_at ?? '')}`
: sync.canSign
? '可在下方签发'
: '需管理员签发'}
</small>
</div>
<div>
<dt>Wiki 发布方式</dt>
<dd>{target ? '完整快照' : '未接入'}</dd>
<dt>最近预备份</dt>
<dd className={prebackup.state === 'known' ? '' : 'rel-unknown'}>
{prebackup.state === 'known' ? '已登记' : '无'}
</dd>
<small>
{prebackup.state === 'known' && prebackup.version
? stamp(prebackup.version.created_at)
: '同步时自动生成'}
</small>
</div>
</dl>
{target?.source_identity ? (
<details className="rel-source-identity">
<summary>来源身份与完整摘要</summary>
<p>
来源实例:{target.source_identity.project} / {target.source_identity.app}
</p>
<p>
来源租户 / 知识库:{target.source_identity.tenant_id} / {target.source_identity.knowledge_base_id}
</p>
<p>来源身份:{target.source_id}</p>
<p>快照摘要:{target.snapshot_id}</p>
</details>
<div className="rel-status-actions">
<p className="rel-next">
<span>下一步</span>
{prepAction && prepAction.disabled === false && !runningJob ? prepAction.hint : primaryAction.hint}
</p>
{prepAction && !runningJob ? (
<button
type="button"
className="rel-secondary"
onClick={prepAction.run}
disabled={prepAction.disabled}
title={prepAction.hint}
>
{prepAction.label}
</button>
) : null}
<button
type="button"
className="rel-primary"
onClick={primaryAction.run}
disabled={primaryAction.disabled}
title={primaryAction.hint}
>
{primaryAction.label}
</button>
<button type="button" className="rel-secondary" onClick={() => onDrawer(true)}>
版本与快照
</button>
</div>
{gate.reasons.length > 0 ? (
<p className="rel-hint">还差 {gate.reasons.length} 项条件,展开“发布前检查”查看原因。</p>
) : null}
<ul className="rel-checklist">
<li className={target ? 'ok' : 'unknown'}>
{target
? `✓ 文档解析与索引完整(${target.totals.chunks ?? 0} 分块 / ${target.totals.index_documents ?? 0} 索引)`
: '○ 文档解析与索引:未接入'}
{target ? (
<em className="rel-scope">
依据 {stamp(target.created_at)} 封存的测试库全库快照,不代表实时测试库已就绪
</em>
) : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ Wiki 快照完整(${target.totals.wiki_pages ?? 0} 页)` : '○ Wiki 快照:未接入'}
{target ? <em className="rel-scope">同一份封存快照,不是实时 Wiki 队列状态</em> : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ 清单与摘要登记:${target.parts.length} 项部件摘要已记录` : '○ 数据完整性:尚无封存可核验'}
{target ? (
<em className="rel-scope">封存时逐项哈希登记;列表只校验清单自身,字节级复核在同步/恢复执行前进行</em>
) : null}
</li>
</ul>
</div>
<details className="rel-check" id="rel-check" open={gate.reasons.length > 0}>
<summary>
发布前检查
{gate.reasons.length > 0 ? `(${gate.reasons.length} 项未满足)` : '(已满足)'}
</summary>
{gate.reasons.length > 0 ? (
<ul className="rel-gate" aria-label="启动同步的缺项">
{gate.reasons.map((reason) => (
@@ -2098,26 +2073,47 @@ export function ReleaseTargetsView(props: ViewProps) {
))}
</ul>
) : null}
<p className="rel-footnote">启动后先固定测试版本,再备份生产。备份失败或恢复条件不满足,不进入生产写入。</p>
</div>
<MaintenanceCard
maintenance={maintenance}
ownerJob={maintenanceOwnerJob}
scope={scope}
canWrite={canWrite}
onRecover={onRecover}
/>
<ul className="rel-checklist">
<li className={target ? 'ok' : 'unknown'}>
{target
? `✓ 文档解析与索引完整(${target.totals.chunks ?? 0} 分块 / ${target.totals.index_documents ?? 0} 索引)`
: '○ 文档解析与索引:未接入(尚无封存)'}
{target ? (
<em className="rel-scope">
依据 {stamp(target.created_at)} 封存的测试库全库快照,不代表实时测试库已就绪
</em>
) : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ Wiki 快照完整(${target.totals.wiki_pages ?? 0} 页)` : '○ Wiki 快照:未接入(尚无封存)'}
{target ? <em className="rel-scope">同一份封存快照,不是实时 Wiki 队列状态</em> : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ 清单与摘要登记:${target.parts.length} 项部件摘要` : '○ 数据完整性:未接入(尚无封存可核验)'}
{target ? (
<em className="rel-scope">封存时逐项哈希登记;列表只校验清单自身,字节级复核在同步/恢复执行前进行</em>
) : null}
</li>
</ul>
<RestoreVerificationSection
scope={scope}
isAdmin={sync.canSign}
onAccepted={verification.onAccepted}
onComplete={verification.onComplete}
/>
</details>
{active ? (
<ProgressBody
view={view}
now={now}
onOpen={() => onDrawer(true)}
canReconcileCapture={canReconcileCapture}
pendingReconcileCapture={pendingReconcileCapture}
onReconcileCapture={onReconcileCapture}
/>
<div id="rel-progress">
<ProgressBody
view={view}
now={now}
onOpen={() => onDrawer(true)}
canReconcileCapture={canReconcileCapture}
pendingReconcileCapture={pendingReconcileCapture}
onReconcileCapture={onReconcileCapture}
/>
</div>
) : (
<ReadyBody
view={view}
@@ -2139,6 +2135,38 @@ export function ReleaseTargetsView(props: ViewProps) {
/>
)}
<details className="rel-advanced">
<summary>高级与历史(目标维护、差异明细、来源身份)</summary>
<MaintenanceCard
maintenance={maintenance}
ownerJob={maintenanceOwnerJob}
scope={scope}
canWrite={canWrite}
onRecover={onRecover}
/>
<ChangeTable diff={diff} />
<p className="rel-target-identity" aria-label="实际目标实例">
目标实例 {view.overview?.target_instance || view.overview?.executor?.instance || '未读取'} · 项目{' '}
{view.overview?.target_project || view.overview?.executor?.project || '未读取'} · 知识库{' '}
{view.overview?.target_knowledge_base_id || target?.knowledge_base_id || '未读取'}({scopeName(scope)})
{productionStale ? <em className="rel-scope">({STALE_NOTE})</em> : null}
</p>
{target?.source_identity ? (
<details className="rel-source-identity">
<summary>来源身份与完整摘要</summary>
<p>
来源实例:{target.source_identity.project} / {target.source_identity.app}
</p>
<p>
来源租户 / 知识库:{target.source_identity.tenant_id} / {target.source_identity.knowledge_base_id}
</p>
<p>来源身份:{target.source_id}</p>
<p>快照摘要:{target.snapshot_id}</p>
</details>
) : null}
<p className="rel-footnote">同步会先固定测试版本,再备份生产;备份失败或恢复条件不满足时不进入生产写入。</p>
</details>
<Drawer
view={view}
page={page}
+40 -16
View File
@@ -124,22 +124,46 @@ export function RoutingBindingsSection() {
</p>
) : null}
{bindings ? (
<div className="kb-binding-grid">
{renderSide(
'对内知识库',
bindings.internal_kb_id,
bindings.internal_kb_name,
bindings.internal_env_fallback,
bindings.internal_bound_by_ui
)}
{renderSide(
'对外知识库',
bindings.external_kb_id,
bindings.external_kb_name,
bindings.external_env_fallback,
bindings.external_bound_by_ui
)}
</div>
<>
<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>
</>
) : null}
{bindings && !bindings.weknora_connected ? (
<p className="hint">当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。</p>
+8
View File
@@ -118,6 +118,14 @@ 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
+53 -7
View File
@@ -1,6 +1,12 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { SystemSettingsView, ppSourceConnections, visibleSaveMessage } from './SystemSettings'
import {
SystemSettingsView,
ppSourceConnections,
refreshSettingsInput,
serviceSettingsInput,
visibleSaveMessage,
} from './SystemSettings'
import { AuthContext } from './auth'
import type { MonitorOverview } from './monitor'
import type { CatalogSource } from './sourceCatalog'
@@ -147,7 +153,7 @@ describe('SystemSettingsView service configuration', () => {
for (const text of [
'测试地址',
'生产地址',
'生产 ID',
'生产租户 ID',
'知识库 ID',
'保存并启用服务配置',
'https://weknora.test.example',
@@ -273,9 +279,9 @@ describe('SystemSettingsView', () => {
'finalizing 2小时',
'文档状态刷新间隔',
'15秒',
'解析停滞判定',
'解析停滞阈值',
'30分钟',
'保存并应用刷新与告警参数',
'保存刷新与告警参数',
])
expect(refreshHtml).toContain(text)
expect(visibleSaveMessage('已保存', true)).toBeNull()
@@ -322,8 +328,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 知识库')
@@ -423,7 +429,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('生产写入:开启')
@@ -641,3 +647,43 @@ 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')
})
})
+155 -63
View File
@@ -12,6 +12,8 @@ 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'
@@ -35,6 +37,7 @@ interface Props {
productionEnabled: boolean
productionBackupRestoreVerified?: boolean
routingCapabilities: CatalogRoutingCapabilities
workerCapabilities?: WorkerCapabilities | null
loading: boolean
saving: boolean
error: string | null
@@ -42,16 +45,16 @@ interface Props {
onSave: (input: UISettingsCandidateInput) => void
onSourcesChanged: () => void
onRefresh: () => void
initialSection?: SectionKey
// 兼容旧入口:'bindings'/'production-bindings' 已合并为“知识库映射”。
initialSection?: SectionKey | 'bindings' | 'production-bindings'
}
type SectionKey = 'sources' | 'services' | 'bindings' | 'production-bindings' | 'storage' | 'refresh' | 'members'
type SectionKey = 'sources' | 'services' | 'knowledge-map' | 'storage' | 'refresh' | 'members'
const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
{ key: 'sources', label: '数据源配置' },
{ key: 'services', label: '服务配置' },
{ key: 'bindings', label: '测试知识库绑定' },
{ key: 'production-bindings', label: '生产知识库绑定' },
{ key: 'knowledge-map', label: '知识库映射' },
{ key: 'storage', label: '存储与备份' },
{ key: 'refresh', label: '刷新策略' },
{ key: 'members', label: '成员与角色', adminOnly: true },
@@ -75,6 +78,44 @@ 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]
@@ -92,6 +133,14 @@ 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
@@ -127,6 +176,7 @@ export function SystemSettingsView({
productionEnabled,
productionBackupRestoreVerified = false,
routingCapabilities,
workerCapabilities = null,
loading,
saving,
error,
@@ -137,7 +187,11 @@ export function SystemSettingsView({
}: Props) {
const auth = useOptionalAuth()
const identity = auth?.identity ?? null
const [section, setSection] = useState<SectionKey>(initialSection)
const [section, setSection] = useState<SectionKey>(
initialSection === 'bindings' || initialSection === 'production-bindings'
? 'knowledge-map'
: (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)
@@ -183,21 +237,28 @@ export function SystemSettingsView({
productionTenantID.trim() !== settings.production_tenant_id ||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id)
)
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 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 saveEndpoint = () => {
setDirty(false)
onSave(candidateInput())
onSave(serviceInput())
}
return (
<main className="page-shell system-settings">
@@ -211,7 +272,7 @@ export function SystemSettingsView({
{error}
</div>
) : null}
{monitor && settings ? (
{settings || monitor ? (
<div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">
{sections
@@ -258,14 +319,13 @@ export function SystemSettingsView({
<SourceManagementDetails connections={listedConnections} onSourcesChanged={onSourcesChanged} />
</section>
) : null}
{section === 'services' ? (
{section === 'services' && settings ? (
<section className="settings-panel wide" id="settings-services">
<div className="settings-section-heading">
<div>
<h2>服务配置</h2>
<p>
只配四项:测试地址、生产地址、生产 ID、知识库
ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。
四项可写:测试地址、生产地址、生产租户、生产知识库。保存前会做真实探活与列库核验,凭据只写不读。
</p>
</div>
</div>
@@ -273,8 +333,12 @@ export function SystemSettingsView({
<div className="environment-cards">
<article>
<b>测试 WeKnora</b>
<span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<span>{testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
<small className={`worker-capability ${workerCapabilities?.test_upload.state ?? 'unknown'}`}>
{testUploadLabel(workerCapabilities)}
{workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''}
</small>
</article>
<article className="production">
<b>生产 WeKnora</b>
@@ -316,7 +380,7 @@ export function SystemSettingsView({
/>
</label>
<label>
生产 ID
生产租户 ID
<input
value={productionTenantID}
onChange={(event) => {
@@ -369,13 +433,15 @@ export function SystemSettingsView({
>
{saving ? '正在验证并启用…' : '保存并启用服务配置'}
</button>
<small>
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 #
片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID
是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 +
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
</small>
<details className="settings-details">
<summary>保存规则与核验说明</summary>
<small>
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,
凭据一律走文件引用);生产租户 ID 为十进制数字;知识库 ID 粘贴 URL 不会通过。
保存会生成修订、真实验证后原子启用;端点回答“没有这个知识库”或租户不符会拒收,
端点抖动、鉴权失败或未配置生产凭据只警告不拦。
</small>
</details>
{serviceSettingsValid ? null : (
<p className="error-message" role="alert">
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
@@ -393,8 +459,17 @@ export function SystemSettingsView({
)}
</section>
) : null}
{section === 'bindings' ? <RoutingBindingsSection /> : null}
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
{section === 'knowledge-map' ? (
<>
<p className="settings-hint-wide">
一张图看清三件事:<strong>入库目标</strong>(来源打标分发到此库)、
<strong>封存源</strong>(整库封存实际导出的库)、<strong>生产目标</strong>(同步写入的库)。
前两者不一致时,发布页显示的名字与封存出来的内容会对不上。
</p>
<RoutingBindingsSection />
<ProductionBindingsSection />
</>
) : null}
{section === 'storage' ? (
<>
<LibraryStorageSection />
@@ -402,12 +477,12 @@ export function SystemSettingsView({
</>
) : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' ? (
{section === 'refresh' && settings ? (
<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>
@@ -440,7 +515,7 @@ export function SystemSettingsView({
</select>
</label>
<label>
解析停滞判定
解析停滞阈值
<select
value={stalled}
onChange={(event) => {
@@ -453,7 +528,7 @@ export function SystemSettingsView({
</select>
</label>
<label>
finalizing 告警
收尾超时告警
<select
value={finalizing}
onChange={(event) => {
@@ -486,17 +561,20 @@ export function SystemSettingsView({
<button
onClick={() => {
setDirty(false)
onSave(candidateInput())
onSave(refreshInput())
}}
disabled={!canSave}
disabled={!canSave || !refreshSettingsDirty}
>
{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)}
@@ -523,41 +601,48 @@ 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([
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)
track(fetchCatalogSources(controller.signal), setSources, '数据源'),
track(fetchSourceConnectionList(controller.signal), setConnections, '来源连接'),
track(fetchMonitorOverview(controller.signal), setMonitor, '监控'),
track(
fetchReleaseCapabilities(controller.signal),
(capabilities) => {
setProductionEnabled(capabilities.production_release_requests_enabled)
setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified)
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)
})
},
'发布能力'
),
track(fetchCatalogRoutingCapabilities(controller.signal), setRoutingCapabilities, '路由能力'),
track(fetchWorkerCapabilities(controller.signal), setWorkerCapabilities, '执行器能力'),
track(fetchActiveUISettings(controller.signal), setSettings, '系统设置'),
]).finally(() => {
if (controller.signal.aborted) return
setError(failures.length ? failures.join(';') : null)
setLoading(false)
})
return () => controller.abort()
}, [revision])
@@ -571,6 +656,12 @@ 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}` : ''}`
)
@@ -593,6 +684,7 @@ export function SystemSettings() {
productionEnabled={productionEnabled}
productionBackupRestoreVerified={productionBackupRestoreVerified}
routingCapabilities={routingCapabilities}
workerCapabilities={workerCapabilities}
loading={loading}
saving={saving}
error={error}
+31 -35
View File
@@ -43,29 +43,27 @@ 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)
@@ -114,20 +112,18 @@ 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()
})
+11 -13
View File
@@ -67,20 +67,18 @@ 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)
+77
View File
@@ -711,3 +711,80 @@
border-radius: 7px;
padding: 8px;
}
/* 发布管理精简版:一个状态卡 + 一个主按钮,其余收进折叠区。 */
.rel-status {
display: grid;
gap: 14px;
padding: 18px 20px;
}
.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;
font-weight: 600;
font-size: 15px;
word-break: break-all;
}
.rel-status-grid small {
display: block;
margin-top: 4px;
color: var(--muted-foreground);
font-size: 12px;
}
.rel-status-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
.rel-next {
flex: 1 1 320px;
margin: 0;
color: var(--muted-foreground);
font-size: 13px;
}
.rel-next span {
display: inline-block;
margin-right: 8px;
padding: 1px 8px;
border-radius: 999px;
background: var(--accent);
color: var(--foreground);
font-size: 12px;
}
.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;
}
+32 -42
View File
@@ -400,22 +400,20 @@ 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')
@@ -619,12 +617,10 @@ 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: [] })
@@ -639,12 +635,10 @@ 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'],
@@ -669,14 +663,12 @@ 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' })
@@ -691,13 +683,11 @@ 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,6 +14,11 @@ 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 {
@@ -38,6 +43,18 @@ 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,
}
}
+29 -33
View File
@@ -5,26 +5,24 @@ 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)
@@ -34,22 +32,20 @@ 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,
+85 -93
View File
@@ -59,57 +59,53 @@ 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('公司级技术支持知识库')
@@ -248,22 +244,20 @@ 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',
@@ -301,40 +295,38 @@ 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
@@ -0,0 +1,56 @@
// 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,3 +882,28 @@ 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;
}
+10 -14
View File
@@ -127,13 +127,11 @@ 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' })
@@ -155,13 +153,11 @@ 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({
+6 -8
View File
@@ -205,15 +205,13 @@ 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)