Compare commits

..

17 Commits

Author SHA1 Message Date
姚章浩 c33c7e2700 fix(release): 接受预览提示中的带引号范围确认
build / build (push) Successful in 2m22s
2026-11-24 14:54:05 +08:00
zheromiku 91f9e00010 Merge pull request 'feat(release): 知识治理预检交接与固定版本发布' (#33) from feat/release-comment-handoff into main
build / build (push) Successful in 2m17s
2026-11-24 14:46:00 +08:00
姚章浩 9952412eff fix(release): 兼容发布预览的富文本回读
build / build (push) Successful in 2m15s
2026-11-24 14:43:03 +08:00
姚章浩 4a12b20e9b feat(release): 从预检评论接单并固定候选版本
build / build (push) Successful in 2m28s
2026-11-24 14:39:43 +08:00
zheromiku 8d873680cc Merge pull request #32 from hifox-agent/miku/CYWL-18
build / build (push) Successful in 2m31s
成员与角色:新增成员改为标题按钮 + 右侧抽屉
2026-11-24 13:07:33 +08:00
Zhero & Miku edd90b253e Merge origin/main into hifox-agent/miku/CYWL-18
build / build (push) Successful in 2m45s
同步 main@d3c4351;CHANGELOG 双方快照并存,本任务保持 0.1.416。
2026-11-24 13:04:19 +08:00
zheromiku d3c435183e Merge pull request #31 from hifox-agent/miku/CYWL-17
build / build (push) Successful in 2m51s
feat(settings): 参数设置按来源与目录、解析监控分组
2026-11-24 12:57:22 +08:00
Zhero & Miku aa75dc6d44 feat(settings): 参数设置按来源与目录、解析监控分组
build / build (push) Successful in 2m6s
- 入口与页面标题由「刷新策略」改为「参数设置」,移除旧入口
- 按产品归属分组:来源与目录(文档/资源刷新间隔)、解析监控(停滞阈值/入库并发)
- 保留单位、调大调小后果与 worker 生效说明,收尾超时仍不展示
- 字段名/单位收敛到 REFRESH_FIELD_META,避免视图与校验文案各写一份后漂移
- 新增挂载测试覆盖非法值禁用保存、不发请求、保留其他输入与原样回传隐藏字段
- 同步 CHANGELOG、验收清单与运维手册
2026-11-24 12:38:59 +08:00
狐友 GXXP & Miku 25d574f3de fix(web): keep trigger focus when closing member drawer via backdrop
build / build (push) Successful in 2m7s
Prevent the backdrop mousedown default from moving focus to body, so closing the drawer always restores focus to the 新增成员 trigger as the drawer contract requires.
2026-11-24 12:28:41 +08:00
Zhero & Miku c96189db1b feat(settings): 刷新策略改为刷新与入库
build / build (push) Successful in 2m31s
四项参数改为带单位/提示的数值输入,越界就地提示并禁用保存;
删除无消费者的收尾超时 UI,finalizing 设置仍按服务器值回传;
补充解析单测与验收/运维文档。
验证:vitest 23 passed、tsc、vite build、check_changelog。
2026-11-24 12:07:09 +08:00
狐友 GXXP & Miku 1dfa4fa7fc feat(web): added member creation drawer with inline validation
- Replaced the inline member form with a header button and right-side drawer.
- Added inline validation, 409/400 field mapping, dirty-close confirm, and focus handling.
- Added MembersRequestError with HTTP status and a mounted regression test.
2026-11-24 12:06:54 +08:00
zheromiku d76363c117 Merge pull request 'feat(settings): 存储与备份只读摘要页对齐验收' (#30) from hifox-agent/len/CYWL-16 into main
build / build (push) Successful in 2m8s
2026-11-24 11:56:21 +08:00
狐友 GXXP & LEN b2248a9b64 feat(settings): 存储与备份只读摘要页对齐验收
build / build (push) Successful in 2m12s
- 单一「存储与备份」页:目录、最近成功/失败、归档占用、磁盘剩余四张卡片 + 备份目录条
- 四条容量告警按磁盘可用/配额已用阈值给出 正常/注意/需处理,缺数显示 未知 而非正常
- 批次表默认 20 条 + 加载更多,展示失败原因与单条复制;60 秒自动刷新
- 未接入/未上报/过期/不完整/不可用分状态措辞,不用 0 冒充
- 移除计划编辑、下发、立即备份与库内诊断块(写端点保留)
- compose 接线 LIBRARY_CAPACITY_BUDGET_BYTES 与 BACKUP_HOST_* 只读元数据
2026-11-24 11:53:49 +08:00
狐友 GXXP & Miku 8c84c9c601 fix(kb-bindings): allow key entry on private HTTP consoles
build / build (push) Successful in 2m26s
- Accept the private-console transport with an exact Origin/Host match; the http console is not a secure context, so Chrome sends no Sec-Fetch-Site and that requirement made every real write 400.
- Reject bracketed non-IPv6 host spellings, including ported forms, instead of normalising them to loopback.
- Show the plaintext-warning copy or the disabled state from a tri-state capability field; old APIs keep the legacy message.
- Document WEKNORA_ALLOW_PRIVATE_HTTP in .env.example and the operations runbook.
2026-11-24 11:22:06 +08:00
zheromiku 660320d646 Merge pull request 'fix(cd): 核验主站首页的 SSO 同源改写' (#29) from fix/cd-serving-proof into main
build / build (push) Successful in 1m46s
2026-11-23 22:00:48 +08:00
姚章浩 0e33f21206 fix(cd): 校验主站单点登录代理处理后的首页
build / build (push) Successful in 1m51s
2026-11-23 21:58:48 +08:00
zheromiku 83bba09cde Merge pull request 'fix(cd): 派发前交接并校验验收归档' (#28) from fix/cd-verified-bundle-handoff into main
build / build (push) Successful in 1m53s
2026-11-23 21:48:05 +08:00
44 changed files with 3616 additions and 3345 deletions
+2
View File
@@ -28,6 +28,8 @@ QA_AI_MASTER_KEY_FILE=
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE=
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
WEKNORA_ALLOW_PRIVATE_HTTP=false
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
QA_AI_DNS_OVER_TLS=
+51
View File
@@ -1,5 +1,56 @@
# Changelog
## 开发快照 0.1.417(知识治理发布助理接收提测交接)
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
- 负责人回复预览确认范围,候选验收报告按实际归档归集到发布单。
## 开发快照 0.1.416(成员管理:新增成员改为右侧抽屉)
### Fixed
- **新增入口移到标题栏**:成员表格下方常驻表单改为「成员与角色」标题右侧的
`新增成员` 按钮,点击从右侧滑出抽屉;桌面宽 480px,窄屏铺满,表单字段与
重置密码弹层共用同一套控件与校验提示。
- **关闭前确认未保存输入**:Esc、取消、关闭按钮与遮罩点击在草稿非空时先确认;
清空草稿后直接关闭并把焦点还给触发按钮;创建请求进行中忽略一切关闭请求。
- **创建失败留在抽屉**:409 固定到用户名行,400 收敛为表单级提示,二者都保留
已填内容;成功后关闭抽屉、刷新列表,页级错误/成功条只承载加载与行内操作。
### Changed
- **请求错误带 HTTP 状态**:`web/src/members.ts` 的失败改为 `MembersRequestError`
(含 `status`),组件按 409/400 分流,不再依赖错误文案匹配。
## 开发快照 0.1.415(系统设置:刷新策略改为按模块分组的参数设置)
### Changed
- **入口改为「参数设置」**:系统设置左侧子导航与页面标题由「刷新策略」替换为「参数设置」,
旧入口不再出现。
- **参数按模块分组**:按产品归属固定为「来源与目录」(文档状态刷新间隔 15/30/60 秒、
资源刷新间隔 30/60 秒)与「解析监控」(解析停滞阈值 30/60 分钟、入库并发上限 1..16);
分组标题下不叠加说明段。
- **数值输入与就地校验**:四个下拉改为文本数值输入;空值、非整数、`+15`/`1e1`、全角数字
与越界值当场红字提示并禁用保存,不发请求;并发不再受旧下拉六档限制。
- **保留现状说明与保存边界**:每项保留单位与调大/调小后果;解析停滞阈值保留 worker 1 分钟
内生效说明;保存仍只提交参数分区,且原样回传未展示的 `finalizing_after_seconds` 与连接字段。
- **去掉无消费者的收尾超时展示**:本页不再展示「收尾超时告警」,成功消息与底部摘要也不再
播报它;API/DB/worker 与 `finalizing` 处理状态均未改动。
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
### Fixed
- **私网 http 控制台无法录入 API Key**:页面过去只看浏览器 URL 决定能否录入,而服务端写侧
已按 `WEKNORA_ALLOW_PRIVATE_HTTP` 放行私网 http,导致「开关开着、输入框仍禁用」。GET
`/api/v1/kb-bindings` 现在返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
开关与受信反代判定;API 未返回该字段时前端按不可录入处理(失败关闭)。写侧判定不变。
- **明文录入没有风险提示**:能力位开启且页面经非回环 http 打开时,Key 输入下方常驻提示密钥
将明文传输;HTTPS 反代未配置 `QA_AI_TRUST_TLS_PROXY` 时改为提示该配置,不再笼统要求 HTTPS。
- **`Host: [::1]`(无端口)被误判为非回环**:地址规范化统一去掉 IPv6 方括号与可选端口,
回环写入不再被拒;受信反代能力位对 GET 只依赖 `X-Forwarded-Proto`(浏览器无法伪造该头)。
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
### Fixed
+8
View File
@@ -52,6 +52,14 @@ services:
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
# 「存储与备份」摘要页的归档配额(字节)。留空 = 未设置,页面显示"配额未设置";
# 显式写 0 会被 appconfig 拒绝(必须为正整数),所以只能用空串表示未设置。
LIBRARY_CAPACITY_BUDGET_BYTES: "${LIBRARY_CAPACITY_BUDGET_BYTES:-}"
# 宿主每 5 分钟上报的整库备份元数据快照(collector 写入,平台只读)。
# 留空 = 未接线,页面按验收显示"主机未上报";路径必须是宿主机侧绝对路径。
BACKUP_HOST_METADATA_PATH: "${BACKUP_HOST_METADATA_PATH:-}"
BACKUP_HOST_METADATA_MAX_AGE: "${BACKUP_HOST_METADATA_MAX_AGE:-15m}"
BACKUP_HOST_READONLY_HOST_PATH: "${BACKUP_HOST_READONLY_HOST_PATH:-}"
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
+8
View File
@@ -2,6 +2,14 @@
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
## 从提测评论接单
白小浅在业务单提交通过的预检后,评论自动化把来源任务和评论 UUID 交给 `scripts/release_handoff.py preflight`。执行器核验作者、最新结论、知识治理仓库的落地记录、主线范围和所选版本的 CI。相同业务单与提交复用同一发布单。已在测试中的旧单可用 `recover <业务任务号>` 从原记录补接。
发布单的预览列明线上基线、候选提交及所有其他随批提交。负责人在**该预览的评论线程**回复「确认范围」后准备候选。已有负责人计划仍可使用。每项来源支持 `{"task":"<UUID>","pr":123}` 或 `{"task":"<UUID>","commit":"<完整落地 SHA>"}`。固定历史候选可用 `release_assistant.py plan <发布单> <业务单>:<来源> --sha <完整 SHA>`。
候选就绪后,业务和批次 QA 均按下方格式提交真实报告。`kg-qa-v1` 评论触发登记,两处报告全部齐全才写入验收记录。已在「测试中」的业务单通过原单召唤 QA 执行新包复测。遇到建单或派测回执未知,核对远端记录后恢复。
## 发起候选
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
+9 -1
View File
@@ -70,6 +70,14 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET
`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以
录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台
自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传
`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。
先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
@@ -176,7 +184,7 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
| 参数设置 | 文档工程师 | 「来源与目录」文档/资源刷新间隔;「解析监控」停滞阈值、入库并发上限(1..16,版本化 + 原子切换);finalizing 设置仅在 API/DB 保留,页面不展示 |
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
## 9. 备份与恢复运维 **【新】**
+8 -4
View File
@@ -284,10 +284,14 @@
- 立即备份:按钮变"备份进行中…"→ 约 50 秒后自动刷出新结果(异步 202 + 在途单飞,重复点击不会跑两次)
- 状态:✅ 2026-10-09 面板实测(写操作仅管理员:`PUT/POST /api/v1/backup-schedule*`)
### D5 刷新策略
- 入口:**系统设置 → 刷新策略**(文档工程师可改)
- 期望:文档/资源刷新间隔、停滞判定、finalizing 时长;保存先验证再原子启用、旧版本留审计
- 状态:✅(`ui_settings` 版本化激活测试)
### D5 参数设置
- 入口:**系统设置 → 参数设置**(文档工程师可改)
- 期望:按「来源与目录」「解析监控」两组呈现。来源与目录:文档状态刷新间隔(15/30/60 秒)、
资源刷新间隔(30/60 秒);解析监控:解析停滞阈值(30/60 分钟)、入库并发上限(1..16)。
四项以数值输入呈现,单位与调大/调小后果常驻,越界就地提示并禁用保存;保存先验证再原子
启用、旧版本留审计。收尾超时告警不再在页面任何位置出现;API/DB 的
`finalizing_after_seconds` 与 `finalizing` 处理状态不变。
- 状态:✅(`ui_settings` 版本化激活测试;本任务补数值校验与浏览器实测)
### D6 成员与角色
- 入口:**系统设置 → 成员与角色**(管理员)
+7 -1
View File
@@ -34,7 +34,13 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
for _, view := range views {
storageReady = storageReady || view.StorageReady
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"environments": views,
"storage_ready": storageReady,
// The page cannot test the server's transport rule from the browser URL
// alone (a TLS proxy and an untrusted proxy look identical there).
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
}})
}
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
+93
View File
@@ -128,3 +128,96 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
}
}
}
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
for _, tc := range []struct {
name string
host string
allow bool
want bool
}{
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private console without toggle", host: "172.29.151.11:28188", want: false},
{name: "loopback console", host: "127.0.0.1:8080", want: true},
} {
t.Run(tc.name, func(t *testing.T) {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = tc.allow
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
request.Host = tc.host
response := httptest.NewRecorder()
config.handleKBBindings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
var payload struct {
Data struct {
SecretEntryAllowed bool `json:"secret_entry_allowed"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.SecretEntryAllowed != tc.want {
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
}
})
}
}
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
const (
privateHost = "172.29.151.11:28188"
origin = "http://172.29.151.11:28188"
)
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
save := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
return response
}
catalog := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog",
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
return response
}
enabled := kbBindingHandler(t, store)
enabled.WeKnoraAllowPrivateHTTP = true
if response := save(enabled); response.Code != http.StatusOK {
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
}
if response := catalog(enabled); response.Code != http.StatusOK {
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String())
}
disabled := kbBindingHandler(t, store)
if response := save(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String())
}
if response := catalog(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String())
}
}
+71 -14
View File
@@ -16,14 +16,7 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
if r.TLS != nil {
return true
}
host := r.Host
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
host = parsedHost
}
if strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
if loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
@@ -36,12 +29,14 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match.
// still requires an exact Origin/Host match. It deliberately does not require
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
// http console on a private address never carries that header.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) {
return true
}
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
if !allowPrivateHTTP {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
@@ -53,8 +48,70 @@ func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, all
return false
}
host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil {
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
}
return strings.EqualFold(host, "localhost")
return privateAddressHost(host)
}
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
// it cannot simply call secretTransportAllowed: that gate guards a write and
// therefore insists on a same-origin Origin header, which a GET navigation
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
// browsers cannot set it and the deployment already declares the proxy
// trusted; a forged header still cannot make the write gate accept anything.
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if r.TLS != nil || loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
return allowPrivateHTTP && privateAddressHost(r.Host)
}
// requestHostname strips the optional port and IPv6 brackets. Brackets come
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
// ported forms are not address spellings the server or a browser ever emits,
// so they stay untouched and keep failing the address checks.
func requestHostname(host string) string {
host = strings.TrimSpace(host)
if strings.HasPrefix(host, "[") {
end := strings.Index(host, "]")
if end <= 0 {
return host
}
ip := net.ParseIP(host[1:end])
if ip == nil || ip.To4() != nil {
return host
}
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
return host
}
return ip.String()
}
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
return parsedHost
}
return host
}
// loopbackHost is the address-only part of the secret transport rule: a
// request from this machine never crosses a network.
func loopbackHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// privateAddressHost accepts loopback and private addresses. Names other than
// localhost are rejected because the deployment toggle is about addresses,
// not about trusting whatever DNS resolves to.
func privateAddressHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
}
+112
View File
@@ -0,0 +1,112 @@
package httpapi
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
cases := []struct {
name string
host string
tls bool
xfp string
trust bool
allow bool
want bool
}{
{name: "direct TLS", host: "console.example", tls: true, want: true},
{name: "loopback name", host: "localhost:8080", want: true},
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
{name: "loopback v6 without port", host: "[::1]", want: true},
// Bracketed non-IPv6 hosts are not address spellings; they must not
// borrow loopback trust from the bracket stripper.
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
{name: "public name with toggle", host: "console.example", allow: true, want: false},
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
// A forged header must not beat the address rule when the proxy is not trusted.
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
request.Host = tc.host
if tc.tls {
request.TLS = &tls.ConnectionState{}
}
if tc.xfp != "" {
request.Header.Set("X-Forwarded-Proto", tc.xfp)
}
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
}
})
}
}
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = "[::1]"
if !secretTransportAllowed(request, false) {
t.Fatal("bare [::1] Host was rejected as a loopback transport")
}
request.Host = "console.example"
if secretTransportAllowed(request, false) {
t.Fatal("public name without TLS was accepted")
}
}
// Plain-http consoles are not secure contexts, so Chrome never sends
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
request.Host = "192.168.50.134:18093"
request.Header.Set("Origin", "http://192.168.50.134:18093")
if !secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
}
request.Header.Set("Origin", "http://evil.example")
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("cross-origin request was accepted as a private console")
}
request.Header.Set("Origin", "http://192.168.50.134:18093")
if secretTransportAllowedForPrivateConsole(request, false, false) {
t.Fatal("private console was accepted with the deployment toggle off")
}
}
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", "http://"+host)
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatalf("Host %q was accepted as a private console", host)
}
}
}
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
}
}
+37 -4
View File
@@ -42,12 +42,19 @@ def owner_plan(task_id):
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
match = next((row for row in matches if row), None)
if match is None:
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
plan = json.loads(match[1])
from release_handoff import frozen_approval
plan = frozen_approval(task_id)
cd.require(plan, 'release owner must confirm the scope preview or post a kg-release-v1 plan')
else:
plan = json.loads(match[1])
candidate.check_plan(plan)
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
for item in plan['items']:
requirement = task(item['task'])
if 'commit' in item:
# The owner's authenticated plan binds this requirement to the exact landed commit.
# verify_source also checks the complete first-parent range and exact candidate CI.
continue
identifier = requirement.get('identifier')
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
@@ -96,21 +103,47 @@ def publish_candidate(plan, receipt, run):
f'归档 `{receipt["bundle"]}`\n\n'
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
f'发布任务 {task(plan["task"])["url"]}')
body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。'
'业务单记录用例,发布单记录批次回归;每份报告附对应证据。')
key = 'ready ' + receipt['bundle']
add_comment(plan['task'], key, body)
for item in plan['items']:
item_id = item['task']
status = (task(item_id).get('status') or {}).get('id')
if status == TESTING:
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
f'{item_id}: another QA round is already in progress')
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
f'{item_id}: another QA round is already in progress')
add_comment(item_id, key, body)
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
summon_qa(plan, item_id, body)
continue
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
add_comment(item_id, key, body)
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
f'{item_id}: task status changed during candidate handoff')
managed = (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file()
invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json')
if managed:
cd.record(invitation, {'state': 'sending'})
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
if managed:
cd.record(invitation, {'state': 'sent', 'via': 'status'})
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。')
def summon_qa(plan, target, body):
directory = STATE / cd.acceptance_digest(plan)
path = directory / (target + '.qa-invite.json')
if path.exists():
cd.require(cd.read_json(cd.immutable_file(path)).get('state') == 'sent', 'QA invitation outcome needs reconciliation')
return
cd.record(path, {'state': 'sending'})
result = hfx.hifox(CLI, 'task', 'summon', target, '--agent', 'crew:baa5ca58-1228-4da5-9bf8-b9927075e4be', '--body', body)
cd.record(path, {'state': 'sent', 'result': result})
def register(task_id):
+10 -3
View File
@@ -42,9 +42,12 @@ def check_plan(plan):
items = plan['items']
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
for item in items:
cd.require(isinstance(item, dict) and set(item) == {'task', 'pr'} and cd.matches(cd.UUID, item['task'])
and item['task'] != plan['task'] and type(item['pr']) is int and item['pr'] > 0, 'invalid requirement or PR')
cd.require(len({i['task'] for i in items}) == len(items) == len({i['pr'] for i in items}),
cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and item['task'] != plan['task'],
'invalid requirement identity')
by_pr = set(item) == {'task', 'pr'} and type(item['pr']) is int and item['pr'] > 0
by_commit = set(item) == {'task', 'commit'} and cd.matches(cd.SHA, item['commit'])
cd.require(by_pr or by_commit, 'invalid requirement or PR/landed commit')
cd.require(len({i['task'] for i in items}) == len(items) == len({i.get('pr', i.get('commit')) for i in items}),
'duplicate requirement or PR')
extra = plan['extra']
cd.require(isinstance(extra, list) and len(extra) <= 100 and all(cd.matches(cd.SHA, s) for s in extra)
@@ -55,6 +58,10 @@ def check_scope(plan, read_pr, first_parents):
check_plan(plan)
required = set(plan['extra'])
for item in plan['items']:
if 'commit' in item:
cd.require(item['commit'] not in required, 'landed commit is listed in multiple scope entries')
required.add(item['commit'])
continue
pr = read_pr(item['pr'])
sha = pr.get('merge_commit_sha')
cd.require(pr.get('merged') is True and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, sha),
+1 -1
View File
@@ -446,7 +446,7 @@ def cmd_internal_contracts(go: str) -> int:
cwd=ROOT).returncode
if qa_rc:
return qa_rc
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
for pattern in ('test_production_cd.py', 'test_candidate_release.py', 'test_release_handoff.py'):
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
if cd_rc:
return cd_rc
+9 -1
View File
@@ -667,7 +667,15 @@ class LiveHost:
def read_asset(path):
return run(['docker', 'exec', name, 'cat', '/usr/share/nginx/html' + path], 'read running web asset')
require(origin_index == read_asset('/index.html'), 'served index differs from running web image')
image_index = read_asset('/index.html')
if origin_index != image_index:
# The main site's SSO proxy strips the crossorigin attribute on same-origin assets.
config = run(['docker', 'exec', name, 'cat', '/etc/nginx/conf.d/default.conf'],
'read active web configuration')
expected = re.sub(rb'(<(?:script|link)\b[^<>]*?) crossorigin(?= (?:src|href)="/assets/)',
rb'\1 ', image_index)
require(b"sub_filter 'crossorigin' '';" in config and origin_index == expected,
'served index differs from running web image')
for path, served_digest in assets.items():
require(hashlib.sha256(read_asset(path)).hexdigest() == served_digest, 'served asset differs from running web image')
return assets
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Read live release evidence and preview a plan without publishing or dispatching."""
import argparse
import json
from pathlib import Path
import re
import sys
from urllib.error import HTTPError
import candidate_coordinator as coordinator
import candidate_release as candidate
import candidate_worker as worker
import production_cd as cd
SOURCE = Path.home() / '.local/share/kg-candidate-source.git'
SITE = 'http://100.85.111.121:8088/'
def task_record(value):
cd.require(cd.matches(cd.UUID, value) or re.fullmatch(r'CYWL-[1-9][0-9]{0,8}', value),
'provide a task UUID or CYWL task number')
record = coordinator.hfx.hifox(coordinator.CLI, 'task', 'view', value)
cd.require(isinstance(record, dict) and record.get('spaceId') == cd.SPACE, 'task is outside the release space')
cd.require(cd.matches(cd.UUID, record.get('id')) and value in (record['id'], record.get('identifier')),
'task identity did not match')
return record
def ci_state(sha):
status = candidate.read_forge(f'{candidate.API}/commits/{sha}/status')
contexts = {line.split('#', 1)[0].strip() for line in candidate.CONTEXTS.read_text().splitlines()} - {''}
latest = {name: next((row for row in status.get('statuses') or [] if row.get('context') == name), None)
for name in sorted(contexts)}
result = {}
for name, row in latest.items():
row = row or {}
url = (row.get('target_url') or '').replace('http://192.168.50.223:3000/', cd.FORGE + '/', 1)
if url.startswith('/' + cd.REPO + '/'):
url = cd.FORGE + url
result[name] = {'status': row.get('status', 'not_reported'), 'url': url if url.startswith(cd.FORGE + '/') else ''}
return result
def snapshot():
branch = candidate.read_forge(f'{candidate.API}/branches/main')
sha = branch['commit']['id']
cd.require(cd.matches(cd.SHA, sha), 'Gitea did not return a full main SHA')
active = worker.main_site_sha()
block = None
try:
coordinator.runtime.qa_database(Path.home() / '.config/knowledge-governance/qa.json')
except (cd.CDError, coordinator.runtime.qa_env.QAError, OSError):
block = '候选执行机未就绪。缺少可用的专用 QA 数据库连接配置。'
return {'main_sha': sha, 'main_ci': ci_state(sha), 'site': SITE, 'site_api_sha': active,
'candidate_configuration_block': block}
def pr_record(number):
cd.require(type(number) is int and number > 0, 'invalid PR number')
result = candidate.read_forge(f'{candidate.API}/pulls/{number}')
return {**result, 'public_url': f'{cd.FORGE}/{cd.REPO}/pulls/{number}'}
def describe_task(value):
task = task_record(value)
acceptance = cd.metadata(task, 'cd_acceptance')
release = cd.metadata(task, 'cd_release')
result = {'task': task['identifier'], 'uuid': task['id'], 'url': task['url'],
'status': (task.get('status') or {}).get('name'), 'acceptance': acceptance, 'release': release}
try:
plan = coordinator.owner_plan(task['id'])
except cd.CDError as exc:
result['candidate'] = {'state': 'unavailable', 'reason': str(exc)}
return result
key = cd.acceptance_digest(plan)
receipt = coordinator.STATE / key / 'ready.json'
dispatch = coordinator.STATE / (key + '.dispatch.json')
if receipt.is_file():
data = cd.read_json(cd.immutable_file(receipt))
result['candidate'] = {field: data.get(field) for field in ('sha', 'bundle', 'url', 'mode', 'ready_at')}
elif dispatch.is_file():
data = cd.read_json(cd.immutable_file(dispatch))
result['candidate'] = {field: data.get(field) for field in ('state', 'run', 'url')}
if data.get('run') and cd.matches(coordinator.hfx.RUN_ID, data['run']):
run = candidate.read_forge(candidate.API + '/actions/runs/' + data['run'])
result['candidate'].update(workflow_status=run.get('status'), conclusion=run.get('conclusion'))
else:
result['candidate'] = {'state': 'unprepared', 'sha': plan['sha']}
return result
def preview(release_task, items, candidate_sha=None):
state = snapshot()
sha, base = candidate_sha or state['main_sha'], state['site_api_sha']
cd.require(cd.matches(cd.SHA, sha), 'invalid candidate SHA')
launch = task_record(release_task)
cd.require((launch.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
'choose a separate pre-approval release task')
content = []
landed = set()
for pair in items:
task_key, separator, number = pair.partition(':')
if separator and cd.matches(cd.SHA, number):
requirement = task_record(task_key)
landed.add(number)
content.append({'task': requirement['id'], 'commit': number})
continue
cd.require(bool(separator) and bool(re.fullmatch(r'[1-9][0-9]{0,8}', number)), 'expected task:PR')
requirement = task_record(task_key)
pr = pr_record(int(number))
change = pr.get('merge_commit_sha')
cd.require(pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, change),
f'PR #{number} has not landed on main')
fields = [pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')]
cd.require(bool(re.search(rf"(?<![\w-]){re.escape(requirement['identifier'])}(?!\w)",
' '.join(value or '' for value in fields), re.IGNORECASE)), 'PR task mismatch')
landed.add(change)
content.append({'task': requirement['id'], 'pr': int(number)})
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=SOURCE)
cd.require(candidate.git('rev-parse', 'origin/main', cwd=SOURCE) == state['main_sha'], 'main changed while reading release scope')
cd.require(candidate.git('merge-base', sha, base, cwd=SOURCE, allowed=(0, 1)) == base,
'main does not contain the running source')
rows = candidate.git('log', '--first-parent', '--format=%H %s', f'{base}..{sha}', cwd=SOURCE).splitlines()
extra = [{'sha': line.split(' ', 1)[0], 'subject': line.partition(' ')[2]}
for line in rows if line.split(' ', 1)[0] not in landed]
plan = {'task': launch['id'], 'base': base, 'sha': sha, 'items': content, 'extra': [row['sha'] for row in extra]}
candidate.verify_source(plan, SOURCE)
return {'state': 'preview_only', 'release_task': launch['url'], 'plan': plan,
'extra_for_owner_review': extra, 'candidate_ci': ci_state(sha), 'main_ci': state['main_ci'],
'candidate_configuration_block': state['candidate_configuration_block']}
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
status = sub.add_parser('status')
status.add_argument('--task')
status.add_argument('--pr', type=int)
plan = sub.add_parser('plan')
plan.add_argument('release_task')
plan.add_argument('items', nargs='+', metavar='TASK:PR_OR_COMMIT')
plan.add_argument('--sha')
args = parser.parse_args()
if args.command == 'plan':
result = preview(args.release_task, args.items, args.sha)
else:
result = snapshot()
if args.pr is not None:
pr = pr_record(args.pr)
result['pr'] = {'number': args.pr, 'state': pr.get('state'), 'url': pr['public_url'],
'merged': pr.get('merged'), 'landed_sha': pr.get('merge_commit_sha'),
'head_sha': (pr.get('head') or {}).get('sha')}
if args.task:
result['release_task'] = describe_task(args.task)
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
try:
main()
except HTTPError as exc:
sys.exit(f'Release assistant: provider HTTP {exc.code}')
except cd.CDError as exc:
sys.exit(f'Release assistant: {exc}')
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
sys.exit(f'Release assistant: {type(exc).__name__}')
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event."""
import argparse
import html
import json
import re
import sys
import candidate_coordinator as coordinator
import candidate_release as candidate
import production_cd as cd
import release_assistant as assistant
WHITE = '85f8325f-2b75-423d-a05a-4c7b2dd2c8e6'
ASSISTANT = '3b0b9cbb-d46d-4a06-b6cb-bafa7837499b'
DEVELOPERS = {'ea783c59-2100-465b-96d9-b02846b15a69', '6643e064-50de-49c5-bdaa-efc916187165',
'649363a5-34e5-49c9-b0bc-7fa0371c5a86'}
DIRECTORY = coordinator.STATE / 'handoffs'
REPO_URL = cd.FORGE + '/' + cd.REPO
def cli(*args):
return coordinator.hfx.hifox(coordinator.CLI, *args)
def comments(task):
return cli('task', 'comment', 'list', task, '--limit', '0')
def author(row):
return (row.get('author') or {}).get('id')
def review_identity(task, rows, event):
reviews = sorted((r for r in rows if author(r) == WHITE and r.get('taskId') == task['id']
and r['content'].startswith('🚦')), key=lambda r: r['createdAt'], reverse=True)
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
review = reviews[0]
cd.require(review['content'].startswith('🚦 可测试 ✅') and f"mention://task/{task['id']}" in review['content'].splitlines()[0],
'preflight is not a passing verdict for this task')
hashes = set(re.findall(r'落地\s*(?:(merge))?\s*`([0-9a-f]{7,40})`', review['content']))
cd.require(len(hashes) == 1, 'preflight needs an unambiguous landed commit')
short = hashes.pop()
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
if packages:
cd.require(packages[0]['createdAt'] <= review['createdAt'], 'new developer delivery needs fresh preflight')
return short, packages[0]['content'] if packages else ''
def resolve(task, event):
cd.require(task['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'require a QA-stage business task')
cd.require(not any(f.get('name') == 'staging_tag' and (f.get('value') or {}).get('text') == 'manual'
for f in task.get('customFields') or []), 'manually managed QA task')
short, package = review_identity(task, comments(task['id']), event)
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=assistant.SOURCE)
sha = candidate.git('rev-parse', '--verify', short + '^{commit}', cwd=assistant.SOURCE)
cd.require(cd.matches(cd.SHA, sha), 'ambiguous landed commit')
# For standard merges, the first-parent merge message supplies the PR number. Verify its identity with Gitea.
subject = candidate.git('show', '-s', '--format=%s', sha, cwd=assistant.SOURCE)
numbers = set(re.findall(r'#(\d+)\b', subject)) | set(re.findall(re.escape(REPO_URL) + r'/pulls/(\d+)\b', package))
for number in sorted(numbers):
pr = assistant.pr_record(int(number))
if pr.get('merge_commit_sha') == sha and pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main':
fields = ' '.join(v or '' for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
if re.search(rf"(?<![\w-]){re.escape(task['identifier'])}(?![\w-])", fields, re.I):
return sha, number
cd.require(REPO_URL + '/commit/' + sha in package and re.search(r'已合并[^\n]*' + sha, package),
'developer delivery does not confirm this landed revision in the governance repository')
return sha, sha
def frozen_approval(task_id, comment_id=None):
"""An owner reply to the specific, unedited scope preview authorizes this immutable local plan."""
path = DIRECTORY / (task_id + '.preview.json')
if not path.exists():
return None
saved = cd.read_json(cd.immutable_file(path))
rows = comments(task_id)
parent = next((r for r in rows if r['id'] == saved['comment']), {})
cd.require(parent.get('content') == saved['content'], 'scope preview has changed')
replies = [r for r in rows if r.get('parentId') == saved['comment'] and author(r) == cd.RELEASE_OWNER
and (r.get('author') or {}).get('type') == 'human' and not r.get('runId')]
if replies:
latest = max(replies, key=lambda r: r['createdAt'])
if ((comment_id is None or latest['id'] == comment_id)
and latest['content'].strip() in ('确认范围', '「确认范围」')):
return saved['plan']
return None
def preflight(task, event=None):
sha, ref = resolve(task, event)
label = f"知识治理发布批次|{task['identifier']} · {sha[:12]}"
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
claim = DIRECTORY / f"{task['id']}-{sha}.json"
with cd.deploy_lock(DIRECTORY / 'handoff.lock'):
# Validate range, all ingredients and CI before creating any task. A fresh UUID is only a dry-run identity.
import uuid
scope = {'task': str(uuid.uuid4()), 'items': [{'task': task['id'], **({'commit': sha} if ref == sha else {'pr': int(ref)})}],
'sha': sha, 'base': assistant.worker.main_site_sha()}
scope['extra'] = [s for s in candidate.git('rev-list', '--first-parent', f"{scope['base']}..{sha}", cwd=assistant.SOURCE).splitlines() if s != sha]
candidate.verify_source(scope, assistant.SOURCE)
if event:
review_identity(task, comments(task['id']), event)
children = cli('task', 'list', '--parent', task['id'], '--limit', '100')
matches = [r for r in children if r['title'] == label]
cd.require(len(children) < 100 and len(matches) <= 1, 'ambiguous release record')
if matches:
cd.require(claim.exists(), 'unclaimed release record needs reconciliation')
launch = coordinator.task(matches[0]['id'])
else:
cd.require(not claim.exists(), 'previous creation outcome needs reconciliation')
cd.record(claim, {'state': 'creating'})
created = cli('task', 'create', '--space', cd.SPACE, '--parent', task['id'], '--type', '需求',
'--title', label, '--status', '待开始', '--assignee', 'agent:' + ASSISTANT,
'--body', f"{task['identifier']} 独立发布单。系统将回填版本范围预览,请等待负责人确认。")
launch = coordinator.task(created['id'])
cd.require(launch['parentTaskId'] == task['id'] and launch['title'] == label and
(launch.get('delegate') or {}).get('id') == ASSISTANT, 'release handoff readback mismatch')
cd.record(claim, {'state': 'created', 'release': launch['id']})
scope['task'] = launch['id']
candidate.check_plan(scope)
path = DIRECTORY / (launch['id'] + '.preview.json')
if path.exists():
saved = cd.read_json(cd.immutable_file(path))
cd.require(scope == saved['plan'], 'baseline or scope changed; review a fresh batch')
return {'state': 'existing_preview', 'url': launch['url'], 'plan': scope}
lines = [f"{s[:12]} {candidate.git('show', '-s', '--format=%s', s, cwd=assistant.SOURCE)}" for s in scope['extra']]
safe_title = ' '.join(task['title'].splitlines()).replace('```', '')
body = f"发布范围预览 · {task['identifier']}\n\n线上基线 `{scope['base']}`\n\n候选 `{sha}`\n\n本次修复:{safe_title}\n\n同批改动:\n" + '\n'.join(lines or ['无']) + '\n\n请负责人在这条评论下回复「确认范围」,系统将据此准备候选包。'
marker = '[KG candidate scope ' + cd.acceptance_digest(scope) + ']'
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')]
if not entries:
cli('task', 'comment', launch['id'], '--body', marker + '\n\n' + body)
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')]
cd.require(len(entries) == 1, 'expected one scope preview comment')
stored = entries[0]
normalized = html.unescape(stored['content']).replace(
f"[{task['identifier']}](mention://task/{task['id']})", task['identifier'])
cd.require(normalized == marker + '\n\n' + body, 'scope preview readback differs from plan')
comment = stored['id']
cd.record(path, {'plan': scope, 'comment': comment, 'content': stored['content']})
return {'state': 'awaiting_scope', 'url': launch['url'], 'plan': scope}
def qa(task, row):
cd.require(author(row) in coordinator.QA_AUTHORS and row.get('taskId') == task['id'], 'require designated QA author')
match = coordinator.QA_FENCE.search(row['content'])
cd.require(match, 'missing structured QA evidence')
report = json.loads(match[1]); bundle = report.get('bundle')
cd.require(cd.matches(cd.HASH, bundle), 'missing tested archive digest')
hits = []
for p in coordinator.STATE.glob('*/ready.json'):
receipt = cd.read_json(cd.immutable_file(p))
if receipt.get('bundle') == bundle and receipt.get('sha') == report.get('sha'):
manifest = cd.read_json(cd.immutable_file(p.parent / 'bundle/release.json'))
hits.append(manifest['task'])
cd.require(len(hits) == 1, 'require one formal candidate for this report')
plan = coordinator.owner_plan(hits[0])
cd.require(task['id'] in [plan['task']] + [i['task'] for i in plan['items']], 'report is outside the batch')
return coordinator.register(hits[0])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('preflight', 'qa', 'scope', 'recover'))
parser.add_argument('task'); parser.add_argument('comment', nargs='?'); args = parser.parse_args()
task = assistant.task_record(args.task)
if args.action == 'recover':
return preflight(task)
cd.require(cd.matches(cd.UUID, args.comment), 'require comment event UUID')
rows = comments(task['id']); row = next((r for r in rows if r['id'] == args.comment), {})
cd.require(row.get('taskId') == task['id'], 'event comment belongs to another task')
if args.action == 'preflight':
return preflight(task, args.comment)
if args.action == 'scope':
cd.require(frozen_approval(task['id'], row['id']),
'require the release owner reply on the exact scope preview')
return coordinator.queue(task['id'])
return qa(task, row)
if __name__ == '__main__':
try:
print(json.dumps(main(), ensure_ascii=False))
except (cd.CDError, OSError, ValueError, KeyError) as exc:
sys.exit(f'Release handoff: {exc}')
+7
View File
@@ -28,6 +28,13 @@ class CandidateReleaseTest(unittest.TestCase):
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, OTHER, B])
def test_reviewed_direct_commit_can_be_pinned_before_later_main_changes(self):
plan = dict(self.plan, items=[{'task': QA1, 'commit': B}], extra=[A])
candidate.check_scope(plan, self.prs.__getitem__, [B, A])
for invalid in (dict(plan, extra=[A, B]), dict(plan, items=[{'task': QA1, 'commit': B[:7]}])):
with self.assertRaises(cd.CDError):
candidate.check_scope(invalid, self.prs.__getitem__, [B, A])
def test_pr_must_be_merged_on_main_and_match_range(self):
self.prs[20]['base']['ref'] = 'test'
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
+42
View File
@@ -0,0 +1,42 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import release_handoff as h
class ReleaseHandoffTest(unittest.TestCase):
def setUp(self):
self.task = {'id': 'task'}
self.review = {'id': 'comment', 'taskId': 'task', 'createdAt': '2', 'author': {'id': h.WHITE},
'content': '🚦 可测试 ✅|[任务](mention://task/task)\n落地 `abcdef1`'}
def test_latest_passing_review_and_task_identity(self):
self.assertEqual(h.review_identity(self.task, [self.review], 'comment')[0], 'abcdef1')
for invalid in (dict(self.review, author={'id': 'other'}), dict(self.review, taskId='other'),
dict(self.review, content='🚦 不可测试,引用「可测试」')):
with self.assertRaises(h.cd.CDError):
h.review_identity(self.task, [invalid], 'comment')
newer = dict(self.review, id='new', createdAt='3', content='🚦 未通过')
with self.assertRaises(h.cd.CDError):
h.review_identity(self.task, [self.review, newer], 'comment')
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
h.cd.record(Path(tmp) / 'task.preview.json', saved)
parent = {'id': 'preview', 'content': saved['content']}
reply = {'id': 'ok', 'createdAt': '2', 'content': '确认范围', 'parentId': 'preview',
'author': {'id': h.cd.RELEASE_OWNER, 'type': 'human'}}
with patch.object(h, 'comments', return_value=[parent, reply]):
self.assertEqual(h.frozen_approval('task'), saved['plan'])
quoted = dict(reply, content='「确认范围」')
with patch.object(h, 'comments', return_value=[parent, quoted]):
self.assertEqual(h.frozen_approval('task', 'ok'), saved['plan'])
self.assertIsNone(h.frozen_approval('task', 'other'))
for bad in (dict(reply, parentId=None), dict(reply, runId='agent-run'), dict(reply, content='先不确认范围')):
with patch.object(h, 'comments', return_value=[parent, bad]):
self.assertIsNone(h.frozen_approval('task'))
with patch.object(h, 'comments', return_value=[dict(parent, content='changed'), reply]), self.assertRaises(h.cd.CDError):
h.frozen_approval('task')
-717
View File
@@ -1,717 +0,0 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import {
BackupScheduleView,
backupDaysValid,
backupMonthsValid,
backupTimeValid,
copyBackupPath,
formatBackupBytes,
inventoryAlerts,
inventorySnapshotState,
inventoryUsage,
runMoment,
storageAlerts,
storageAlertSummary,
storageUsage,
} from './BackupScheduleSection'
import type { StorageDiskObservation } from './BackupScheduleSection'
import type { BackupInventory } from './backupInventory'
import type { BackupSchedule } from './backupSchedule'
const base: BackupSchedule = {
enabled: true,
schedule_time: '03:30',
retention_days: 7,
retention_months: 3,
updated_by: 'yaozhanghao',
updated_at: '2026-10-09T12:00:00Z',
last_applied_at: '2026-10-09T12:00:00Z',
last_applied_summary: '每天 03:30 · 保留 7 天 · 每月归档 3 份',
host_configured: true,
host_target: 'weknora-test',
host_endpoint: '100.85.111.121:22',
host_reachable: true,
host_error: '',
host_schedule_enabled: true,
host_schedule_time: '03:30',
host_keep_days: 7,
host_keep_months: 3,
host_cron_lines: [
'30 03 * * * root /bin/bash /opt/weknora-test/logical-backup.sh >> /srv/kb-backups/logs/logical-backup.log 2>&1',
],
host_cron_service: 'active',
host_script_present: true,
last_run_stamp: '20261009T052909Z',
last_run_created_at: '2026-10-09T05:29:09Z',
last_run_duration_seconds: 33,
last_run_total_bytes: 778_502_144,
last_run_databases: ['weknora_test', 'dobotai_prod'],
last_run_failed_databases: [],
last_run_error: '',
in_sync: true,
applied: true,
apply_error: '',
running: false,
running_started_at: '',
run_last_error: '',
}
const GiB = 1024 * 1024 * 1024
const diskFixture = (overrides: Partial<StorageDiskObservation> = {}): StorageDiskObservation => ({
total_bytes: 240 * GiB,
free_bytes: 48 * GiB,
backup_bytes: 62 * GiB,
other_volume_backup_bytes: 0,
quota_bytes: 100 * GiB,
reserve_bytes: 10 * GiB,
estimate_bytes: 12 * GiB,
sampled_at: '2026-11-19T02:00:00Z',
...overrides,
})
const inventoryFixture = (overrides: Partial<BackupInventory> = {}): BackupInventory => {
const baseInventory: BackupInventory = {
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/knowledge-governance/backup-host/metadata.json',
collected_at: '2026-11-19T03:30:00Z',
age_seconds: 10,
max_age_seconds: 900,
schema_version: 1,
generation: '20261119T033000Z-abc123',
host: 'weknora-test',
collector_version: 'backup-metadata/1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'weknora-test:/srv/kb-backups/rds-logical',
observed_at: '2026-11-19T03:30:10Z',
error: '',
measurement: 'host_collector',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 240 * GiB,
free_bytes: 48 * GiB,
available_bytes: 45 * GiB,
used_bytes: 192 * GiB,
},
batches: [
{
stamp: '20261118T193001Z',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z',
manifest_state: 'ok',
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json',
kind: 'rds-logical-backup',
created_at: '20261118T193001Z',
started_at: '20261118T192908Z',
duration_seconds: 53,
manifest_total_bytes: 1_393_646_469,
apparent_bytes: 1_393_646_469,
actual_bytes: 1_500_000_000,
file_count: 214,
sizes_complete: true,
databases: [
{
name: 'weknora_v090prod',
dir_name: 'weknora_v090prod.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 700_000,
actual_bytes: 720_896,
file_count: 12,
},
{
name: 'weknora_test',
dir_name: 'weknora_test.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_test.dir',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_test.dir',
present: true,
failed: true,
in_manifest: true,
apparent_bytes: 10,
actual_bytes: 4096,
file_count: 1,
},
],
},
{
stamp: '20261117T193001Z',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z',
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z',
manifest_state: 'invalid',
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/MANIFEST.json',
manifest_error: '清单无法解析:unexpected end of JSON input',
kind: '',
created_at: '',
started_at: '',
duration_seconds: 0,
manifest_total_bytes: 0,
apparent_bytes: 2048,
actual_bytes: 4096,
file_count: 1,
sizes_complete: true,
databases: [
{
name: 'weknora_archive',
dir_name: 'weknora_archive.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/weknora_archive.dir',
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
present: false,
failed: false,
in_manifest: false,
apparent_bytes: 0,
actual_bytes: 0,
file_count: 0,
},
],
},
],
totals: {
batch_count: 2,
database_count: 3,
apparent_bytes: 1_393_648_517,
actual_bytes: 1_500_004_096,
latest_stamp: '20261118T193001Z',
latest_actual_bytes: 1_500_000_000,
complete: true,
},
incomplete_count: 1,
skipped: [{ name: 'junk', reason: '不是批次目录' }],
truncated: false,
}
return { ...baseInventory, ...overrides }
}
const view = (
overrides: Partial<BackupSchedule> = {},
extra: Record<string, unknown> = {},
disk: StorageDiskObservation | null = null
) => {
const schedule = { ...base, ...overrides }
return renderToStaticMarkup(
<BackupScheduleView
schedule={schedule}
isAdmin={(extra.isAdmin as boolean) ?? true}
loading={false}
probing={false}
busy={(extra.busy as 'save' | 'apply' | 'run' | null) ?? null}
error={(extra.error as string | null) ?? null}
message={(extra.message as string) ?? ''}
enabledDraft={(extra.enabledDraft as boolean) ?? schedule.enabled}
timeDraft={(extra.timeDraft as string) ?? schedule.schedule_time}
daysDraft={(extra.daysDraft as string) ?? String(schedule.retention_days)}
monthsDraft={(extra.monthsDraft as string) ?? String(schedule.retention_months)}
onEnabledChange={vi.fn()}
onTimeChange={vi.fn()}
onDaysChange={vi.fn()}
onMonthsChange={vi.fn()}
onSave={vi.fn()}
onApply={vi.fn()}
onRunNow={vi.fn()}
onReload={vi.fn()}
disk={disk}
inventory={(extra.inventory as BackupInventory) ?? null}
inventoryLoading={(extra.inventoryLoading as boolean) ?? false}
inventoryError={(extra.inventoryError as string | null) ?? null}
onReloadInventory={vi.fn()}
/>
)
}
describe('BackupScheduleView', () => {
it('按真实契约给出范围与读写方向,并把立即备份限定为整批', () => {
const html = view()
for (const text of [
'存储与备份',
'数据库整库逻辑备份',
'范围与读写方向',
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'元数据快照未读取',
'元数据快照未读取:目录不可验证,不按设置推定',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
'不开放单库动作',
'仅备份该库(不可用)',
])
expect(html).toContain(text)
// 不存在把整批接口包装成单库操作的按钮文案。
expect(html).not.toContain('>立即备份</button>')
expect(html).not.toContain('生产 090')
expect(html).not.toContain('weknora_v090prod')
})
it('策略区分主机生效状态与编辑草稿,保留期与时间仍是真实可保存字段', () => {
const html = view({}, { timeDraft: '05:10', daysDraft: '14' })
expect(html).toContain('主机生效:每天 03:30 · 保留 7 天 · 每月 3 份 · 与设置已一致')
expect(html).toContain('最后下发(历史)')
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
expect(html).toContain('编辑草稿:每天 05:10 · 保留 14 天')
expect(html).toContain('有未保存修改,主机仍按生效计划执行')
expect(html).toContain('type="time"')
expect(html).toContain('value="05:10"')
expect(html).toContain('储存天数')
expect(html).toContain('每月归档保留')
expect(html).toContain('保存并下发到主机')
expect(html).toContain('重新下发当前设置')
})
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
expect(html).toContain('元数据快照未读取')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
expect(html).toContain('不会被保存')
expect(html).toContain('保存只提交后端契约里的四项')
expect(html).toContain('disabled')
})
it('宿主快照:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
const html = view({}, { inventory: inventoryFixture() })
for (const text of [
'备份记录',
'2 批 · 元数据快照',
'最近批次 20261118T193001Z',
'清单完整',
'清单损坏',
'批次戳 20261118T193001Z',
'实际占盘',
'weknora_v090prod',
'weknora_test',
'已写入',
'失败',
'目录缺失',
'/srv/kb-backups/rds-logical/20261118T193001Z',
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
'/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
'复制子库目录',
'清单无法解析',
'有 1 个',
'junk(不是批次目录)',
'恢复验证:未接线',
])
expect(html).toContain(text)
expect(html).not.toContain('子库路径待接口返回')
expect(html).not.toContain('复制目录(不可用)')
})
it('没有快照:不展示任何历史批次或伪造路径', () => {
const html = view()
expect(html).toContain('尚未读取宿主元数据快照')
expect(html).not.toContain('批次戳')
expect(html).not.toContain('/srv/kb-backups/rds-logical')
})
it('快照未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
const base = inventoryFixture()
const html = view(
{},
{
inventory: inventoryFixture({
wired: false,
metadata: {
...base.metadata,
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
}),
}
)
expect(html).toContain('元数据快照未接线')
expect(html).toContain('未读到批次不等于没有备份')
expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
})
it('快照可读但没有批次时说明不能据此判断成功/失败', () => {
const html = view(
{
last_run_stamp: '',
last_run_created_at: '',
last_run_databases: [],
last_run_total_bytes: 0,
host_reachable: false,
},
{
inventory: inventoryFixture({
batches: [],
totals: {
batch_count: 0,
database_count: 0,
apparent_bytes: 0,
actual_bytes: 0,
latest_stamp: '',
latest_actual_bytes: 0,
complete: true,
},
}),
}
)
expect(html).toContain('宿主快照可读,但没有批次目录')
expect(html).toContain('不能证明备份成功或失败')
})
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
const html = view({}, { isAdmin: false })
expect(html).toContain('定时备份设置仅管理员可修改')
expect(html).toContain('立即备份仅管理员可触发')
expect(html).not.toContain('保存并下发到主机')
expect(html).not.toContain('立即备份一次(整批')
})
it('无主机凭据:不能宣称远端计划停止,历史下发只作历史记录', () => {
const html = view({
host_configured: false,
host_reachable: false,
host_error: '目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)',
in_sync: false,
})
expect(html).toContain('平台未挂载主机凭据(远端状态未知)')
expect(html).toContain('无法确认当前主机计划')
expect(html).toContain('远端 cron 可能仍在执行')
expect(html).toContain('历史下发不能代替实时状态')
expect(html).toContain('最后下发(历史)')
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
expect(html).toContain('无法比对(未读取主机计划)')
expect(html).toContain('未探测(平台未挂载主机凭据)')
expect(html).toContain('目标主机凭据未挂载')
// 没读到主机就断言"不会执行"是同类误报。
expect(html).not.toContain('不会执行')
expect(html).not.toContain('未接通备份执行主机')
expect(html).toContain('disabled')
})
it('主机已接线但尚未探测:区分"连不上"与"还没读",不按设置推定', () => {
const html = view({ host_reachable: false, host_error: '', host_checked_at: '', in_sync: false })
expect(html).toContain('weknora-test · 尚未探测')
expect(html).not.toContain('weknora-test · 连接失败')
expect(html).toContain('尚未探测当前主机计划:不能按设置或历史下发推定')
expect(html).toContain('尚未比对')
expect(html).toContain('尚未探测主机,无法确认下一次执行')
})
it('连不上主机:报连接失败与拨号地址,脚本状态写未知而不是"缺失"', () => {
const html = view({
host_reachable: false,
host_endpoint: '120.76.217.51:22',
host_error:
'目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知(拨号地址 120.76.217.51:22)',
in_sync: false,
host_script_present: false,
})
expect(html).toContain('weknora-test · 连接失败')
expect(html).toContain('120.76.217.51:22')
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
expect(html).not.toContain('<dt>备份脚本</dt><dd>缺失</dd>')
expect(html).toContain('主机连不上:以下&quot;主机生效&quot;状态未知')
expect(html).toContain('无法比对(主机不可达)')
})
it('已连上且脚本真的不在:这时才显示"缺失"', () => {
const html = view({ host_reachable: true, host_script_present: false, in_sync: false })
expect(html).toContain('weknora-test · 已连接')
expect(html).toContain('缺失')
expect(html).not.toContain('未知(未连上主机')
})
it('待下发(主机上的计划与设置不一致)时提示', () => {
const html = view({ host_schedule_time: '05:00', in_sync: false })
expect(html).toContain('待下发')
expect(html).toContain('每天 05:00')
})
it('在途备份:只报在途与开始时间,不造百分比', () => {
const html = view({ running: true, running_started_at: '2026-10-09T12:30:00Z' })
expect(html).toContain('备份进行中…')
expect(html).toContain('正在备份')
expect(html).toContain('没有真实百分比接口')
})
it('非法输入就地拦截,且保存按钮在未改动时不可点', () => {
const html = view({}, { timeDraft: '25:99', daysDraft: '0' })
expect(html).toContain('定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。')
expect(html).toContain('disabled')
expect(backupTimeValid('03:30')).toBe(true)
expect(backupTimeValid('24:00')).toBe(false)
expect(backupDaysValid(0)).toBe(false)
expect(backupDaysValid(365)).toBe(true)
expect(backupMonthsValid(0)).toBe(true)
expect(backupMonthsValid(25)).toBe(false)
})
it('展示失败的库与最近一次读取错误', () => {
const html = view({ last_run_failed_databases: ['rdsadmin'], last_run_error: '清单无法解析' })
expect(html).toContain('rdsadmin')
expect(html).toContain('清单无法解析')
})
it('最近一次备份不重复显示同一个时间戳', () => {
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '20261009T060736Z' })).toBe('')
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '' })).toBe('')
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '2026-10-09T06:07:36Z' })).not.toBe('')
})
it('体积格式化:未知与零分开', () => {
expect(formatBackupBytes(0)).toBe('0 B')
expect(formatBackupBytes(null)).toBe('—')
expect(formatBackupBytes(undefined)).toBe('—')
expect(formatBackupBytes(1024 * 1024)).toBe('1.0 MiB')
expect(formatBackupBytes(4096)).toBe('4.0 KiB')
expect(formatBackupBytes(720896)).toBe('0.7 MiB')
expect(formatBackupBytes(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
})
})
describe('整盘占用与告警', () => {
it('没有快照时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
expect(html).toContain('占盘未知 · 不使用部分字节')
expect(html).toContain('宿主单项元数据采集器')
expect(html).toContain('无法判定')
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
expect(html).not.toContain('总容量 240 GiB')
expect(html).not.toContain('总容量 500 GiB')
expect(html).not.toContain('可再写')
})
it('四段色带按真实读数计算:系统其他、备份已用、配额内空闲、配额外空闲', () => {
const usage = storageUsage(diskFixture())
expect(usage.system_other).toBe(130 * GiB) // 240 - 48 - 62
expect(usage.backup).toBe(62 * GiB)
expect(usage.quota_free).toBe(38 * GiB)
expect(usage.beyond_quota_free).toBe(10 * GiB) // 48 - 38
expect(usage.allowance).toBe(38 * GiB)
const html = view({}, {}, diskFixture())
expect(html).toContain('系统其他占用 130 GiB')
expect(html).toContain('备份已用 62 GiB')
expect(html).toContain('配额内空闲 38 GiB')
expect(html).toContain('配额外空闲 10 GiB')
expect(html).toContain('四项均正常')
})
it('磁盘不足:只剩磁盘告警,差值与预计新增都来自读数', () => {
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(false)
expect(storageAlertSummary(alerts)).toBe('磁盘不足')
const html = view({}, {}, diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
expect(html).toContain('差 2 GiB')
})
it('配额不足:磁盘够、配额差 7 GiB', () => {
const alerts = storageAlerts(diskFixture({ backup_bytes: 95 * GiB }))
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'quota_low')?.detail).toContain('差 7 GiB')
expect(storageAlertSummary(alerts)).toBe('配额不足')
})
it('两者同时不足:第三条告警成立', () => {
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, backup_bytes: 95 * GiB }))
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(true)
expect(storageAlertSummary(alerts)).toContain('磁盘与配额同时不足')
})
it('配额超出物理空闲:配额余量大于盘上空闲时单独告警', () => {
const alerts = storageAlerts(diskFixture({ quota_bytes: 200 * GiB }))
expect(alerts.find((item) => item.code === 'quota_over_physical')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'quota_over_physical')?.detail).toContain('超出部分画不进磁盘')
})
it('缺下次新增体积时,磁盘/配额判定保持未知而不是默认正常', () => {
const alerts = storageAlerts(diskFixture({ estimate_bytes: null }))
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
})
it('真实快照:整盘色带取采集器容量与 st_blocks 实际占盘', () => {
const inventory = inventoryFixture()
const usage = inventoryUsage(inventory)
expect(usage).not.toBeNull()
expect(usage!.total).toBe(240 * GiB)
expect(usage!.free).toBe(45 * GiB)
expect(usage!.backup).toBe(1_500_004_096)
expect(usage!.system_other).toBe(192 * GiB - 1_500_004_096)
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(true)
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
expect(storageAlertSummary(alerts)).toBe('磁盘项正常 · 配额字段未接线')
const html = view({}, { inventory })
for (const text of [
'宿主采集器实测',
'系统其他占用',
'备份实际占盘',
'可用',
'配额内/外 —(无配额字段)',
'文件系统已用',
'采集时间',
'读回时间',
'(API 读回)',
'备份文件系统必须由备份主机可写',
'空间预测仅以上次整批实际占盘 1.40 GiB',
'宿主采集器:/dev/sdb1 挂在 /srv/kb-backups',
'磁盘项正常 · 配额字段未接线',
'0.7 MiB',
'重新盘点(仅重读快照)',
])
expect(html).toContain(text)
expect(html).not.toContain('挂载可写')
expect(html).not.toContain('不是只读')
expect(html).not.toContain('缺主机磁盘读数')
expect(html).not.toContain('0.0 MiB')
})
it('过期快照:目录与历史标已过期,不显示未接线,也不沿用旧批次/旧容量', () => {
const base = inventoryFixture()
const stale = inventoryFixture({
metadata: {
...base.metadata,
valid: false,
fresh: false,
complete: false,
age_seconds: 1200,
error: '元数据已陈旧:采集于 2026-11-19T03:30:00Z,超过 15m0s',
},
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
// 即使 API 意外保留旧批次,页面也不得用过期快照的路径/容量。
batches: base.batches,
})
expect(inventorySnapshotState(stale)).toBe('stale')
expect(inventoryUsage(stale)).toBeNull()
const alerts = inventoryAlerts(stale)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('陈旧')
const html = view({}, { inventory: stale })
for (const text of [
'元数据快照已过期',
'采集时间',
'年龄 1200 秒 / 上限 900 秒',
'已过期',
'读回时间',
'(API 读回)',
'不展示旧批次',
'元数据快照已过期:目录不可验证,不沿用旧路径',
'等待宿主重新采集',
'旧批次、旧目录与旧容量都不再展示',
])
expect(html).toContain(text)
expect(html).not.toContain('元数据快照未接线')
expect(html).not.toContain('/20261118T193001Z')
expect(html).not.toContain('实际占盘 1.40 GiB')
expect(html).not.toContain('文件系统已用')
})
it('未配置快照:明确未接线,不能冒充过期或展示目录/历史', () => {
const base = inventoryFixture()
const unconfigured = inventoryFixture({
wired: false,
metadata: {
...base.metadata,
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
source: '',
root: '',
host_root: '',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
batches: [],
})
expect(inventorySnapshotState(unconfigured)).toBe('unconfigured')
const html = view({}, { inventory: unconfigured })
expect(html).toContain('元数据快照未接线')
expect(html).toContain('目录不可证明')
expect(html).not.toContain('元数据快照已过期')
expect(html).not.toContain('不展示旧目录路径')
})
it('快照请求失败:与未配置/过期分开,不展示目录或旧批次', () => {
const html = view({}, { inventoryError: 'HTTP 503' })
expect(html).toContain('元数据快照读取失败')
expect(html).toContain('快照请求失败:HTTP 503')
expect(html).toContain('目录不可验证')
expect(html).not.toContain('元数据快照未接线')
expect(html).not.toContain('元数据快照已过期')
})
it('不完整快照:容量图与占盘不使用部分字节', () => {
const base = inventoryFixture()
const inventory = inventoryFixture({
metadata: {
...base.metadata,
complete: false,
error: '采集不完整:遍历失败:PermissionError: Permission denied',
},
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
batches: base.batches.map((batch) => ({
...batch,
apparent_bytes: null,
actual_bytes: null,
file_count: null,
sizes_complete: false,
sizes_error: '宿主采集器该项不完整,占盘未知',
databases: batch.databases.map((database) => ({
...database,
apparent_bytes: null,
actual_bytes: null,
file_count: null,
})),
})),
})
expect(inventoryUsage(inventory)).toBeNull()
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('不完整')
expect(storageAlertSummary(alerts)).toBe('无法判定(缺读数与配额字段)')
const html = view({}, { inventory })
expect(html).toContain('占盘未知 · 不使用部分字节')
expect(html).toContain('采集快照不完整:所有批次占盘与容量未知')
expect(html).toContain('占盘未知(采集不完整)')
expect(html).not.toContain('备份实际占盘 1.40 GiB')
expect(html).not.toContain('缺主机磁盘读数')
})
it('复制路径:空值与不可用按钮不谎报成功', async () => {
expect(await copyBackupPath('')).toBe(false)
})
})
File diff suppressed because it is too large Load Diff
+70 -2
View File
@@ -32,6 +32,12 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
})
const snapshot = {
data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true },
}
const snapshotWith = (secretEntryAllowed: boolean) => ({
data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed },
})
const snapshotWithoutCapability = {
data: { environments: [binding('test'), binding('production')], storage_ready: true },
}
const catalog = {
@@ -110,11 +116,11 @@ afterEach(async () => {
vi.unstubAllGlobals()
})
const render = async (role: 'admin' | 'viewer' = 'admin') => {
const render = async (role: 'admin' | 'viewer' = 'admin', consoleLocation?: { protocol: string; hostname: string }) => {
await act(async () => {
root.render(
<AuthContext.Provider value={auth(role)}>
<KnowledgeBaseBinding />
<KnowledgeBaseBinding consoleLocation={consoleLocation} />
</AuthContext.Provider>
)
})
@@ -272,4 +278,66 @@ describe('KnowledgeBaseBinding', () => {
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
expect(save?.hasAttribute('disabled')).toBe(true)
})
it('disables key entry when the server reports no accepted transport', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render()
await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(true)
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
})
it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true')
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
})
it('does not blame a proxy when an older API omits the capability', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability)))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
})
it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(false)
expect(host.textContent).toContain('密钥会以明文经过这段内网')
expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true')
})
it('does not warn on an HTTPS console the server already trusts', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).not.toContain('密钥会以明文经过这段内网')
})
it('keeps existing-key operations available while key entry is closed', async () => {
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false)))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
return Promise.resolve(json({ data: binding('test') }))
})
vi.stubGlobal('fetch', fetchMock)
await render()
await click('验证并读取知识库')
await choose('对内知识库', 'kb-new-in-0001')
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
// 没有新密钥也能改选库:keep 不经过密钥传输闸门。
expect(save?.hasAttribute('disabled')).toBe(false)
await click('保存测试绑定')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
const body = JSON.parse(String(put![1]?.body))
expect(body.key_action).toBe('keep')
expect(body.api_key).toBeUndefined()
expect(host.textContent).toContain('已保存测试绑定')
})
})
+32 -4
View File
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useOptionalAuth } from './auth'
import { secretEntryAllowed } from './secureEntry'
import { plaintextRemoteConsole } from './secureEntry'
import {
KBBindingError,
duplicateSelection,
@@ -82,7 +82,18 @@ const fallbackLabel = (fallback: string): string =>
const statusTone = (status: KBCatalog['status']): string =>
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
export function KnowledgeBaseBinding() {
interface ConsoleLocation {
protocol: string
hostname: string
}
// consoleLocation is injected by tests that need both console shapes; the app
// always uses the real window.
export function KnowledgeBaseBinding({
consoleLocation,
}: {
consoleLocation?: ConsoleLocation
} = {}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null)
@@ -135,7 +146,13 @@ export function KnowledgeBaseBinding() {
const busyNow = busy[env]
const notice = notices[env]
const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location)
const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
// The server decides whether it will accept a key on this connection; the
// browser URL cannot tell a trusted TLS proxy from an untrusted one.
const secretEntryAllowed = snapshot?.secret_entry_allowed
const secure = secretEntryAllowed === true
const plaintext = secure && plaintextRemoteConsole(console)
const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:'
const storageReady = Boolean(snapshot?.storage_ready)
const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
@@ -518,9 +535,20 @@ export function KnowledgeBaseBinding() {
)}
</div>
</div>
{!secure ? (
{untrustedProxy ? (
<p className="settings-warn">
服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递
X-Forwarded-Proto。
</p>
) : !secure ? (
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
) : null}
{plaintext ? (
<p className="settings-warn">
当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网
HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。
</p>
) : null}
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
) : null}
-175
View File
@@ -1,175 +0,0 @@
import { useEffect, useState } from 'react'
import { fetchLibraryStorage, formatBytes, type LibraryStorage } from './librarySnapshots'
import './libraryStorage.css'
// 系统设置 → 存储管理:只读展示整库归档的真实口径。
// 保留策略、依赖保护、清理预览都只是"如果清理会怎样",没有任何删除动作;
// 自动清理恒为关闭,策略未设置时不生成候选。
export function LibraryStorageSection() {
const [data, setData] = useState<LibraryStorage | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const controller = new AbortController()
fetchLibraryStorage(controller.signal)
.then((value) => {
setData(value)
setError(null)
})
.catch((loadError) => {
if ((loadError as Error).name === 'AbortError') return
setError(loadError instanceof Error ? loadError.message : '读取存储用量失败')
})
.finally(() => setLoading(false))
return () => controller.abort()
}, [])
const plan = data?.plan
const policyConfigured = Boolean(plan?.policy_configured)
return (
<section className="library-storage" aria-label="存储管理">
<header>
<h3>归档占用(版本快照,不是数据库备份)</h3>
<p>
只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。
这些归档文件与上面的整库数据库备份分开计量,不能相加。
</p>
</header>
{loading ? <p className="library-storage-hint">读取中…</p> : null}
{error ? (
<div className="library-storage-blocked">
<strong>读取失败</strong>
<p>{error}</p>
</div>
) : null}
{data && !data.available ? <p className="library-storage-hint">{data.reason || '归档未接线'}</p> : null}
{data?.available ? (
<>
<dl className="library-storage-grid">
<div>
<dt>版本数</dt>
<dd>{data.versions.length}</dd>
</div>
<div>
<dt>被版本引用的去重内容</dt>
<dd>{formatBytes(data.content_bytes)}</dd>
</div>
<div>
<dt>blob 文件(表观)</dt>
<dd>{formatBytes(data.blob_file_bytes)}</dd>
</div>
<div>
<dt>blob 实际分配</dt>
<dd>{formatBytes(data.blob_allocated_bytes)}</dd>
</div>
<div>
<dt>未被任何版本引用</dt>
<dd>
{data.unreferenced_blobs} 个 / {formatBytes(data.unreferenced_bytes)}
</dd>
</div>
<div>
<dt>清单文件</dt>
<dd>{formatBytes(data.manifest_file_bytes)}</dd>
</div>
</dl>
<div className="library-storage-panel">
<h4>容量门禁</h4>
{data.capacity.configured ? (
<p>
预算 {formatBytes(data.capacity.budget_bytes)} · 当前 {formatBytes(data.capacity.current_bytes)} ·
目标版本约 {formatBytes(data.capacity.required_bytes)} →{' '}
{data.capacity.ok ? '可写入' : `阻断:${data.capacity.reason}`}
</p>
) : (
<p className="library-storage-warn">
容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,生产写入按阻断处理。
</p>
)}
</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) => (
<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)}(共享归档文件不会因此释放,这不是可回收空间)。
</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>
)
}
+224
View File
@@ -0,0 +1,224 @@
// @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 type { Mock } from 'vitest'
import { MembersSection } from './MembersSection'
type FetchStub = (path: string, init?: RequestInit) => Promise<Response>
let root: Root, host: HTMLDivElement
let fetcher: Mock<FetchStub>
let postStatus: 'ok' | 400 | 409 | 'pending'
let releasePost: (() => void) | null
const PASSWORD = 'test-only-pass'
const roster = [
{
id: 'u1',
username: 'wangwu',
display_name: '王五',
role: 'engineer',
state: 'active',
must_change_password: false,
last_login_at: null,
},
]
const json = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status })
const dialog = () => host.querySelector<HTMLElement>('[role=dialog]')
const trigger = () => host.querySelector<HTMLButtonElement>('button[aria-label="新增成员"]')
const submit = () =>
[...(dialog()?.querySelectorAll('button') ?? [])].find((b) => b.textContent?.trim() === '新增成员') as
HTMLButtonElement | undefined
const button = (label: string) =>
[...(dialog()?.querySelectorAll('button') ?? [])].find((b) => b.textContent?.trim() === label) as
HTMLButtonElement | undefined
const input = (label: string) => {
const wrapper = [...(dialog()?.querySelectorAll('label') ?? [])].find((l) =>
l.textContent?.trimStart().startsWith(label)
)
return wrapper?.querySelector('input') as HTMLInputElement | undefined
}
const alerts = () => [...host.querySelectorAll('[role=alert]')]
const type = async (label: string, value: string) => {
const field = input(label)
expect(field, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(field, value)
field!.dispatchEvent(new Event('input', { bubbles: true }))
})
}
const open = async () => {
await act(async () => trigger()!.click())
}
const pressEscape = async () => {
await act(async () => {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }))
})
}
const fillValid = async () => {
await type('用户名', 'li.si')
await type('姓名', ' 李四 ')
await type('初始密码', PASSWORD)
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
postStatus = 'ok'
releasePost = null
host = document.createElement('div')
document.body.append(host)
root = createRoot(host)
fetcher = vi.fn(async (path: string, init?: RequestInit) => {
const method = init?.method ?? 'GET'
const created = () => {
const body = JSON.parse(String(init?.body)) as Record<string, unknown>
return json({ id: 'u2', state: 'active', must_change_password: true, last_login_at: null, ...body }, 201)
}
if (path === '/api/v1/users' && method === 'GET') return json(roster)
if (path === '/api/v1/users' && method === 'POST') {
if (postStatus === 409) return new Response(JSON.stringify({ error: 'username already exists' }), { status: 409 })
if (postStatus === 400) return new Response(JSON.stringify({ error: 'invalid user' }), { status: 400 })
if (postStatus === 'pending') {
const promise = new Promise<Response>((resolve) => {
releasePost = () => resolve(created())
})
return promise
}
return created()
}
throw new Error(`unexpected ${method} ${path}`)
})
vi.stubGlobal('fetch', fetcher)
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
describe('成员新增抽屉', () => {
it('starts with a header button and no inline form or dialog', async () => {
await act(async () => root.render(<MembersSection />))
expect(trigger()).toBeTruthy()
expect(dialog()).toBeNull()
expect(host.querySelector('.member-create-form')).toBeNull()
})
it('opens an accessible drawer and focuses the username field', async () => {
await act(async () => root.render(<MembersSection />))
await open()
expect(dialog()).toBeTruthy()
expect(dialog()!.getAttribute('aria-modal')).toBe('true')
expect(dialog()!.textContent).toContain('新增成员')
expect(document.activeElement).toBe(input('用户名'))
})
it('reports every empty field on submit without sending a request', async () => {
await act(async () => root.render(<MembersSection />))
await open()
await act(async () => submit()!.click())
expect(dialog()).toBeTruthy()
expect(alerts().map((node) => node.textContent)).toEqual(
expect.arrayContaining(['请输入用户名', '请输入姓名', '请输入初始密码'])
)
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(0)
})
it('creates a trimmed member, closes, reloads, and restores focus', async () => {
await act(async () => root.render(<MembersSection />))
await open()
await fillValid()
await act(async () => submit()!.click())
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')
expect(JSON.parse(String(post?.[1]?.body))).toEqual({
username: 'li.si',
display_name: '李四',
role: 'engineer',
password: PASSWORD,
})
expect(dialog()).toBeNull()
expect(host.textContent).toContain('成员 li.si 已创建,初始密码只用于首次登录')
expect(
fetcher.mock.calls.filter(([path, init]) => path === '/api/v1/users' && init?.method === 'GET')
).toHaveLength(2)
expect(document.activeElement).toBe(trigger())
})
it('keeps the draft and pins a 409 to the username field', async () => {
await act(async () => root.render(<MembersSection />))
postStatus = 409
await open()
await fillValid()
await act(async () => submit()!.click())
expect(dialog()).toBeTruthy()
expect(dialog()!.textContent).toContain('该用户名已存在')
expect(input('初始密码')!.value).toBe(PASSWORD)
expect(alerts().filter((node) => !dialog()!.contains(node))).toHaveLength(0)
})
it('shows a form-level chinese error for 400 and stays open', async () => {
await act(async () => root.render(<MembersSection />))
postStatus = 400
await open()
await fillValid()
await act(async () => submit()!.click())
expect(dialog()).toBeTruthy()
expect(dialog()!.textContent).toContain('用户信息不符合规则,请检查用户名与密码')
expect(input('初始密码')!.value).toBe(PASSWORD)
})
it('asks before discarding a dirty draft and honours the answer', async () => {
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
await act(async () => root.render(<MembersSection />))
await open()
await type('用户名', 'li.si')
await pressEscape()
expect(confirm).toHaveBeenCalledWith('放弃未保存的新增成员?')
expect(dialog()).toBeTruthy()
confirm.mockReturnValue(true)
await pressEscape()
expect(dialog()).toBeNull()
await open()
expect(input('用户名')!.value).toBe('')
})
it('closes a clean draft without confirmation', async () => {
const confirm = vi.spyOn(window, 'confirm')
await act(async () => root.render(<MembersSection />))
await open()
await pressEscape()
expect(confirm).not.toHaveBeenCalled()
expect(dialog()).toBeNull()
})
it('ignores close requests while the create request is in flight', async () => {
const confirm = vi.spyOn(window, 'confirm')
await act(async () => root.render(<MembersSection />))
postStatus = 'pending'
await open()
await fillValid()
await act(async () => submit()!.click())
expect(dialog()!.textContent).toContain('创建中…')
await pressEscape()
await act(async () => button('取消')!.click())
expect(dialog()).toBeTruthy()
expect(confirm).not.toHaveBeenCalled()
await act(async () => {
releasePost!()
await Promise.resolve()
})
expect(dialog()).toBeNull()
})
})
+245 -60
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
MembersRequestError,
createManagedUser,
fetchManagedUsers,
resetManagedUserPassword,
@@ -12,6 +13,41 @@ import { PasswordInput } from './PasswordInput'
export const memberRoleLabels = roleLabels
type Draft = {
username: string
display_name: string
role: ManagedUser['role']
password: string
}
type DraftErrors = Partial<Record<'username' | 'display_name' | 'password', string>>
const emptyDraft = (): Draft => ({ username: '', display_name: '', role: 'engineer', password: '' })
function validateDraft(form: Draft): DraftErrors {
const errors: DraftErrors = {}
const username = form.username.trim()
if (!username) {
errors.username = '请输入用户名'
} else if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(username)) {
errors.username = '用户名需 2–64 位,以小写字母或数字开头,可含 . _ -'
}
const displayName = form.display_name.trim()
if (!displayName) {
errors.display_name = '请输入姓名'
} else if (displayName.length > 128) {
errors.display_name = '姓名最多 128 字'
}
if (!form.password) {
errors.password = '请输入初始密码'
} else if (form.password.length < 8) {
errors.password = '初始密码至少 8 位'
} else if (form.password.length > 128) {
errors.password = '初始密码最多 128 位'
}
return errors
}
function friendly(cause: unknown, fallback: string): string {
return cause instanceof Error && cause.message ? cause.message : fallback
}
@@ -26,12 +62,12 @@ export function MembersSection() {
// 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。
const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null)
const [resetValue, setResetValue] = useState('')
const [form, setForm] = useState({
username: '',
display_name: '',
role: 'engineer' as ManagedUser['role'],
password: '',
})
const [form, setForm] = useState<Draft>(emptyDraft)
const [drawerOpen, setDrawerOpen] = useState(false)
const [fieldErrors, setFieldErrors] = useState<DraftErrors>({})
const [createError, setCreateError] = useState<string | null>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
const usernameRef = useRef<HTMLInputElement>(null)
const load = useCallback(async () => {
setLoading(true)
@@ -63,17 +99,80 @@ export function MembersSection() {
}
}
const create = () =>
run(
'create',
async () => {
await createManagedUser(form)
setForm({ username: '', display_name: '', role: 'engineer', password: '' })
},
`成员 ${form.username} 已创建,初始密码只用于首次登录`
)
const resetDraft = useCallback(() => {
setForm(emptyDraft())
setFieldErrors({})
setCreateError(null)
}, [])
const formValid = /^[a-z0-9][a-z0-9._-]{1,63}$/.test(form.username.trim()) && form.password.length >= 8
const closeDrawer = useCallback(() => {
setDrawerOpen(false)
resetDraft()
triggerRef.current?.focus()
}, [resetDraft])
const dirty = form.username !== '' || form.display_name !== '' || form.role !== 'engineer' || form.password !== ''
const requestClose = useCallback(() => {
if (busy === 'create') return
if (dirty && !window.confirm('放弃未保存的新增成员?')) return
closeDrawer()
}, [busy, dirty, closeDrawer])
useEffect(() => {
if (drawerOpen) usernameRef.current?.focus()
}, [drawerOpen])
useEffect(() => {
if (!drawerOpen) return
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return
event.preventDefault()
requestClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [drawerOpen, requestClose])
const patchForm = (patch: Partial<Draft>) => {
setForm((current) => ({ ...current, ...patch }))
setFieldErrors((current) => {
const next = { ...current }
for (const key of Object.keys(patch) as (keyof DraftErrors)[]) delete next[key]
return next
})
}
const submitCreate = async () => {
if (busy === 'create') return
const errors = validateDraft(form)
setFieldErrors(errors)
if (Object.keys(errors).length > 0) return
const username = form.username.trim()
setBusy('create')
setCreateError(null)
try {
await createManagedUser({
username,
display_name: form.display_name.trim(),
role: form.role,
password: form.password,
})
setMessage(`成员 ${username} 已创建,初始密码只用于首次登录`)
closeDrawer()
await load()
} catch (cause) {
if (cause instanceof MembersRequestError && cause.status === 409) {
setFieldErrors({ username: '该用户名已存在' })
} else if (cause instanceof MembersRequestError && cause.status === 400) {
setCreateError('用户信息不符合规则,请检查用户名与密码')
} else {
setCreateError(friendly(cause, '新增成员失败'))
}
} finally {
setBusy(null)
}
}
return (
<section className="settings-panel wide" id="settings-members">
@@ -82,6 +181,18 @@ export function MembersSection() {
<h2>成员与角色</h2>
<p>登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。</p>
</div>
<button
ref={triggerRef}
type="button"
className="primary"
aria-label="新增成员"
onClick={() => {
setCreateError(null)
setDrawerOpen(true)
}}
>
<span aria-hidden="true">+</span> 新增成员
</button>
</div>
{loading ? <p>加载成员…</p> : null}
{error ? (
@@ -190,50 +301,124 @@ export function MembersSection() {
</tbody>
</table>
</div>
<div className="member-create-form" aria-label="新增成员">
<label>
用户名
<input
value={form.username}
maxLength={64}
placeholder="小写字母/数字,如 zhangsan"
onChange={(event) => setForm((current) => ({ ...current, username: event.target.value.toLowerCase() }))}
/>
</label>
<label>
姓名
<input
value={form.display_name}
maxLength={128}
onChange={(event) => setForm((current) => ({ ...current, display_name: event.target.value }))}
/>
</label>
<label>
角色
<select
value={form.role}
onChange={(event) =>
setForm((current) => ({ ...current, role: event.target.value as ManagedUser['role'] }))
}
>
<option value="viewer">观察者</option>
<option value="engineer">知识工程师</option>
<option value="admin">管理员</option>
</select>
</label>
<label>
初始密码(≥8 位,首登强制修改)
<PasswordInput
value={form.password}
autoComplete="new-password"
onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))}
/>
</label>
<button type="button" disabled={!formValid || busy === 'create'} onClick={() => void create()}>
新增成员
</button>
</div>
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
{drawerOpen ? (
<div
className="member-drawer-backdrop"
onMouseDown={(event) => {
if (event.target !== event.currentTarget) return
// 阻止默认聚焦把焦点从触发按钮夺走:关闭后焦点必须回到「新增成员」。
event.preventDefault()
requestClose()
}}
>
<aside className="member-drawer" role="dialog" aria-modal="true" aria-labelledby="member-drawer-title">
<div className="member-drawer-header">
<h3 id="member-drawer-title">新增成员</h3>
<button
type="button"
className="member-drawer-close"
aria-label="关闭新增成员"
disabled={busy === 'create'}
onClick={requestClose}
>
<span aria-hidden="true">×</span>
</button>
</div>
<form
className="member-drawer-form"
onSubmit={(event) => {
event.preventDefault()
void submitCreate()
}}
>
<div className="member-drawer-body">
{createError ? (
<p className="member-drawer-error member-drawer-form-error" role="alert">
{createError}
</p>
) : null}
<label className="member-drawer-field" htmlFor="member-new-username">
<span>用户名</span>
<input
ref={usernameRef}
id="member-new-username"
value={form.username}
maxLength={64}
autoComplete="username"
aria-invalid={Boolean(fieldErrors.username)}
aria-describedby="member-new-username-note"
onChange={(event) => patchForm({ username: event.target.value.toLowerCase() })}
/>
<small
id="member-new-username-note"
className={fieldErrors.username ? 'member-drawer-error' : 'member-drawer-hint'}
role={fieldErrors.username ? 'alert' : undefined}
>
{fieldErrors.username ?? '小写字母/数字,可含 . _ -'}
</small>
</label>
<label className="member-drawer-field" htmlFor="member-new-display-name">
<span>姓名</span>
<input
id="member-new-display-name"
value={form.display_name}
maxLength={128}
autoComplete="name"
aria-invalid={Boolean(fieldErrors.display_name)}
aria-describedby={fieldErrors.display_name ? 'member-new-display-name-note' : undefined}
onChange={(event) => patchForm({ display_name: event.target.value })}
/>
{fieldErrors.display_name ? (
<small id="member-new-display-name-note" className="member-drawer-error" role="alert">
{fieldErrors.display_name}
</small>
) : null}
</label>
<label className="member-drawer-field" htmlFor="member-new-role">
<span>角色</span>
<select
id="member-new-role"
value={form.role}
onChange={(event) => patchForm({ role: event.target.value as ManagedUser['role'] })}
>
<option value="viewer">观察者</option>
<option value="engineer">知识工程师</option>
<option value="admin">管理员</option>
</select>
</label>
<label className="member-drawer-field" htmlFor="member-new-password">
<span>初始密码</span>
<PasswordInput
id="member-new-password"
value={form.password}
autoComplete="new-password"
maxLength={128}
aria-invalid={Boolean(fieldErrors.password)}
aria-describedby="member-new-password-note"
onChange={(event) => patchForm({ password: event.target.value })}
/>
<small
id="member-new-password-note"
className={fieldErrors.password ? 'member-drawer-error' : 'member-drawer-hint'}
role={fieldErrors.password ? 'alert' : undefined}
>
{fieldErrors.password ?? '至少 8 位,首次登录强制修改'}
</small>
</label>
</div>
<div className="member-drawer-actions">
<button type="button" className="secondary-action" disabled={busy === 'create'} onClick={requestClose}>
取消
</button>
<button type="submit" className="primary" disabled={busy === 'create'}>
{busy === 'create' ? '创建中…' : '新增成员'}
</button>
</div>
</form>
</aside>
</div>
) : null}
{resetTarget ? (
<div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码">
<h3>重置 {resetTarget.username} 的临时密码</h3>
+280
View File
@@ -0,0 +1,280 @@
// @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 { StorageBackupSummary } from './StorageBackupSummary'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
const GIB = 1024 ** 3
const TB = 1024 * GIB
const batch = (index: number, overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => {
const stamp = `202611${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}0000Z`
const created = `2026-11-${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}:00:00Z`
return {
stamp,
path: `/srv/kb-backups/rds-logical/${stamp}`,
host_path: `/srv/kb-backups/rds-logical/${stamp}`,
manifest_state: 'ok',
manifest_path: `/srv/kb-backups/rds-logical/${stamp}/MANIFEST.json`,
kind: 'rds',
created_at: created,
started_at: created,
duration_seconds: 240,
manifest_total_bytes: 10 * GIB,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
sizes_complete: true,
databases: [
{
name: 'weknora',
dir_name: 'weknora.dir',
path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
host_path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
},
],
...overrides,
}
}
const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/kb-backups/metadata.json',
collected_at: '2026-11-24T10:17:00Z',
age_seconds: 60,
max_age_seconds: 900,
schema_version: 1,
generation: 'g-1',
host: 'backup-host',
collector_version: '1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 1.2 * TB,
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
totals: {
batch_count: 2,
database_count: 2,
apparent_bytes: 20 * GIB,
actual_bytes: 18 * GIB,
latest_stamp: '20261124T000000Z',
latest_actual_bytes: 9 * GIB,
complete: true,
},
incomplete_count: 0,
skipped: [],
truncated: false,
...overrides,
})
const archive: LibraryStorage = {
available: true,
archive_root: '/var/lib/knowledge-governance/library',
versions: [],
content_bytes: 41_231_686_042,
blob_file_bytes: 0,
blob_allocated_bytes: 0,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 0,
policy: { keep_versions: 0, keep_days: 0 },
capacity: {
budget_bytes: 100 * GIB,
current_bytes: 41_231_686_042,
required_bytes: 0,
projected_bytes: 41_231_686_042,
configured: true,
ok: true,
},
automatic_cleanup: false,
notes: [],
}
let root: Root
let container: HTMLDivElement
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
const paths = (): string[] => fetcher.mock.calls.map((call) => String(call[0]))
const flush = async () => {
await act(async () => {
await Promise.resolve()
await Promise.resolve()
})
}
beforeEach(() => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
fetcher = vi.fn(async (path: string) => {
if (path.endsWith('/inventory')) {
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
}
return new Response(JSON.stringify(archive), { status: 200 })
})
vi.stubGlobal('fetch', fetcher)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
vi.unstubAllGlobals()
vi.useRealTimers()
})
describe('StorageBackupSummary', () => {
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
expect(text).toContain('备份目录')
expect(text).toContain('/srv/kb-backups/rds-logical')
expect(text).toContain('最近成功')
expect(text).toContain('最近失败')
expect(text).toContain('归档占用')
expect(text).toContain('38.4 GB')
expect(text).toContain('配额 100 GB')
expect(text).toContain('磁盘剩余')
expect(text).toContain('1.2 TB')
expect(text).toContain('上次上报')
expect(text).toContain('清单损坏')
expect(container.querySelectorAll('tbody tr')).toHaveLength(2)
expect(container.querySelectorAll('.storage-alerts li')).toHaveLength(4)
expect(text).not.toContain('无法判定')
expect(text).not.toContain('未接线')
expect(text).not.toContain('示例')
})
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
vi.useFakeTimers()
act(() => root.render(<StorageBackupSummary />))
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
})
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
})
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
})
it('shows 主机未上报 with the last report time and no zero placeholders when the host is unwired', async () => {
fetcher.mockImplementation(async (path: string) => {
if (path.endsWith('/inventory')) {
const wired = inventory()
return new Response(
JSON.stringify({
data: {
...wired,
wired: false,
root: '',
host_root: '',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
},
}),
{ status: 200 }
)
}
return new Response(
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
{
status: 200,
}
)
})
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
expect(text).toContain('主机未上报')
expect(text).toContain('上次上报 —')
expect(text).toContain('未接入宿主上报')
expect(text).not.toContain('0 B')
expect(text).not.toContain('0 GB')
expect(container.querySelectorAll('tbody tr')).toHaveLength(0)
expect(text).toContain('主机未上报(上次上报 —)')
})
it('copies a path once the browser grants clipboard access', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
act(() => root.render(<StorageBackupSummary />))
await flush()
const button = container.querySelector<HTMLButtonElement>('button[aria-label="复制备份目录"]')
expect(button).not.toBeNull()
await act(async () => {
button!.click()
await Promise.resolve()
})
expect(writeText).toHaveBeenCalledWith('/srv/kb-backups/rds-logical')
expect(button!.textContent).toBe('已复制')
})
it('pages long batch lists 20 at a time', async () => {
fetcher.mockImplementation(async (path: string) => {
if (path.endsWith('/inventory')) {
const batches = Array.from({ length: 25 }, (_, index) => batch(index))
return new Response(
JSON.stringify({ data: { ...inventory(), batches, totals: { ...inventory().totals, batch_count: 25 } } }),
{ status: 200 }
)
}
return new Response(JSON.stringify(archive), { status: 200 })
})
act(() => root.render(<StorageBackupSummary />))
await flush()
expect(container.querySelectorAll('tbody tr')).toHaveLength(20)
const more = container.querySelector<HTMLButtonElement>('.storage-more')
expect(more?.textContent).toContain('剩余 5 个')
await act(async () => {
more!.click()
})
expect(container.querySelectorAll('tbody tr')).toHaveLength(25)
expect(container.querySelector('.storage-more')).toBeNull()
})
})
+271
View File
@@ -0,0 +1,271 @@
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
import { useCallback, useEffect, useRef, useState } from 'react'
import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory } from './backupInventory'
import { fetchLibraryStorage } from './librarySnapshots'
import type { LibraryStorage } from './librarySnapshots'
import {
UNKNOWN,
batchOutcome,
batchWhen,
formatSize,
formatWhen,
hostState,
hostValueLabel,
pendingAlertCount,
storageAlerts,
summaryCards,
} from './storageSummary'
import type { HostState } from './storageSummary'
import './storageBackup.css'
export const REFRESH_INTERVAL_MS = 60_000
const BATCH_PAGE = 20
export async function copyText(value: string): Promise<boolean> {
if (!value) return false
try {
await navigator.clipboard.writeText(value)
return true
} catch {
// 内网 http 页面没有 clipboard 权限时退回选中,不谎报"已复制"。
const area = document.createElement('textarea')
area.value = value
area.setAttribute('readonly', '')
area.style.position = 'fixed'
area.style.opacity = '0'
document.body.append(area)
area.focus()
area.select()
const copied = document.execCommand('copy')
area.remove()
return copied
}
}
const hostStateLabel = (state: HostState): string => {
switch (state) {
case 'unwired':
return '未接入宿主上报'
case 'missing':
return '尚无上报表'
case 'stale':
return '上次上报已过期'
case 'invalid':
return '上次上报不可用'
case 'incomplete':
return '本次上报不完整'
default:
return ''
}
}
export function StorageBackupSummary() {
const [inventory, setInventory] = useState<BackupInventory | null>(null)
const [archive, setArchive] = useState<LibraryStorage | null>(null)
const [archiveFailed, setArchiveFailed] = useState(false)
const [errors, setErrors] = useState<string[]>([])
const [loading, setLoading] = useState(true)
const [visible, setVisible] = useState(BATCH_PAGE)
const [copied, setCopied] = useState('')
const inFlight = useRef(false)
const copiedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const load = useCallback(async () => {
if (inFlight.current) return
inFlight.current = true
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
const nextErrors: string[] = []
if (inventoryResult.status === 'fulfilled') {
setInventory(inventoryResult.value)
} else {
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
}
if (archiveResult.status === 'fulfilled') {
setArchive(archiveResult.value)
setArchiveFailed(archiveResult.value === null)
if (archiveResult.value === null) nextErrors.push('读取归档占用失败')
} else {
setArchiveFailed(true)
nextErrors.push(archiveResult.reason instanceof Error ? archiveResult.reason.message : '读取归档占用失败')
}
setErrors(nextErrors)
setLoading(false)
inFlight.current = false
}, [])
useEffect(() => {
void load()
const timer = setInterval(() => {
if (document.visibilityState === 'hidden') return
void load()
}, REFRESH_INTERVAL_MS)
return () => {
clearInterval(timer)
clearTimeout(copiedTimer.current)
}
}, [load])
const state = hostState(inventory)
const alerts = storageAlerts(inventory, archive, archiveFailed)
const cards = summaryCards(inventory, archive, archiveFailed)
const batches = inventory?.batches ?? []
const shown = batches.slice(0, visible)
const handleCopy = (key: string, value: string) => {
void copyText(value).then((ok) => {
if (!ok) return
setCopied(key)
clearTimeout(copiedTimer.current)
copiedTimer.current = setTimeout(() => setCopied(''), 2000)
})
}
const lastReport = formatWhen(inventory?.metadata.collected_at)
const stateNote = hostStateLabel(state)
return (
<section className="settings-panel storage-summary" aria-label="存储与备份">
<header className="storage-summary-head">
<div>
<h2>存储与备份</h2>
{stateNote ? <p className="storage-summary-state">{stateNote}</p> : null}
</div>
<div className="storage-summary-meta">
<span>上次上报 {lastReport || UNKNOWN}</span>
<button type="button" className="storage-refresh" onClick={() => void load()} disabled={loading}>
刷新
</button>
</div>
</header>
{errors.length > 0 ? (
<p className="storage-summary-error" role="alert">
{errors.join(';')}
</p>
) : null}
{loading ? (
<p className="storage-summary-loading">正在读取存储与备份…</p>
) : (
<>
<div className="storage-cards">
{cards.map((card) => (
<div className={card.key === 'root' ? 'storage-card storage-card-root' : 'storage-card'} key={card.key}>
<span className="storage-card-label">{card.label}</span>
<span className={card.unknown ? 'storage-card-value is-unknown' : 'storage-card-value'}>
{card.value}
</span>
<span className="storage-card-note">
{card.note}
{card.copy ? (
<button
type="button"
className="storage-copy"
onClick={() => handleCopy(card.key, card.copy!)}
aria-label={`复制${card.label}`}
>
{copied === card.key ? '已复制' : '复制'}
</button>
) : null}
</span>
</div>
))}
</div>
<section className="storage-alerts" aria-label="容量告警">
<header>
<h3>容量告警</h3>
<span
className={pendingAlertCount(alerts) > 0 ? 'storage-alert-count is-pending' : 'storage-alert-count'}
>
{pendingAlertCount(alerts)} 项需处理
</span>
</header>
<ul>
{alerts.map((alert) => (
<li key={alert.key} data-tone={alert.tone}>
<span className="storage-alert-label">{alert.label}</span>
<span className="storage-alert-value">{alert.value}</span>
<span className="storage-alert-conclusion" data-tone={alert.tone}>
{alert.conclusion}
</span>
</li>
))}
</ul>
</section>
<section className="storage-batches" aria-label="备份批次">
<header>
<h3>备份批次</h3>
<span>{batches.length > 0 ? `共 ${batches.length} 个` : ''}</span>
</header>
{batches.length === 0 ? (
<p className="storage-batches-empty">
{state === 'ready' || state === 'incomplete'
? '暂无批次'
: `${hostValueLabel(state)}(上次上报 ${lastReport || UNKNOWN})`}
</p>
) : (
<table>
<thead>
<tr>
<th>时间</th>
<th>结果</th>
<th>大小</th>
<th>批次</th>
<th>路径</th>
<th aria-label="复制" />
</tr>
</thead>
<tbody>
{shown.map((batch) => {
const outcome = batchOutcome(batch)
return (
<tr key={batch.stamp}>
<td className="storage-batch-time">{batchWhen(batch)}</td>
<td>
<span
className={outcome.failed ? 'storage-batch-result is-failed' : 'storage-batch-result is-ok'}
>
{outcome.failed ? '失败' : '成功'}
</span>
{outcome.reasons.length > 0 ? (
<p className="storage-batch-reason">{outcome.reasons.join(';')}</p>
) : null}
</td>
<td className="storage-batch-size">{formatSize(batch.actual_bytes)}</td>
<td className="storage-batch-stamp">{batch.stamp}</td>
<td className="storage-batch-path" title={batch.path}>
<span>{batch.path}</span>
</td>
<td>
<button
type="button"
className="storage-copy"
onClick={() => handleCopy(batch.stamp, batch.path)}
aria-label={`复制路径 ${batch.stamp}`}
>
{copied === batch.stamp ? '已复制' : '复制'}
</button>
</td>
</tr>
)
})}
</tbody>
</table>
)}
{visible < batches.length ? (
<button type="button" className="storage-more" onClick={() => setVisible((value) => value + BATCH_PAGE)}>
加载更多(剩余 {batches.length - visible} 个)
</button>
) : null}
</section>
</>
)}
</section>
)
}
+118
View File
@@ -0,0 +1,118 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SystemSettingsView } from './SystemSettings'
import type { UISettings } from './uiSettings'
let root: Root, host: HTMLDivElement
const settings: UISettings = {
id: 'uis-active',
state: 'active',
document_refresh_seconds: 30,
resource_refresh_seconds: 30,
stalled_after_seconds: 1800,
finalizing_after_seconds: 7200,
ingestion_concurrency: 8,
test_weknora_base_url: '',
production_weknora_base_url: '',
production_tenant_id: '',
production_knowledge_base_id: '',
updated_by: 'admin',
created_at: '2026-11-24T04:15:00Z',
activated_at: '2026-11-24T04:15:00Z',
retired_at: null,
error_code: '',
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
host = document.createElement('div')
document.body.append(host)
root = createRoot(host)
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
})
const renderView = async (onSave: (input: unknown) => void) => {
await act(async () =>
root.render(
<SystemSettingsView
sources={[]}
connections={[]}
monitor={null}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={onSave}
onSourcesChanged={() => {}}
onRefresh={() => {}}
initialSection="refresh"
/>
)
)
}
const input = (label: string) => {
const found = [...host.querySelectorAll('label')]
.find((item) => item.textContent?.startsWith(label))
?.querySelector('input')
expect(found, label).toBeTruthy()
return found!
}
const type = async (label: string, value: string) => {
const target = input(label)
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(target, value)
target.dispatchEvent(new Event('input', { bubbles: true }))
})
}
const saveButton = () =>
[...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === '保存参数设置')!
describe('参数设置保存边界', () => {
it('keeps other inputs, blocks invalid saves and sends the hidden contract fields unchanged', async () => {
const onSave = vi.fn()
await renderView(onSave)
expect(saveButton().disabled).toBe(true)
await type('解析停滞阈值', '45')
expect(host.textContent).toContain('解析停滞阈值只能是 30/60 分钟;当前 45')
expect(input('解析停滞阈值').getAttribute('aria-invalid')).toBe('true')
expect(saveButton().disabled).toBe(true)
// 直接点击禁用按钮也不能绕过校验触发保存。
await act(async () => saveButton().click())
expect(onSave).not.toHaveBeenCalled()
// 同组和另一组的已填值都不因单个字段非法被清空。
expect(input('文档状态刷新间隔').value).toBe('30')
expect(input('资源刷新间隔').value).toBe('30')
expect(input('入库并发上限').value).toBe('8')
await type('解析停滞阈值', '60')
expect(input('解析停滞阈值').getAttribute('aria-invalid')).toBe('false')
expect(saveButton().disabled).toBe(false)
await act(async () => saveButton().click())
expect(onSave).toHaveBeenCalledWith({
document_refresh_seconds: 30,
resource_refresh_seconds: 30,
stalled_after_seconds: 3600,
finalizing_after_seconds: 7200,
ingestion_concurrency: 8,
test_weknora_base_url: '',
production_weknora_base_url: '',
production_tenant_id: '',
production_knowledge_base_id: '',
})
})
})
+127 -15
View File
@@ -3,7 +3,10 @@ import { describe, expect, it, vi } from 'vitest'
import {
SystemSettingsView,
ppSourceConnections,
refreshDraftText,
refreshSettingsDirty,
refreshSettingsInput,
parseRefreshDrafts,
serviceSettingsInput,
visibleSaveMessage,
} from './SystemSettings'
@@ -173,13 +176,13 @@ describe('SystemSettingsView', () => {
loading={false}
saving={false}
error={null}
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
saveMessage="设置已验证并启用:文档15秒、资源30秒、停滞30分钟、入库并发 2"
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
/>
)
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '刷新策略'])
for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '参数设置'])
expect(html).toContain(text)
// 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。
for (const removed of [
@@ -256,9 +259,9 @@ describe('SystemSettingsView', () => {
initialSection="storage"
/>
)
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
// 存储与备份分区是只读摘要页:SSR 先给加载态,静态占位文案不再存在。
expect(storageHtml).toContain('存储与备份')
expect(storageHtml).toContain('正在读取备份计划…')
expect(storageHtml).toContain('正在读取存储与备份…')
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
const refreshHtml = renderToStaticMarkup(
<SystemSettingsView
@@ -271,7 +274,7 @@ describe('SystemSettingsView', () => {
loading={false}
saving={false}
error={null}
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
saveMessage="设置已验证并启用:文档15秒、资源30秒、停滞30分钟、入库并发 2"
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
@@ -279,16 +282,38 @@ describe('SystemSettingsView', () => {
/>
)
for (const text of [
'刷新与告警参数已验证并启用',
'停滞30分钟',
'finalizing 2小时',
'参数设置',
'来源与目录',
'解析监控',
'文档状态刷新间隔',
'15秒',
'解析监控按此周期刷新文档状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
'资源刷新间隔',
'解析监控按此周期刷新资源与服务状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
'解析停滞阈值',
'30分钟',
'保存刷新与告警参数',
'超过此时长没有进展就标记停滞;调大更容忍长解析,调小更快标记停滞',
'入库并发上限',
'调大入库更快、写入压力更高;调小更稳,排队更久',
'保存参数设置',
'当前:文档 15 秒、资源 30 秒、停滞 30 分钟、入库并发 2。',
])
expect(refreshHtml).toContain(text)
for (const removed of ['收尾超时告警', 'finalizing', '刷新与入库', '保存刷新与告警参数'])
expect(refreshHtml).not.toContain(removed)
const sourcesGroup = refreshHtml.slice(
refreshHtml.indexOf('data-refresh-group="sources"'),
refreshHtml.indexOf('data-refresh-group="parsing"')
)
const parsingGroup = refreshHtml.slice(refreshHtml.indexOf('data-refresh-group="parsing"'))
expect(sourcesGroup).toContain('文档状态刷新间隔')
expect(sourcesGroup).toContain('资源刷新间隔')
expect(sourcesGroup).not.toContain('解析停滞阈值')
expect(sourcesGroup).not.toContain('入库并发上限')
expect(parsingGroup).toContain('解析停滞阈值')
expect(parsingGroup).toContain('入库并发上限')
expect(parsingGroup).not.toContain('文档状态刷新间隔')
expect(parsingGroup).not.toContain('资源刷新间隔')
expect(refreshHtml).toContain('aria-invalid="false"')
expect(refreshHtml).toContain('inputMode="numeric"')
expect(visibleSaveMessage('已保存', true)).toBeNull()
expect(visibleSaveMessage('已保存', false)).toBe('已保存')
expect(html).not.toContain('本地模拟')
@@ -671,20 +696,24 @@ describe('保存边界(F03)', () => {
production_knowledge_base_id: 'kb-server',
} as unknown as UISettings
it('保存刷新策略时忽略服务分区里未保存的地址', () => {
it('保存参数设置时忽略服务分区里未保存的地址,并原样回传 finalizing', () => {
const input = refreshSettingsInput(server, {
documentRefresh: 60,
resourceRefresh: 60,
stalled: 3600,
finalizing: 14400,
concurrency: 4,
concurrency: 7,
})
expect(input.test_weknora_base_url).toBe('https://server.test')
expect(input.production_weknora_base_url).toBe('https://server.prod')
expect(input.production_tenant_id).toBe('10000')
expect(input.production_knowledge_base_id).toBe('kb-server')
expect(input.finalizing_after_seconds).toBe(server.finalizing_after_seconds)
expect(input.document_refresh_seconds).toBe(60)
expect(input.stalled_after_seconds).toBe(3600)
expect(input.ingestion_concurrency).toBe(7)
})
it('保存服务配置时忽略刷新分区里未保存的参数', () => {
it('保存服务配置时忽略参数分区里未保存的参数', () => {
const input = serviceSettingsInput(server, {
testEndpoint: 'https://draft.test',
endpoint: 'https://draft.prod',
@@ -696,3 +725,86 @@ describe('保存边界(F03)', () => {
expect(input.test_weknora_base_url).toBe('https://draft.test')
})
})
describe('参数设置的文本草稿解析', () => {
const drafts = (patch: Record<string, string> = {}) => ({ ...refreshDraftText(settings), ...patch })
it('把活动设置转成带单位的草稿(停滞用分钟)', () => {
expect(refreshDraftText(settings)).toEqual({
documentRefresh: '15',
resourceRefresh: '30',
stalled: '30',
concurrency: '2',
})
})
it('接受白名单与 1..16 的整数,停滞分钟换算成秒', () => {
const parsed = parseRefreshDrafts({
documentRefresh: '60',
resourceRefresh: '60',
stalled: '60',
concurrency: '16',
})
expect(parsed.errors).toEqual({
documentRefresh: null,
resourceRefresh: null,
stalled: null,
concurrency: null,
})
expect(parsed.values).toEqual({
documentRefresh: 60,
resourceRefresh: 60,
stalled: 3600,
concurrency: 16,
})
})
it('接受并发 5/7/9(后端范围 1..16,而不是旧下拉六档)', () => {
for (const value of ['5', '7', '9']) {
expect(parseRefreshDrafts(drafts({ concurrency: value })).values?.concurrency).toBe(Number(value))
}
})
it('拒绝空值、非整数、越界与全角数字,并给出字段级提示', () => {
const cases: [Record<string, string>, string, string][] = [
[{ documentRefresh: '' }, 'documentRefresh', '不能为空'],
[{ documentRefresh: '1' }, 'documentRefresh', '15/30/60'],
[{ documentRefresh: '2.5' }, 'documentRefresh', '必须是整数'],
[{ documentRefresh: '+15' }, 'documentRefresh', '必须是整数'],
[{ documentRefresh: '1e1' }, 'documentRefresh', '必须是整数'],
[{ documentRefresh: '15' }, 'documentRefresh', '必须是整数'],
[{ documentRefresh: '15abc' }, 'documentRefresh', '必须是整数'],
[{ resourceRefresh: '15' }, 'resourceRefresh', '30/60'],
[{ stalled: '45' }, 'stalled', '30/60'],
[{ stalled: '0.5' }, 'stalled', '必须是整数'],
[{ concurrency: '0' }, 'concurrency', '1~16'],
[{ concurrency: '99' }, 'concurrency', '1~16'],
[{ concurrency: '2.5' }, 'concurrency', '必须是整数'],
]
for (const [patch, field, message] of cases) {
const parsed = parseRefreshDrafts(drafts(patch))
expect(parsed.values, `${field} ${patch[field]}`).toBeNull()
expect(parsed.errors[field as keyof typeof parsed.errors]).toContain(message)
}
})
it('错误文案使用完整字段名', () => {
expect(parseRefreshDrafts(drafts({ documentRefresh: '1' })).errors.documentRefresh).toContain(
'文档状态刷新间隔只能是 15/30/60 秒'
)
expect(parseRefreshDrafts(drafts({ stalled: '45' })).errors.stalled).toContain('解析停滞阈值只能是 30/60 分钟')
})
it('任一字段非法时整体 values 为 null,避免夹带默认值保存', () => {
const parsed = parseRefreshDrafts(drafts({ concurrency: '99' }))
expect(parsed.values).toBeNull()
expect(parsed.errors.documentRefresh).toBeNull()
})
it('脏值按解析后的数值比较:015 等价 15,改值或非法值才变脏', () => {
expect(refreshSettingsDirty(drafts(), settings)).toBe(false)
expect(refreshSettingsDirty(drafts({ documentRefresh: '015' }), settings)).toBe(false)
expect(refreshSettingsDirty(drafts({ concurrency: '7' }), settings)).toBe(true)
expect(refreshSettingsDirty(drafts({ documentRefresh: '1' }), settings)).toBe(true)
})
})
+97 -128
View File
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { BackupScheduleSection } from './BackupScheduleSection'
import { LibraryStorageSection } from './LibraryStorageSection'
import { StorageBackupSummary } from './StorageBackupSummary'
import { QAModelSettings } from './QAModelSettings'
import { MembersSection } from './MembersSection'
import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement'
@@ -23,13 +22,26 @@ import { archiveSourceConnection, fetchSourceConnectionList } from './sourceConn
import type { SourceConnectionListItem } from './sourceConnections'
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings'
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
import { refreshSettingsInput } from './settingsInputs'
import {
parseRefreshDrafts,
REFRESH_FIELD_META,
refreshDraftText,
refreshSettingsDirty,
refreshSettingsInput,
} from './settingsInputs'
import type { RefreshDrafts, RefreshField } from './settingsInputs'
import './systemSettings.css'
// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出,
// 连接配置已从「服务配置」迁到「知识库绑定」。这些纯函数仍从本模块导出,
// 既有调用与回归测试的导入路径不变。
export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs'
export type { RefreshDrafts, ServiceDrafts } from './settingsInputs'
export {
parseRefreshDrafts,
refreshDraftText,
refreshSettingsDirty,
refreshSettingsInput,
serviceSettingsInput,
} from './settingsInputs'
export type { RefreshDrafts, RefreshValues, ServiceDrafts } from './settingsInputs'
interface Props {
sources: CatalogSource[]
@@ -58,10 +70,23 @@ const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
{ key: 'services', label: 'AI 模型连接' },
{ key: 'knowledge-bindings', label: '知识库绑定' },
{ key: 'storage', label: '存储与备份' },
{ key: 'refresh', label: '刷新策略' },
{ key: 'refresh', label: '参数设置' },
{ key: 'members', label: '成员与角色', adminOnly: true },
] as { key: SectionKey; label: string; adminOnly?: boolean }[]
const refreshHints: Record<RefreshField, string> = {
documentRefresh: '解析监控按此周期刷新文档状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
resourceRefresh: '解析监控按此周期刷新资源与服务状态;调小更及时、请求更频繁,调大更省请求、更新更慢',
stalled: '超过此时长没有进展就标记停滞;调大更容忍长解析,调小更快标记停滞',
concurrency: '调大入库更快、写入压力更高;调小更稳,排队更久',
}
// 产品定义的分组与归属,顺序即页面呈现顺序。
const refreshGroups: { key: string; title: string; fields: RefreshField[] }[] = [
{ key: 'sources', title: '来源与目录', fields: ['documentRefresh', 'resourceRefresh'] },
{ key: 'parsing', title: '解析监控', fields: ['stalled', 'concurrency'] },
]
const sourceTypeLabels: Record<string, string> = {
dingtalk: '钉钉知识库',
pp: 'PP 资料下载中心',
@@ -104,41 +129,30 @@ export function SystemSettingsView({
? 'knowledge-bindings'
: (initialSection as SectionKey)
)
const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15)
const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30)
const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800)
const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200)
const [concurrency, setConcurrency] = useState<number>(settings?.ingestion_concurrency ?? 2)
const [dirty, setDirty] = useState(false)
// 输入框用文本草稿而不是 number:浏览器会吞掉 1e1/+15,无法展示「非法」提示。
const [refreshDrafts, setRefreshDrafts] = useState<RefreshDrafts>(() =>
settings
? refreshDraftText(settings)
: { documentRefresh: '15', resourceRefresh: '30', stalled: '30', concurrency: '2' }
)
// 统一入口后,清单里列全部来源(钉钉知识库 / 钉盘 / PP),不再只显示 PP。
const listedConnections = connections
useEffect(() => {
if (!settings) return
setDocumentRefresh(settings.document_refresh_seconds)
setResourceRefresh(settings.resource_refresh_seconds)
setStalled(settings.stalled_after_seconds)
setFinalizing(settings.finalizing_after_seconds)
setConcurrency(settings.ingestion_concurrency)
setDirty(false)
setRefreshDrafts(refreshDraftText(settings))
}, [settings])
const canSave = Boolean(settings && !saving)
const parsedRefresh = parseRefreshDrafts(refreshDrafts)
const refreshDirty = settings ? refreshSettingsDirty(refreshDrafts, settings) : false
const canSave = Boolean(settings && !saving && parsedRefresh.values)
const isAdmin = identity?.role === 'admin'
const refreshSettingsDirty = Boolean(
settings &&
(documentRefresh !== settings.document_refresh_seconds ||
resourceRefresh !== settings.resource_refresh_seconds ||
stalled !== settings.stalled_after_seconds ||
finalizing !== settings.finalizing_after_seconds ||
concurrency !== settings.ingestion_concurrency)
)
// 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
// 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。
// 保存边界:参数分区只带参数草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
// 互不夹带(未保存的地址不会因为保存参数设置被写进去)。
const refreshInput = (): UISettingsCandidateInput =>
settings
? refreshSettingsInput(settings, { documentRefresh, resourceRefresh, stalled, finalizing, concurrency })
settings && parsedRefresh.values
? refreshSettingsInput(settings, parsedRefresh.values)
: ({} as UISettingsCandidateInput)
return (
<main className="page-shell system-settings">
@@ -242,116 +256,71 @@ export function SystemSettingsView({
</details>
</>
) : null}
{section === 'storage' ? (
<>
<BackupScheduleSection />
<LibraryStorageSection />
</>
) : null}
{section === 'storage' ? <StorageBackupSummary /> : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' && settings ? (
<section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading">
<div>
<h2>刷新策略</h2>
<p>保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
<h2>参数设置</h2>
</div>
<span className="safe-badge">当前活动版本</span>
</div>
<div className="safe-setting-grid">
<label>
文档状态刷新间隔
<select
value={documentRefresh}
onChange={(event) => {
setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60)
setDirty(true)
}}
>
<option value={15}>15秒</option>
<option value={30}>30秒</option>
<option value={60}>1分钟</option>
</select>
</label>
<label>
资源刷新间隔
<select
value={resourceRefresh}
onChange={(event) => {
setResourceRefresh(Number(event.target.value) as 30 | 60)
setDirty(true)
}}
>
<option value={30}>30秒</option>
<option value={60}>1分钟</option>
</select>
</label>
<label>
解析停滞阈值
<select
value={stalled}
onChange={(event) => {
setStalled(Number(event.target.value) as 1800 | 3600)
setDirty(true)
}}
>
<option value={1800}>30分钟</option>
<option value={3600}>1小时</option>
</select>
</label>
<label>
收尾超时告警
<select
value={finalizing}
onChange={(event) => {
setFinalizing(Number(event.target.value) as 7200 | 14400)
setDirty(true)
}}
>
<option value={7200}>2小时</option>
<option value={14400}>4小时</option>
</select>
</label>
<label>
入库并发上限
<select
value={concurrency}
onChange={(event) => {
setConcurrency(Number(event.target.value))
setDirty(true)
}}
>
<option value={1}>1(谨慎,MinerU 并发 1)</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value={4}>4</option>
<option value={6}>6</option>
<option value={8}>8</option>
</select>
</label>
<div className="settings-param-groups">
{refreshGroups.map((group) => (
<section className="settings-param-group" key={group.key} data-refresh-group={group.key}>
<h3>{group.title}</h3>
<div className="safe-setting-grid">
{group.fields.map((key) => {
const meta = REFRESH_FIELD_META[key]
const hint = refreshHints[key]
const error = parsedRefresh.errors[key]
const hintID = `refresh-${key}-hint`
const errorID = `refresh-${key}-error`
return (
<label key={key}>
{meta.label}
<span className="settings-field-control">
<input
type="text"
inputMode="numeric"
autoComplete="off"
value={refreshDrafts[key]}
aria-invalid={error ? 'true' : 'false'}
aria-describedby={error ? `${hintID} ${errorID}` : hintID}
onChange={(event) =>
setRefreshDrafts((drafts) => ({ ...drafts, [key]: event.target.value }))
}
/>
<span className="settings-field-unit">{meta.unit}</span>
</span>
<small className="settings-field-hint" id={hintID}>
{hint}
</small>
{error ? (
<span className="settings-field-error" id={errorID} role="alert">
{error}
</span>
) : null}
</label>
)
})}
</div>
</section>
))}
</div>
<button
onClick={() => {
setDirty(false)
onSave(refreshInput())
}}
disabled={!canSave || !refreshSettingsDirty}
>
{saving ? '正在验证并应用…' : '保存刷新与告警参数'}
<button onClick={() => onSave(refreshInput())} disabled={!canSave || !refreshDirty}>
{saving ? '正在验证并应用…' : '保存参数设置'}
</button>
{visibleSaveMessage(saveMessage, dirty) ? (
{visibleSaveMessage(saveMessage, refreshDirty) ? (
<p className="success-message" role="status">
{saveMessage}
</p>
) : null}
<p className="settings-warn">
解析停滞阈值保存后由 worker 在 1 分钟内生效;收尾超时告警目前只保存配置,判定尚未接入。
</p>
<p className="settings-warn">解析停滞阈值保存后由 worker 在 1 分钟内生效。</p>
<p className="settings-hint">保存只改这组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
<small>
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '}
{settings.ingestion_concurrency}。
{`当前:文档 ${settings.document_refresh_seconds} 秒、资源 ${settings.resource_refresh_seconds} 秒、停滞 ${settings.stalled_after_seconds / 60} 分钟、入库并发 ${settings.ingestion_concurrency}。`}
</small>
</section>
) : null}
@@ -435,7 +404,7 @@ export function SystemSettings() {
// 探测失败不影响保存结果,页面保留上一次观测。
}
setSaveMessage(
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${active.stalled_after_seconds / 60}分钟、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '保存系统设置失败')
-87
View File
@@ -1,87 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule'
const payload = {
enabled: true,
schedule_time: '03:30',
retention_days: 7,
retention_months: 3,
updated_by: 'yaozhanghao',
updated_at: '2026-10-09T12:00:00Z',
last_applied_at: '',
last_applied_summary: '',
host_configured: true,
host_target: 'weknora-test',
host_reachable: true,
host_error: '',
host_schedule_enabled: true,
host_schedule_time: '03:30',
host_keep_days: 7,
host_keep_months: 3,
host_cron_lines: ['30 03 * * * root …'],
host_cron_service: 'active',
host_script_present: true,
last_run_stamp: '20261009T052909Z',
last_run_created_at: '2026-10-09T05:29:09Z',
last_run_duration_seconds: 33,
last_run_total_bytes: 778502144,
last_run_databases: ['weknora_test'],
last_run_failed_databases: [],
last_run_error: '',
in_sync: true,
applied: true,
apply_error: '',
running: false,
running_started_at: '',
run_last_error: '',
}
const jsonResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
afterEach(() => {
vi.unstubAllGlobals()
})
describe('backupSchedule 客户端', () => {
it('解析计划三要素与主机回执', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: payload }))
)
const schedule = await fetchBackupSchedule()
expect(schedule.schedule_time).toBe('03:30')
expect(schedule.retention_days).toBe(7)
expect(schedule.host_cron_lines).toHaveLength(1)
expect(schedule.last_run_failed_databases).toEqual([])
})
it('缺计划字段就报错,绝不把默认值伪装成真实设置', async () => {
const broken = { ...payload } as Record<string, unknown>
delete broken.retention_days
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: broken }))
)
await expect(fetchBackupScheduleHost()).rejects.toThrow('存储与备份响应缺少计划字段')
})
it('保存失败时把后端的中文原因透出来', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400))
)
await expect(
saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 })
).rejects.toThrow('储存天数需在 1~365 之间,收到 0')
})
it('立即备份返回 202 时识别为已启动', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202))
)
await expect(runBackupNow()).resolves.toEqual({ started: true, running: true })
})
})
-187
View File
@@ -1,187 +0,0 @@
import { newOperationID } from './operationKey'
// 「系统设置 → 存储与备份」:整库逻辑备份的定时计划(时间 + 储存天数)与主机回执。
export interface BackupSchedule {
enabled: boolean
schedule_time: string
retention_days: number
retention_months: number
updated_by: string
updated_at: string
last_applied_at: string
last_applied_summary: string
host_configured: boolean
host_target: string
// host_endpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。
host_endpoint: string
host_reachable: boolean
host_error: string
host_schedule_enabled: boolean
host_schedule_time: string
// 主机若没有返回真实 next-run,保持空串;页面不得用历史下发时间推算。
host_next_run?: string
host_checked_at?: string
host_keep_days: number
host_keep_months: number
host_cron_lines: string[]
host_cron_service: string
host_script_present: boolean
last_run_stamp: string
last_run_created_at: string
last_run_duration_seconds: number
last_run_total_bytes: number
last_run_databases: string[]
last_run_failed_databases: string[]
last_run_error: string
in_sync: boolean
applied: boolean
apply_error: string
running: boolean
running_started_at: string
run_last_error: string
}
export interface BackupRunStart {
started: boolean
running: boolean
}
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
const asString = (value: unknown): string => (typeof value === 'string' ? value : '')
const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
const asStringList = (value: unknown): string[] =>
Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
// 严格解析:计划三要素(时间/天数/月数)必须是正确类型,缺一个就整块报错,
// 而不是让界面显示成"默认 03:30 / 7 天"这种假状态。
function scheduleProjection(item: Record<string, unknown>): BackupSchedule {
if (
typeof item.schedule_time !== 'string' ||
typeof item.retention_days !== 'number' ||
typeof item.retention_months !== 'number'
) {
throw new Error('存储与备份响应缺少计划字段(schedule_time / retention_days / retention_months)')
}
return {
enabled: item.enabled === true,
schedule_time: item.schedule_time,
retention_days: item.retention_days,
retention_months: item.retention_months,
updated_by: asString(item.updated_by),
updated_at: asString(item.updated_at),
last_applied_at: asString(item.last_applied_at),
last_applied_summary: asString(item.last_applied_summary),
host_configured: item.host_configured === true,
host_target: asString(item.host_target),
host_endpoint: asString(item.host_endpoint),
host_reachable: item.host_reachable === true,
host_error: asString(item.host_error),
host_schedule_enabled: item.host_schedule_enabled === true,
host_schedule_time: asString(item.host_schedule_time),
host_next_run: asString(item.host_next_run),
host_checked_at: asString(item.host_checked_at),
host_keep_days: asNumber(item.host_keep_days),
host_keep_months: asNumber(item.host_keep_months),
host_cron_lines: asStringList(item.host_cron_lines),
host_cron_service: asString(item.host_cron_service),
host_script_present: item.host_script_present === true,
last_run_stamp: asString(item.last_run_stamp),
last_run_created_at: asString(item.last_run_created_at),
last_run_duration_seconds: asNumber(item.last_run_duration_seconds),
last_run_total_bytes: asNumber(item.last_run_total_bytes),
last_run_databases: asStringList(item.last_run_databases),
last_run_failed_databases: asStringList(item.last_run_failed_databases),
last_run_error: asString(item.last_run_error),
in_sync: item.in_sync === true,
applied: item.applied === true,
apply_error: asString(item.apply_error),
running: item.running === true,
running_started_at: asString(item.running_started_at),
run_last_error: asString(item.run_last_error),
}
}
async function readSchedule(path: string, failure: string, signal?: AbortSignal): Promise<BackupSchedule> {
const response = await fetch(path, { signal, headers: { Accept: 'application/json' } })
if (!response.ok) throw new Error(`${failure}(HTTP ${response.status})`)
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
return scheduleProjection(value.data)
}
export function fetchBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
return readSchedule('/api/v1/backup-schedule', '读取备份计划失败', signal)
}
// host 端点会 SSH 探测目标主机(计划 + 最近一次结果),单独调用以免拖慢首屏。
export function fetchBackupScheduleHost(signal?: AbortSignal): Promise<BackupSchedule> {
return readSchedule('/api/v1/backup-schedule/host', '读取目标主机上的备份状态失败', signal)
}
async function writeSchedule(
path: string,
method: string,
body: unknown,
failure: string,
signal?: AbortSignal
): Promise<BackupSchedule> {
const response = await fetch(path, {
method,
signal,
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
body: body === undefined ? undefined : JSON.stringify(body),
})
if (!response.ok) {
let reason = `${failure}(HTTP ${response.status})`
try {
const payload = (await response.json()) as unknown
if (record(payload) && typeof payload.error === 'string') reason = payload.error
} catch {
/* keep the status text */
}
throw new Error(reason)
}
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
return scheduleProjection(value.data)
}
export interface BackupScheduleInput {
enabled: boolean
schedule_time: string
retention_days: number
retention_months: number
// 默认 true:保存后立刻下发到目标主机(页面按钮"保存并下发")。
apply?: boolean
}
export function saveBackupSchedule(input: BackupScheduleInput, signal?: AbortSignal): Promise<BackupSchedule> {
return writeSchedule('/api/v1/backup-schedule', 'PUT', input, '保存备份计划失败', signal)
}
export function applyBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
return writeSchedule('/api/v1/backup-schedule/apply', 'POST', undefined, '下发备份计划失败', signal)
}
export async function runBackupNow(signal?: AbortSignal): Promise<BackupRunStart> {
const response = await fetch('/api/v1/backup-schedule/run', {
method: 'POST',
signal,
headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() },
})
if (!response.ok) {
let reason = `触发备份失败(HTTP ${response.status})`
try {
const payload = (await response.json()) as unknown
if (record(payload) && typeof payload.error === 'string') reason = payload.error
} catch {
/* keep the status text */
}
throw new Error(reason)
}
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('触发备份响应无效')
return { started: value.data.started === true, running: value.data.running === true }
}
+20
View File
@@ -39,11 +39,13 @@ describe('knowledgeBaseBindings', () => {
data: {
environments: [binding('test'), binding('production')],
storage_ready: true,
secret_entry_allowed: true,
},
})
expect(parsed.test.base_url).toBe('https://test.example')
expect(parsed.production.internal_kb_name).toBe('内部资料')
expect(parsed.storage_ready).toBe(true)
expect(parsed.secret_entry_allowed).toBe(true)
const asRecord = parsed.test as unknown as Record<string, unknown>
expect(asRecord.api_key).toBeUndefined()
expect(asRecord.key_ciphertext).toBeUndefined()
@@ -53,6 +55,24 @@ describe('knowledgeBaseBindings', () => {
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
})
it('leaves the capability absent when an older API does not report it', () => {
const parsed = parseKBBindingSnapshot({
data: { environments: [binding('test'), binding('production')], storage_ready: true },
})
expect(parsed.secret_entry_allowed).toBeUndefined()
})
it('keeps an explicit refusal distinguishable from a missing field', () => {
const parsed = parseKBBindingSnapshot({
data: {
environments: [binding('test'), binding('production')],
storage_ready: true,
secret_entry_allowed: false,
},
})
expect(parsed.secret_entry_allowed).toBe(false)
})
it('shows a short id next to the name so same-name bases are distinguishable', () => {
expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…')
expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)')
+10 -1
View File
@@ -34,6 +34,9 @@ export interface KBBindingSnapshot {
test: KBEnvironmentBinding
production: KBEnvironmentBinding
storage_ready: boolean
// Absent stays absent: an older API must not be reported as an untrusted
// proxy, and it must still fail closed for key entry.
secret_entry_allowed?: boolean
}
export interface KBCatalogOption {
@@ -130,7 +133,13 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
const test = byEnvironment.get('test')
const production = byEnvironment.get('production')
if (!test || !production) throw new Error('知识库绑定响应缺少环境')
return { test, production, storage_ready: bool(value.data.storage_ready) }
return {
test,
production,
storage_ready: bool(value.data.storage_ready),
secret_entry_allowed:
typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined,
}
}
// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。
-99
View File
@@ -1,99 +0,0 @@
.library-storage {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
padding: 16px 18px;
margin-bottom: 18px;
background: #fff;
}
.library-storage header h3 {
margin: 0 0 4px;
font-size: 16px;
}
.library-storage header p {
margin: 0 0 12px;
font-size: 12px;
color: var(--ink-mute, #64748b);
line-height: 1.6;
}
.library-storage-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px;
margin: 0 0 12px;
}
.library-storage-grid div {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 9px 11px;
}
.library-storage-grid dt {
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.library-storage-grid dd {
margin: 3px 0 0;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.library-storage-limits {
margin: 0;
padding-left: 18px;
font-size: 12px;
color: #986b24;
line-height: 1.8;
}
.library-storage-hint {
margin: 0;
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-storage-blocked {
border: 1px solid #f3c2b8;
background: #fff6f3;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-blocked strong {
display: block;
font-size: 12px;
color: #a03a1e;
}
.library-storage-blocked p {
margin: 2px 0 0;
font-size: 12px;
color: #7c2d12;
}
.library-storage-panel {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-panel h4 {
margin: 0 0 6px;
font-size: 13px;
}
.library-storage-panel p {
margin: 0 0 6px;
font-size: 12px;
line-height: 1.7;
color: #3f5566;
}
.library-storage-warn {
color: #986b24 !important;
}
.library-storage-versions {
margin: 4px 0 0;
padding-left: 18px;
font-size: 12px;
line-height: 1.8;
color: #3f5566;
}
.library-storage-blocked-list {
margin: 4px 0 0;
padding-left: 18px;
font-size: 12px;
color: #a03a1e;
}
+11 -1
View File
@@ -15,6 +15,16 @@ export const managedUserRoles = ['viewer', 'engineer', 'admin'] as const
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
export class MembersRequestError extends Error {
readonly status: number
constructor(message: string, status: number) {
super(message)
this.name = 'MembersRequestError'
this.status = status
}
}
function parseUser(raw: unknown): ManagedUser {
if (
!record(raw) ||
@@ -50,7 +60,7 @@ async function call(url: string, init: RequestInit, message: string): Promise<un
})
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: string } | null
throw new Error(payload?.error || `${message}(HTTP ${response.status})`)
throw new MembersRequestError(payload?.error || `${message}(HTTP ${response.status})`, response.status)
}
return response.json()
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { plaintextRemoteConsole, secretEntryAllowed } from './secureEntry'
describe('secureEntry', () => {
it('accepts HTTPS and loopback whatever the deployment toggle says', () => {
for (const location of [
{ protocol: 'https:', hostname: 'kb.example' },
{ protocol: 'http:', hostname: 'localhost' },
{ protocol: 'http:', hostname: '127.0.0.1' },
{ protocol: 'http:', hostname: '[::1]' },
{ protocol: 'http:', hostname: '::1' },
]) {
expect(secretEntryAllowed(location), JSON.stringify(location)).toBe(true)
expect(plaintextRemoteConsole(location)).toBe(false)
}
})
it('treats plain HTTP from any other host as a plaintext network path', () => {
for (const hostname of ['172.29.151.11', '10.0.0.5', 'kb.internal.example', '203.0.113.10']) {
const location = { protocol: 'http:', hostname }
expect(secretEntryAllowed(location), hostname).toBe(false)
expect(plaintextRemoteConsole(location), hostname).toBe(true)
}
})
})
+7
View File
@@ -3,3 +3,10 @@
export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
}
// True when a key typed here would cross a network in the clear, even though
// the server presently allows it. Drives the warning only, never the gate:
// the gate is the server-reported capability.
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
return !secretEntryAllowed(location)
}
+89 -13
View File
@@ -1,6 +1,6 @@
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
// 保存边界是纯函数:连接分区只取连接草稿,刷新分区只取刷新草稿,
// 保存边界是纯函数:连接分区只取连接草稿,参数分区只取参数草稿,
// 另一侧一律用服务器当前值。组件与测试共用同一实现。
export interface ServiceDrafts {
testEndpoint: string
@@ -8,13 +8,87 @@ export interface ServiceDrafts {
productionTenantID: string
productionKnowledgeBaseID: string
}
export interface RefreshDrafts {
documentRefresh: 15 | 30 | 60
resourceRefresh: 30 | 60
stalled: 1800 | 3600
finalizing: 7200 | 14400
concurrency: number
export type RefreshField = 'documentRefresh' | 'resourceRefresh' | 'stalled' | 'concurrency'
export type RefreshDrafts = Record<RefreshField, string>
export type RefreshValues = Record<RefreshField, number>
export type RefreshParseResult = {
values: RefreshValues | null
errors: Record<RefreshField, string | null>
}
export interface RefreshFieldMeta {
label: string
unit: string
}
interface RefreshRule extends RefreshFieldMeta {
allowed?: number[]
min?: number
max?: number
// 草稿单位与存储单位不同:停滞输入分钟、接口收秒。
toStored: (value: number) => number
}
// 展示与错误文案共用同一份字段名/单位,避免两处各写一遍后漂移。
export const REFRESH_FIELD_META: Record<RefreshField, RefreshFieldMeta> = {
documentRefresh: { label: '文档状态刷新间隔', unit: '秒' },
resourceRefresh: { label: '资源刷新间隔', unit: '秒' },
stalled: { label: '解析停滞阈值', unit: '分钟' },
concurrency: { label: '入库并发上限', unit: '个' },
}
const REFRESH_RULES: Record<RefreshField, RefreshRule> = {
documentRefresh: { ...REFRESH_FIELD_META.documentRefresh, allowed: [15, 30, 60], toStored: (value) => value },
resourceRefresh: { ...REFRESH_FIELD_META.resourceRefresh, allowed: [30, 60], toStored: (value) => value },
stalled: { ...REFRESH_FIELD_META.stalled, allowed: [30, 60], toStored: (value) => value * 60 },
concurrency: { ...REFRESH_FIELD_META.concurrency, min: 1, max: 16, toStored: (value) => value },
}
const parseField = (field: RefreshField, rawDraft: string): { value: number | null; error: string | null } => {
const rule = REFRESH_RULES[field]
const raw = rawDraft.trim()
if (!raw) return { value: null, error: `${rule.label}不能为空` }
// 不用 Number()/parseInt():空串、全角数字、"15abc" 都会被静默转成数字。
if (!/^\d+$/.test(raw)) return { value: null, error: `${rule.label}必须是整数` }
const value = Number(raw)
if (rule.allowed) {
if (!rule.allowed.includes(value))
return { value: null, error: `${rule.label}只能是 ${rule.allowed.join('/')} ${rule.unit};当前 ${raw}` }
} else if (rule.min !== undefined && rule.max !== undefined && (value < rule.min || value > rule.max)) {
return { value: null, error: `${rule.label}只能是 ${rule.min}~${rule.max} 的整数;当前 ${raw}` }
}
return { value: rule.toStored(value), error: null }
}
export const refreshDraftText = (settings: UISettings): RefreshDrafts => ({
documentRefresh: String(settings.document_refresh_seconds),
resourceRefresh: String(settings.resource_refresh_seconds),
stalled: String(settings.stalled_after_seconds / 60),
concurrency: String(settings.ingestion_concurrency),
})
export const parseRefreshDrafts = (drafts: RefreshDrafts): RefreshParseResult => {
const errors = {} as Record<RefreshField, string | null>
const values = {} as RefreshValues
for (const field of Object.keys(REFRESH_RULES) as RefreshField[]) {
const parsed = parseField(field, drafts[field])
errors[field] = parsed.error
if (parsed.value !== null) values[field] = parsed.value
}
return { values: Object.values(errors).every((error) => error === null) ? values : null, errors }
}
export const refreshSettingsDirty = (drafts: RefreshDrafts, settings: UISettings): boolean => {
const parsed = parseRefreshDrafts(drafts)
if (!parsed.values) return true
return (
parsed.values.documentRefresh !== settings.document_refresh_seconds ||
parsed.values.resourceRefresh !== settings.resource_refresh_seconds ||
parsed.values.stalled !== settings.stalled_after_seconds ||
parsed.values.concurrency !== settings.ingestion_concurrency
)
}
export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts): UISettingsCandidateInput => ({
document_refresh_seconds: settings.document_refresh_seconds,
resource_refresh_seconds: settings.resource_refresh_seconds,
@@ -26,12 +100,14 @@ export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts
production_tenant_id: drafts.productionTenantID.trim(),
production_knowledge_base_id: drafts.productionKnowledgeBaseID.trim(),
})
export const refreshSettingsInput = (settings: UISettings, drafts: RefreshDrafts): UISettingsCandidateInput => ({
document_refresh_seconds: drafts.documentRefresh,
resource_refresh_seconds: drafts.resourceRefresh,
stalled_after_seconds: drafts.stalled,
finalizing_after_seconds: drafts.finalizing,
ingestion_concurrency: drafts.concurrency,
export const refreshSettingsInput = (settings: UISettings, values: RefreshValues): UISettingsCandidateInput => ({
// 范围由 parseRefreshDrafts 白名单保证;这里只把 number 收回契约的枚举类型。
document_refresh_seconds: values.documentRefresh as UISettings['document_refresh_seconds'],
resource_refresh_seconds: values.resourceRefresh as UISettings['resource_refresh_seconds'],
stalled_after_seconds: values.stalled as UISettings['stalled_after_seconds'],
// 参数分区不展示收尾超时,但契约必填且写侧按服务器值判权限:原样回传,绝不置空。
finalizing_after_seconds: settings.finalizing_after_seconds,
ingestion_concurrency: values.concurrency,
test_weknora_base_url: settings.test_weknora_base_url,
production_weknora_base_url: settings.production_weknora_base_url,
production_tenant_id: settings.production_tenant_id,
+320 -372
View File
@@ -1,424 +1,372 @@
/* 「系统设置 → 存储与备份」:数据库整库逻辑备份。
原型里的单条整盘图与告警在这里保留位置;真实读数未接线时用虚底而不是假容量。 */
.storage-settings-panel {
/* 存储与备份:只读摘要页。全部颜色走 tokens,状态色沿用全局 fail/warn/done。 */
.storage-summary {
display: flex;
flex-direction: column;
gap: 14px;
gap: 18px;
}
.storage-settings-panel .settings-section-heading p {
.storage-summary-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.storage-summary-head h2 {
margin: 0;
max-width: 78ch;
color: var(--ink-mute, #64748b);
font-size: 11px;
line-height: 1.7;
font-size: 16px;
color: var(--ink-strong);
}
/* 主机读回用两栏事实表;窄列时自动落成一栏,避免 dd 把 dt 挤成竖排。 */
.settings-panel .storage-settings-grid {
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
.storage-summary-state {
margin: 4px 0 0;
font-size: 12px;
color: var(--c-warn);
}
.settings-panel .storage-settings-grid > dl {
grid-template-columns: minmax(104px, max-content) minmax(0, 1fr);
.storage-summary-meta {
display: flex;
align-items: center;
gap: 12px;
font-size: 12px;
color: var(--ink-mute);
}
.storage-settings-panel code {
.storage-refresh,
.storage-more {
border: 1px solid var(--border-strong);
background: var(--bg-panel);
border-radius: 6px;
padding: 5px 12px;
font-size: 12px;
color: var(--ink-base);
cursor: pointer;
}
.storage-refresh:hover,
.storage-more:hover {
background: var(--bg-hover);
}
.storage-refresh:disabled {
color: var(--ink-faint);
cursor: default;
}
.storage-summary-error {
margin: 0;
padding: 8px 12px;
border-radius: 6px;
border: 1px solid var(--c-fail-border);
background: var(--c-fail-bg);
color: var(--c-fail);
font-size: 12px;
}
.storage-summary-loading {
margin: 0;
font-size: 13px;
color: var(--ink-mute);
}
.storage-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 12px;
}
.storage-card {
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-panel);
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.storage-card-label {
font-size: 12px;
color: var(--ink-mute);
}
.storage-card-value {
font-size: 24px;
font-weight: 600;
line-height: 1.15;
color: var(--ink-strong);
overflow-wrap: anywhere;
}
.storage-block {
border-top: 1px solid var(--border-base, #e2e8f0);
padding-top: 12px;
.storage-card-value.is-unknown {
font-size: 15px;
font-weight: 500;
color: var(--ink-mute);
}
.storage-block-heading {
/* 备份目录是配置事实而不是指标:独占一行、字号收小,避免长路径撑爆卡片。 */
.storage-card-root {
grid-column: 1 / -1;
}
.storage-card-root .storage-card-value {
font-size: 16px;
line-height: 1.35;
overflow-wrap: anywhere;
}
.storage-card-note {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--ink-mute);
min-height: 18px;
}
.storage-copy {
border: 1px solid var(--border-base);
background: var(--bg-soft);
border-radius: 5px;
padding: 1px 7px;
font-size: 11px;
color: var(--ink-mute);
cursor: pointer;
flex: none;
}
.storage-copy:hover {
background: var(--bg-hover);
color: var(--ink-base);
}
.storage-alerts,
.storage-batches {
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-panel);
overflow: hidden;
}
.storage-alerts > header,
.storage-batches > header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px 14px;
flex-wrap: wrap;
margin-bottom: 6px;
gap: 12px;
padding: 12px 16px;
border-bottom: 1px solid var(--border-soft);
}
.storage-block-heading h3 {
.storage-alerts h3,
.storage-batches h3 {
margin: 0;
font-size: 13px;
color: var(--ink-base);
color: var(--ink-strong);
}
.storage-block-heading button {
font: inherit;
font-size: 10px;
padding: 3px 9px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
.storage-batches > header span,
.storage-alert-count {
font-size: 12px;
color: var(--ink-mute);
}
.storage-block-heading button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-chip {
border-radius: 999px;
padding: 2px 9px;
font-size: 10px;
border: 1px solid var(--border-base, #e2e8f0);
color: var(--ink-mute, #64748b);
}
.storage-chip.ok {
color: #17695a;
border-color: #a9d5c8;
background: #effaf5;
}
.storage-chip.warn {
color: #985d10;
border-color: #f0d3a4;
background: #fff8ec;
}
.storage-chip.off {
color: var(--ink-mute, #64748b);
background: var(--bg-soft, #f6f8fa);
}
.settings-panel .storage-facts {
display: grid;
grid-template-columns: minmax(96px, max-content) minmax(0, 1fr);
gap: 5px 14px;
margin: 6px 0;
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.settings-panel .storage-facts dd {
margin: 0;
color: var(--ink-base);
overflow-wrap: anywhere;
}
.storage-inline-note {
display: block;
color: var(--ink-mute, #64748b);
font-size: 10px;
}
.storage-block-actions {
display: flex;
align-items: center;
gap: 8px 12px;
flex-wrap: wrap;
margin: 7px 0;
}
.storage-block-actions .hint {
max-width: 72ch;
}
.storage-block-actions button {
font: inherit;
font-size: 11px;
padding: 5px 11px;
border-radius: 6px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
}
.storage-block-actions button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-block-actions button.primary {
background: #185f78;
border-color: #185f78;
color: #fff;
}
.storage-progress {
margin: 6px 0;
}
.storage-running {
margin: 0 0 5px;
font-size: 11px;
color: var(--ink-base);
}
.storage-progress-bar {
width: 100%;
height: 10px;
}
.storage-disk-track {
display: flex;
height: 22px;
margin: 8px 0;
border-radius: 5px;
overflow: hidden;
background: #e4e9ef;
outline: 1px solid #aab9c1;
}
.storage-disk-other {
background: #77889a;
}
.storage-disk-zone {
display: flex;
background: #c0dfed;
box-shadow: inset 0 0 0 1px #6191a8;
}
.storage-disk-used {
background: #19698c;
}
.storage-disk-blank {
background: #e4e9ef;
}
.storage-disk-track-unknown {
display: flex;
align-items: center;
justify-content: center;
background: repeating-linear-gradient(45deg, #eef2f5 0 6px, #e1e7eb 6px 12px);
border: 1px dashed #aab9c1;
outline: none;
color: #576674;
font-size: 10px;
}
.storage-disk-low .storage-disk-other {
background: #9d625d;
}
.storage-disk-low .storage-disk-used {
background: #be6c10;
}
.storage-disk-low .storage-disk-zone {
background: #ffe0a8;
}
.storage-disk-legend {
display: flex;
gap: 6px 16px;
flex-wrap: wrap;
font-size: 10px;
color: #3f5566;
}
.storage-dot {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 4px;
border-radius: 2px;
vertical-align: -1px;
}
.storage-dot.other {
background: #77889a;
}
.storage-dot.used {
background: #19698c;
}
.storage-dot.zone {
background: #c0dfed;
}
.storage-dot.blank {
background: #e4e9ef;
outline: 1px solid #c4ced6;
}
.storage-metric {
margin: 6px 0 2px;
font-size: 11px;
.storage-alert-count.is-pending {
color: var(--c-fail);
font-weight: 600;
}
.storage-manifest {
font-size: 10px;
padding: 1px 7px;
border-radius: 999px;
border: 1px solid var(--border-base, #e2e8f0);
}
.storage-manifest.ok {
color: #17695a;
border-color: #a9d5c8;
background: #effaf5;
}
.storage-manifest.missing,
.storage-manifest.invalid {
color: #a03a1e;
border-color: #f3c2b8;
background: #fff6f3;
}
.storage-path-row {
display: grid;
grid-template-columns: max-content minmax(0, 1fr) max-content;
gap: 4px 8px;
align-items: center;
margin: 5px 0;
}
.storage-path-row small {
color: var(--ink-mute, #64748b);
}
.storage-path-row code {
font-size: 10px;
padding: 3px 6px;
border-radius: 4px;
background: var(--bg-soft, #f6f8fa);
overflow-wrap: anywhere;
}
.storage-path-row button,
.storage-sublibraries button {
font: inherit;
font-size: 10px;
padding: 3px 8px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
}
.storage-path-row button:disabled,
.storage-sublibraries button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-sublibrary-path {
margin: 2px 0 0;
grid-template-columns: minmax(0, 1fr) max-content;
}
.storage-alert-summary {
margin: 8px 0 0;
font-size: 11px;
font-weight: 600;
color: #3f5566;
}
.storage-alerts {
.storage-alerts ul {
list-style: none;
margin: 8px 0 0;
margin: 0;
padding: 0;
display: grid;
gap: 5px;
}
.storage-alerts li {
display: grid;
grid-template-columns: max-content max-content minmax(0, 1fr);
gap: 4px 10px;
align-items: baseline;
font-size: 10px;
padding: 4px 8px;
border-radius: 6px;
background: var(--bg-soft, #f6f8fa);
grid-template-columns: 180px minmax(0, 1fr) 84px;
gap: 12px;
align-items: center;
padding: 10px 16px;
border-bottom: 1px solid var(--border-soft);
font-size: 13px;
}
.storage-alerts li strong {
font-size: 11px;
.storage-alerts li:last-child {
border-bottom: none;
}
.storage-alerts li small {
color: var(--ink-mute, #64748b);
.storage-alert-label {
color: var(--ink-base);
}
.storage-alert-value {
color: var(--ink-mute);
overflow-wrap: anywhere;
}
.storage-alerts .alert-on {
background: #fff1ec;
color: #a03a1e;
.storage-alert-conclusion {
justify-self: end;
border-radius: 999px;
padding: 2px 10px;
font-size: 12px;
border: 1px solid var(--border-base);
color: var(--ink-mute);
background: var(--bg-soft);
}
.storage-alerts .alert-ok {
background: #f0faf6;
color: #17695a;
.storage-alert-conclusion[data-tone='ok'] {
color: var(--c-done);
border-color: var(--c-done-border);
background: var(--c-done-bg);
}
.storage-alerts .alert-unknown {
background: #f8f5ee;
color: #715c2c;
.storage-alert-conclusion[data-tone='warn'] {
color: var(--c-warn);
border-color: var(--c-warn-border);
background: var(--c-warn-bg);
}
.storage-plan {
margin: 4px 0;
font-size: 11px;
color: #3f5566;
.storage-alert-conclusion[data-tone='bad'] {
color: var(--c-fail);
border-color: var(--c-fail-border);
background: var(--c-fail-bg);
}
.storage-policy-editor {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 6px;
}
.storage-policy-editor > label {
display: grid;
gap: 3px;
font-size: 10px;
color: var(--ink-mute, #64748b);
}
.storage-policy-editor input[type='text'],
.storage-policy-editor input[type='time'],
.storage-policy-editor input[type='number'] {
.storage-batches table {
width: 100%;
max-width: 320px;
font: inherit;
font-size: 11px;
padding: 5px 8px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
border-collapse: collapse;
font-size: 12px;
table-layout: fixed;
}
.storage-policy-editor input:disabled {
background: var(--bg-soft, #f1f4f6);
color: var(--ink-mute, #64748b);
.storage-batches th {
text-align: left;
font-weight: 500;
color: var(--ink-mute);
padding: 8px 16px;
border-bottom: 1px solid var(--border-soft);
}
.storage-checkbox {
display: flex !important;
align-items: center;
gap: 6px;
font-size: 11px !important;
color: var(--ink-base) !important;
.storage-batches td {
padding: 10px 16px;
border-bottom: 1px solid var(--border-soft);
vertical-align: top;
color: var(--ink-base);
}
.storage-policy-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 8px 12px;
.storage-batches th:nth-child(1),
.storage-batches td:nth-child(1) {
width: 96px;
}
.storage-policy-grid label {
display: grid;
gap: 3px;
font-size: 10px;
color: var(--ink-mute, #64748b);
.storage-batches th:nth-child(2),
.storage-batches td:nth-child(2) {
width: 200px;
}
.storage-policy-grid input {
width: 100%;
.storage-batches th:nth-child(3),
.storage-batches td:nth-child(3) {
width: 88px;
}
.storage-batch {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 8px;
padding: 8px 10px;
.storage-batches th:nth-child(4),
.storage-batches td:nth-child(4) {
width: 170px;
}
.storage-batches th:nth-child(6),
.storage-batches td:nth-child(6) {
width: 64px;
}
.storage-batch-time,
.storage-batch-stamp {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.storage-batch-size {
white-space: nowrap;
}
.storage-batch-result {
display: inline-block;
border-radius: 999px;
padding: 1px 9px;
border: 1px solid var(--border-base);
font-size: 11px;
}
.storage-batch summary {
display: flex;
gap: 6px 14px;
flex-wrap: wrap;
align-items: baseline;
cursor: pointer;
.storage-batch-result.is-ok {
color: var(--c-done);
border-color: var(--c-done-border);
background: var(--c-done-bg);
}
.storage-batch summary strong.ok {
color: #17695a;
.storage-batch-result.is-failed {
color: var(--c-fail);
border-color: var(--c-fail-border);
background: var(--c-fail-bg);
}
.storage-batch summary strong.off {
color: #a03a1e;
.storage-batch-reason {
margin: 4px 0 0;
font-size: 11px;
color: var(--c-fail);
white-space: normal;
overflow-wrap: anywhere;
}
.storage-batch p {
margin: 6px 0;
color: #3f5566;
/* 长路径中间截断:保留结尾(批次目录名),从开头省略。 */
.storage-batch-path {
min-width: 0;
}
.storage-sublibraries {
list-style: none;
margin: 6px 0;
padding: 0;
display: grid;
gap: 4px;
.storage-batch-path > span {
display: block;
direction: rtl;
unicode-bidi: plaintext;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--ink-mute);
}
.storage-sublibraries li {
display: grid;
grid-template-columns: minmax(120px, max-content) max-content minmax(0, 1fr);
gap: 4px 10px;
align-items: baseline;
padding: 3px 6px;
border-radius: 5px;
background: var(--bg-soft, #f6f8fa);
.storage-batches-empty {
margin: 0;
padding: 24px 16px;
font-size: 13px;
color: var(--ink-mute);
text-align: center;
}
.storage-sublibrary-path {
grid-column: 1 / -1;
.storage-more {
display: block;
margin: 12px auto;
}
.storage-sublibraries .ok {
color: #17695a;
}
.storage-sublibraries .off {
color: #a03a1e;
}
.storage-sublibraries small {
color: var(--ink-mute, #64748b);
}
.storage-verify {
margin: 6px 0 0;
color: #715c2c;
font-size: 10px;
}
@media (max-width: 700px) {
.storage-facts,
.storage-sublibraries li,
@media (max-width: 720px) {
.storage-alerts li {
grid-template-columns: minmax(0, 1fr);
grid-template-columns: minmax(0, 1fr) 84px;
}
.storage-alerts .storage-alert-value {
grid-column: 1 / -1;
grid-row: 2;
}
.storage-batches table {
table-layout: auto;
}
.storage-batches th:nth-child(4),
.storage-batches td:nth-child(4),
.storage-batches th:nth-child(5),
.storage-batches td:nth-child(5) {
display: none;
}
}
+308
View File
@@ -0,0 +1,308 @@
import { describe, expect, it } from 'vitest'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
import {
DISK_CRITICAL_AVAILABLE_PERCENT,
batchOutcome,
formatSize,
formatWhen,
hostState,
orderedBatches,
pendingAlertCount,
recentOutcome,
storageAlerts,
summaryCards,
} from './storageSummary'
const GIB = 1024 ** 3
const TB = 1024 * GIB
export const batch = (overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => ({
stamp: '20261124T020000Z',
path: '/srv/kb-backups/rds-logical/20261124T020000Z',
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z',
manifest_state: 'ok',
manifest_path: '/srv/kb-backups/rds-logical/20261124T020000Z/MANIFEST.json',
kind: 'rds',
created_at: '2026-11-24T02:00:00Z',
started_at: '2026-11-24T02:00:00Z',
duration_seconds: 240,
manifest_total_bytes: 10 * GIB,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
sizes_complete: true,
databases: [
{
name: 'weknora',
dir_name: 'weknora.dir',
path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
},
],
...overrides,
})
export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/kb-backups/metadata.json',
collected_at: '2026-11-24T10:17:00Z',
age_seconds: 60,
max_age_seconds: 900,
schema_version: 1,
generation: 'g-1',
host: 'backup-host',
collector_version: '1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 1.2 * TB,
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
batches: [batch()],
totals: {
batch_count: 1,
database_count: 1,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
latest_stamp: '20261124T020000Z',
latest_actual_bytes: 9 * GIB,
complete: true,
},
incomplete_count: 0,
skipped: [],
truncated: false,
...overrides,
})
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
available: true,
archive_root: '/var/lib/knowledge-governance/library',
versions: [],
content_bytes: 41_231_686_042,
blob_file_bytes: 0,
blob_allocated_bytes: 0,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 0,
policy: { keep_versions: 0, keep_days: 0 },
capacity: {
budget_bytes: 100 * GIB,
current_bytes: 41_231_686_042,
required_bytes: 0,
projected_bytes: 41_231_686_042,
configured: true,
ok: true,
},
automatic_cleanup: false,
notes: [],
...overrides,
})
const unreported = (): BackupInventory =>
inventory({
wired: false,
metadata: {
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
path: '',
collected_at: '',
age_seconds: 0,
max_age_seconds: 900,
schema_version: 0,
generation: '',
host: '',
collector_version: '',
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
root: '',
host_root: '',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
batches: [],
totals: {
batch_count: 0,
database_count: 0,
apparent_bytes: null,
actual_bytes: null,
latest_stamp: '',
latest_actual_bytes: null,
complete: false,
},
})
describe('formatSize', () => {
it('keeps one decimal below 100 units and never calls an unknown value zero', () => {
expect(formatSize(41_231_686_042)).toBe('38.4 GB')
expect(formatSize(100 * GIB)).toBe('100 GB')
expect(formatSize(1.2 * TB)).toBe('1.2 TB')
expect(formatSize(2 * TB)).toBe('2 TB')
expect(formatSize(0)).toBe('0 B')
expect(formatSize(null)).toBe('—')
expect(formatSize(undefined)).toBe('—')
})
})
describe('hostState', () => {
it('separates unreported, stale, incomplete and ready snapshots', () => {
expect(hostState(null)).toBe('loading')
expect(hostState(unreported())).toBe('unwired')
expect(hostState(inventory({ metadata: { ...inventory().metadata, present: false } }))).toBe('missing')
expect(hostState(inventory({ metadata: { ...inventory().metadata, fresh: false } }))).toBe('stale')
expect(hostState(inventory({ metadata: { ...inventory().metadata, complete: false } }))).toBe('incomplete')
expect(hostState(inventory())).toBe('ready')
})
})
describe('batchOutcome', () => {
it('reports manifest damage and failed databases as failure reasons', () => {
expect(batchOutcome(batch())).toEqual({ failed: false, reasons: [] })
expect(batchOutcome(batch({ manifest_state: 'missing' })).reasons).toEqual(['清单缺失'])
expect(
batchOutcome(
batch({
manifest_state: 'invalid',
manifest_error: 'MANIFEST.json 无法解析',
databases: [{ ...batch().databases[0], failed: true }],
})
)
).toEqual({ failed: true, reasons: ['清单损坏', 'MANIFEST.json 无法解析', '子库失败:weknora'] })
})
})
describe('recentOutcome', () => {
it('uses the newest batch per outcome and counts only the 7 day window', () => {
const now = Date.parse('2026-11-24T12:00:00Z')
const outcome = recentOutcome(
[
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
batch({ stamp: '20261123T020000Z', created_at: '2026-11-23T02:00:00Z', manifest_state: 'invalid' }),
batch({ stamp: '20261101T020000Z', created_at: '2026-11-01T02:00:00Z', manifest_state: 'missing' }),
],
now
)
expect(outcome.latestSuccessAt).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(outcome.latestFailureAt).toBe(formatWhen('2026-11-23T02:00:00Z'))
expect(outcome.successCount).toBe(1)
expect(outcome.failureCount).toBe(1)
})
it('orders batches by time even when the host sends them unsorted', () => {
const ordered = orderedBatches([
batch({ stamp: '20261122T020000Z', created_at: '2026-11-22T02:00:00Z' }),
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
])
expect(ordered.map((item) => item.stamp)).toEqual(['20261124T020000Z', '20261122T020000Z'])
})
})
describe('summaryCards', () => {
it('shows real values when the host reported and the archive is available', () => {
const cards = summaryCards(inventory(), archive(), false)
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(byKey.failure).toBe('无')
expect(byKey.archive).toBe('38.4 GB')
expect(byKey.disk).toBe('1.2 TB')
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
})
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
const cards = summaryCards(unreported(), archive({ available: false }), false)
for (const key of ['root', 'success', 'failure', 'disk']) {
const card = cards.find((item) => item.key === key)!
expect(card.value).toBe('主机未上报')
expect(card.note).toBe('上次上报 —')
}
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
expect(cards.some((card) => card.value === '0 B')).toBe(false)
})
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
})
})
describe('storageAlerts', () => {
it('judges disk and quota independently and counts pending rows', () => {
const healthy = storageAlerts(inventory(), archive(), false)
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
expect(pendingAlertCount(healthy)).toBe(0)
const nearQuota = storageAlerts(
inventory(),
archive({
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
}),
false
)
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
expect(pendingAlertCount(nearQuota)).toBe(1)
})
it('flags both-insufficient and quota larger than physical free space', () => {
const tight = storageAlerts(
inventory({
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 0.01 * TB,
available_bytes: 0.01 * TB,
used_bytes: 1.99 * TB,
},
}),
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
false
)
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
expect(tight.find((row) => row.key === 'quota_over_physical')?.conclusion).toBe('需处理')
expect(pendingAlertCount(tight)).toBe(4)
expect(DISK_CRITICAL_AVAILABLE_PERCENT).toBe(5)
})
it('never claims a conclusion without numbers', () => {
const alerts = storageAlerts(unreported(), null, true)
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
})
})
+348
View File
@@ -0,0 +1,348 @@
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
// /api/v1/library/storage (归档库自身的占用与配额)
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
// 磁盘:可用空间 < 5% 红,< 10% 黄
// 配额:已用 >= 100% 红,>= 90% 黄
export const DISK_CRITICAL_AVAILABLE_PERCENT = 5
export const DISK_WARN_AVAILABLE_PERCENT = 10
export const QUOTA_CRITICAL_USED_PERCENT = 100
export const QUOTA_WARN_USED_PERCENT = 90
export const RECENT_WINDOW_DAYS = 7
export type Tone = 'ok' | 'warn' | 'bad' | 'none'
export type HostState = 'loading' | 'unwired' | 'missing' | 'stale' | 'invalid' | 'incomplete' | 'ready'
// 陈旧在先:stale 的快照会被后端判为 invalid,但"上次上报时间"仍然可读。
export const hostState = (inventory: BackupInventory | null): HostState => {
if (!inventory) return 'loading'
if (!inventory.wired) return 'unwired'
if (!inventory.metadata.present) return 'missing'
if (!inventory.metadata.fresh) return 'stale'
if (!inventory.metadata.valid) return 'invalid'
if (!inventory.metadata.complete) return 'incomplete'
return 'ready'
}
export const UNREPORTED = '主机未上报'
// 没有可用的上报表时的说法要和真实原因一致:未接入/从未上报、过期、不可用是三件事。
export const hostValueLabel = (state: HostState): string => {
switch (state) {
case 'unwired':
case 'missing':
return UNREPORTED
case 'stale':
return '上报已过期'
case 'invalid':
return '上报不可用'
default:
return UNKNOWN
}
}
export const UNKNOWN = '—'
// 结论未知与数值缺失是两件事:数值缺用“—”,无法判断结论用“未知”。
export const UNKNOWN_STATE = '未知'
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] as const
export function formatSize(bytes: number | null | undefined): string {
if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return UNKNOWN
if (bytes === 0) return '0 B'
let value = bytes
let index = 0
while (value >= 1024 && index < UNITS.length - 1) {
value /= 1024
index += 1
}
const digits = index === 0 || value >= 100 ? 0 : 1
const text = value.toFixed(digits).replace(/\.0$/, '')
return `${text} ${UNITS[index]}`
}
// 本地时间 MM/DD HH:mm;无法解析时返回空串,由调用方显示 "—"。
export function formatWhen(value: string | null | undefined): string {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
const STAMP = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?$/
const stampTime = (stamp: string): number => {
const match = STAMP.exec(stamp)
if (!match) return 0
return Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6])
}
export function batchWhen(batch: BackupInventoryBatch): string {
const iso = formatWhen(batch.created_at) || formatWhen(batch.started_at)
if (iso) return iso
const parsed = stampTime(batch.stamp)
return parsed ? formatWhen(new Date(parsed).toISOString()) || UNKNOWN : UNKNOWN
}
const batchTime = (batch: BackupInventoryBatch): number => {
const created = Date.parse(batch.created_at)
if (!Number.isNaN(created)) return created
const started = Date.parse(batch.started_at)
if (!Number.isNaN(started)) return started
return stampTime(batch.stamp)
}
export function orderedBatches(batches: BackupInventoryBatch[]): BackupInventoryBatch[] {
return [...batches].sort((left, right) => batchTime(right) - batchTime(left))
}
export interface BatchOutcome {
failed: boolean
reasons: string[]
}
// 失败判定:任一子库失败、清单缺失或损坏都算失败。宿主上报里没有自由文本原因,
// 页面只写能证明的事实(清单状态、失败子库名),不编造原因。
export function batchOutcome(batch: BackupInventoryBatch): BatchOutcome {
const reasons: string[] = []
if (batch.manifest_state === 'missing') reasons.push('清单缺失')
if (batch.manifest_state === 'invalid') reasons.push('清单损坏')
const manifestError = batch.manifest_error?.trim()
if (manifestError) reasons.push(manifestError)
const failedDatabases = batch.databases.filter((database) => database.failed).map((database) => database.name)
if (failedDatabases.length > 0) reasons.push(`子库失败:${failedDatabases.join('、')}`)
return { failed: reasons.length > 0, reasons }
}
export interface RecentOutcome {
latestSuccessAt: string
latestFailureAt: string
successCount: number
failureCount: number
}
export function recentOutcome(batches: BackupInventoryBatch[], now: number = Date.now()): RecentOutcome {
const windowStart = now - RECENT_WINDOW_DAYS * 24 * 60 * 60 * 1000
let latestSuccessAt = ''
let latestFailureAt = ''
let successCount = 0
let failureCount = 0
for (const batch of orderedBatches(batches)) {
const failed = batchOutcome(batch).failed
const when = batchWhen(batch)
const at = batchTime(batch)
if (failed) {
if (!latestFailureAt) latestFailureAt = when
} else if (!latestSuccessAt) {
latestSuccessAt = when
}
if (at >= windowStart) {
if (failed) failureCount += 1
else successCount += 1
}
}
return { latestSuccessAt, latestFailureAt, successCount, failureCount }
}
export interface SummaryCard {
key: string
label: string
value: string
note: string
copy?: string
unknown: boolean
}
const lastReportNote = (inventory: BackupInventory): string =>
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
export function summaryCards(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryCard[] {
const state = hostState(inventory)
const facts = state === 'ready' || state === 'incomplete'
const sizes = state === 'ready'
const pending = Boolean(inventory) && state !== 'loading'
const recent = inventory && facts ? recentOutcome(inventory.batches) : null
const hostValue = pending && !facts ? hostValueLabel(state) : UNKNOWN
const hostNote = pending ? lastReportNote(inventory!) : UNKNOWN
const partialNote = facts && !sizes ? '本次上报不完整' : hostNote
const root = inventory ? inventory.host_root || inventory.root : ''
const rootKnown = facts && Boolean(root)
const capacity = inventory?.capacity
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
const archiveKnown = Boolean(archive?.available) && !archiveFailed
return [
{
key: 'root',
label: '备份目录',
value: rootKnown ? root : hostValue,
note: rootKnown ? inventory!.metadata.host || UNKNOWN : partialNote,
copy: rootKnown ? root : undefined,
unknown: !rootKnown,
},
{
key: 'success',
label: '最近成功',
value: recent ? recent.latestSuccessAt || '无' : hostValue,
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.successCount} 次` : partialNote,
unknown: !recent,
},
{
key: 'failure',
label: '最近失败',
value: recent ? recent.latestFailureAt || '无' : hostValue,
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.failureCount} 次` : partialNote,
unknown: !recent,
},
{
key: 'archive',
label: '归档占用',
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
note: archiveFailed
? '归档读取失败'
: !archive || !archive.available
? '归档不可用'
: archive.capacity.configured
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
: '配额未设置',
unknown: !archiveKnown,
},
{
key: 'disk',
label: '磁盘剩余',
value: diskKnown ? formatSize(capacity!.available_bytes) : sizes ? UNKNOWN : hostValue,
note: diskKnown
? `共 ${formatSize(capacity!.total_bytes)} · 可用 ${availablePercent}%`
: sizes
? '容量未上报'
: partialNote,
unknown: !diskKnown,
},
]
}
export interface SummaryAlert {
key: string
label: string
value: string
tone: Tone
conclusion: string
}
export interface StorageFacts {
diskAvailableBytes: number | null
diskTotalBytes: number | null
archiveUsedBytes: number | null
archiveBudgetBytes: number | null
}
export function storageFacts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): StorageFacts {
const capacity = inventory?.capacity
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
return {
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
}
}
const tonePercent = (value: number, warn: number, critical: number): Tone =>
value >= critical ? 'bad' : value >= warn ? 'warn' : 'ok'
const conclusionText = (tone: Tone): string =>
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
export function storageAlerts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryAlert[] {
const state = hostState(inventory)
const facts = storageFacts(inventory, archive, archiveFailed)
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
const diskTone: Tone = diskKnown
? availablePercent < DISK_CRITICAL_AVAILABLE_PERCENT
? 'bad'
: availablePercent < DISK_WARN_AVAILABLE_PERCENT
? 'warn'
: 'ok'
: 'none'
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
const quotaTone: Tone = quotaKnown
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
: 'none'
const bothTone: Tone =
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
const overPhysical: Tone =
diskKnown && facts.archiveBudgetBytes !== null
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
? 'bad'
: 'ok'
: 'none'
const hostValue = hostValueLabel(state)
return [
{
key: 'disk_low',
label: '磁盘不足',
value: diskKnown ? `${formatSize(facts.diskAvailableBytes)}(可用 ${availablePercent}%)` : hostValue,
tone: diskTone,
conclusion: diskKnown ? conclusionText(diskTone) : UNKNOWN_STATE,
},
{
key: 'quota_low',
label: '配额不足',
value: quotaKnown
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
: archiveFailed
? UNKNOWN
: archive?.available
? '配额未设置'
: UNKNOWN,
tone: quotaTone,
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
},
{
key: 'both_low',
label: '磁盘与配额同时不足',
value: diskKnown && quotaKnown ? `磁盘可用 ${availablePercent}% · 配额已用 ${usedPercent}%` : hostValue,
tone: bothTone,
conclusion: diskKnown && quotaKnown ? conclusionText(bothTone) : UNKNOWN_STATE,
},
{
key: 'quota_over_physical',
label: '配额超出物理空闲',
value:
diskKnown && facts.archiveBudgetBytes !== null
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
: UNKNOWN,
tone: overPhysical,
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
},
]
}
export const pendingAlertCount = (alerts: SummaryAlert[]): number =>
alerts.filter((alert) => alert.tone === 'warn' || alert.tone === 'bad').length
-25
View File
@@ -2282,28 +2282,3 @@ tbody tr:hover {
.topbar-user-menu button:hover {
background: var(--bg-hover);
}
.member-create-form {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: flex-end;
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--border-soft);
}
.member-create-form label {
display: grid;
gap: 5px;
font-size: 12.5px;
color: var(--ink-base);
font-weight: 600;
}
.member-create-form input,
.member-create-form select {
padding: 8px 10px;
border: 1px solid var(--border-strong);
border-radius: 6px;
font: inherit;
background: var(--bg-panel);
}
+185 -3
View File
@@ -155,10 +155,28 @@
color: var(--ink-mute);
font-size: 8px;
}
.settings-param-groups {
display: grid;
gap: 14px;
}
.settings-param-group + .settings-param-group {
border-top: 1px solid var(--border-base);
padding-top: 14px;
}
.settings-param-group h3 {
margin: 0 0 10px;
color: var(--ink-base);
font-size: 12px;
}
.settings-hint {
margin: 6px 0 0;
color: var(--ink-mute);
font-size: 10px;
}
.safe-setting-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.safe-setting-grid label {
display: grid;
@@ -166,12 +184,39 @@
color: var(--ink-mute);
font-size: 10px;
}
.safe-setting-grid select {
.safe-setting-grid input {
border: 1px solid var(--border-strong);
border-radius: 7px;
padding: 8px;
background: var(--bg-panel);
color: var(--ink-base);
width: 100%;
min-width: 0;
}
.safe-setting-grid input[aria-invalid='true'] {
border-color: var(--c-fail);
}
.settings-field-control {
display: flex;
align-items: center;
gap: 6px;
}
.settings-field-control input {
flex: 1;
}
.settings-field-unit {
flex: none;
font-size: 9px;
}
.settings-field-hint {
color: var(--ink-mute);
font-size: 8px;
line-height: 1.5;
}
.settings-field-error {
color: var(--c-fail);
font-size: 8px;
line-height: 1.5;
}
.locked-gates {
display: flex;
@@ -889,6 +934,143 @@ button.link {
font-size: 12px;
}
/* 新增成员抽屉:右侧滑入,表单与表格同屏隔离,Esc 仅在无未保存输入时关闭。 */
.member-drawer-backdrop {
position: fixed;
z-index: 60;
inset: 0;
display: flex;
justify-content: flex-end;
background: rgb(15 23 32 / 40%);
}
.member-drawer {
display: flex;
flex-direction: column;
width: min(480px, 100vw);
height: 100%;
border-left: 1px solid var(--border-base);
background: var(--bg-panel);
box-shadow: var(--shadow-float);
animation: member-drawer-in 160ms ease-out;
}
@keyframes member-drawer-in {
from {
transform: translateX(100%);
}
to {
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.member-drawer {
animation: none;
}
}
.member-drawer-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid var(--border-soft);
}
.member-drawer-header h3 {
margin: 0;
font-size: 16px;
}
.member-drawer-close {
display: grid;
place-items: center;
width: 32px;
height: 32px;
padding: 0;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--ink-mute);
font-size: 20px;
line-height: 1;
box-shadow: none;
}
.member-drawer-close:hover:not(:disabled) {
background: var(--bg-hover);
color: var(--ink-base);
}
.member-drawer-form {
display: flex;
flex: 1;
min-height: 0;
flex-direction: column;
}
.member-drawer-body {
display: grid;
flex: 1;
gap: 14px;
align-content: start;
overflow: auto;
padding: 18px 20px;
}
.member-drawer-field {
display: grid;
gap: 6px;
color: var(--ink-base);
font-size: 13px;
font-weight: 600;
}
.member-drawer-field input,
.member-drawer-field select {
width: 100%;
padding: 8px 10px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--bg-panel);
color: var(--ink-base);
font: inherit;
font-weight: 400;
}
.member-drawer-field input:focus,
.member-drawer-field select:focus {
outline: 2px solid var(--c-run);
outline-offset: 1px;
border-color: transparent;
}
.member-drawer-field [aria-invalid='true'] {
border-color: var(--c-fail);
}
.member-drawer-field .password-field input {
padding-right: 56px;
}
.member-drawer-hint {
color: var(--ink-mute);
font-size: 11px;
font-weight: 400;
}
.member-drawer-error {
margin: 0;
color: var(--c-fail);
font-size: 11px;
font-weight: 400;
}
.member-drawer-form-error {
padding: 8px 10px;
border: 1px solid var(--c-fail-border);
border-radius: 8px;
background: var(--c-fail-bg);
}
.member-drawer-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding: 14px 20px;
border-top: 1px solid var(--border-soft);
background: var(--bg-panel);
}
@media (max-width: 650px) {
.member-drawer {
width: 100%;
}
}
.member-reset-dialog {
margin-top: 16px;
border: 1px solid var(--border);