Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6826f37bbd | |||
| 86343d286e | |||
| 9eeb4c7206 | |||
| 5c2ba3e06f | |||
| efa26813dd | |||
| 371d8a60a0 | |||
| bceb7ba682 | |||
| c1bdbe181e | |||
| 5798183392 | |||
| 7567159dc0 | |||
| 37d8761721 | |||
| fe9d055522 | |||
| e4e3d85657 | |||
| 6a12196bf3 | |||
| 8210af7847 | |||
| e5040d88d8 | |||
| 839b4ca2cf | |||
| b662520439 | |||
| 9dddda8491 | |||
| 28fb449d17 | |||
| f45b6fc8c9 | |||
| dc28f0b65c | |||
| 1b2db5045a | |||
| f9e8e5e013 |
@@ -27,8 +27,6 @@ QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
|
||||
WEKNORA_RUNTIME_KEY_FILE=
|
||||
# 导入对账(T6)总开关:只接线对账服务、只用知识库绑定里的租户 Key。
|
||||
# 与 TEST_WEKNORA_ENABLED(旧取件/上传链路)解耦;默认关闭,生产按授权再开。
|
||||
RECONCILIATION_ENABLED=false
|
||||
|
||||
@@ -1,5 +1,25 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.427(导入对账:平台 Key 自动带工作空间)
|
||||
|
||||
### Added
|
||||
|
||||
- **WeKnora 客户端支持平台 Key**:绑定页保存的 Key 若是 platform scope,上游的租户接口会回 `409 TENANT_REQUIRED`;客户端此时用同一把 Key 查 `/api/v1/tenants/all`,按工作空间逐个重试原请求,成功后缓存 ID 并在后续请求带上 `X-Tenant-ID`。租户 Key 不触发该路径,行为不变;JSON 请求体在重试时会被重放(上限 1 MiB),上传流式接口不走这条路径。
|
||||
- 覆盖三种情形:平台 Key 首次拒绝后重放成功、租户 Key 从不发 `X-Tenant-ID`、普通 409(上传冲突)不被误判成 `TENANT_REQUIRED`。
|
||||
|
||||
### Changed
|
||||
|
||||
- **为什么需要这一步**:WeKnora v0.9.1 把 `/api/v1/system/admin/runtime/*` 声明为 `apiKeyPlatform`,网关在能力判定之前就拒绝租户 Key,`system_runtime_read` 授给租户 Key 也无效。要想「运行时读与对账共用一把 Key」,绑定里必须是平台 Key,而平台 Key 访问租户资源必须点名工作空间。
|
||||
- 同步 `docs/IMPORT_RECONCILIATION_REQUIREMENTS.md` §5/Q7:写清平台 Key 约束、工作空间自动识别,以及建议的最小能力集。
|
||||
|
||||
## 开发快照 0.1.426(导入对账:运行时读复用知识库绑定 Key)
|
||||
|
||||
### Changed
|
||||
|
||||
- **运行时读不再单独维护平台只读 Key**:「导入对账」的 WeKnora 队列与「WeKnora 处理详情」改为每次请求解析「系统设置 → 知识库绑定」测试环境的地址与 Key,与对账扫描共用同一个 resolver;换 Key 保存后下一次请求即生效,无需重启。删除 `WEKNORA_RUNTIME_KEY_FILE` 配置、0400 文件读取与启动 WARN,`weknora.ReadRuntimeKeyFile` 一并移除。
|
||||
- **三种失败可区分**:绑定未配置/不可用 → 503 `runtime_read_unavailable`;上游 401/403 → 502 `runtime_read_forbidden`(缺 `system_runtime_read`);超时/DNS/连接失败 → 502 `runtime_read_unreachable`。`/api/v1/monitor/overview` 在队列不可用时给出 `weknora_queue_error`,页面显示三句不同指引,且保留「在 WeKnora 中打开」链接。
|
||||
- 同步 `docs/IMPORT_RECONCILIATION_REQUIREMENTS.md` §5/Q7、`docs/WEKNORA_091_PHASE_PLAN.md` 与 `docs/OPERATIONS_RUNBOOK.md`;`api/openapi.yaml` 的 progress 契约增加 502。
|
||||
|
||||
## 开发快照 0.1.425(WeKnora 0.9.1:schema 137 + 漏表门禁 + 编辑历史搬运)
|
||||
|
||||
### Added
|
||||
|
||||
+11
-1
@@ -50,7 +50,7 @@
|
||||
"/api/v1/reconciliation/findings/{id}/writeback": {"post":{"tags":["Reconciliation"],"operationId":"writebackReconciliationFinding","summary":"仅限 R5:以 WeKnora 状态回写台账 processing_state,写审计;completed 不可降级","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"reconciliation_writeback_stale 或迁移不允许"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/requeue": {"post":{"tags":["Reconciliation"],"operationId":"requeueReconciliationFinding","summary":"仅限 R1/R4:R1 清空 document_id 后重排上传;R4 先删旧知识再重传,删除失败则台账不变","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"finding 状态或台账身份已变化"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/remove": {"post":{"tags":["Reconciliation"],"operationId":"removeReconciliationFinding","summary":"仅限 R2:按远端 document_id 从测试库删除;404 视为已删除;重复点击幂等","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"该文档已被现行台账收养"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;未配置平台只读 Key 时返回 503 runtime_read_unavailable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
|
||||
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;绑定未配置/不可用返回 503 runtime_read_unavailable,上游 401/403 返回 502 runtime_key_forbidden,连接或运行时读失败返回 502 runtime_unreachable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"$ref":"#/components/responses/BadGateway"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
|
||||
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
|
||||
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。未覆盖的是否正确固定为待确认,拒绝是或否;已覆盖点踩固定为否。quality.correctness_rule=coverage-correctness-v1标记覆盖/正确性固定投影,原字段和复核证据保留","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
|
||||
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
|
||||
@@ -6161,6 +6161,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"BadGateway": {
|
||||
"description": "上游 WeKnora 拒绝或不可达:runtime_read_forbidden(Key 缺 system_runtime_read)或 runtime_read_unreachable(超时/DNS/连接失败)。",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ServiceUnavailable": {
|
||||
"description": "依赖的第三方或本地工具当前不可用(例如 dws 未登录/权限不足)。",
|
||||
"content": {
|
||||
|
||||
+11
-20
@@ -209,38 +209,29 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
result := readinessProber.Check(probeCtx)
|
||||
return result.Target, result.Err
|
||||
}
|
||||
// The runtime read (queues / document progress) and the reconciliation remote
|
||||
// must resolve the SAME knowledge-base binding: an admin who saves a new test
|
||||
// key in the console gets it applied on the next request, without a restart.
|
||||
resolveTestConnection := func(resolveCtx context.Context) (string, string, error) {
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
}
|
||||
knowledgeBaseLister := &weKnoraLister{
|
||||
resolve: func(resolveCtx context.Context) (string, string, error) {
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return connection.BaseURL, connection.APIKey, err
|
||||
},
|
||||
resolve: resolveTestConnection,
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
runtimeKey := ""
|
||||
if config.WeKnoraRuntimeKeyFile != "" {
|
||||
key, keyErr := weknora.ReadRuntimeKeyFile(config.WeKnoraRuntimeKeyFile)
|
||||
if keyErr != nil {
|
||||
log.Printf("WARN: WeKnora runtime read key is unavailable; runtime endpoints degrade to 503")
|
||||
} else {
|
||||
runtimeKey = key
|
||||
}
|
||||
}
|
||||
runtimeProvider := reconciliation.NewRuntimeProvider(reconciliation.RuntimeConfig{
|
||||
BaseURL: testEndpointResolver,
|
||||
APIKey: runtimeKey,
|
||||
Resolve: resolveTestConnection,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
})
|
||||
reconciliationRemote := &weknoraaccess.Client{
|
||||
Resolver: readiness.Resolver{
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
ResolveConnection: resolveTestConnection,
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
},
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
|
||||
@@ -68,9 +68,6 @@ services:
|
||||
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级;
|
||||
# Key 本身只挂载 secret 文件,绝不写进 compose。
|
||||
WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}"
|
||||
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
|
||||
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
|
||||
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
|
||||
|
||||
@@ -109,7 +109,7 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
|
||||
| --- | --- | --- |
|
||||
| 全量列出库内条目 | `GET /knowledge-bases/{id}/knowledge`(分页;可按 `parse_status`、`source`、时间、目录筛选) | 现有租户 API Key |
|
||||
| 单条确认 | `GET /knowledge/{id}` | 现有租户 API Key |
|
||||
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | **平台级 API Key,能力 `system_runtime_read`**(上游 `routes_auth_tenant.go:356`) |
|
||||
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | 知识库绑定(测试环境)里的 Key,需能力 `system_runtime_read`(上游 `routes_auth_tenant.go:356`) |
|
||||
| 队列深度 | `GET /system/admin/runtime/queues` | 同上 |
|
||||
|
||||
条目中对账要用的字段:`id`、`knowledge_base_id`、`channel`、`metadata`、`file_hash`、`parse_status`、`stall_state`、`enable_status`、`updated_at`。
|
||||
@@ -118,12 +118,15 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
|
||||
|
||||
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
|
||||
|
||||
**平台级 Key 的配置契约(Q7 已裁定)**
|
||||
**运行时读 Key 的配置契约(Q7,2026-12-02 改判,同日修正)**
|
||||
|
||||
- 键名 `WEKNORA_RUNTIME_KEY_FILE`,值为**绝对路径**,secret 文件挂载进容器;不写进 compose 环境变量、不进 Git。
|
||||
- 启动时读取一次,权限 0400;换 Key 需重启平台(与现有 `*_API_KEY_FILE` 一致,不做热加载)。
|
||||
- “变量为空”与“变量有值但文件缺失/不可读”要区分:前者静默降级;后者启动不失败,写一条 WARN 日志,运行时按未配置处理。
|
||||
- 两种情况都让 `runtime/queues`、`runtime/documents/{id}` 返回 503 `runtime_read_unavailable`,`/monitor/overview` 的 `weknora_queues` 为 `null`;对账本身只需租户 Key,照常运行。
|
||||
- 不再单独维护平台级只读 Key:「导入对账」的 `runtime/queues` 与 `runtime/documents/{id}`(以及页面上的「WeKnora 处理详情」)直接使用「系统设置 → 知识库绑定」测试环境保存的地址与 Key,与对账扫描共用同一个 resolver。
|
||||
- **绑定里的 Key 必须是平台 Key**:WeKnora v0.9.1 的 `/api/v1/system/admin/runtime/*` 由 `apiKeyPlatform` 声明为 `PlatformOnly`,`internal/middleware/api_key_gate.go` 在能力判定之前就先拒绝非 platform scope 的 Key,所以租户 Key 即使授予 `system_runtime_read` 也会得到 403。改动前实测:租户 Key 打 queues 403、打 `knowledge-bases` 200;平台 Key 反之。
|
||||
- **平台 Key 访问租户资源要带工作空间**:缺少 `X-Tenant-ID` 时上游返回 `409 TENANT_REQUIRED`。平台在首次遇到该响应时用同一把 Key 请求 `/api/v1/tenants/all`,按返回的工作空间逐个重试原请求,成功后缓存该 ID 并在后续请求带上 `X-Tenant-ID`;租户 Key 不会触发这条路径,行为与之前一致。
|
||||
- 绑定 Key 建议按最小权限配置(`system_runtime_read` + `retrieve`,需要列库时再加 `manage_kbs`),不要保存带租户管理/写能力的全权限 Key。
|
||||
- 每次请求解析绑定;管理员换 Key 保存后,下一次请求即生效,不需要重启 API。不再读取任何 Key 文件。
|
||||
- 绑定未配置或无法解密 → 503 `runtime_read_unavailable`,页面指向绑定页;上游 401/403 → 502 `runtime_key_forbidden`,页面提示去 WeKnora 授权 `system_runtime_read`;连接或运行时读失败 → 502 `runtime_unreachable`,页面提示连不上 WeKnora。
|
||||
- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身。
|
||||
|
||||
## 6. 运行方式
|
||||
|
||||
@@ -154,7 +157,7 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
|
||||
| POST | `/api/v1/reconciliation/findings/{id}/writeback` | 仅限 R5:以 WeKnora 状态回写台账,写审计;返回更新后的 finding | 管理员、文档工程师 |
|
||||
| POST | `/api/v1/reconciliation/findings/{id}/requeue` | 仅限 R1/R4:R1 清空 `knowledge_id` 后重排上传;R4 先删旧 knowledge 再重传,删除失败则动作失败且台账不变;写审计 | 管理员、文档工程师 |
|
||||
| POST | `/api/v1/reconciliation/findings/{id}/remove` | 仅限 R2:按 `knowledge_id` 从测试库删除,404 视为已删除;写审计;重复点击幂等 | 管理员 |
|
||||
| GET | `/api/v1/reconciliation/documents/{document_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key 时返回 503 `runtime_read_unavailable` | 所有登录角色 |
|
||||
| GET | `/api/v1/reconciliation/documents/{document_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key、Key 无权限、连接不可达时返回 503,code 分别为 `runtime_read_unavailable` / `runtime_key_forbidden` / `runtime_unreachable` | 所有登录角色 |
|
||||
| GET | `/api/v1/monitor/overview`(已有) | 新增 `weknora_queues` 字段(来自 `runtime/queues`,不可用时为 null);删除 Embedding/LLM 两张常量"未知"卡 | 不变 |
|
||||
|
||||
**`/api/v1/monitor/tasks`(已有,T6a 增量)**:每行新增可选 `weknora_url`(目标测试知识库的 WeKnora 控制台链接;未配置测试端点时为空字符串),供文件详情抽屉在 progress 返回 503 时显示跳转链接。该字段为附加字段,既有字段与筛选语义不变;与 finding 的 `weknora_url` 使用同一拼接规则(`internal/platform/weknora.KnowledgeBaseConsoleURL`)。
|
||||
@@ -240,7 +243,7 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
|
||||
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||
| Q7 | 运行时读 Key 的配置键名 | **已裁定(2026-12-02 改判)**:不再单独配置;复用知识库绑定(测试环境)的地址与 Key |
|
||||
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加“距上次发布 N 天” |
|
||||
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受并发增删造成的个别漏项在下一批补上,不引入游标 |
|
||||
|
||||
@@ -82,6 +82,8 @@ http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,
|
||||
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
|
||||
「同 ID 语义」,提示里会写明。
|
||||
|
||||
**导入对账的运行时读。** 队列栏与「WeKnora 处理详情」复用本页保存的测试环境地址与 Key(该 Key 需在 WeKnora 授予 `system_runtime_read`),不再挂载单独的只读 Key 文件。换 Key 保存后下一次刷新即生效,无需重启 API。三种失败提示分别指向:绑定未配置/不可用 → 本页;缺权限 → WeKnora 授权;连不上 → 检查地址与网络。
|
||||
|
||||
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
|
||||
|
||||
```bash
|
||||
|
||||
@@ -120,7 +120,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
- [ ] `schema_migrations` 应为 `137, false`
|
||||
- [ ] 抽查原有知识库的检索、问答是否正常
|
||||
- [ ] 测试环境额外检查:平台走一轮「取件 → 上传 → 解析 → 完成」
|
||||
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 创建平台级 API Key,只授予 `system_runtime_read` 能力,以 secret 文件形式交给平台(不写进 Git 或 compose),然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。生产不需要这个 Key
|
||||
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 给「系统设置 → 知识库绑定」里保存的那把 Key 授予 `system_runtime_read` 能力,然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。不再创建/挂载独立的平台只读 Key;生产不需要该能力
|
||||
- [ ] 生产额外检查:平台发布通道只读预检(`release-diag`)通过
|
||||
|
||||
**回退**:不能直接换回旧镜像。向下迁移会删除凭据表、截短审计字段。正确做法是停止写入后,用升级前的备份恢复数据库、存储和配置,再切回 v0.9.0 镜像。
|
||||
@@ -145,7 +145,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
- 新建 `reconciliation_runs` / `reconciliation_findings` 两张表:`runs` 永久保留;`findings` 按 `run_id` 整批清理,保留最近 30 批且不超过 90 天(Q5)。同一测试库的 `running` 批次用部分唯一索引约束(`WHERE state='running'`)。
|
||||
- 对账扫描使用 `page_size=1000`:要把 `internal/platform/weknora/client.go` 的 `validPage` 上限从 100 放开(或给对账单独一条扫描路径),不能沿用上传恢复的 100。扫描全程串行(在途 1 个请求),R1/R2 确认可用 `reconciliation_confirm_concurrency`(默认 1、上限 8),不复用 `ingestion_concurrency`。
|
||||
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `window_overlapped=true`,该批 R1/R2 的 `confirmation_state='pending'`(Q6)。
|
||||
- 平台级只读 Key 走 `WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,启动读取一次,不做热加载);未配置或文件不可读时 `runtime/*` 返回 503 `runtime_read_unavailable`,对账不受影响(Q7)。
|
||||
- 运行时读(队列与处理详情)复用知识库绑定(测试环境)的地址与 Key,每次请求解析、保存后即时生效,不单独维护 Key 文件;绑定不可用返回 503 `runtime_read_unavailable`,上游 401/403 返回 502 `runtime_key_forbidden`,连接或运行时读失败返回 502 `runtime_unreachable`,对账不受影响(Q7,2026-12-02 改判)。
|
||||
- 状态映射只写在服务端一处,接口返回 `normalized_state`;R5 回写按迁移矩阵校验,`completed` 不可降级。
|
||||
- 处置动作:新增 finding 级 `requeue`(R1/R4)与 `remove`(R2);R6 复用现有 `POST /test-publications/{id}/removal`(`removal-retry` 只重试已失败移除)。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
|
||||
- 扫描保留 offset 翻页,不引入游标;并发增删造成的个别漏项在下一批补上(Q10)。
|
||||
@@ -164,7 +164,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||
| Q7 | 运行时读 Key 的配置键名 | **已裁定(2026-12-02 改判)**:不再单独配置;复用知识库绑定(测试环境)的地址与 Key |
|
||||
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加"距上次发布 N 天" |
|
||||
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受个别漏项下一批补上,不引入游标 |
|
||||
|
||||
@@ -59,9 +59,6 @@ type Config struct {
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
// WeKnoraRuntimeKeyFile 是测试实例平台级只读 Key(0400,绝对路径)。空值=
|
||||
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
|
||||
WeKnoraRuntimeKeyFile string
|
||||
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
|
||||
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
|
||||
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
|
||||
@@ -242,7 +239,6 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
WeKnoraRuntimeKeyFile: strings.TrimSpace(getenv("WEKNORA_RUNTIME_KEY_FILE")),
|
||||
ReconciliationDailyAt: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_DAILY_AT")), "02:00"),
|
||||
ReconciliationTimezone: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_TIMEZONE")), "Asia/Shanghai"),
|
||||
ReconciliationScheduleEnabled: true,
|
||||
@@ -406,9 +402,6 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
|
||||
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
|
||||
@@ -105,6 +105,10 @@ type RecordQuery struct {
|
||||
Keyword string
|
||||
Cursor string
|
||||
Limit int
|
||||
// Granularity is only honoured by the statistics dashboard. Empty keeps the
|
||||
// historical weekly board; "day"|"week"|"month"|"custom" makes every panel
|
||||
// follow the selected Window alone.
|
||||
Granularity string
|
||||
}
|
||||
|
||||
type QualityKey struct {
|
||||
|
||||
@@ -115,6 +115,10 @@ type MonitorOverview struct {
|
||||
// WeKnoraQueues is a safe projection of the test instance runtime queues.
|
||||
// nil means "not configured or unreadable", never "healthy empty".
|
||||
WeKnoraQueues *WeKnoraQueueSummary `json:"weknora_queues"`
|
||||
// WeKnoraQueueError carries the classified reason when WeKnoraQueues is nil
|
||||
// (binding missing, key lacks permission, or instance unreachable). Empty
|
||||
// means no runtime queue reader was wired.
|
||||
WeKnoraQueueError string `json:"weknora_queue_error,omitempty"`
|
||||
}
|
||||
|
||||
// WeKnoraQueueSummary is the bounded queue projection the console may show.
|
||||
|
||||
@@ -19,10 +19,11 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Filters map[string]string `json:"filters,omitempty"`
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Filters map[string]string `json:"filters,omitempty"`
|
||||
Granularity string `json:"granularity,omitempty"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
@@ -38,7 +39,7 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters})
|
||||
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters, Granularity: request.Granularity})
|
||||
if e != nil {
|
||||
if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
writeQualityError(w, e)
|
||||
|
||||
@@ -29,6 +29,27 @@ func (s *dashboardReaderSpy) ReadMasterDashboard(ctx context.Context, q dobotaio
|
||||
s.masterCalls++
|
||||
return s.ReadDashboard(ctx, q)
|
||||
}
|
||||
func TestQADashboardForwardsGranularityToTheReader(t *testing.T) {
|
||||
reader := &dashboardReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dash-admin"] = "usr-boss"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 12, 3, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
body := `{"start":"2026-11-01T00:00:00+08:00","end":"2026-12-01T00:00:00+08:00","keyword":"","granularity":"month"}`
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(body))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-dashboard")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("month dashboard status=%d want200", w.Code)
|
||||
}
|
||||
if reader.query.Granularity != "month" {
|
||||
t.Fatalf("granularity = %q, want month", reader.query.Granularity)
|
||||
}
|
||||
}
|
||||
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
||||
reader := &dashboardReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
|
||||
@@ -46,6 +46,10 @@ func writeReconciliationError(w http.ResponseWriter, err error) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "reconciliation record not found"})
|
||||
case errors.Is(err, reconciliation.ErrActionConflict), errors.Is(err, reconciliation.ErrActionNotAllowed):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_state_changed", "code": "reconciliation_state_changed"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeForbidden):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_key_forbidden", "code": "runtime_key_forbidden"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnreachable):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_unreachable", "code": "runtime_unreachable"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnavailable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_read_unavailable", "code": "runtime_read_unavailable"})
|
||||
case errors.Is(err, reconciliation.ErrRemoteFailed):
|
||||
|
||||
@@ -126,3 +126,44 @@ func TestReconciliationFindingTypeValidation(t *testing.T) {
|
||||
t.Fatalf("invalid type = %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconciliationProgressRejectsMalformedDocumentIDWith400(t *testing.T) {
|
||||
service := &reconciliationServiceStub{}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{
|
||||
"/api/v1/reconciliation/documents//progress",
|
||||
"/api/v1/reconciliation/documents/doc-1/extra/progress",
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, path, roleViewer, ""))
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "invalid document id") {
|
||||
t.Fatalf("%s = %d %s, want 400 invalid document id", path, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconciliationProgressClassifiesRuntimeFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
err error
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
{reconciliation.ErrRuntimeForbidden, http.StatusBadGateway, "runtime_key_forbidden"},
|
||||
{reconciliation.ErrRuntimeUnreachable, http.StatusBadGateway, "runtime_unreachable"},
|
||||
{reconciliation.ErrRuntimeUnavailable, http.StatusServiceUnavailable, "runtime_read_unavailable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: &reconciliationServiceStub{err: tc.err}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/documents/doc-1/progress", roleViewer, ""))
|
||||
if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.code) {
|
||||
t.Fatalf("%v = %d %s, want %d %s", tc.err, recorder.Code, recorder.Body.String(), tc.status, tc.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -855,15 +855,32 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/job-failures/{id}/requeue", func(w http.ResponseWriter, r *http.Request) {
|
||||
requeueJobFailure(w, r, config)
|
||||
})
|
||||
// 契约要求非法 document_id 返回 400:空段(documents//progress)会被 ServeMux
|
||||
// 规范化成 307,含未编码斜杠的 id 会落到 404。这里在路由前判定形状,且不新增
|
||||
// 端点(契约已冻结);放在鉴权之后,未登录仍是 401,保持 401 → 400 的顺序。
|
||||
guard := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
const prefix = "/api/v1/reconciliation/documents/"
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
rest := strings.TrimPrefix(r.URL.Path, prefix)
|
||||
segments := strings.Split(rest, "/")
|
||||
if strings.Contains(r.URL.Path, "//") || len(segments) != 2 || segments[0] == "" || segments[1] != "progress" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid document id"})
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
if config.Auth != nil {
|
||||
if config.Auth.Store == nil {
|
||||
return nil, errors.New("auth configuration requires a store")
|
||||
}
|
||||
config.authRoutes(mux)
|
||||
config.userRoutes(mux)
|
||||
return masterNoStore(config.Auth.authenticate(mux)), nil
|
||||
return masterNoStore(config.Auth.authenticate(guard(mux))), nil
|
||||
}
|
||||
return masterNoStore(mux), nil
|
||||
return masterNoStore(guard(mux)), nil
|
||||
}
|
||||
|
||||
type createJobRequest struct {
|
||||
|
||||
@@ -30,9 +30,9 @@ func ValidEnvironment(value string) bool {
|
||||
|
||||
func EnvironmentLabel(value string) string {
|
||||
if value == EnvProduction {
|
||||
return "生产 090"
|
||||
return "生产知识库"
|
||||
}
|
||||
return "测试 090"
|
||||
return "测试知识库"
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -221,3 +221,12 @@ func TestAuditTextBoundsWithoutSplittingUTF8(t *testing.T) {
|
||||
t.Fatal("blank audit source must stay empty, never a placeholder")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvironmentLabelNamesTheKnowledgeBaseNotTheOldVersion(t *testing.T) {
|
||||
if got := EnvironmentLabel(EnvTest); got != "测试知识库" {
|
||||
t.Fatalf("test label = %q", got)
|
||||
}
|
||||
if got := EnvironmentLabel(EnvProduction); got != "生产知识库" {
|
||||
t.Fatalf("production label = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
type Database interface {
|
||||
@@ -133,9 +134,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
governance.MonitorService{Key: "oss", Name: "OSS", State: "unknown", Detail: "未配置独立健康探测", ObservedAt: now},
|
||||
)
|
||||
if provider.runtimeQueues != nil {
|
||||
if queues, queueErr := provider.runtimeQueues.Queues(ctx); queueErr == nil {
|
||||
overview.WeKnoraQueues = queues
|
||||
}
|
||||
overview.WeKnoraQueues, overview.WeKnoraQueueError = runtimeQueueProjection(ctx, provider.runtimeQueues)
|
||||
}
|
||||
rows, err := provider.db.Query(ctx, `SELECT p.test_kb_id,
|
||||
CASE WHEN COUNT(DISTINCT p.target_scope)=1 THEN MIN(p.target_scope) ELSE 'mixed' END,
|
||||
@@ -162,6 +161,9 @@ FROM test_publications p
|
||||
JOIN source_item_versions version ON version.id=p.source_item_version_id
|
||||
JOIN source_items item ON item.id=version.source_item_id
|
||||
LEFT JOIN removal_candidates removal_candidate ON removal_candidate.publication_id=p.id
|
||||
-- 整库都被顶替过的 KB 只剩历史行:不排除就仍会占一行「0 条」,
|
||||
-- 还会出现在导入对账的库下拉里,点下去直接打在已删除的库上。
|
||||
WHERE p.superseded_at IS NULL
|
||||
GROUP BY p.test_kb_id
|
||||
ORDER BY p.test_kb_id`)
|
||||
if err != nil {
|
||||
@@ -396,3 +398,16 @@ func monitorStageDetail(ingestState, processingState, errorCode string) string {
|
||||
return "等待远端状态更新"
|
||||
}
|
||||
}
|
||||
|
||||
// runtimeQueueProjection keeps the overview at 200 while stating why the queue
|
||||
// is absent: nil queues + the classified code, never a healthy empty queue.
|
||||
func runtimeQueueProjection(ctx context.Context, reader QueueReader) (*governance.WeKnoraQueueSummary, string) {
|
||||
if reader == nil {
|
||||
return nil, ""
|
||||
}
|
||||
queues, err := reader.Queues(ctx)
|
||||
if err != nil {
|
||||
return nil, reconciliation.RuntimeErrorCode(err)
|
||||
}
|
||||
return queues, ""
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package monitoring
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
func TestParseCPUStatAndMemoryInfo(t *testing.T) {
|
||||
idle, total, err := parseCPUStat("cpu 100 20 30 400 50 6 7 8 0 0\n")
|
||||
@@ -22,3 +29,41 @@ func TestCPUPercentUsesTwoMonotonicSamples(t *testing.T) {
|
||||
t.Fatal("non-monotonic CPU counters must fail closed to zero")
|
||||
}
|
||||
}
|
||||
|
||||
type stubQueueReader struct {
|
||||
summary *governance.WeKnoraQueueSummary
|
||||
err error
|
||||
}
|
||||
|
||||
func (reader stubQueueReader) Queues(context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
return reader.summary, reader.err
|
||||
}
|
||||
|
||||
func TestRuntimeQueueProjectionStatesWhyQueueIsAbsent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{name: "binding unavailable", err: reconciliation.ErrRuntimeUnavailable, code: "runtime_read_unavailable"},
|
||||
{name: "key forbidden", err: reconciliation.ErrRuntimeForbidden, code: "runtime_key_forbidden"},
|
||||
{name: "unreachable", err: reconciliation.ErrRuntimeUnreachable, code: "runtime_unreachable"},
|
||||
{name: "unclassified", err: errors.New("boom"), code: ""},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{err: testCase.err})
|
||||
if queues != nil || code != testCase.code {
|
||||
t.Fatalf("queues=%v code=%q, want nil/%q", queues, code, testCase.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{Available: true}
|
||||
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{summary: summary})
|
||||
if queues != summary || code != "" {
|
||||
t.Fatalf("available queue projection = %v/%q", queues, code)
|
||||
}
|
||||
if queues, code := runtimeQueueProjection(context.Background(), nil); queues != nil || code != "" {
|
||||
t.Fatalf("unwired projection = %v/%q", queues, code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +128,21 @@ SET publication_id = EXCLUDED.publication_id,
|
||||
resolution_reason = '',
|
||||
created_at = EXCLUDED.created_at
|
||||
RETURNING job_id
|
||||
), parked_publication AS (
|
||||
-- 上传重试耗尽时把对账面同步成失败:否则 publication 停在
|
||||
-- pending/uploading,重试入口(要求 failed/stalled)永远 409,
|
||||
-- 页面上的「重试」看起来点了没反应。
|
||||
UPDATE test_publications p
|
||||
SET ingest_state = CASE WHEN p.ingest_state = 'uploading' THEN 'failed' ELSE p.ingest_state END,
|
||||
processing_state = 'failed',
|
||||
last_error = $3,
|
||||
updated_at = $4
|
||||
FROM updated
|
||||
WHERE updated.state = 'failed'
|
||||
AND updated.type = 'test.upload'
|
||||
AND updated.payload->>'publication_id' = p.id
|
||||
AND p.knowledge_id = ''
|
||||
RETURNING p.id
|
||||
)
|
||||
SELECT id FROM updated
|
||||
`
|
||||
|
||||
@@ -112,3 +112,51 @@ func TestScheduledReconciliationClaimsOncePerDayAfterFailure(t *testing.T) {
|
||||
t.Fatalf("next-day claim claimed=%t err=%v", claimed, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadReconciliationActionViewJoinsWithoutAmbiguity freezes the action-view
|
||||
// SQL: it joins reconciliation_runs and test_publications, both of which also
|
||||
// own id/title/path, so an unqualified column list fails with
|
||||
// `column reference "id" is ambiguous` and every writeback/requeue/remove
|
||||
// answered 500 instead of touching the finding.
|
||||
func TestLoadReconciliationActionViewJoinsWithoutAmbiguity(t *testing.T) {
|
||||
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := time.Date(2026, 12, 1, 2, 0, 0, 0, time.UTC)
|
||||
exec := func(query string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, query, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
exec(`INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-action','dingtalk','处置视图用例',TRUE)`)
|
||||
exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state)
|
||||
VALUES('si-action','conn-action','action.md',repeat('d',64),'处置视图','file','blocked')`)
|
||||
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-action','si-action','r1','verified')`)
|
||||
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
|
||||
VALUES('pub-action','sv-action','kb-action','doc-action','uploaded','completed','unpublished')`)
|
||||
exec(`INSERT INTO reconciliation_runs(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
VALUES('run-action','kb-action','succeeded','manual',$1,'{}'::jsonb,$1)`, started)
|
||||
exec(`INSERT INTO reconciliation_findings(id,run_id,finding_type,publication_id,knowledge_id,title,ledger_state,suggested_action)
|
||||
VALUES('finding-action','run-action','R6','pub-action','doc-action','处置视图','completed','enter_removal')`)
|
||||
|
||||
store := NewStore(pool)
|
||||
view, err := store.LoadReconciliationActionView(ctx, "finding-action")
|
||||
if err != nil {
|
||||
t.Fatalf("action view error = %v (ambiguous columns surface here)", err)
|
||||
}
|
||||
if view.TestKBID != "kb-action" || !view.CurrentExists || view.CurrentProcessingState != "completed" ||
|
||||
view.CurrentKnowledgeID != "doc-action" || view.Finding.ID != "finding-action" {
|
||||
t.Fatalf("action view = %#v", view)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -315,6 +316,19 @@ const reconciliationFindingColumns = `id,run_id,finding_type,publication_id,know
|
||||
target_scope,ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
|
||||
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,weknora_url`
|
||||
|
||||
// qualifiedFindingColumns prefixes every column with the table alias. A bare
|
||||
// column list breaks as soon as the finding is joined with reconciliation_runs
|
||||
// or test_publications: those tables also have id/title/path/source, so
|
||||
// PostgreSQL rejects the statement with "column reference \"id\" is ambiguous"
|
||||
// and every writeback/requeue/remove answered 500.
|
||||
func qualifiedFindingColumns(alias string) string {
|
||||
columns := strings.Split(reconciliationFindingColumns, ",")
|
||||
for index, column := range columns {
|
||||
columns[index] = alias + "." + strings.TrimSpace(column)
|
||||
}
|
||||
return strings.Join(columns, ",")
|
||||
}
|
||||
|
||||
func scanReconciliationFinding(row rowScanner) (governance.ReconciliationFinding, error) {
|
||||
var finding governance.ReconciliationFinding
|
||||
if err := row.Scan(&finding.ID, &finding.RunID, &finding.Type, &finding.PublicationID, &finding.DocumentID,
|
||||
@@ -390,7 +404,7 @@ func lockOpenReconciliationFinding(ctx context.Context, tx pgx.Tx, id string) er
|
||||
func (s *Store) LoadReconciliationActionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
|
||||
var view governance.ReconciliationActionView
|
||||
var currentExists bool
|
||||
row := s.db.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+`,
|
||||
row := s.db.QueryRow(ctx, `SELECT `+qualifiedFindingColumns("finding")+`,
|
||||
run.test_kb_id,run.started_at,
|
||||
publication.id IS NOT NULL,
|
||||
COALESCE(publication.processing_state,''),COALESCE(publication.knowledge_id,''),
|
||||
|
||||
@@ -273,8 +273,8 @@ WITH updated AS (
|
||||
max_attempts, idempotency_key, created_at, updated_at
|
||||
)
|
||||
SELECT 'job-' || substring(md5($1 || '#test.poll#' || updated.retry_count || '#1') from 1 for 32),
|
||||
'test.poll', $4::jsonb, 'pending', $5, $6, $7,
|
||||
'test-poll:' || $1 || ':' || updated.retry_count || ':1', $3, $3
|
||||
'test.poll', $5::jsonb, 'pending', $6, $7, $8,
|
||||
'test-poll:' || $1 || ':' || updated.retry_count || ':1', $4, $4
|
||||
FROM updated
|
||||
ON CONFLICT (idempotency_key) DO NOTHING
|
||||
)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -102,6 +103,13 @@ type Client struct {
|
||||
apiKey string
|
||||
httpClient *http.Client
|
||||
maxResponseBytes int64
|
||||
|
||||
// tenantMu guards tenantID: a platform-scoped key must name the workspace
|
||||
// it acts on (X-Tenant-ID), so the first call that is refused with
|
||||
// TENANT_REQUIRED discovers the workspace once and every later call reuses
|
||||
// it. Tenant keys never trigger this path.
|
||||
tenantMu sync.Mutex
|
||||
tenantID string
|
||||
}
|
||||
|
||||
func NewClient(config ClientConfig) (*Client, error) {
|
||||
@@ -224,6 +232,13 @@ func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (Knowled
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
// A platform-scoped key is refused with 409 TENANT_REQUIRED until it names a
|
||||
// workspace, and a multipart body cannot be replayed: the workspace has to be
|
||||
// attached here, from the one BeginTask already discovered. Leaving it off
|
||||
// turned every upload into a "conflict" that the handler read as a duplicate.
|
||||
if tenant := c.currentTenant(); tenant != "" {
|
||||
req.Header.Set("X-Tenant-ID", tenant)
|
||||
}
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
@@ -237,8 +252,19 @@ func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (Knowled
|
||||
|
||||
var response knowledgeResponse
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
if err := c.decodeBody(resp, &response); err != nil {
|
||||
return Knowledge{}, err
|
||||
payload, readErr := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
|
||||
resp.Body.Close()
|
||||
if readErr != nil {
|
||||
return Knowledge{}, errors.New("read WeKnora response")
|
||||
}
|
||||
// TENANT_REQUIRED shares the 409 status with a real duplicate. Reading it
|
||||
// as ErrConflict made the caller adopt a "duplicate" that never existed,
|
||||
// so it is reported as a bare 409 and dead-letters with a clear reason.
|
||||
if bytes.Contains(payload, []byte(`"TENANT_REQUIRED"`)) {
|
||||
return Knowledge{}, &HTTPError{StatusCode: http.StatusConflict}
|
||||
}
|
||||
if err := json.Unmarshal(payload, &response); err != nil {
|
||||
return Knowledge{}, errors.New("decode WeKnora response")
|
||||
}
|
||||
return response.Data, ErrConflict
|
||||
}
|
||||
@@ -446,25 +472,140 @@ func (c *Client) doJSON(ctx context.Context, method, path string, body io.Reader
|
||||
return c.doJSONQuery(ctx, method, path, nil, body, target)
|
||||
}
|
||||
|
||||
// maxJSONRequestBody bounds the buffered request body a retry can replay.
|
||||
// Every JSON call here carries a small filter object; uploads stream through
|
||||
// UploadFile and never reach this path.
|
||||
const maxJSONRequestBody int64 = 1 << 20
|
||||
|
||||
func (c *Client) doJSONQuery(ctx context.Context, method, path string, query url.Values, body io.Reader, target any) error {
|
||||
var payload []byte
|
||||
if body != nil {
|
||||
read, err := io.ReadAll(io.LimitReader(body, maxJSONRequestBody+1))
|
||||
if err != nil {
|
||||
return errors.New("read WeKnora request body")
|
||||
}
|
||||
if int64(len(read)) > maxJSONRequestBody {
|
||||
return errors.New("WeKnora request body exceeds size limit")
|
||||
}
|
||||
payload = read
|
||||
}
|
||||
response, err := c.send(ctx, method, path, query, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tenantRequired(response) {
|
||||
// A platform-scoped key is refused until it names its workspace. The
|
||||
// binding page stores whichever key the operator saved, so discover the
|
||||
// workspace from the same key instead of asking for a second setting.
|
||||
tenants, err := c.platformTenants(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, tenant := range tenants {
|
||||
c.rememberTenant(tenant)
|
||||
response, err = c.send(ctx, method, path, query, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !tenantRequired(response) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if response.status < 200 || response.status >= 300 {
|
||||
return &HTTPError{StatusCode: response.status}
|
||||
}
|
||||
if err := json.Unmarshal(response.body, target); err != nil {
|
||||
return errors.New("decode WeKnora response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type rawResponse struct {
|
||||
status int
|
||||
body []byte
|
||||
}
|
||||
|
||||
// send performs one request with the currently known workspace header.
|
||||
func (c *Client) send(ctx context.Context, method, path string, query url.Values, payload []byte) (*rawResponse, error) {
|
||||
endpoint := c.endpoint(path)
|
||||
if len(query) > 0 {
|
||||
endpoint += "?" + query.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
|
||||
var reader io.Reader
|
||||
if payload != nil {
|
||||
reader = bytes.NewReader(payload)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, reader)
|
||||
if err != nil {
|
||||
return errors.New("create WeKnora request")
|
||||
return nil, errors.New("create WeKnora request")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
if tenant := c.currentTenant(); tenant != "" {
|
||||
req.Header.Set("X-Tenant-ID", tenant)
|
||||
}
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send WeKnora request: %w", err)
|
||||
return nil, fmt.Errorf("send WeKnora request: %w", err)
|
||||
}
|
||||
return c.decodeResponse(resp, target)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, errors.New("read WeKnora response")
|
||||
}
|
||||
if int64(len(body)) > c.maxResponseBytes {
|
||||
return nil, errors.New("WeKnora response exceeds size limit")
|
||||
}
|
||||
return &rawResponse{status: resp.StatusCode, body: body}, nil
|
||||
}
|
||||
|
||||
// tenantRequired reports WeKnora's 409 TENANT_REQUIRED refusal, which is
|
||||
// distinct from an upload conflict despite sharing the status code.
|
||||
func tenantRequired(response *rawResponse) bool {
|
||||
return response != nil && response.status == http.StatusConflict &&
|
||||
bytes.Contains(response.body, []byte(`"TENANT_REQUIRED"`))
|
||||
}
|
||||
|
||||
// platformTenants lists the workspaces a platform-scoped key may act on. The
|
||||
// route is tenant-optional, so it answers before any workspace is known.
|
||||
func (c *Client) platformTenants(ctx context.Context) ([]string, error) {
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Items []struct {
|
||||
ID uint64 `json:"id"`
|
||||
} `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/tenants/all", nil, nil, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenants := make([]string, 0, len(response.Data.Items))
|
||||
for _, item := range response.Data.Items {
|
||||
if item.ID != 0 {
|
||||
tenants = append(tenants, fmt.Sprint(item.ID))
|
||||
}
|
||||
}
|
||||
if len(tenants) == 0 {
|
||||
return nil, errors.New("WeKnora platform key has no workspace to act on")
|
||||
}
|
||||
return tenants, nil
|
||||
}
|
||||
|
||||
func (c *Client) currentTenant() string {
|
||||
c.tenantMu.Lock()
|
||||
defer c.tenantMu.Unlock()
|
||||
return c.tenantID
|
||||
}
|
||||
|
||||
func (c *Client) rememberTenant(tenant string) {
|
||||
c.tenantMu.Lock()
|
||||
defer c.tenantMu.Unlock()
|
||||
c.tenantID = tenant
|
||||
}
|
||||
|
||||
func (c *Client) decodeResponse(resp *http.Response, target any) error {
|
||||
|
||||
@@ -469,3 +469,199 @@ func TestClientClassifiesTimeoutAsRetryable(t *testing.T) {
|
||||
t.Fatalf("GetKnowledge() error = %v, want retryable timeout", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A platform-scoped key is refused with TENANT_REQUIRED until it names a
|
||||
// workspace. The client must discover that workspace with the same key and
|
||||
// replay the call, then reuse the header for later calls.
|
||||
func TestClientResolvesWorkspaceForPlatformKey(t *testing.T) {
|
||||
const apiKey = "platform" + "-key"
|
||||
var listCalls, tenantCalls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/tenants/all":
|
||||
tenantCalls.Add(1)
|
||||
if got := r.Header.Get("X-API-Key"); got != apiKey {
|
||||
t.Fatalf("tenants X-API-Key = %q", got)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"items":[{"id":10000,"name":"workspace"}]}}`))
|
||||
case "/api/v1/knowledge-bases":
|
||||
listCalls.Add(1)
|
||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required: platform API keys must send X-Tenant-ID"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[{"id":"kb-1","name":"测试库","knowledge_count":1,"chunk_count":2,"tenant_id":10000}]}`))
|
||||
case "/api/v1/knowledge/knowledge-1":
|
||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"completed"}}`))
|
||||
default:
|
||||
t.Fatalf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bases, err := client.ListKnowledgeBases(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListKnowledgeBases() error = %v", err)
|
||||
}
|
||||
if len(bases) != 1 || bases[0].ID != "kb-1" {
|
||||
t.Fatalf("bases = %#v", bases)
|
||||
}
|
||||
if _, err := client.GetKnowledge(context.Background(), "knowledge-1"); err != nil {
|
||||
t.Fatalf("GetKnowledge() after discovery error = %v", err)
|
||||
}
|
||||
if tenantCalls.Load() != 1 {
|
||||
t.Fatalf("tenant discovery calls = %d, want 1", tenantCalls.Load())
|
||||
}
|
||||
if listCalls.Load() != 2 {
|
||||
t.Fatalf("knowledge-base calls = %d, want 2 (refused + replay)", listCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A tenant key never sends X-Tenant-ID and never asks for the workspace list.
|
||||
func TestClientTenantKeyNeverSendsWorkspaceHeader(t *testing.T) {
|
||||
const apiKey = "tenant" + "-key"
|
||||
var tenantCalls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/tenants/all" {
|
||||
tenantCalls.Add(1)
|
||||
t.Fatalf("tenant key must not query the workspace list")
|
||||
}
|
||||
if got := r.Header.Get("X-Tenant-ID"); got != "" {
|
||||
t.Fatalf("X-Tenant-ID = %q, want empty for a tenant key", got)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[{"id":"kb-1","name":"测试库","knowledge_count":1,"chunk_count":2,"tenant_id":10000}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.ListKnowledgeBases(context.Background()); err != nil {
|
||||
t.Fatalf("ListKnowledgeBases() error = %v", err)
|
||||
}
|
||||
if tenantCalls.Load() != 0 {
|
||||
t.Fatalf("tenant discovery calls = %d", tenantCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A multipart upload cannot be replayed, so the workspace that BeginTask
|
||||
// discovered has to ride on the upload request itself. Without it a 0.9
|
||||
// platform key gets 409 TENANT_REQUIRED and the caller reads that as a
|
||||
// duplicate document.
|
||||
func TestUploadFileSendsDiscoveredWorkspace(t *testing.T) {
|
||||
const apiKey = "platform" + "-key"
|
||||
var uploadTenant atomic.Value
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/tenants/all":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"items":[{"id":10000}]}}`))
|
||||
case "/api/v1/knowledge-bases/kb-1":
|
||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-1","tenant_id":10000}}`))
|
||||
case "/api/v1/knowledge-bases/kb-1/knowledge/file":
|
||||
uploadTenant.Store(r.Header.Get("X-Tenant-ID"))
|
||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"processing"}}`))
|
||||
default:
|
||||
t.Fatalf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.GetKnowledgeBase(context.Background(), "kb-1"); err != nil {
|
||||
t.Fatalf("GetKnowledgeBase() error = %v", err)
|
||||
}
|
||||
knowledge, err := client.UploadFile(context.Background(), UploadRequest{
|
||||
KnowledgeBaseID: "kb-1",
|
||||
FileName: "doc.pdf",
|
||||
Content: strings.NewReader("%PDF-1.4"),
|
||||
})
|
||||
if err != nil || knowledge.ID != "knowledge-1" {
|
||||
t.Fatalf("UploadFile() = %#v, %v", knowledge, err)
|
||||
}
|
||||
if got, _ := uploadTenant.Load().(string); got != "10000" {
|
||||
t.Fatalf("upload X-Tenant-ID = %q, want 10000", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A workspace refusal on the upload is not a duplicate: it must surface as a
|
||||
// plain 409 so the handler dead-letters it with a readable reason.
|
||||
func TestUploadFileTenantRequiredIsNotDuplicate(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "platform-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = client.UploadFile(context.Background(), UploadRequest{
|
||||
KnowledgeBaseID: "kb-1",
|
||||
FileName: "doc.pdf",
|
||||
Content: strings.NewReader("%PDF-1.4"),
|
||||
})
|
||||
if errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("TENANT_REQUIRED was reported as a duplicate conflict: %v", err)
|
||||
}
|
||||
var httpErr *HTTPError
|
||||
if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("UploadFile() error = %v, want HTTPError 409", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A real duplicate still reports ErrConflict so the handler can adopt the
|
||||
// existing knowledge instead of dead-lettering.
|
||||
func TestUploadFileKeepsDuplicateConflict(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"success":false,"data":{"id":"knowledge-9","knowledge_base_id":"kb-1","file_hash":"abc"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "tenant-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
knowledge, err := client.UploadFile(context.Background(), UploadRequest{
|
||||
KnowledgeBaseID: "kb-1",
|
||||
FileName: "doc.pdf",
|
||||
Content: strings.NewReader("%PDF-1.4"),
|
||||
})
|
||||
if !errors.Is(err, ErrConflict) || knowledge.ID != "knowledge-9" {
|
||||
t.Fatalf("UploadFile() = %#v, %v want duplicate conflict", knowledge, err)
|
||||
}
|
||||
}
|
||||
|
||||
// An upload conflict keeps its own meaning: 409 without TENANT_REQUIRED is not
|
||||
// treated as a workspace refusal.
|
||||
func TestTenantRequiredIgnoresPlainConflict(t *testing.T) {
|
||||
if tenantRequired(&rawResponse{status: http.StatusConflict, body: []byte(`{"error":"already exists"}`)}) {
|
||||
t.Fatal("plain 409 must not be classified as TENANT_REQUIRED")
|
||||
}
|
||||
if !tenantRequired(&rawResponse{status: http.StatusConflict, body: []byte(`{"code":"TENANT_REQUIRED"}`)}) {
|
||||
t.Fatal("TENANT_REQUIRED 409 must be classified")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,42 +47,3 @@ func ReadAPIKeyFile(path string) (string, error) {
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
|
||||
// contract at mode 0400: unlike tenant keys (0600), this key must not be
|
||||
// readable by the process owner's group and never leaves the API process.
|
||||
func ReadRuntimeKeyFile(path string) (string, error) {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open runtime key file: %w", err)
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
|
||||
if file == nil {
|
||||
_ = syscall.Close(fd)
|
||||
return "", errors.New("open runtime key file: invalid file descriptor")
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("inspect runtime key file: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", errors.New("runtime key file must be a regular file")
|
||||
}
|
||||
if info.Mode().Perm() != 0o400 {
|
||||
return "", errors.New("runtime key file permissions must be 0400")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read runtime key file: %w", err)
|
||||
}
|
||||
if len(body) > maxAPIKeyFileBytes {
|
||||
return "", errors.New("runtime key file is too large")
|
||||
}
|
||||
key := strings.TrimSpace(string(body))
|
||||
if key == "" {
|
||||
return "", errors.New("runtime key file is empty")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
@@ -53,20 +53,3 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
|
||||
path := t.TempDir() + "/runtime-key"
|
||||
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := ReadRuntimeKeyFile(path)
|
||||
if err != nil || key != "runtime-secret" {
|
||||
t.Fatalf("key=%q err=%v", key, err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadRuntimeKeyFile(path); err == nil {
|
||||
t.Fatal("0600 runtime key must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,28 +42,33 @@ type DashboardRegion struct {
|
||||
UsageCoverage qaopsquality.Rate `json:"usage_coverage"`
|
||||
}
|
||||
type Dashboard struct {
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Filters map[string]string `json:"filters,omitempty"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision"`
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
TotalIssues int `json:"total_issues"`
|
||||
NewThisWeek int `json:"new_this_week"`
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
MonthStart time.Time `json:"month_start"`
|
||||
Quality qaopsquality.Summary `json:"quality"`
|
||||
IssueTypes []DashboardCount `json:"issue_types"`
|
||||
Products []DashboardCount `json:"products"`
|
||||
Daily []DashboardDaily `json:"daily"`
|
||||
Regions []DashboardRegion `json:"regions"`
|
||||
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
||||
ReportedWeeks []DashboardReported `json:"reported_weeks"`
|
||||
CumulativeWeeks []DashboardCumulative `json:"cumulative_weeks"`
|
||||
QualityPeriod *DashboardQualityPeriod `json:"quality_period,omitempty"`
|
||||
MonthlyQuality *DashboardStrictQuality `json:"monthly_quality,omitempty"`
|
||||
CalendarMonths []DashboardMonth `json:"calendar_months"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Filters map[string]string `json:"filters,omitempty"`
|
||||
Granularity string `json:"granularity,omitempty"`
|
||||
Period *DashboardPeriod `json:"period,omitempty"`
|
||||
PeriodIssues *int `json:"period_issues,omitempty"`
|
||||
PrevPeriodIssues *int `json:"prev_period_issues,omitempty"`
|
||||
PeriodQuality *DashboardStrictQuality `json:"period_quality,omitempty"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision"`
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
TotalIssues int `json:"total_issues"`
|
||||
NewThisWeek int `json:"new_this_week"`
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
MonthStart time.Time `json:"month_start"`
|
||||
Quality qaopsquality.Summary `json:"quality"`
|
||||
IssueTypes []DashboardCount `json:"issue_types"`
|
||||
Products []DashboardCount `json:"products"`
|
||||
Daily []DashboardDaily `json:"daily"`
|
||||
Regions []DashboardRegion `json:"regions"`
|
||||
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
||||
ReportedWeeks []DashboardReported `json:"reported_weeks"`
|
||||
CumulativeWeeks []DashboardCumulative `json:"cumulative_weeks"`
|
||||
QualityPeriod *DashboardQualityPeriod `json:"quality_period,omitempty"`
|
||||
MonthlyQuality *DashboardStrictQuality `json:"monthly_quality,omitempty"`
|
||||
CalendarMonths []DashboardMonth `json:"calendar_months"`
|
||||
}
|
||||
|
||||
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
)
|
||||
|
||||
// The statistics board accepts an explicit granularity so every panel is cut
|
||||
// from ONE selected range. Empty granularity keeps the historical weekly board
|
||||
// (start/end derived from the selected week) byte-for-byte unchanged.
|
||||
const (
|
||||
dashboardGranularityDay = "day"
|
||||
dashboardGranularityWeek = "week"
|
||||
dashboardGranularityMonth = "month"
|
||||
dashboardGranularityCustom = "custom"
|
||||
)
|
||||
|
||||
func validDashboardGranularity(kind string) bool {
|
||||
switch kind {
|
||||
case "", dashboardGranularityDay, dashboardGranularityWeek, dashboardGranularityMonth, dashboardGranularityCustom:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type DashboardPeriod struct {
|
||||
Kind string `json:"kind"`
|
||||
Label string `json:"label"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
PrevStart time.Time `json:"prev_start"`
|
||||
PrevEnd time.Time `json:"prev_end"`
|
||||
}
|
||||
|
||||
// dashboardPeriod describes the selected range in Beijing time and derives the
|
||||
// immediately preceding range of the same length so the board can show a
|
||||
// like-for-like comparison instead of a second, hidden time window.
|
||||
func dashboardPeriod(kind string, start, end time.Time) DashboardPeriod {
|
||||
local := start.In(dashboardLocation)
|
||||
finishLocal := end.In(dashboardLocation)
|
||||
out := DashboardPeriod{Kind: kind, Start: start, End: end, PrevEnd: start}
|
||||
switch kind {
|
||||
case dashboardGranularityDay:
|
||||
out.Label = local.Format("2006-01-02")
|
||||
out.PrevStart = start.AddDate(0, 0, -1)
|
||||
case dashboardGranularityWeek:
|
||||
first := local.AddDate(0, 0, -((int(local.Weekday()) + 6) % 7))
|
||||
year, week := first.ISOWeek()
|
||||
out.Label = fmt.Sprintf("%d 第%d周", year, week)
|
||||
out.PrevStart = start.AddDate(0, 0, -7)
|
||||
case dashboardGranularityMonth:
|
||||
out.Label = local.Format("2006-01")
|
||||
out.PrevStart = start.AddDate(0, -1, 0)
|
||||
default:
|
||||
out.Label = fmt.Sprintf("%s 至 %s", local.Format("2006-01-02"), finishLocal.Format("2006-01-02"))
|
||||
out.PrevStart = start.Add(-end.Sub(start))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// dashboardPeriodIssues counts records whose original asked_at falls inside the
|
||||
// selected range. The historical "total_issues" keeps counting everything up to
|
||||
// the range end, so the two numbers stay distinguishable on the board.
|
||||
func (s *Store) dashboardPeriodIssues(ctx context.Context, tx pgx.Tx, q dobotaiops.RecordQuery, master bool, start, end time.Time) (int, error) {
|
||||
table, question := "qa_ops_mirror_records", "lower(question)"
|
||||
if master {
|
||||
table = "qa_ops_master_read_model"
|
||||
question = "lower(question||E'\\n'||chinese_question||E'\\n'||COALESCE(ai_fields->>'question_chinese',''))"
|
||||
}
|
||||
sql := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 AND ($4='' OR position(%s IN %s)>0)`, table, question, question)
|
||||
args := []any{s.tenant, start, end, q.Keyword}
|
||||
if q.MatchIDs != nil {
|
||||
sql += " AND id=ANY($5::text[])"
|
||||
args = append(args, q.MatchIDs)
|
||||
}
|
||||
var n int
|
||||
if err := tx.QueryRow(ctx, sql, args...).Scan(&n); err != nil {
|
||||
return 0, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// A monthly board must cut every panel from the selected range: the in-range
|
||||
// count, the daily trend, the strict quality sample and the previous range.
|
||||
func TestMonthlyGranularityCutsEveryPanelFromTheSelectedRange(t *testing.T) {
|
||||
pool := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(pool, "fixture-monthly-period")
|
||||
queue := pg.NewStore(pool)
|
||||
rows := make([]dobotaiops.MirrorRecord, 0, 3)
|
||||
for _, spec := range []struct{ id, askedAt string }{
|
||||
{"oct-record", "2026-10-15T08:00:00+08:00"},
|
||||
{"nov-early", "2026-11-02T08:00:00+08:00"},
|
||||
{"nov-late", "2026-11-30T08:00:00+08:00"},
|
||||
} {
|
||||
entry := fixtureEntry(spec.id, "已有资料")
|
||||
var wire map[string]any
|
||||
if err := json.Unmarshal(entry.Payload, &wire); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wire["asked_at"] = spec.askedAt
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
rows = append(rows, entry)
|
||||
}
|
||||
job := claimMirrorJob(t, s, queue, "monthly-period-seed")
|
||||
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
|
||||
return &fixtureSource{rows: rows}, nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-11-01T00:00:00+08:00")
|
||||
end, _ := time.Parse(time.RFC3339, "2026-12-01T00:00:00+08:00")
|
||||
// The handler builds the window through dobotaiops.NewWindow, which
|
||||
// normalises both ends to UTC. Feed the store the same shape here, otherwise
|
||||
// this test keeps a +08 location the production path never has.
|
||||
start, end = start.UTC(), end.UTC()
|
||||
got, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{
|
||||
Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end},
|
||||
Granularity: dashboardGranularityMonth,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Period == nil || got.Period.Kind != dashboardGranularityMonth || got.Period.Label != "2026-11" {
|
||||
t.Fatalf("period = %+v", got.Period)
|
||||
}
|
||||
if !got.Period.PrevStart.Equal(start.AddDate(0, -1, 0)) || !got.Period.PrevEnd.Equal(start) {
|
||||
t.Fatalf("previous range = %s..%s", got.Period.PrevStart, got.Period.PrevEnd)
|
||||
}
|
||||
if got.PeriodIssues == nil || *got.PeriodIssues != 2 {
|
||||
t.Fatalf("period issues = %v, want 2", got.PeriodIssues)
|
||||
}
|
||||
if got.PrevPeriodIssues == nil || *got.PrevPeriodIssues != 1 {
|
||||
t.Fatalf("previous period issues = %v, want 1", got.PrevPeriodIssues)
|
||||
}
|
||||
if got.TotalIssues != 3 {
|
||||
t.Fatalf("cumulative total = %d, want 3 (everything before the range end)", got.TotalIssues)
|
||||
}
|
||||
if len(got.Daily) != 30 || got.Daily[0].Date != "2026-11-01" || got.Daily[29].Date != "2026-11-30" {
|
||||
t.Fatalf("daily trend does not cover the whole month: %d points, first=%v", len(got.Daily), got.Daily[0])
|
||||
}
|
||||
sum := 0
|
||||
for _, point := range got.Daily {
|
||||
sum += point.Count
|
||||
}
|
||||
if sum != *got.PeriodIssues || got.NewThisWeek != *got.PeriodIssues {
|
||||
t.Fatalf("daily sum=%d, new_this_week=%d, period=%d", sum, got.NewThisWeek, *got.PeriodIssues)
|
||||
}
|
||||
if got.PeriodQuality == nil || got.PeriodQuality.Records != got.Quality.Total {
|
||||
t.Fatalf("period quality = %+v, quality total = %d", got.PeriodQuality, got.Quality.Total)
|
||||
}
|
||||
}
|
||||
|
||||
// Omitting granularity must keep the weekly board exactly as before.
|
||||
func TestWeeklyBoardKeepsLegacyPanelsWithoutGranularity(t *testing.T) {
|
||||
pool := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(pool, "fixture-weekly-legacy")
|
||||
queue := pg.NewStore(pool)
|
||||
entry := fixtureEntry("legacy-week", "已有资料")
|
||||
var wire map[string]any
|
||||
_ = json.Unmarshal(entry.Payload, &wire)
|
||||
wire["asked_at"] = "2026-11-30T08:00:00+08:00"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
job := claimMirrorJob(t, s, queue, "legacy-week-seed")
|
||||
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
|
||||
return &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}, nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-11-30T00:00:00+08:00")
|
||||
end, _ := time.Parse(time.RFC3339, "2026-12-03T00:00:00+08:00")
|
||||
got, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Period != nil || got.PeriodIssues != nil || got.PeriodQuality != nil || got.Granularity != "" {
|
||||
t.Fatalf("granularity leaked into the legacy board: %+v", got.Period)
|
||||
}
|
||||
if got.NewThisWeek != 1 || len(got.Daily) != 3 {
|
||||
t.Fatalf("legacy weekly panels changed: new=%d daily=%d", got.NewThisWeek, len(got.Daily))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mustShanghai(t *testing.T, value string) time.Time {
|
||||
t.Helper()
|
||||
parsed, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", value, err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func TestDashboardPeriodResolution(t *testing.T) {
|
||||
monthStart := mustShanghai(t, "2026-11-01T00:00:00+08:00")
|
||||
monthEnd := mustShanghai(t, "2026-12-01T00:00:00+08:00")
|
||||
month := dashboardPeriod(dashboardGranularityMonth, monthStart, monthEnd)
|
||||
if month.Label != "2026-11" {
|
||||
t.Fatalf("month label = %q, want 2026-11", month.Label)
|
||||
}
|
||||
if !month.PrevStart.Equal(mustShanghai(t, "2026-10-01T00:00:00+08:00")) || !month.PrevEnd.Equal(monthStart) {
|
||||
t.Fatalf("month prev range = %s..%s", month.PrevStart, month.PrevEnd)
|
||||
}
|
||||
|
||||
weekStart := mustShanghai(t, "2026-11-30T00:00:00+08:00")
|
||||
week := dashboardPeriod(dashboardGranularityWeek, weekStart, mustShanghai(t, "2026-12-07T00:00:00+08:00"))
|
||||
if week.Label != "2026 第49周" {
|
||||
t.Fatalf("week label = %q", week.Label)
|
||||
}
|
||||
if !week.PrevStart.Equal(mustShanghai(t, "2026-11-23T00:00:00+08:00")) {
|
||||
t.Fatalf("week prev start = %s", week.PrevStart)
|
||||
}
|
||||
|
||||
day := dashboardPeriod(dashboardGranularityDay, weekStart, weekStart.AddDate(0, 0, 1))
|
||||
if day.Label != "2026-11-30" || !day.PrevStart.Equal(weekStart.AddDate(0, 0, -1)) {
|
||||
t.Fatalf("day period = %+v", day)
|
||||
}
|
||||
|
||||
customEnd := mustShanghai(t, "2026-11-05T00:00:00+08:00")
|
||||
custom := dashboardPeriod(dashboardGranularityCustom, monthStart, customEnd)
|
||||
if !custom.PrevStart.Equal(mustShanghai(t, "2026-10-28T00:00:00+08:00")) || !custom.PrevEnd.Equal(monthStart) {
|
||||
t.Fatalf("custom prev range = %s..%s", custom.PrevStart, custom.PrevEnd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardGranularityValidation(t *testing.T) {
|
||||
for _, kind := range []string{"", "day", "week", "month", "custom"} {
|
||||
if !validDashboardGranularity(kind) {
|
||||
t.Fatalf("expected %q to be valid", kind)
|
||||
}
|
||||
}
|
||||
for _, kind := range []string{"year", "Week", "quarter"} {
|
||||
if validDashboardGranularity(kind) {
|
||||
t.Fatalf("expected %q to be rejected", kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,9 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
||||
if !s.valid() {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !validDashboardGranularity(q.Granularity) {
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if q.Window.TenantKey != s.tenant || !utf8.ValidString(q.Keyword) || utf8.RuneCountInString(q.Keyword) > 200 || strings.ContainsRune(q.Keyword, 0) {
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
@@ -221,7 +224,15 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
||||
}
|
||||
out.Quality = qaopsquality.Summarize(views)
|
||||
products, types, daily := map[string]int{}, map[string]int{}, map[string]int{}
|
||||
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
dailyFrom := out.WeekStart
|
||||
if q.Granularity != "" {
|
||||
// Window.Start is UTC (NewWindow normalises it); the trend keys and the
|
||||
// per-record buckets are Beijing dates, so cut the range in Beijing time
|
||||
// or the first/last day drifts by one and the last day's records fall
|
||||
// outside the pre-filled keys (the board then looks inconsistent).
|
||||
dailyFrom = q.Window.Start.In(dashboardLocation)
|
||||
}
|
||||
for day := dailyFrom; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
daily[day.Format("2006-01-02")] = 0
|
||||
}
|
||||
regionIndex := map[string]int{}
|
||||
@@ -237,10 +248,18 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
||||
users[region.Name] = map[string]bool{}
|
||||
out.Regions = append(out.Regions, r)
|
||||
}
|
||||
inPeriod := 0
|
||||
for _, r := range records {
|
||||
if !r.at.Before(out.WeekStart) {
|
||||
out.NewThisWeek++
|
||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
||||
if q.Granularity == "" {
|
||||
if !r.at.Before(out.WeekStart) {
|
||||
out.NewThisWeek++
|
||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
||||
}
|
||||
} else if !r.at.Before(q.Window.Start) {
|
||||
inPeriod++
|
||||
if _, ok := daily[r.at.In(dashboardLocation).Format("2006-01-02")]; ok {
|
||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
||||
}
|
||||
}
|
||||
if !r.at.Before(q.Window.Start) {
|
||||
v, ok := views[r.id]
|
||||
@@ -260,10 +279,24 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
||||
}
|
||||
out.Products = dashboardCategories(products)
|
||||
out.IssueTypes = dashboardCategories(types)
|
||||
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
for day := dailyFrom; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
date := day.Format("2006-01-02")
|
||||
out.Daily = append(out.Daily, DashboardDaily{Date: date, Count: daily[date]})
|
||||
}
|
||||
if q.Granularity != "" {
|
||||
period := dashboardPeriod(q.Granularity, q.Window.Start, q.Window.End)
|
||||
out.Granularity = q.Granularity
|
||||
out.Period = &period
|
||||
out.PeriodIssues = &inPeriod
|
||||
// Keep the historical invariant "daily sums up to new_this_week" so old
|
||||
// clients that only know this field still agree with the trend panel.
|
||||
out.NewThisWeek = inPeriod
|
||||
prev, err := s.dashboardPeriodIssues(ctx, tx, q, master, period.PrevStart, period.PrevEnd)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.PrevPeriodIssues = &prev
|
||||
}
|
||||
for i := range out.Regions {
|
||||
r := &out.Regions[i]
|
||||
if r.Users != nil {
|
||||
@@ -307,6 +340,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
||||
out.QualityPeriod = &DashboardQualityPeriod{Month: month.Format("2006-01"), Start: month, CutoffAt: cutoff, CalculatedAt: calculated, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy}
|
||||
rates := dashboardStrictQuality(timeline, month, cutoff)
|
||||
out.MonthlyQuality = &rates
|
||||
if q.Granularity != "" {
|
||||
periodRates := dashboardStrictQuality(timeline, q.Window.Start, q.Window.End)
|
||||
out.PeriodQuality = &periodRates
|
||||
}
|
||||
out.CalendarMonths = dashboardCalendarMonths(timeline, cutoff, calculated)
|
||||
} else {
|
||||
out.CumulativeWeeks = []DashboardCumulative{}
|
||||
|
||||
@@ -2,6 +2,8 @@ package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -9,9 +11,12 @@ import (
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// RuntimeConfig.Resolve runs for every request instead of once at startup: the
|
||||
// runtime read uses the same knowledge-base binding (test environment) as the
|
||||
// reconciliation remote, so an admin saving a new key must take effect on the
|
||||
// next request without restarting the API.
|
||||
type RuntimeConfig struct {
|
||||
BaseURL func(context.Context) string
|
||||
APIKey string
|
||||
Resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
@@ -19,8 +24,7 @@ type RuntimeConfig struct {
|
||||
}
|
||||
|
||||
type RuntimeProvider struct {
|
||||
baseURL func(context.Context) string
|
||||
apiKey string
|
||||
resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
@@ -32,26 +36,28 @@ func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
|
||||
config.Now = time.Now
|
||||
}
|
||||
return &RuntimeProvider{
|
||||
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
|
||||
resolve: config.Resolve, timeout: config.Timeout,
|
||||
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Available() bool {
|
||||
return p != nil && p.apiKey != "" && p.baseURL != nil
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
|
||||
if !p.Available() {
|
||||
if p == nil || p.resolve == nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL := strings.TrimSpace(p.baseURL(ctx))
|
||||
if baseURL == "" {
|
||||
baseURL, apiKey, err := p.resolve(ctx)
|
||||
if err != nil {
|
||||
// Not configured, storage locked, or the saved key cannot be opened:
|
||||
// all of them mean "no usable binding", never "upstream rejected us".
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL, apiKey = strings.TrimSpace(baseURL), strings.TrimSpace(apiKey)
|
||||
if baseURL == "" || apiKey == "" {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: p.apiKey,
|
||||
APIKey: apiKey,
|
||||
Timeout: p.timeout,
|
||||
AllowDockerHTTP: p.allowDockerHTTP,
|
||||
AllowPrivateHTTP: p.allowPrivateHTTP,
|
||||
@@ -62,6 +68,18 @@ func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, e
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// classifyRuntimeReadFailure separates the two reasons an operator can act on:
|
||||
// 401/403 means the bound key lacks system_runtime_read; everything else
|
||||
// (timeout, DNS, connection, upstream error) means the read itself failed.
|
||||
func classifyRuntimeReadFailure(err error) error {
|
||||
switch weknora.StatusCode(err) {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return ErrRuntimeForbidden
|
||||
default:
|
||||
return ErrRuntimeUnreachable
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
client, err := p.client(ctx)
|
||||
if err != nil {
|
||||
@@ -73,7 +91,7 @@ func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueS
|
||||
defer cancel()
|
||||
queues, err := client.Queues(queueCtx)
|
||||
if err != nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
return nil, classifyRuntimeReadFailure(err)
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{
|
||||
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
|
||||
@@ -99,7 +117,7 @@ func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID strin
|
||||
if weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationProgress{}, err
|
||||
}
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
return governance.ReconciliationProgress{}, classifyRuntimeReadFailure(err)
|
||||
}
|
||||
progress := governance.ReconciliationProgress{
|
||||
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
|
||||
|
||||
@@ -7,12 +7,17 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
func staticConnection(baseURL, apiKey string) func(context.Context) (string, string, error) {
|
||||
return func(context.Context) (string, string, error) { return baseURL, apiKey, nil }
|
||||
}
|
||||
|
||||
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != "runtime-key" {
|
||||
@@ -37,8 +42,8 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
queues, err := provider.Queues(context.Background())
|
||||
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
|
||||
@@ -53,22 +58,89 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The binding is editable from the console, so the provider must ask for the
|
||||
// key on every request instead of freezing the first one it sees.
|
||||
func TestRuntimeProviderResolvesKeyOnEveryRequest(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.Header.Get("X-API-Key"))
|
||||
mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"available": true, "queues": []map[string]any{}})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
mu.Lock()
|
||||
key := "old-key"
|
||||
mu.Unlock()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return server.URL, key, nil
|
||||
},
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
key = "new-key"
|
||||
mu.Unlock()
|
||||
if _, err := provider.Queues(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(seen) != 2 || seen[0] != "old-key" || seen[1] != "new-key" {
|
||||
t.Fatalf("request keys = %v, want [old-key new-key]", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) { return "", "", nil },
|
||||
})
|
||||
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("unconfigured queues err=%v", err)
|
||||
}
|
||||
broken := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) {
|
||||
return "", "", errors.New("binding storage is not ready")
|
||||
},
|
||||
})
|
||||
if _, err := broken.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("broken binding err=%v", err)
|
||||
}
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
|
||||
t.Fatalf("missing document err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeErrorCodeDistinguishesStates(t *testing.T) {
|
||||
cases := map[string]error{
|
||||
"runtime_read_unavailable": ErrRuntimeUnavailable,
|
||||
"runtime_key_forbidden": ErrRuntimeForbidden,
|
||||
"runtime_unreachable": ErrRuntimeUnreachable,
|
||||
"": errors.New("unclassified"),
|
||||
}
|
||||
for want, err := range cases {
|
||||
if got := RuntimeErrorCode(err); got != want {
|
||||
t.Fatalf("RuntimeErrorCode(%v) = %q, want %q", err, got, want)
|
||||
}
|
||||
}
|
||||
if got := RuntimeErrorCode(nil); got != "" {
|
||||
t.Fatalf("RuntimeErrorCode(nil) = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The progress passthrough is a projection, not a proxy: whatever extra fields
|
||||
// the platform endpoint returns (keys, authorization headers, token echoes) must
|
||||
// never reach the browser. This guards the shape if someone later switches to
|
||||
@@ -89,8 +161,8 @@ func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
|
||||
if err != nil {
|
||||
@@ -107,3 +179,44 @@ func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
|
||||
t.Fatalf("projection dropped real fields: %#v", progress)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderClassifiesForbiddenAndUnreachable(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
want error
|
||||
}{
|
||||
{"forbidden", http.StatusForbidden, ErrRuntimeForbidden},
|
||||
{"unauthorized", http.StatusUnauthorized, ErrRuntimeForbidden},
|
||||
{"upstream-500", http.StatusInternalServerError, ErrRuntimeUnreachable},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tc.status)
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, tc.want) {
|
||||
t.Fatalf("status %d err=%v, want %v", tc.status, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderClassifiesClosedListenerAsUnreachable(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{}})
|
||||
}))
|
||||
url := server.URL
|
||||
server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: staticConnection(url, "runtime-key"), Timeout: 2 * time.Second,
|
||||
})
|
||||
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnreachable) {
|
||||
t.Fatalf("closed listener err=%v, want %v", err, ErrRuntimeUnreachable)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
@@ -21,8 +22,35 @@ var (
|
||||
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
|
||||
ErrRemoteFailed = errors.New("reconciliation remote call failed")
|
||||
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
|
||||
// ErrRuntimeForbidden / ErrRuntimeUnreachable 把「Key 无权限」与「连不上」
|
||||
// 从 ErrRuntimeUnavailable 里拆出来:页面要给两种不同的中文,不能再折叠。
|
||||
ErrRuntimeForbidden = errors.New("weknora runtime key forbidden")
|
||||
ErrRuntimeUnreachable = errors.New("weknora runtime read unreachable")
|
||||
)
|
||||
|
||||
// RuntimeErrorCode is the stable code the browser branches on. Unclassified
|
||||
// failures return "" so callers keep their generic fallback instead of guessing.
|
||||
func RuntimeErrorCode(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ErrRuntimeForbidden):
|
||||
return "runtime_key_forbidden"
|
||||
case errors.Is(err, ErrRuntimeUnreachable):
|
||||
return "runtime_unreachable"
|
||||
case errors.Is(err, ErrRuntimeUnavailable):
|
||||
return "runtime_read_unavailable"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// knowledgeBaseMissing 只认 WeKnora 明确回答的 404 —— 库被删掉、或 ID 属于
|
||||
// 别的环境/租户。它与网络不通、Key 无权限要分开:这三种情况的处置完全不同,
|
||||
// 页面把 404 说成「检查地址与 Key」会让工程师去改一个根本没坏的配置。
|
||||
func knowledgeBaseMissing(err error) bool {
|
||||
var httpErr *weknora.HTTPError
|
||||
return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
|
||||
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
|
||||
@@ -249,6 +277,9 @@ func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
|
||||
}
|
||||
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
|
||||
if err != nil {
|
||||
if knowledgeBaseMissing(err) {
|
||||
return finished("remote_kb_missing")
|
||||
}
|
||||
return finished("remote_unavailable")
|
||||
}
|
||||
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
|
||||
@@ -326,8 +357,16 @@ func (s *Service) Progress(ctx context.Context, documentID string) (governance.R
|
||||
switch {
|
||||
case err == nil:
|
||||
return progress, nil
|
||||
case errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable), errors.Is(err, ErrRuntimeUnavailable):
|
||||
// Provider 已经分好类;这里若再折叠,页面就永远看不到两种不同原因。
|
||||
return governance.ReconciliationProgress{}, err
|
||||
case weknora.StatusCode(err) == 404:
|
||||
return governance.ReconciliationProgress{}, ErrNotFound
|
||||
case errors.Is(err, ErrRuntimeUnavailable), errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable):
|
||||
// The provider already classified the failure; collapsing it here would
|
||||
// erase the distinction between "no binding", "no permission" and
|
||||
// "unreachable" that the page needs.
|
||||
return governance.ReconciliationProgress{}, err
|
||||
default:
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
}
|
||||
|
||||
@@ -145,6 +145,7 @@ type fakeReconciliationRemote struct {
|
||||
missing map[string]bool
|
||||
gets map[string]weknora.Knowledge
|
||||
listErr error
|
||||
beginErr error
|
||||
pageSizes []int
|
||||
deleteCalls int
|
||||
listInFlight int
|
||||
@@ -152,6 +153,9 @@ type fakeReconciliationRemote struct {
|
||||
}
|
||||
|
||||
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
|
||||
if f.beginErr != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, f.beginErr
|
||||
}
|
||||
return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil
|
||||
}
|
||||
func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) {
|
||||
@@ -395,6 +399,24 @@ func (r *concurrencyRemote) GetKnowledge(context.Context, string) (weknora.Knowl
|
||||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||||
}
|
||||
|
||||
// 库被删掉时,远端回的是 404,不是网络故障。批次必须落成 remote_kb_missing,
|
||||
// 页面才能提示「去选当前绑定的库」,而不是让人去改没坏的地址与 Key。
|
||||
func TestExecuteRunReportsMissingKnowledgeBase(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-gone", State: "running", StartedAt: now}}
|
||||
remote := &fakeReconciliationRemote{beginErr: &weknora.HTTPError{StatusCode: 404}}
|
||||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if store.failCode != "remote_kb_missing" {
|
||||
t.Fatalf("fail code = %q", store.failCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", StartedAt: now}}
|
||||
@@ -580,3 +602,39 @@ func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
|
||||
t.Fatalf("payload = %s", request.Payload)
|
||||
}
|
||||
}
|
||||
|
||||
type failingRuntime struct{ err error }
|
||||
|
||||
func (runtime failingRuntime) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||||
return governance.ReconciliationProgress{}, runtime.err
|
||||
}
|
||||
|
||||
// Progress must not re-collapse the provider's classification: the page needs
|
||||
// "no binding", "no permission" and "unreachable" to stay distinct.
|
||||
func TestProgressPreservesClassifiedRuntimeErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want error
|
||||
}{
|
||||
{name: "unavailable", err: ErrRuntimeUnavailable, want: ErrRuntimeUnavailable},
|
||||
{name: "forbidden", err: ErrRuntimeForbidden, want: ErrRuntimeForbidden},
|
||||
{name: "unreachable", err: ErrRuntimeUnreachable, want: ErrRuntimeUnreachable},
|
||||
{name: "not found", err: &weknora.HTTPError{StatusCode: http.StatusNotFound}, want: ErrNotFound},
|
||||
{name: "unclassified", err: errors.New("boom"), want: ErrRuntimeUnavailable},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
service, err := New(Config{
|
||||
Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{},
|
||||
Runtime: failingRuntime{err: testCase.err},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("Progress err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -123,7 +124,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
uploadMD5, _ := handler.hashSpool(candidate)
|
||||
now := handler.now()
|
||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||
return ErrUploadStateConflict
|
||||
return fmt.Errorf("%w: %v", ErrUploadStateConflict, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -194,7 +195,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
}
|
||||
now := handler.now()
|
||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||
return ErrUploadStateConflict
|
||||
return fmt.Errorf("%w: %v", ErrUploadStateConflict, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -404,7 +404,12 @@ def dingtalk_live_raw_key(manifest):
|
||||
for index in range(len(parts)):
|
||||
drive = space_id.isdigit()
|
||||
args = ['drive', '+list', '--space-id', space_id] if drive else ['wiki', '+node-list', '--workspace', space_id]
|
||||
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
|
||||
# 翻页上限开关按命令族不同:wiki 叫 --page-limit,drive +list 叫 --max-pages。
|
||||
# 混用会得到 `unknown flag: --page-limit`,被分类成 unknown 而成为终态失败。
|
||||
if drive:
|
||||
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--max-pages', '200']
|
||||
else:
|
||||
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
|
||||
if folder:
|
||||
args += ['--folder', folder]
|
||||
payload, verdict = dws_run(args, timeout=180)
|
||||
@@ -412,7 +417,13 @@ def dingtalk_live_raw_key(manifest):
|
||||
raise _dws_error(verdict)
|
||||
data = payload.get('data', {}) if isinstance(payload, dict) else {}
|
||||
entries = data.get('files' if drive else 'nodes')
|
||||
if not isinstance(entries, list) or data.get('hasMore') is not False or data.get('autoPageComplete') is not True:
|
||||
# 两族命令的“翻完了”证据不同:wiki 给 data.autoPageComplete,drive +list 只在
|
||||
# meta.pagination.endpoint_exhausted 里给。缺这一条会被当成目录读不全而永远可重试。
|
||||
meta = payload.get('meta') if isinstance(payload, dict) else None
|
||||
pagination = meta.get('pagination') if isinstance(meta, dict) else None
|
||||
exhausted = (data.get('autoPageComplete') is True
|
||||
or (isinstance(pagination, dict) and pagination.get('endpoint_exhausted') is True))
|
||||
if not isinstance(entries, list) or data.get('hasMore') is not False or not exhausted:
|
||||
raise FetchError('DingTalk directory response is incomplete', retryable=True, code='source_lookup_incomplete')
|
||||
matches = []
|
||||
for entry in entries:
|
||||
|
||||
@@ -410,53 +410,6 @@ export function ModulePage({
|
||||
return (
|
||||
<div className="release-module">
|
||||
<ReleaseTargets />
|
||||
<details className="release-legacy">
|
||||
<summary>文档级发布(旧流程,折叠保留):单篇文档发布成功不等于整库发布成功</summary>
|
||||
<ReleaseManagement
|
||||
reviewPage={reviewPage}
|
||||
reviewLoading={reviewLoading}
|
||||
reviewError={reviewError}
|
||||
reviewingId={reviewingId}
|
||||
batchPage={batchPage}
|
||||
batchDetail={batchDetail}
|
||||
batchLoading={batchLoading}
|
||||
batchError={batchError}
|
||||
mutatingBatchId={mutatingBatchId}
|
||||
onReview={onReview}
|
||||
onBatchReview={onBatchReview}
|
||||
reviewBatchMessage={reviewBatchMessage}
|
||||
onReviewRefresh={onReviewRefresh}
|
||||
onCreateBatch={onCreateBatch}
|
||||
onSealBatch={onSealBatch}
|
||||
onSelectBatch={onSelectBatch}
|
||||
onBatchRefresh={onBatchRefresh}
|
||||
releaseCapabilities={releaseCapabilities}
|
||||
releasePlan={releasePlan}
|
||||
releaseChangeSet={releaseChangeSet}
|
||||
changeSetBusy={changeSetBusy}
|
||||
changeSetError={changeSetError}
|
||||
onGenerateChangeSet={onGenerateChangeSet}
|
||||
onConfirmChangeSet={onConfirmChangeSet}
|
||||
selectedDeleteIDs={selectedDeleteIDs}
|
||||
onToggleDelete={onToggleDelete}
|
||||
executionPage={executionPage}
|
||||
executionDetail={executionDetail}
|
||||
executionChain={executionChain}
|
||||
executionLoading={executionLoading}
|
||||
executionError={executionError}
|
||||
onSelectExecution={onSelectExecution}
|
||||
onExecutionRefresh={onExecutionRefresh}
|
||||
pendingReleaseAction={pendingReleaseAction}
|
||||
releaseActionPhrase={releaseActionPhrase}
|
||||
releaseActionBusy={releaseActionBusy}
|
||||
releaseActionError={releaseActionError}
|
||||
releaseActionMessage={releaseActionMessage}
|
||||
onStartReleaseAction={onStartReleaseAction}
|
||||
onReleaseActionPhrase={onReleaseActionPhrase}
|
||||
onSubmitReleaseAction={onSubmitReleaseAction}
|
||||
onCancelReleaseAction={onCancelReleaseAction}
|
||||
/>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -140,12 +140,12 @@ describe('KnowledgeBaseBinding', () => {
|
||||
})
|
||||
)
|
||||
await render()
|
||||
expect(host.textContent).toContain('当前生效 · 测试 090')
|
||||
expect(host.textContent).toContain('当前生效 · 测试知识库')
|
||||
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
|
||||
|
||||
await click('验证并读取知识库')
|
||||
await click('生产 090')
|
||||
expect(host.textContent).toContain('当前生效 · 生产 090')
|
||||
await click('生产知识库')
|
||||
expect(host.textContent).toContain('当前生效 · 生产知识库')
|
||||
expect(host.textContent).toContain('production 内部资料')
|
||||
|
||||
await act(async () => {
|
||||
@@ -175,7 +175,7 @@ describe('KnowledgeBaseBinding', () => {
|
||||
expect(host.textContent).toContain('候选实例拒绝保存')
|
||||
// 顶部当前生效仍是旧值;草稿只存在于下方。
|
||||
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
|
||||
expect(host.textContent).not.toContain('当前生效 · 测试 090新内部库')
|
||||
expect(host.textContent).not.toContain('当前生效 · 测试知识库新内部库')
|
||||
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
|
||||
expect(put).toBeTruthy()
|
||||
const body = JSON.parse(String((put![1] as { body: string }).body))
|
||||
@@ -250,11 +250,11 @@ describe('KnowledgeBaseBinding', () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
|
||||
await render('viewer')
|
||||
expect(host.textContent).toContain('普通用户只读')
|
||||
expect(host.textContent).toContain('当前生效 · 测试 090')
|
||||
expect(host.textContent).toContain('当前生效 · 测试知识库')
|
||||
expect(host.querySelectorAll('input')).toHaveLength(0)
|
||||
expect(
|
||||
[...host.querySelectorAll('button')].every((button) =>
|
||||
['测试 090', '生产 090'].includes(button.textContent?.trim() ?? '')
|
||||
['测试知识库', '生产知识库'].includes(button.textContent?.trim() ?? '')
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
@@ -21,9 +21,10 @@ import type {
|
||||
} from './knowledgeBaseBindings'
|
||||
import { validServiceEndpoint } from './uiSettings'
|
||||
|
||||
// 环境名只表达用途,不把版本号写进去:实例已迁到 0.9.1,090 是历史部署名。
|
||||
const environments: { key: KBEnvironment; label: string; short: string }[] = [
|
||||
{ key: 'test', label: '测试 090', short: '测试' },
|
||||
{ key: 'production', label: '生产 090', short: '生产' },
|
||||
{ key: 'test', label: '测试知识库', short: '测试' },
|
||||
{ key: 'production', label: '生产知识库', short: '生产' },
|
||||
]
|
||||
|
||||
type Busy = '' | 'catalog' | 'saving'
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { associateLegacySource, LegacySourceAssociation } from './LegacySourceAssociation'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const reply = (status: number, data: unknown) => new Response(JSON.stringify(data), { status })
|
||||
|
||||
it('only sends exact snapshot and scope; association is not publishing', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
reply(200, { associated: true, published: false, snapshot_id: 'snapshot', source_id: 'a'.repeat(64) })
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
expect(await associateLegacySource('internal', 'snapshot')).toBe('a'.repeat(64))
|
||||
expect(fetchMock.mock.calls).toHaveLength(1)
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/library/source-associations')
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ scope: 'internal', snapshot_id: 'snapshot' })
|
||||
})
|
||||
|
||||
it('rejects wrong-snapshot and incomplete readback, and shows evidence errors', async () => {
|
||||
for (const value of [
|
||||
{ associated: true, published: false, snapshot_id: 'wrong', source_id: 'a'.repeat(64) },
|
||||
{ associated: true, snapshot_id: 'snapshot' },
|
||||
]) {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(200, value)))
|
||||
await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('来源关联回执')
|
||||
}
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(409, { error: 'original capture identity mismatch' })))
|
||||
await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('original capture identity mismatch')
|
||||
})
|
||||
|
||||
it('hides association controls from non-admin and distinguishes it from publication', () => {
|
||||
expect(
|
||||
renderToStaticMarkup(
|
||||
<LegacySourceAssociation scope="internal" snapshots={[]} admin={false} onBound={async () => {}} />
|
||||
)
|
||||
).toBe('')
|
||||
const html = renderToStaticMarkup(
|
||||
<LegacySourceAssociation scope="internal" snapshots={[]} admin onBound={async () => {}} />
|
||||
)
|
||||
expect(html).toContain('只追加治理关联')
|
||||
expect(html).toContain('disabled')
|
||||
expect(html).toContain('核验原证据并关联')
|
||||
})
|
||||
@@ -1,83 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import type { LibrarySnapshot } from './librarySnapshots'
|
||||
|
||||
export async function associateLegacySource(scope: string, snapshotID: string): Promise<string> {
|
||||
const response = await fetch('/api/v1/library/source-associations', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ scope, snapshot_id: snapshotID }),
|
||||
})
|
||||
const value = (await response.json().catch(() => null)) as Record<string, unknown> | null
|
||||
if (!response.ok)
|
||||
throw new Error(typeof value?.error === 'string' ? value.error : `来源关联失败(HTTP ${response.status})`)
|
||||
if (
|
||||
value?.associated !== true ||
|
||||
value.published !== false ||
|
||||
value.snapshot_id !== snapshotID ||
|
||||
typeof value.source_id !== 'string' ||
|
||||
!/^[a-f0-9]{64}$/.test(value.source_id)
|
||||
) {
|
||||
throw new Error('来源关联回执不完整或快照身份不符')
|
||||
}
|
||||
return value.source_id
|
||||
}
|
||||
|
||||
export function LegacySourceAssociation({
|
||||
scope,
|
||||
snapshots,
|
||||
admin,
|
||||
onBound,
|
||||
}: {
|
||||
scope: string
|
||||
snapshots: LibrarySnapshot[]
|
||||
admin: boolean
|
||||
onBound: () => Promise<void>
|
||||
}) {
|
||||
const [snapshotID, setSnapshotID] = useState('')
|
||||
const [pending, setPending] = useState(false)
|
||||
const [notice, setNotice] = useState('')
|
||||
if (!admin) return null
|
||||
const choices = snapshots.filter((item) => item.scope === scope)
|
||||
const bind = async () => {
|
||||
if (pending || !choices.some((item) => item.snapshot_id === snapshotID)) return
|
||||
setPending(true)
|
||||
setNotice('')
|
||||
try {
|
||||
const sourceID = await associateLegacySource(scope, snapshotID)
|
||||
setNotice(`来源证据已核验关联:${sourceID}。没有发布内容;发布授权与写入闸门仍独立检查。`)
|
||||
await onBound()
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : '来源关联失败')
|
||||
} finally {
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<details className="rel-source-identity">
|
||||
<summary>关联旧封存的原始来源证据(管理员)</summary>
|
||||
<p>
|
||||
只追加治理关联,保留原快照与摘要。服务端核对原捕获响应、执行器指纹及清单;备份、来源不符或证据缺失均拒绝,不凭同一范围认领。
|
||||
</p>
|
||||
<label>
|
||||
待核验的历史快照
|
||||
<select
|
||||
aria-label="待核验的历史快照"
|
||||
value={snapshotID}
|
||||
disabled={pending}
|
||||
onChange={(event) => setSnapshotID(event.target.value)}
|
||||
>
|
||||
<option value="">选择准确快照摘要</option>
|
||||
{choices.map((item) => (
|
||||
<option key={item.snapshot_id} value={item.snapshot_id}>
|
||||
{item.snapshot_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" disabled={pending || !snapshotID} onClick={() => void bind()}>
|
||||
{pending ? '核验中…' : '核验原证据并关联'}
|
||||
</button>
|
||||
{notice ? <p role="status">{notice}</p> : null}
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -33,7 +33,7 @@ describe('question dashboard projections', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QADashboardView data={parseQADashboard(dashboardFixture)} loading={false} error="" onRetry={vi.fn()} />
|
||||
)
|
||||
for (const title of ['问题总数', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
|
||||
for (const title of ['累计总量', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
|
||||
expect(html).toContain(title)
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
|
||||
+14
-4
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { QAQuery } from './qaOps'
|
||||
import { fetchQADashboard, liveDashboardQuery } from './qaDashboardData'
|
||||
import type { QADashboardData } from './qaDashboardData'
|
||||
import type { QADashboardData, DashboardGranularity } from './qaDashboardData'
|
||||
import { QADashboardDrawing } from './QADashboardDrawing'
|
||||
import { createDashboardPNG } from './qaDashboardExport'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
@@ -38,7 +38,11 @@ export function QADashboardView({ data, loading, error, onRetry }: QADashboardPr
|
||||
link = document.createElement('a'),
|
||||
week = currentQAWeek(new Date(data.week_start))
|
||||
link.href = url
|
||||
link.download = `DobotAI_QA_Dashboard_${week.year}_W${String(week.week).padStart(2, '0')}.png`
|
||||
link.download = `DobotAI_QA_Dashboard_${
|
||||
data.period
|
||||
? data.period.label.replace(/[^\w.-]+/g, '_')
|
||||
: `${week.year}_W${String(week.week).padStart(2, '0')}`
|
||||
}.png`
|
||||
document.body.append(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
@@ -81,11 +85,13 @@ export function QADashboard({
|
||||
error,
|
||||
revision,
|
||||
onRetry,
|
||||
granularity,
|
||||
}: {
|
||||
query: QAQuery | null
|
||||
error: string | null
|
||||
revision: number
|
||||
onRetry: () => void
|
||||
granularity?: DashboardGranularity
|
||||
}) {
|
||||
const [data, setData] = useState<QADashboardData | null>(null),
|
||||
[failure, setFailure] = useState(''),
|
||||
@@ -102,7 +108,11 @@ export function QADashboard({
|
||||
setLoading(true)
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const next = await fetchQADashboard(liveDashboardQuery(query, new Date()), abort.signal)
|
||||
const next = await fetchQADashboard(
|
||||
liveDashboardQuery(query, new Date(), granularity),
|
||||
abort.signal,
|
||||
granularity
|
||||
)
|
||||
if (!abort.signal.aborted) {
|
||||
setData(next)
|
||||
setFailure('')
|
||||
@@ -121,7 +131,7 @@ export function QADashboard({
|
||||
abort.abort()
|
||||
if (timer !== undefined) clearTimeout(timer)
|
||||
}
|
||||
}, [query, revision])
|
||||
}, [query, revision, granularity])
|
||||
return (
|
||||
<div className="qa-dashboard-scroll">
|
||||
<QADashboardView data={data} loading={loading} error={error || failure} onRetry={onRetry} />
|
||||
|
||||
@@ -26,7 +26,7 @@ it('draws all eleven panels as a self-contained exportable SVG without HTML exec
|
||||
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={1280} />)
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
for (const title of [
|
||||
'问题总数',
|
||||
'累计总量',
|
||||
'本周新增',
|
||||
'覆盖率',
|
||||
'正确率',
|
||||
|
||||
@@ -544,7 +544,9 @@ export function QADashboardDrawing({
|
||||
unit = (inner - gap * 3) / 4,
|
||||
week = currentQAWeek(new Date(data.week_start)),
|
||||
filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11),
|
||||
heading = `${data.week_start.slice(0, 10)} 起的自然周${data.quality_period ? ` · 质量 ${data.quality_period.month} 月内累计` : ''} · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`,
|
||||
heading = data.period
|
||||
? `${data.period.label} · 全部指标按所选范围统计 · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`
|
||||
: `${data.week_start.slice(0, 10)} 起的自然周${data.quality_period ? ` · 质量 ${data.quality_period.month} 月内累计` : ''} · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`,
|
||||
headingLines = (mobile ? [heading.split(' · ')[0], heading.split(' · ').slice(1).join(' · ')] : [heading]).flatMap(
|
||||
(row) => wrap(row, inner - 16, 10.5)
|
||||
),
|
||||
@@ -633,13 +635,13 @@ export function QADashboardDrawing({
|
||||
background: '#fff',
|
||||
}}
|
||||
>
|
||||
<title>{`问题统计看板 · ${week.year}年第${week.week}周`}</title>
|
||||
<title>{`问题统计看板 · ${data.period ? data.period.label : `${week.year}年第${week.week}周`}`}</title>
|
||||
<rect width={w} height={height} fill="#fff" />
|
||||
<text x={pad + 6} y={27} fontSize={mobile ? 17 : 21} fontWeight={700} fill={ink}>
|
||||
问题统计看板
|
||||
</text>
|
||||
<text x={w - pad - 6} y={27} textAnchor="end" fontSize={12} fill={muted}>
|
||||
{week.year} · W{String(week.week).padStart(2, '0')}
|
||||
{data.period ? data.period.label : `${week.year} · W${String(week.week).padStart(2, '0')}`}
|
||||
</text>
|
||||
{headingLines.map((row, index) => (
|
||||
<Text key={index} x={pad + 6} y={46 + index * 14} width={inner - 16} size={10.5} fill={muted} value={row} />
|
||||
@@ -649,37 +651,45 @@ export function QADashboardDrawing({
|
||||
) : null}
|
||||
<Metric
|
||||
box={metrics[0]}
|
||||
title="问题总数"
|
||||
title="累计总量"
|
||||
en="Total Issues"
|
||||
id="total"
|
||||
value={data.total_issues}
|
||||
tint="#fff4e2"
|
||||
color="#c69b00"
|
||||
subtitle="所选周截止前累计"
|
||||
subtitle={data.period ? `截至 ${data.end.slice(0, 10)} 累计` : '所选周截止前累计'}
|
||||
/>
|
||||
<Metric
|
||||
box={metrics[1]}
|
||||
title="本周新增"
|
||||
en="New This week"
|
||||
title={data.period ? '本期新增' : '本周新增'}
|
||||
en="New This Period"
|
||||
id="new-week"
|
||||
value={data.new_this_week}
|
||||
value={data.period_issues ?? data.new_this_week}
|
||||
tint="#ececff"
|
||||
color="#4056d6"
|
||||
subtitle="所选自然周"
|
||||
subtitle={
|
||||
data.period
|
||||
? `${
|
||||
data.prev_period_issues === undefined
|
||||
? data.period.label
|
||||
: `${data.period.label} · 上期 ${data.prev_period_issues} 条`
|
||||
}`
|
||||
: '所选自然周'
|
||||
}
|
||||
/>
|
||||
<Gauge
|
||||
box={metrics[2]}
|
||||
title="覆盖率"
|
||||
en={`Coverage Rate${data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
||||
en={`Coverage Rate${data.period ? ` · ${data.period.label}` : data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
||||
id="coverage"
|
||||
rate={data.monthly_quality?.coverage ?? data.quality.rates.coverage}
|
||||
rate={data.period_quality?.coverage ?? data.monthly_quality?.coverage ?? data.quality.rates.coverage}
|
||||
/>
|
||||
<Gauge
|
||||
box={metrics[3]}
|
||||
title="正确率"
|
||||
en={`Accuracy Rate${data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
||||
en={`Accuracy Rate${data.period ? ` · ${data.period.label}` : data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
||||
id="accuracy"
|
||||
rate={data.monthly_quality?.correctness ?? data.quality.rates.correctness}
|
||||
rate={data.period_quality?.correctness ?? data.monthly_quality?.correctness ?? data.quality.rates.correctness}
|
||||
/>
|
||||
<Pie box={pie} points={data.issue_types} />
|
||||
<Products box={products} points={data.products} />
|
||||
|
||||
+105
-23
@@ -7,6 +7,7 @@ import './qaOps.css'
|
||||
import { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering'
|
||||
import { QARegionalStatistics } from './QADepartmentStatistics'
|
||||
import { QADashboard } from './QADashboard'
|
||||
import type { DashboardGranularity } from './qaDashboardData'
|
||||
import { QAWeekly } from './QAWeekly'
|
||||
import { QAInlineFields } from './QAInlineFields'
|
||||
import { QAHeaderFieldFilter, useQAFieldFilterOptions } from './QAFieldFilters'
|
||||
@@ -410,10 +411,37 @@ export function QAOperationsView(props: ViewProps) {
|
||||
)
|
||||
}
|
||||
|
||||
type QARangeKind = 'week' | 'month' | 'custom'
|
||||
const beijingInput = (now = new Date()) => new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 16)
|
||||
function monthInputValue(now = new Date()) {
|
||||
return beijingInput(now).slice(0, 7)
|
||||
}
|
||||
function monthQueryRange(month: string, now = new Date()) {
|
||||
const [year, monthNumber] = month.split('-').map(Number)
|
||||
if (!Number.isInteger(year) || !Number.isInteger(monthNumber) || monthNumber < 1 || monthNumber > 12)
|
||||
throw new Error('月份无效')
|
||||
const start = `${month}-01T00:00`
|
||||
const nextYear = monthNumber === 12 ? year + 1 : year
|
||||
const nextMonth = monthNumber === 12 ? 1 : monthNumber + 1
|
||||
const end = `${nextYear}-${String(nextMonth).padStart(2, '0')}-01T00:00`
|
||||
const current = beijingInput(now)
|
||||
const bounded = end > current ? current : end
|
||||
if (bounded <= start) throw new Error('该月份尚未开始,请选择已开始的时间范围')
|
||||
return { start, end: bounded }
|
||||
}
|
||||
|
||||
function initialDraft() {
|
||||
const current = currentQAWeek()
|
||||
const { year, week, start, end } = qaWeekQueryRange(current.year, current.week)
|
||||
return { year, week: week as number | null, start, end, keyword: '' }
|
||||
return {
|
||||
kind: 'week' as QARangeKind,
|
||||
year,
|
||||
week: week as number | null,
|
||||
month: monthInputValue(),
|
||||
start,
|
||||
end,
|
||||
keyword: '',
|
||||
}
|
||||
}
|
||||
|
||||
export function QAOperations() {
|
||||
@@ -425,6 +453,7 @@ export function QAOperations() {
|
||||
const auth = useOptionalAuth()
|
||||
const canRead = auth?.identity?.role === 'admin'
|
||||
const [draft, setDraft] = useState(initialDraft)
|
||||
const [granularity, setGranularity] = useState<DashboardGranularity>('week')
|
||||
const [filters, setFilters] = useState<NonNullable<QAQuery['filters']>>({})
|
||||
const [exporting, setExporting] = useState(false),
|
||||
[exportError, setExportError] = useState('')
|
||||
@@ -452,6 +481,7 @@ export function QAOperations() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!canRead || query) return
|
||||
setGranularity(draft.kind)
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(draft.start),
|
||||
end: qaDateTimeToISO(draft.end),
|
||||
@@ -551,6 +581,7 @@ export function QAOperations() {
|
||||
end = qaDateTimeToISO(draft.end)
|
||||
if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间')
|
||||
if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围')
|
||||
setGranularity(draft.kind)
|
||||
setQuery({ start, end, keyword: draft.keyword, cursor: '', filters: { ...filters } })
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '时间格式无效')
|
||||
@@ -633,33 +664,83 @@ export function QAOperations() {
|
||||
<>
|
||||
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
|
||||
<form className="qa-ops-query" onSubmit={submit}>
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
filters: { ...filters },
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) =>
|
||||
setDraft((old) =>
|
||||
week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) }
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label>
|
||||
统计范围
|
||||
<select
|
||||
aria-label="统计范围"
|
||||
value={draft.kind}
|
||||
onChange={(event) => {
|
||||
const kind = event.target.value as QARangeKind
|
||||
if (kind === 'week') {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
} else if (kind === 'month') {
|
||||
const month = draft.month || monthInputValue()
|
||||
try {
|
||||
const range = monthQueryRange(month)
|
||||
setDraft({ ...draft, kind, month, week: null, ...range })
|
||||
} catch {
|
||||
setDraft({ ...draft, kind, month, week: null })
|
||||
}
|
||||
} else {
|
||||
setDraft({ ...draft, kind })
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="week">按周</option>
|
||||
<option value="month">按月</option>
|
||||
<option value="custom">自定义</option>
|
||||
</select>
|
||||
</label>
|
||||
{draft.kind === 'week' ? (
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
filters: { ...filters },
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) =>
|
||||
setDraft((old) =>
|
||||
week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) }
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{draft.kind === 'month' ? (
|
||||
<label>
|
||||
月份
|
||||
<input
|
||||
type="month"
|
||||
aria-label="统计月份"
|
||||
value={draft.month}
|
||||
max={monthInputValue()}
|
||||
onChange={(event) => {
|
||||
const month = event.target.value
|
||||
try {
|
||||
const range = monthQueryRange(month)
|
||||
setDraft({ ...draft, month, week: null, ...range })
|
||||
} catch {
|
||||
setDraft({ ...draft, month })
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<label>
|
||||
开始时间(北京时间)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.start}
|
||||
onChange={(e) => setDraft({ ...draft, start: e.target.value, week: null })}
|
||||
onChange={(e) => setDraft({ ...draft, start: e.target.value, week: null, kind: 'custom' })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
@@ -668,7 +749,7 @@ export function QAOperations() {
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.end}
|
||||
onChange={(e) => setDraft({ ...draft, end: e.target.value, week: null })}
|
||||
onChange={(e) => setDraft({ ...draft, end: e.target.value, week: null, kind: 'custom' })}
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-ops-keyword">
|
||||
@@ -729,6 +810,7 @@ export function QAOperations() {
|
||||
) : view === 'dashboard' ? (
|
||||
<QADashboard
|
||||
query={query}
|
||||
granularity={granularity}
|
||||
error={error}
|
||||
revision={qualityRevision}
|
||||
onRetry={() => {
|
||||
|
||||
@@ -104,6 +104,21 @@ describe('reconciliation findings', () => {
|
||||
const failed = renderToStaticMarkup(<ReconciliationFindingsView {...props} error="读取对账批次失败" />)
|
||||
expect(failed).toContain('读取对账批次失败')
|
||||
})
|
||||
it('translates a failed batch code instead of rendering the internal code', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ReconciliationFindingsView
|
||||
{...props}
|
||||
runs={{
|
||||
items: [{ ...run, state: 'failed', error_code: 'remote_unavailable' }],
|
||||
total: 1,
|
||||
limit: 20,
|
||||
offset: 0,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('测试知识库连接失败')
|
||||
expect(html).not.toContain('remote_unavailable')
|
||||
})
|
||||
it('links a finding to WeKnora when the backend supplies a URL', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<FindingDetail
|
||||
@@ -117,19 +132,33 @@ describe('reconciliation findings', () => {
|
||||
})
|
||||
|
||||
describe('ServiceStrip queue availability', () => {
|
||||
const overview = (queues: MonitorOverview['weknora_queues']) =>
|
||||
({ weknora_queues: queues, health: [] }) as unknown as MonitorOverview
|
||||
const overview = (queues: MonitorOverview['weknora_queues'], queueError?: string) =>
|
||||
({ weknora_queues: queues, weknora_queue_error: queueError, health: [] }) as unknown as MonitorOverview
|
||||
|
||||
it('states an unavailable queue instead of rendering 0 waiting · 0 active', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ServiceStrip
|
||||
overview={overview({ available: false, queues_error: true, workers_error: false, queues: [], timestamp: 0 })}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('队列不可用')
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_unavailable')} />)
|
||||
expect(html).toContain('未配置知识库绑定或绑定不可用')
|
||||
expect(html).not.toContain('0 等待')
|
||||
})
|
||||
|
||||
it('tells the operator to authorize the missing permission', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_key_forbidden')} />)
|
||||
expect(html).toContain('当前 Key 缺少平台运行时读权限')
|
||||
expect(html).not.toContain('连不上 WeKnora')
|
||||
expect(html).not.toContain('runtime_key_forbidden')
|
||||
})
|
||||
|
||||
it('reports an unreachable instance instead of a missing key', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_unreachable')} />)
|
||||
expect(html).toContain('连不上 WeKnora')
|
||||
expect(html).not.toContain('缺少平台运行时读权限')
|
||||
})
|
||||
|
||||
it('falls back to a neutral sentence for an unknown reason', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null)} />)
|
||||
expect(html).toContain('队列暂不可用')
|
||||
})
|
||||
|
||||
it('prints queue depth when the queue is available', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ServiceStrip
|
||||
|
||||
@@ -7,7 +7,8 @@ import type {
|
||||
ReconciliationProgress,
|
||||
ReconciliationRunPage,
|
||||
} from './reconciliationApi'
|
||||
import { fetchReconciliationProgress, ReconciliationRequestError } from './reconciliationApi'
|
||||
import { fetchReconciliationProgress } from './reconciliationApi'
|
||||
import { reconciliationErrorText, reconciliationFailureText, reconciliationStageText } from './reconciliationMessages'
|
||||
import './monitorWorkbench.css'
|
||||
|
||||
const time = (value: string | null | undefined) =>
|
||||
@@ -49,6 +50,7 @@ interface FindingsProps {
|
||||
busy: boolean
|
||||
canOperate: boolean
|
||||
canRemove: boolean
|
||||
bindingMissing?: boolean
|
||||
error: string
|
||||
message: string
|
||||
onTab: (tab: 'findings' | 'platform') => void
|
||||
@@ -67,6 +69,7 @@ interface FindingsProps {
|
||||
// weknora_queues; an unavailable queue is stated, never rendered as a zero.
|
||||
export function ServiceStrip({ overview }: { overview: MonitorOverview | null }) {
|
||||
const queue = overview?.weknora_queues
|
||||
const queueError = overview?.weknora_queue_error
|
||||
const ready = overview?.health.filter((item) => item.readiness === 'ready').length
|
||||
const attention = overview?.health.filter(
|
||||
(item) => item.applicable && item.configured && item.readiness !== 'ready'
|
||||
@@ -81,7 +84,7 @@ export function ServiceStrip({ overview }: { overview: MonitorOverview | null })
|
||||
{queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行
|
||||
</b>
|
||||
) : (
|
||||
<b className="monitor-muted">未配置只读 Key 或队列不可用</b>
|
||||
<b className="monitor-muted">{queueError ? reconciliationFailureText(queueError) : '队列暂不可用'}</b>
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
@@ -152,7 +155,7 @@ export function ReconciliationFindingsView(p: FindingsProps) {
|
||||
</select>
|
||||
</label>
|
||||
{p.canOperate ? (
|
||||
<button className="primary" disabled={p.busy || !p.selectedKB} onClick={p.onCreate}>
|
||||
<button className="primary" disabled={p.busy || (!p.selectedKB && !p.bindingMissing)} onClick={p.onCreate}>
|
||||
{p.busy ? '提交中…' : '立即对账'}
|
||||
</button>
|
||||
) : (
|
||||
@@ -164,7 +167,7 @@ export function ReconciliationFindingsView(p: FindingsProps) {
|
||||
<p className="monitor-muted">
|
||||
{time(run.started_at)} · {run.trigger === 'schedule' ? '定时' : '手动'} · 台账 {run.ledger_count} 条 ·
|
||||
库内 {run.kb_count} 条{run.window_overlapped ? ' · 与整库作业重叠,R1/R2 待确认' : ''}
|
||||
{run.error_code ? ` · 失败:${run.error_code}` : ''}
|
||||
{run.error_code ? ` · 失败:${reconciliationFailureText(run.error_code)}` : ''}
|
||||
</p>
|
||||
<div className="monitor-diff-counts">
|
||||
{countKeys.map((key) => (
|
||||
@@ -369,11 +372,7 @@ export function WeKnoraProgress({
|
||||
.catch((err) => {
|
||||
if (controller.signal.aborted) return
|
||||
setProgress(null)
|
||||
if (err instanceof ReconciliationRequestError && err.code === 'runtime_read_unavailable') {
|
||||
setError('未配置 WeKnora 只读 Key,无法读取实时处理详情。')
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : '读取 WeKnora 处理详情失败')
|
||||
}
|
||||
setError(reconciliationErrorText(err))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
@@ -411,7 +410,7 @@ export function WeKnoraProgress({
|
||||
{progress.stages.map((stage) => (
|
||||
<li key={`${stage.name}-${stage.status}`}>
|
||||
<b>{stage.name}</b> {stage.status}
|
||||
{stage.error_code ? ` · ${stage.error_code}` : ''}
|
||||
{stage.error_code ? ` · ${reconciliationStageText(stage.error_code)}` : ''}
|
||||
{stage.finished_at ? ` · ${time(stage.finished_at)}` : ''}
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -19,7 +19,7 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
describe('WeKnora progress drawer block', () => {
|
||||
it('degrades to a read-only key message on 503', async () => {
|
||||
it('degrades to a binding message on 503', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
@@ -30,7 +30,40 @@ describe('WeKnora progress drawer block', () => {
|
||||
)
|
||||
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
|
||||
expect(container.textContent).toContain('未配置知识库绑定或绑定不可用')
|
||||
})
|
||||
it('names the missing permission when the key is rejected', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_key_forbidden', code: 'runtime_key_forbidden' }), {
|
||||
status: 502,
|
||||
})
|
||||
)
|
||||
)
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<WeKnoraProgress documentID="doc-1" weknoraURL="https://weknora.test/platform/knowledge-bases/kb-1" />
|
||||
)
|
||||
)
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('当前 Key 缺少平台运行时读权限')
|
||||
expect(container.textContent).not.toContain('runtime_key_forbidden')
|
||||
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
|
||||
})
|
||||
it('says the instance is unreachable instead of blaming the key', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_unreachable', code: 'runtime_unreachable' }), {
|
||||
status: 502,
|
||||
})
|
||||
)
|
||||
)
|
||||
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('连不上 WeKnora')
|
||||
expect(container.textContent).not.toContain('缺少平台运行时读权限')
|
||||
})
|
||||
it('shows stages and failures when available', async () => {
|
||||
vi.stubGlobal(
|
||||
@@ -43,7 +76,14 @@ describe('WeKnora progress drawer block', () => {
|
||||
parse_status: 'failed',
|
||||
ingestion_status: 'failed',
|
||||
wiki_status: 'none',
|
||||
stages: [{ name: 'parse', status: 'failed', error_code: 'E1', finished_at: '2026-12-01T00:00:00Z' }],
|
||||
stages: [
|
||||
{
|
||||
name: 'parse',
|
||||
status: 'failed',
|
||||
error_code: 'remote_unavailable',
|
||||
finished_at: '2026-12-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
failures: [
|
||||
{ task_type: 'parse', fail_count: 2, failed_at: '2026-12-01T00:00:00Z', last_error: '解析失败' },
|
||||
],
|
||||
@@ -60,5 +100,7 @@ describe('WeKnora progress drawer block', () => {
|
||||
expect(container.textContent).toContain('parse')
|
||||
expect(container.textContent).toContain('解析失败')
|
||||
expect(container.textContent).toContain('failed')
|
||||
expect(container.textContent).toContain('测试知识库连接失败')
|
||||
expect(container.textContent).not.toContain('remote_unavailable')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -892,6 +892,36 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
|
||||
expect(known).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/)
|
||||
})
|
||||
|
||||
it('生产生效版本就是当前测试封存时,主按钮是不可点的“已同步”,前进方向换成重新封存', () => {
|
||||
const html = render({
|
||||
sync: { canSign: true, pendingGrant: false, onGrant: vi.fn(), canStart: true, pending: false, onStart: vi.fn() },
|
||||
overview: {
|
||||
...overview,
|
||||
gate: { sync_allowed: true, reasons: [] },
|
||||
production: {
|
||||
state: 'known',
|
||||
version: {
|
||||
id: 'v-same',
|
||||
kind: 'production_effective',
|
||||
snapshot_id: internalSnapshot.snapshot_id,
|
||||
version_label: '',
|
||||
source_job_id: 'libsync-1',
|
||||
evidence: {},
|
||||
created_by: 'admin',
|
||||
created_at: '2026-10-29T09:00:00Z',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
// 闸口放行也不许再把同一份内容同步一遍
|
||||
expect(html).not.toContain('▶ 启动同步')
|
||||
expect(html).toMatch(/<button[^>]*class="rel-primary rel-synced"[^>]*disabled[^>]*>✓ 已同步/)
|
||||
expect(html).toContain('生产已是当前测试封存')
|
||||
expect(html).toMatch(/class="rel-secondary"[^>]*>重新封存测试版本/)
|
||||
// 已同步时签发授权没有意义,不出现签发入口
|
||||
expect(html).not.toContain('签发同步授权(30 分钟)')
|
||||
})
|
||||
|
||||
it('闸口全满足时“启动同步”真的可点,并给出执行说明', () => {
|
||||
const html = render({
|
||||
sync: { canSign: false, pendingGrant: false, onGrant: vi.fn(), canStart: true, pending: false, onStart: vi.fn() },
|
||||
|
||||
+76
-69
@@ -1,4 +1,3 @@
|
||||
import { LegacySourceAssociation } from './LegacySourceAssociation'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
createLibraryRestoreAuthorization,
|
||||
@@ -981,10 +980,6 @@ interface ReadyProps {
|
||||
prebackup: LibraryOverview['prebackup']
|
||||
gate: LibraryOverview['gate']
|
||||
authorization: LibraryOverview['authorization']
|
||||
canCapture: boolean
|
||||
canWrite: boolean
|
||||
pendingCapture: boolean
|
||||
onCapture: () => void
|
||||
onOpen: () => void
|
||||
sync: ReleaseSyncActions
|
||||
baseline: ReleaseBaselineActions
|
||||
@@ -1006,16 +1001,12 @@ function ReadyBody({
|
||||
sync,
|
||||
baseline,
|
||||
verification,
|
||||
canCapture,
|
||||
canWrite,
|
||||
pendingCapture,
|
||||
onCapture,
|
||||
onOpen,
|
||||
}: ReadyProps) {
|
||||
const snapshot = view.snapshot
|
||||
return (
|
||||
<>
|
||||
<div className="rel-grid">
|
||||
<div>
|
||||
<ProtectionCard
|
||||
production={production}
|
||||
productionNote={productionNote}
|
||||
@@ -1043,17 +1034,6 @@ function ReadyBody({
|
||||
</header>
|
||||
<StageBar view={view} />
|
||||
</div>
|
||||
<div className="rel-panel rel-seal">
|
||||
<div>
|
||||
<h2>测试库封存</h2>
|
||||
<p>
|
||||
{snapshot
|
||||
? `最近一次封存 ${stamp(snapshot.created_at)},快照 ${snapshot.snapshot_id.slice(0, 12)}。封存只读测试库,不影响生产。`
|
||||
: '还没有测试库封存。封存会短暂停住测试写入者,导出完整版本后恢复。'}
|
||||
</p>
|
||||
</div>
|
||||
<span className="rel-hint">{canCapture ? '封存入口在页面顶部“下一步”。' : captureHint(view, canWrite)}</span>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1884,7 +1864,22 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
|
||||
const sealed = Boolean(view.snapshot)
|
||||
const authorizationActive = authorization.state === 'active'
|
||||
// 主按钮永远是"同步"或"查看当前任务";准备动作(封存/基线/恢复验证/授权)
|
||||
// 生产生效版本就是这份测试封存时,再同步只会把同一份内容重写一遍(还要停机维护),
|
||||
// 所以主按钮改成不可点的"已同步",前进方向换成封存新版本。闸口放行与否不影响这个判断。
|
||||
const inSync =
|
||||
!runningJob &&
|
||||
productionClass === 'known' &&
|
||||
Boolean(target?.snapshot_id) &&
|
||||
production?.version?.snapshot_id === target?.snapshot_id
|
||||
const captureAction = {
|
||||
label: pendingCapture ? '封存中…' : sealed ? '重新封存测试版本' : '封存测试版本',
|
||||
hint: sealed
|
||||
? '生产已是当前测试封存,无需同步;测试库有新内容时先封存新版本。'
|
||||
: '还没有测试库封存。封存只读导出测试库(短暂停住测试写入者),不影响生产。',
|
||||
disabled: pendingCapture,
|
||||
run: onCapture,
|
||||
}
|
||||
// 主按钮永远是"同步"、"已同步"或"查看当前任务";准备动作(封存/基线/授权)
|
||||
// 作为次要按钮按状态出现,页面因此只有一个前进方向。
|
||||
const primaryAction = runningJob
|
||||
? {
|
||||
@@ -1893,38 +1888,44 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
disabled: false,
|
||||
run: () => document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }),
|
||||
}
|
||||
: {
|
||||
label: sync.pending ? '投递中…' : '▶ 启动同步',
|
||||
hint: sync.canStart
|
||||
? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。'
|
||||
: `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`,
|
||||
disabled: !sync.canStart || sync.pending,
|
||||
run: sync.onStart,
|
||||
}
|
||||
: inSync
|
||||
? {
|
||||
label: '✓ 已同步',
|
||||
hint: canCapture ? captureAction.hint : `生产已是当前测试封存,无需同步。${captureHint(view, canWrite)}`,
|
||||
disabled: true,
|
||||
run: () => {},
|
||||
}
|
||||
: {
|
||||
label: sync.pending ? '投递中…' : '▶ 启动同步',
|
||||
hint: sync.canStart
|
||||
? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。'
|
||||
: `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`,
|
||||
disabled: !sync.canStart || sync.pending,
|
||||
run: sync.onStart,
|
||||
}
|
||||
const prepAction = !sealed
|
||||
? canCapture
|
||||
? {
|
||||
label: pendingCapture ? '封存中…' : '封存测试版本',
|
||||
hint: '只读导出测试库,生成一份可发布的整库版本。',
|
||||
disabled: pendingCapture,
|
||||
run: onCapture,
|
||||
}
|
||||
? captureAction
|
||||
: { label: '尚无封存', hint: captureHint(view, canWrite), disabled: true, run: () => {} }
|
||||
: productionClass === 'nonempty' && baseline.canStart
|
||||
? {
|
||||
label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)',
|
||||
hint: '生产目标非空但还没有权威版本,先登记一份基线。',
|
||||
disabled: baseline.pending,
|
||||
run: baseline.onStart,
|
||||
}
|
||||
: !authorizationActive && sync.canSign
|
||||
? {
|
||||
label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)',
|
||||
hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。',
|
||||
disabled: sync.pendingGrant,
|
||||
run: sync.onGrant,
|
||||
}
|
||||
: inSync
|
||||
? canCapture
|
||||
? captureAction
|
||||
: null
|
||||
: productionClass === 'nonempty' && baseline.canStart
|
||||
? {
|
||||
label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)',
|
||||
hint: '生产目标非空但还没有权威版本,先登记一份基线。',
|
||||
disabled: baseline.pending,
|
||||
run: baseline.onStart,
|
||||
}
|
||||
: !authorizationActive && sync.canSign
|
||||
? {
|
||||
label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)',
|
||||
hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。',
|
||||
disabled: sync.pendingGrant,
|
||||
run: sync.onGrant,
|
||||
}
|
||||
: null
|
||||
|
||||
const productionText =
|
||||
productionClass === 'known' && production?.version
|
||||
@@ -1988,8 +1989,13 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
<div className="rel-panel rel-status">
|
||||
<p className="rel-scope-state">
|
||||
{scopeName(scope)} ·{' '}
|
||||
{active ? `${jobKindText(view.job?.kind)}进行中` : sealed ? '已封存,同步按条件放行' : '尚无测试封存'}
|
||||
{sealed ? '(需要新版本时点上方“封存测试版本”)' : ''}
|
||||
{active
|
||||
? `${jobKindText(view.job?.kind)}进行中`
|
||||
: inSync
|
||||
? '生产已是当前测试封存'
|
||||
: sealed
|
||||
? '已封存,同步按条件放行'
|
||||
: '尚无测试封存'}
|
||||
</p>
|
||||
<dl className="rel-status-grid">
|
||||
<div>
|
||||
@@ -1998,6 +2004,15 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
{sealed ? `快照 ${view.snapshot!.snapshot_id.slice(0, 12)}` : '尚无'}
|
||||
</dd>
|
||||
<small>{sealed ? stamp(view.snapshot!.created_at) : '先封存测试版本'}</small>
|
||||
{/* 封存入口跟着"测试封存"这一格走:主操作区已经放了封存按钮时不再重复;
|
||||
不能封存时把接口给的真实原因写在这里,而不是只藏在按钮 title 里。 */}
|
||||
{runningJob || prepAction === captureAction ? null : canCapture ? (
|
||||
<button type="button" className="rel-link rel-cell-action" onClick={onCapture} disabled={pendingCapture}>
|
||||
{captureAction.label}
|
||||
</button>
|
||||
) : (
|
||||
<small className="rel-unknown">{captureHint(view, canWrite)}</small>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<dt>生产当前</dt>
|
||||
@@ -2010,9 +2025,11 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
<small>
|
||||
{authorizationActive
|
||||
? `有效至 ${stamp(authorization.expires_at ?? '')}`
|
||||
: sync.canSign
|
||||
? '可在下方签发'
|
||||
: '需管理员签发'}
|
||||
: inSync
|
||||
? '已同步,无需签发'
|
||||
: sync.canSign
|
||||
? '可在下方签发'
|
||||
: '需管理员签发'}
|
||||
</small>
|
||||
</div>
|
||||
<div>
|
||||
@@ -2045,7 +2062,7 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="rel-primary"
|
||||
className={inSync ? 'rel-primary rel-synced' : 'rel-primary'}
|
||||
onClick={primaryAction.run}
|
||||
disabled={primaryAction.disabled}
|
||||
title={primaryAction.hint}
|
||||
@@ -2056,12 +2073,13 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
版本与快照
|
||||
</button>
|
||||
</div>
|
||||
{gate.reasons.length > 0 ? (
|
||||
{/* 已同步时闸口缺项(多半只是授权过期)跟下一步无关:不催、不自动展开,缺项仍在折叠区里可查。 */}
|
||||
{gate.reasons.length > 0 && !inSync ? (
|
||||
<p className="rel-hint">还差 {gate.reasons.length} 项条件,展开“发布前检查”查看原因。</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<details className="rel-check" id="rel-check" open={gate.reasons.length > 0}>
|
||||
<details className="rel-check" id="rel-check" open={gate.reasons.length > 0 && !inSync}>
|
||||
<summary>
|
||||
发布前检查
|
||||
{gate.reasons.length > 0 ? `(${gate.reasons.length} 项未满足)` : '(已满足)'}
|
||||
@@ -2127,10 +2145,6 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
sync={sync}
|
||||
baseline={baseline}
|
||||
verification={verification}
|
||||
canCapture={canCapture}
|
||||
canWrite={canWrite}
|
||||
pendingCapture={pendingCapture}
|
||||
onCapture={onCapture}
|
||||
onOpen={() => onDrawer(true)}
|
||||
/>
|
||||
)}
|
||||
@@ -2560,13 +2574,6 @@ export function ReleaseTargets() {
|
||||
onCapture={() => void startCapture()}
|
||||
onRecover={(windowJobID) => void recover(windowJobID)}
|
||||
/>
|
||||
<LegacySourceAssociation
|
||||
key={scope}
|
||||
scope={scope}
|
||||
snapshots={page?.snapshots ?? []}
|
||||
admin={role === 'admin'}
|
||||
onBound={() => load()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -228,8 +228,8 @@ describe('SystemSettingsView', () => {
|
||||
)
|
||||
for (const text of [
|
||||
'知识库绑定',
|
||||
'测试 090',
|
||||
'生产 090',
|
||||
'测试知识库',
|
||||
'生产知识库',
|
||||
'正在读取知识库绑定…',
|
||||
'连接与绑定诊断',
|
||||
'测试 WeKnora',
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import type { Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { WeKnoraMonitor } from './WeKnoraMonitor'
|
||||
import { AuthContext } from './auth'
|
||||
import { reconciliationMessages } from './reconciliationMessages'
|
||||
|
||||
const binding = (environment: 'test' | 'production', configured: boolean) => ({
|
||||
environment,
|
||||
revision: 1,
|
||||
base_url: configured ? `https://${environment}.weknora.example` : '',
|
||||
key_configured: configured,
|
||||
key_source: configured ? 'sealed' : '',
|
||||
key_tail: '',
|
||||
internal_kb_id: '',
|
||||
internal_kb_name: '',
|
||||
external_kb_id: '',
|
||||
external_kb_name: '',
|
||||
verification: configured ? 'verified' : 'not_configured',
|
||||
checked_at: null,
|
||||
updated_by: 'admin',
|
||||
updated_at: null,
|
||||
source: 'web',
|
||||
storage_ready: true,
|
||||
replanned: 0,
|
||||
retired_duplicates: 0,
|
||||
internal_fallback: '',
|
||||
external_fallback: '',
|
||||
frozen: 0,
|
||||
retargetable: 0,
|
||||
})
|
||||
|
||||
const auth = {
|
||||
identity: {
|
||||
id: 'admin-1',
|
||||
username: 'admin',
|
||||
display_name: 'admin',
|
||||
role: 'admin' as const,
|
||||
must_change_password: false,
|
||||
},
|
||||
ready: true,
|
||||
login: async () => null,
|
||||
logout: async () => {},
|
||||
changePassword: async () => null,
|
||||
signedOut: 0,
|
||||
notifySignedOut: () => {},
|
||||
}
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
const flush = async () => {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
})
|
||||
}
|
||||
|
||||
const json = (value: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json' } })
|
||||
|
||||
beforeEach(() => {
|
||||
;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const renderMonitor = async () => {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<AuthContext.Provider value={auth}>
|
||||
<WeKnoraMonitor />
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
)
|
||||
await flush()
|
||||
await flush()
|
||||
}
|
||||
|
||||
describe('monitor binding preflight', () => {
|
||||
it('shows the test-binding reason before the KB is selectable and never posts a run', async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
|
||||
const url = String(input)
|
||||
if (url === '/api/v1/kb-bindings') {
|
||||
return json({
|
||||
data: {
|
||||
environments: [binding('test', false), binding('production', true)],
|
||||
storage_ready: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.startsWith('/api/v1/reconciliation/runs')) {
|
||||
return json({ data: { items: [], total: 0, limit: 20, offset: 0 } })
|
||||
}
|
||||
return json({ error: 'not available in this fixture' }, 503)
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await renderMonitor()
|
||||
|
||||
expect(container.textContent).toContain(reconciliationMessages.bindingMissing)
|
||||
const create = [...container.querySelectorAll('button')].find((button) => button.textContent?.trim() === '立即对账')
|
||||
expect(create).toBeTruthy()
|
||||
expect(create?.hasAttribute('disabled')).toBe(false)
|
||||
|
||||
await act(async () => create!.click())
|
||||
await flush()
|
||||
expect(container.textContent).toContain(reconciliationMessages.bindingMissing)
|
||||
const posts = fetchMock.mock.calls.filter(
|
||||
([url, init]) => String(url).includes('/api/v1/reconciliation/runs') && init?.method === 'POST'
|
||||
)
|
||||
expect(posts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('keeps the not-enabled reason when the service is unwired and the binding is also missing', async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
|
||||
const url = String(input)
|
||||
if (url === '/api/v1/kb-bindings') {
|
||||
return json({
|
||||
data: {
|
||||
environments: [binding('test', false), binding('production', false)],
|
||||
storage_ready: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.startsWith('/api/v1/reconciliation/runs')) {
|
||||
return json({ error: 'reconciliation_not_configured', code: 'reconciliation_not_configured' }, 503)
|
||||
}
|
||||
return json({ error: 'not available in this fixture' }, 503)
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await renderMonitor()
|
||||
|
||||
expect(container.textContent).toContain(reconciliationMessages.notEnabled)
|
||||
expect(container.textContent).not.toContain(reconciliationMessages.bindingMissing)
|
||||
|
||||
const create = [...container.querySelectorAll('button')].find((button) => button.textContent?.trim() === '立即对账')
|
||||
expect(create?.hasAttribute('disabled')).toBe(false)
|
||||
await act(async () => create!.click())
|
||||
await flush()
|
||||
expect(container.textContent).toContain(reconciliationMessages.notEnabled)
|
||||
expect(container.textContent).not.toContain(reconciliationMessages.bindingMissing)
|
||||
})
|
||||
})
|
||||
@@ -62,7 +62,7 @@ describe('platform task drawer', () => {
|
||||
)
|
||||
await act(async () => root.render(<TaskDetail item={item} onClose={vi.fn()} />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
|
||||
expect(container.textContent).toContain('未配置知识库绑定或绑定不可用')
|
||||
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
+65
-14
@@ -14,6 +14,7 @@ import {
|
||||
import type { MonitorFilters, MonitorTask, MonitorTaskPage } from './monitorTasks'
|
||||
import { requeueJobFailure, retryPublicationsBatch, startPublicationRemoval } from './testPublications'
|
||||
import { fetchActiveUISettings, settingsRefreshDelays } from './uiSettings'
|
||||
import { fetchKBBindings } from './knowledgeBaseBindings'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { WorkspaceContextTabsSetter } from './workspaceContext'
|
||||
import { ReconciliationFindingsView, FindingDetail, ServiceStrip, WeKnoraProgress } from './ReconciliationFindings'
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
writebackFinding,
|
||||
} from './reconciliationApi'
|
||||
import type { ReconciliationFinding, ReconciliationFindingPage, ReconciliationRunPage } from './reconciliationApi'
|
||||
import { isTestBindingMissing, reconciliationErrorText, reconciliationMessages } from './reconciliationMessages'
|
||||
import './monitorWorkbench.css'
|
||||
|
||||
const emptyRuns: ReconciliationRunPage = { items: [], total: 0, limit: 20, offset: 0 }
|
||||
@@ -604,10 +606,17 @@ export function WeKnoraMonitor({
|
||||
const [findingFilters, setFindingFilters] = useState<FindingFilters>({ type: '', q: '' })
|
||||
const [findingOffset, setFindingOffset] = useState(0)
|
||||
const [selectedKB, setSelectedKB] = useState('')
|
||||
// 下拉里的候选来自台账(test_publications.test_kb_id),可能包含早已被删掉的
|
||||
// 测试库。默认值必须落在「当前绑定的测试库」上,否则一进页面点立即对账就会
|
||||
// 打在死库上,远端只回 404。
|
||||
const [boundKB, setBoundKB] = useState('')
|
||||
const [bindingReady, setBindingReady] = useState(false)
|
||||
const kbPickedRef = useRef(false)
|
||||
const [findingDetail, setFindingDetail] = useState<ReconciliationFinding | null>(null)
|
||||
const [reconLoading, setReconLoading] = useState(true)
|
||||
const [reconBusy, setReconBusy] = useState(false)
|
||||
const [reconError, setReconError] = useState('')
|
||||
const [bindingError, setBindingError] = useState('')
|
||||
const [reconMessage, setReconMessage] = useState('')
|
||||
const [reconRev, setReconRev] = useState(0)
|
||||
const [overview, setOverview] = useState<MonitorOverview | null>(null),
|
||||
@@ -724,9 +733,32 @@ export function WeKnoraMonitor({
|
||||
return () => c.abort()
|
||||
}, [resRev])
|
||||
useEffect(() => {
|
||||
if (selectedKB || !overview?.knowledge_bases.length) return
|
||||
setSelectedKB(overview.knowledge_bases[0].id)
|
||||
}, [overview, selectedKB])
|
||||
if (kbPickedRef.current || !bindingReady || !overview?.knowledge_bases.length) return
|
||||
const ids = overview.knowledge_bases.map((item) => item.id)
|
||||
setSelectedKB(boundKB && ids.includes(boundKB) ? boundKB : ids[0])
|
||||
}, [overview, bindingReady, boundKB])
|
||||
// 绑定快照与批次列表分开取:批次列表成功会清空 reconError,不能把
|
||||
// 「测试环境未配置」也塞进同一个 state,否则一刷新就消失。
|
||||
useEffect(() => {
|
||||
if (tab !== 'findings') return
|
||||
const c = new AbortController()
|
||||
void fetchKBBindings(c.signal)
|
||||
.then((snapshot) => {
|
||||
if (!c.signal.aborted) {
|
||||
setBoundKB(snapshot.test.internal_kb_id)
|
||||
setBindingReady(true)
|
||||
setBindingError(isTestBindingMissing(snapshot) ? reconciliationMessages.bindingMissing : '')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// 预检失败不阻塞页面:真正触发时仍由批次错误兜底。
|
||||
if (!c.signal.aborted) {
|
||||
setBindingReady(true)
|
||||
setBindingError('')
|
||||
}
|
||||
})
|
||||
return () => c.abort()
|
||||
}, [tab, reconRev])
|
||||
useEffect(() => {
|
||||
if (tab !== 'findings') return
|
||||
const c = new AbortController()
|
||||
@@ -742,7 +774,7 @@ export function WeKnoraMonitor({
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted) {
|
||||
setRuns(emptyRuns)
|
||||
setReconError(e instanceof Error ? e.message : '读取对账批次失败')
|
||||
setReconError(reconciliationErrorText(e))
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -767,7 +799,7 @@ export function WeKnoraMonitor({
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted) {
|
||||
setFindings(emptyFindings)
|
||||
setReconError(e instanceof Error ? e.message : '读取差异清单失败')
|
||||
setReconError(reconciliationErrorText(e))
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -777,20 +809,35 @@ export function WeKnoraMonitor({
|
||||
}, [tab, selectedRunID, findingFilters, findingOffset, reconRev])
|
||||
const createRun = async () => {
|
||||
if (reconBusy) return
|
||||
const kbID = selectedKB || overview?.knowledge_bases[0]?.id || ''
|
||||
if (!kbID) {
|
||||
setReconMessage('请先选择测试知识库')
|
||||
return
|
||||
}
|
||||
setReconBusy(true)
|
||||
setReconMessage('')
|
||||
try {
|
||||
// 未启用优先:服务没接线时,绑定缺失只是次要事实;直接调接口只会
|
||||
// 得到同一个 503,页面应保持「未启用」而不是切换成绑定提示。
|
||||
if (reconError === reconciliationMessages.notEnabled) {
|
||||
setReconMessage(reconciliationMessages.notEnabled)
|
||||
return
|
||||
}
|
||||
// 先判绑定再判 KB:绑定被清空时 overview 可能没有可选库,按钮
|
||||
// 若先要求 selectedKB,用户就永远看不到「测试环境未配置」。
|
||||
const binding = await fetchKBBindings().catch(() => null)
|
||||
if (binding && isTestBindingMissing(binding)) {
|
||||
setBindingError(reconciliationMessages.bindingMissing)
|
||||
setReconMessage(reconciliationMessages.bindingMissing)
|
||||
return
|
||||
}
|
||||
setBindingError('')
|
||||
const kbID = selectedKB || overview?.knowledge_bases[0]?.id || ''
|
||||
if (!kbID) {
|
||||
setReconMessage('请先选择测试知识库')
|
||||
return
|
||||
}
|
||||
const run = await createReconciliationRun(kbID)
|
||||
setSelectedRunID(run.id)
|
||||
setReconMessage('已提交对账;扫描在后台执行,完成后刷新可见。')
|
||||
setReconRev((x) => x + 1)
|
||||
} catch (e) {
|
||||
setReconMessage(e instanceof Error ? e.message : '触发对账失败')
|
||||
setReconMessage(reconciliationErrorText(e))
|
||||
} finally {
|
||||
setReconBusy(false)
|
||||
}
|
||||
@@ -818,7 +865,7 @@ export function WeKnoraMonitor({
|
||||
setReconMessage('处置已受理;状态以服务端读回为准。')
|
||||
setReconRev((x) => x + 1)
|
||||
} catch (e) {
|
||||
setReconMessage(e instanceof Error ? e.message : '处置失败')
|
||||
setReconMessage(reconciliationErrorText(e))
|
||||
} finally {
|
||||
setReconBusy(false)
|
||||
}
|
||||
@@ -919,12 +966,16 @@ export function WeKnoraMonitor({
|
||||
filters={findingFilters}
|
||||
selectedRunID={selectedRunID}
|
||||
selectedKB={selectedKB}
|
||||
kbOptions={(overview?.knowledge_bases || []).map((item) => ({ id: item.id, name: item.name }))}
|
||||
kbOptions={(overview?.knowledge_bases || []).map((item) => ({
|
||||
id: item.id,
|
||||
name: item.id === boundKB ? `${item.name}(当前绑定)` : item.name,
|
||||
}))}
|
||||
loading={reconLoading}
|
||||
busy={reconBusy}
|
||||
canOperate={canOperate}
|
||||
canRemove={canRemove}
|
||||
error={reconError}
|
||||
error={reconError || bindingError}
|
||||
bindingMissing={Boolean(bindingError)}
|
||||
message={reconMessage}
|
||||
onTab={setTab}
|
||||
onSelectRun={(id) => {
|
||||
|
||||
@@ -85,6 +85,8 @@ export interface MonitorOverview {
|
||||
pipeline?: IngestionPipeline
|
||||
health: ServiceHealth[]
|
||||
weknora_queues?: WeKnoraQueues | null
|
||||
/** 队列不可用时后端给出的原因码:runtime_read_unavailable / forbidden / unreachable */
|
||||
weknora_queue_error?: string
|
||||
}
|
||||
export interface MonitorFile {
|
||||
name: string
|
||||
|
||||
+104
-37
@@ -68,6 +68,15 @@ export interface DashboardRegion {
|
||||
frequency: number | null
|
||||
usage_coverage: QualityRate
|
||||
}
|
||||
export type DashboardGranularity = 'day' | 'week' | 'month' | 'custom'
|
||||
export interface DashboardPeriod {
|
||||
kind: DashboardGranularity
|
||||
label: string
|
||||
start: string
|
||||
end: string
|
||||
prev_start: string
|
||||
prev_end: string
|
||||
}
|
||||
export interface QADashboardData {
|
||||
filters?: QAQuery['filters']
|
||||
start: string
|
||||
@@ -91,6 +100,11 @@ export interface QADashboardData {
|
||||
quality_period?: DashboardQualityPeriod
|
||||
monthly_quality?: DashboardStrictQuality
|
||||
calendar_months?: DashboardMonth[]
|
||||
granularity?: DashboardGranularity
|
||||
period?: DashboardPeriod
|
||||
period_issues?: number
|
||||
prev_period_issues?: number
|
||||
period_quality?: DashboardStrictQuality
|
||||
}
|
||||
const bad = (): never => {
|
||||
throw new Error('统计看板响应无效,未展示可能失真的指标')
|
||||
@@ -142,6 +156,9 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
Date.parse(month_start) !== month(Date.parse(end) - 1)
|
||||
)
|
||||
return bad()
|
||||
const granularityRaw = v.granularity
|
||||
if (granularityRaw !== undefined && !['day', 'week', 'month', 'custom'].includes(String(granularityRaw))) return bad()
|
||||
const granularity = granularityRaw === undefined ? undefined : (granularityRaw as DashboardGranularity)
|
||||
const quality = parseQualitySummary({
|
||||
summary: v.quality,
|
||||
start,
|
||||
@@ -155,6 +172,63 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
total_issues = count(v.total_issues),
|
||||
new_this_week = count(v.new_this_week)
|
||||
if (new_this_week > total_issues || quality.total > total_issues) return bad()
|
||||
const monthlySource = 'master_live_calendar_month_v1' as const,
|
||||
monthlyPolicy = 'calendar-month-strict-yes-over-yes-no-v2' as const,
|
||||
nextMonth = (at: number) => {
|
||||
const d = new Date(at + offset)
|
||||
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1) - offset
|
||||
},
|
||||
monthLabel = (at: number) => new Date(at + offset).toISOString().slice(0, 7),
|
||||
strictRates = (raw: Record<string, unknown>): DashboardStrictQuality => {
|
||||
const records = count(raw.records),
|
||||
unjudged = count(raw.unjudged),
|
||||
coverage = parseQualityRate(raw.coverage),
|
||||
correctness = parseQualityRate(raw.correctness)
|
||||
if (
|
||||
records > total_issues ||
|
||||
unjudged > records ||
|
||||
coverage.denominator > records ||
|
||||
correctness.denominator + unjudged > records
|
||||
)
|
||||
return bad()
|
||||
return { records, coverage, correctness, unjudged }
|
||||
}
|
||||
let period: DashboardPeriod | undefined
|
||||
let period_issues: number | undefined
|
||||
let prev_period_issues: number | undefined
|
||||
let period_quality: DashboardStrictQuality | undefined
|
||||
if (granularity) {
|
||||
const p = obj(v.period),
|
||||
kind = p.kind,
|
||||
label = text(p.label),
|
||||
periodStart = stamp(p.start),
|
||||
periodEnd = stamp(p.end),
|
||||
prevStart = stamp(p.prev_start),
|
||||
prevEnd = stamp(p.prev_end)
|
||||
if (
|
||||
kind !== granularity ||
|
||||
!label ||
|
||||
Date.parse(periodStart) !== Date.parse(start) ||
|
||||
Date.parse(periodEnd) !== Date.parse(end) ||
|
||||
Date.parse(prevEnd) !== Date.parse(start) ||
|
||||
Date.parse(prevStart) >= Date.parse(prevEnd)
|
||||
)
|
||||
return bad()
|
||||
period = { kind: granularity, label, start: periodStart, end: periodEnd, prev_start: prevStart, prev_end: prevEnd }
|
||||
period_issues = count(v.period_issues)
|
||||
prev_period_issues = count(v.prev_period_issues)
|
||||
if (period_issues !== new_this_week || period_issues > total_issues) return bad()
|
||||
if (v.period_quality !== undefined) {
|
||||
period_quality = strictRates(obj(v.period_quality))
|
||||
if (period_quality.records !== period_issues) return bad()
|
||||
}
|
||||
} else if (
|
||||
v.period !== undefined ||
|
||||
v.period_issues !== undefined ||
|
||||
v.prev_period_issues !== undefined ||
|
||||
v.period_quality !== undefined
|
||||
)
|
||||
return bad()
|
||||
const regionIDs = new Set<string>(),
|
||||
regionNames = new Set<string>()
|
||||
const regions = list(v.regions).map((raw) => {
|
||||
@@ -189,21 +263,22 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
return { id, name, questions, users, roster_people, frequency, usage_coverage }
|
||||
})
|
||||
if (regions.length !== (organization.region_names?.length ?? 0)) return bad()
|
||||
const daily = list(v.daily).map((raw, i) => {
|
||||
const d = obj(raw),
|
||||
date = text(d.date),
|
||||
n = count(d.count)
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
||||
Date.parse(date + 'T00:00:00+08:00') !== Date.parse(week_start) + i * dayMS
|
||||
)
|
||||
return bad()
|
||||
return { date, count: n }
|
||||
})
|
||||
const dailyAnchor = granularity ? start : week_start,
|
||||
daily = list(v.daily).map((raw, i) => {
|
||||
const d = obj(raw),
|
||||
date = text(d.date),
|
||||
n = count(d.count)
|
||||
if (
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
||||
Date.parse(date + 'T00:00:00+08:00') !== Date.parse(dailyAnchor) + i * dayMS
|
||||
)
|
||||
return bad()
|
||||
return { date, count: n }
|
||||
})
|
||||
if (
|
||||
daily.length < 1 ||
|
||||
daily.length > 7 ||
|
||||
daily.reduce((n, r) => n + r.count, 0) !== new_this_week ||
|
||||
daily.length > (granularity ? 92 : 7) ||
|
||||
daily.reduce((n, r) => n + r.count, 0) !== (granularity ? period_issues : new_this_week) ||
|
||||
Date.parse(daily[daily.length - 1].date + 'T00:00:00+08:00') >= Date.parse(end)
|
||||
)
|
||||
return bad()
|
||||
@@ -335,27 +410,6 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
let quality_period: DashboardQualityPeriod | undefined
|
||||
let monthly_quality: DashboardStrictQuality | undefined
|
||||
let calendar_months: DashboardMonth[] | undefined
|
||||
const monthlySource = 'master_live_calendar_month_v1' as const,
|
||||
monthlyPolicy = 'calendar-month-strict-yes-over-yes-no-v2' as const,
|
||||
nextMonth = (at: number) => {
|
||||
const d = new Date(at + offset)
|
||||
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1) - offset
|
||||
},
|
||||
monthLabel = (at: number) => new Date(at + offset).toISOString().slice(0, 7),
|
||||
strictRates = (raw: Record<string, unknown>): DashboardStrictQuality => {
|
||||
const records = count(raw.records),
|
||||
unjudged = count(raw.unjudged),
|
||||
coverage = parseQualityRate(raw.coverage),
|
||||
correctness = parseQualityRate(raw.correctness)
|
||||
if (
|
||||
records > total_issues ||
|
||||
unjudged > records ||
|
||||
coverage.denominator > records ||
|
||||
correctness.denominator + unjudged > records
|
||||
)
|
||||
return bad()
|
||||
return { records, coverage, correctness, unjudged }
|
||||
}
|
||||
if (
|
||||
v.quality_period !== undefined ||
|
||||
v.monthly_quality !== undefined ||
|
||||
@@ -460,6 +514,11 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
}
|
||||
return {
|
||||
filters: parseQualityFilters(v.filters),
|
||||
granularity,
|
||||
period,
|
||||
period_issues,
|
||||
prev_period_issues,
|
||||
period_quality,
|
||||
quality_period,
|
||||
monthly_quality,
|
||||
calendar_months,
|
||||
@@ -483,7 +542,9 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
frozen_weeks,
|
||||
}
|
||||
}
|
||||
export function liveDashboardQuery(query: QAQuery, now: Date): QAQuery {
|
||||
export function liveDashboardQuery(query: QAQuery, now: Date, granularity?: string): QAQuery {
|
||||
// A custom or single-day range is an explicit slice: never stretch it to "now".
|
||||
if (granularity === 'custom' || granularity === 'day') return query
|
||||
const last = currentQAWeek(new Date(Date.parse(query.end) - 1)),
|
||||
current = currentQAWeek(now)
|
||||
if (
|
||||
@@ -495,7 +556,11 @@ export function liveDashboardQuery(query: QAQuery, now: Date): QAQuery {
|
||||
return query
|
||||
return { ...query, end: now.toISOString() }
|
||||
}
|
||||
export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Promise<QADashboardData> {
|
||||
export async function fetchQADashboard(
|
||||
query: QAQuery,
|
||||
signal?: AbortSignal,
|
||||
granularity?: DashboardGranularity
|
||||
): Promise<QADashboardData> {
|
||||
const response = await fetch('/api/v1/qa-ops/dashboard', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
@@ -506,6 +571,7 @@ export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Pr
|
||||
start: query.start,
|
||||
end: query.end,
|
||||
keyword: query.keyword,
|
||||
...(granularity ? { granularity } : {}),
|
||||
}),
|
||||
})
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
@@ -518,7 +584,8 @@ export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Pr
|
||||
Date.parse(data.start) !== Date.parse(query.start) ||
|
||||
Date.parse(data.end) !== Date.parse(query.end) ||
|
||||
data.keyword !== query.keyword ||
|
||||
Object.keys(data.filters ?? {}).length !== 0
|
||||
Object.keys(data.filters ?? {}).length !== 0 ||
|
||||
(granularity ?? undefined) !== data.granularity
|
||||
)
|
||||
throw new Error('看板返回范围与当前查询不一致,请重新读取')
|
||||
return data
|
||||
|
||||
@@ -18,3 +18,8 @@ it('never rolls an already closed selected week into a different week', () => {
|
||||
const closed = { ...query, start: '2026-10-12T00:00:00+08:00', end: '2026-10-19T00:00:00+08:00' }
|
||||
expect(liveDashboardQuery(closed, new Date('2026-10-20T09:00:00+08:00'))).toEqual(closed)
|
||||
})
|
||||
|
||||
it('never stretches an explicit custom range to now', () => {
|
||||
const custom = { ...query, start: '2026-10-01T00:00:00+08:00', end: '2026-10-03T00:00:00+08:00' }
|
||||
expect(liveDashboardQuery(custom, new Date('2026-10-20T09:00:00+08:00'), 'custom')).toEqual(custom)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { QADashboardView } from './QADashboard'
|
||||
import { parseQADashboard } from './qaDashboardData'
|
||||
import { dashboardFixture } from './qaDashboard.fixture'
|
||||
|
||||
const monthStart = '2026-11-01T00:00:00+08:00',
|
||||
monthEnd = '2026-12-01T00:00:00+08:00'
|
||||
const monthFixture = {
|
||||
...dashboardFixture,
|
||||
start: monthStart,
|
||||
end: monthEnd,
|
||||
week_start: '2026-11-30T00:00:00+08:00',
|
||||
month_start: monthStart,
|
||||
total_issues: 120,
|
||||
new_this_week: 30,
|
||||
granularity: 'month',
|
||||
period: {
|
||||
kind: 'month',
|
||||
label: '2026-11',
|
||||
start: monthStart,
|
||||
end: monthEnd,
|
||||
prev_start: '2026-10-01T00:00:00+08:00',
|
||||
prev_end: monthStart,
|
||||
},
|
||||
period_issues: 30,
|
||||
prev_period_issues: 25,
|
||||
daily: Array.from({ length: 30 }, (_, i) => ({ date: `2026-11-${String(i + 1).padStart(2, '0')}`, count: 1 })),
|
||||
frozen_weeks: [],
|
||||
reported_weeks: [],
|
||||
cumulative_weeks: [],
|
||||
period_quality: {
|
||||
records: 30,
|
||||
unjudged: 0,
|
||||
coverage: { numerator: 20, denominator: 30, percent: (100 * 20) / 30 },
|
||||
correctness: { numerator: 18, denominator: 20, percent: 90 },
|
||||
},
|
||||
}
|
||||
|
||||
describe('monthly dashboard range', () => {
|
||||
it('parses a monthly range and keeps the trend over the whole month', () => {
|
||||
const data = parseQADashboard(monthFixture)
|
||||
expect(data.period?.label).toBe('2026-11')
|
||||
expect(data.period_issues).toBe(30)
|
||||
expect(data.prev_period_issues).toBe(25)
|
||||
expect(data.daily).toHaveLength(30)
|
||||
expect(data.period_quality?.coverage.numerator).toBe(20)
|
||||
})
|
||||
|
||||
it('labels the cards from the selected range instead of a hardcoded week', () => {
|
||||
const data = parseQADashboard(monthFixture)
|
||||
const html = renderToStaticMarkup(<QADashboardView data={data} loading={false} error="" onRetry={vi.fn()} />)
|
||||
expect(html).toContain('本期新增')
|
||||
expect(html).toContain('2026-11 · 上期 25 条')
|
||||
expect(html).toContain('全部指标按所选范围统计')
|
||||
expect(html).not.toContain('所选自然周')
|
||||
expect(html).toContain('66.7%')
|
||||
})
|
||||
|
||||
it('rejects a payload that claims a month granularity without a matching period', () => {
|
||||
const { period: _period, ...rest } = monthFixture
|
||||
expect(() => parseQADashboard(rest)).toThrow()
|
||||
})
|
||||
|
||||
it('rejects a trend that does not add up to the period total', () => {
|
||||
const broken = { ...monthFixture, daily: monthFixture.daily.map((p) => ({ ...p, count: 1 })).slice(0, 29) }
|
||||
expect(() => parseQADashboard(broken)).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -3,27 +3,38 @@ const beijing = (at: string) => new Date(Date.parse(at) + 8 * 3600000).toISOStri
|
||||
const windowText = (start: string, end: string) => `北京时间 ${beijing(start)} 至 ${beijing(end)}(终点不含)。`
|
||||
export function dashboardStatisticsHelp(data: QADashboardData): Record<string, string> {
|
||||
const filter = '沿用已执行关键词筛选。',
|
||||
week = windowText(data.start, data.end),
|
||||
regionMonth = windowText(data.month_start, data.end),
|
||||
selected = data.period,
|
||||
period = data.quality_period,
|
||||
rates = data.monthly_quality,
|
||||
qualityRange = period ? windowText(period.start, period.cutoff_at) : week,
|
||||
week = selected ? windowText(selected.start, selected.end) : windowText(data.start, data.end),
|
||||
regionMonth = windowText(data.month_start, data.end),
|
||||
rates = selected ? data.period_quality : data.monthly_quality,
|
||||
qualityRange = selected
|
||||
? windowText(selected.start, selected.end)
|
||||
: period
|
||||
? windowText(period.start, period.cutoff_at)
|
||||
: week,
|
||||
qualityRecords = rates?.records ?? data.quality.total,
|
||||
coverage = rates?.coverage ?? data.quality.rates.coverage,
|
||||
correctness = rates?.correctness ?? data.quality.rates.correctness,
|
||||
periodLabel = selected ? selected.label : '所选自然周',
|
||||
periodCount = selected ? (data.period_issues ?? data.new_this_week) : data.new_this_week,
|
||||
calendar =
|
||||
'每月1日重新累计,不累计之前月份,不平均周百分比;按原始提问时间归月,使用当前有效结论及点踩否,空分母留空。',
|
||||
qualityScope = period
|
||||
? `统计月 ${period.month}。跨月周取周一所在月;当前未结束只截至实际时点。`
|
||||
: '旧接口按所选查询范围统计。'
|
||||
qualityScope = selected
|
||||
? `统计范围 ${selected.label}(${qualityRange})。全部指标与看板筛选同一区间,不混用其它月份。`
|
||||
: period
|
||||
? `统计月 ${period.month}。跨月周取周一所在月;当前未结束只截至实际时点。`
|
||||
: '旧接口按所选查询范围统计。'
|
||||
return {
|
||||
total: `截至北京时间 ${beijing(data.end)}(不含),治理总表历史导入和2.0收录的去重问题记录数,共 ${data.total_issues} 条;不把当前页条数当总数,不因缺少分析字段排除。${filter}`,
|
||||
'new-week': `${windowText(data.week_start, data.end)}本周新增=原始提问时间落在本自然周内的问题数,共 ${data.new_this_week} 条;当前周截至当前,不按导入时间算新增。${filter}`,
|
||||
'new-week': `${week}${periodLabel}新增=原始提问时间落在所选范围内的问题数,共 ${periodCount} 条${
|
||||
selected && data.prev_period_issues !== undefined ? `;同一口径上一区间 ${data.prev_period_issues} 条` : ''
|
||||
};不按导入时间算新增。${filter}`,
|
||||
coverage: `${qualityScope}${qualityRange}${rates ? '覆盖率=覆盖是÷(是+否)×100%。部分覆盖、待确认、未知、空白、失效等不计分母。' : '旧覆盖率=覆盖是÷(覆盖是+覆盖否+部分覆盖)×100%。'}本范围 ${qualityRecords} 条;分子 ${coverage.numerator},分母 ${coverage.denominator},排除 ${qualityRecords - coverage.denominator} 条。${filter}`,
|
||||
accuracy: `${qualityScope}${qualityRange}${rates ? '正确率=正确是÷(是+否)×100%;不限定仅已覆盖问题。' : '旧正确率=已覆盖样本内的正确是÷(是+否)×100%。'}本范围 ${qualityRecords} 条;分子 ${correctness.numerator},分母 ${correctness.denominator},排除 ${qualityRecords - correctness.denominator} 条。待确认、未知、空白、失效等排除;已判定样本正确率不代表全部问题已确认。${filter}`,
|
||||
'issue-types': `${week}按本查询范围内每条问题的当前有效“问题类型”归组,每条计1次;缺失保留“未分类”。饼图占比=该类型条数÷范围内 ${data.quality.total} 条×100%。${filter}`,
|
||||
products: `${week}按当前有效“产品分类”归组,每条问题计1次,数量降序;缺失保留“未分类”,不与问题类型混用。范围共 ${data.quality.total} 条。${filter}`,
|
||||
'issue-trend': `${windowText(data.week_start, data.end)}按原始提问时间在北京时间逐日计数,零提问日保留;各日合计=本周新增 ${data.new_this_week} 条,不按导入日计算。${filter}`,
|
||||
'issue-trend': `${week}按原始提问时间在北京时间逐日计数,零提问日保留;各日合计=${periodLabel}新增 ${periodCount} 条,不按导入日计算。${filter}`,
|
||||
frequency: `${regionMonth}区域平均使用频率=能稳定关联该区域的月内提问条数÷当前配置通讯录去重人数。缺失/待核对身份不强行归属,零分母显示“—”;当前名册不是在职或绩效名单。${filter}`,
|
||||
'usage-coverage': `${regionMonth}区域使用覆盖率=月内稳定身份去重使用人数÷同一区域当前配置通讯录去重人数×100%。零使用者保留在分母,无法关联者不凑人数;无名单或零分母显示“—”,不是绩效结论。${filter}`,
|
||||
'coverage-trend': period
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { ReconciliationRequestError } from './reconciliationApi'
|
||||
import {
|
||||
isTestBindingMissing,
|
||||
reconciliationErrorText,
|
||||
reconciliationFailureText,
|
||||
reconciliationMessages,
|
||||
reconciliationStageText,
|
||||
} from './reconciliationMessages'
|
||||
import type { KBBindingSnapshot } from './knowledgeBaseBindings'
|
||||
|
||||
const snapshot = (test: { base_url: string; key_configured: boolean }): KBBindingSnapshot =>
|
||||
({ test, production: { base_url: 'https://prod.example', key_configured: true } }) as unknown as KBBindingSnapshot
|
||||
|
||||
describe('reconciliation error copy', () => {
|
||||
it('maps the three required failures to distinct Chinese sentences', () => {
|
||||
expect(reconciliationFailureText('reconciliation_not_configured')).toBe(reconciliationMessages.notEnabled)
|
||||
expect(reconciliationFailureText('runtime_key_forbidden')).toBe(reconciliationMessages.runtimeKeyForbidden)
|
||||
expect(reconciliationFailureText('runtime_unreachable')).toBe(reconciliationMessages.runtimeUnreachable)
|
||||
|
||||
const texts = [
|
||||
reconciliationMessages.notEnabled,
|
||||
reconciliationMessages.bindingMissing,
|
||||
reconciliationMessages.runtimeKeyForbidden,
|
||||
reconciliationMessages.runtimeUnreachable,
|
||||
]
|
||||
expect(new Set(texts).size).toBe(texts.length)
|
||||
})
|
||||
|
||||
it('never renders the four internal codes', () => {
|
||||
for (const code of [
|
||||
'reconciliation_not_configured',
|
||||
'reconciliation_failed',
|
||||
'remote_unavailable',
|
||||
'runtime_read_unavailable',
|
||||
]) {
|
||||
const text = reconciliationFailureText(code)
|
||||
expect(text).not.toContain(code)
|
||||
expect(text.trim().length).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('distinguishes a deleted knowledge base from a broken binding', () => {
|
||||
expect(reconciliationFailureText('remote_kb_missing')).toBe(reconciliationMessages.remoteKBMissing)
|
||||
expect(reconciliationFailureText('remote_unavailable')).toBe(reconciliationMessages.remoteFailed)
|
||||
expect(reconciliationMessages.remoteKBMissing).not.toBe(reconciliationMessages.remoteFailed)
|
||||
})
|
||||
|
||||
it('falls back to Chinese for an unknown code instead of echoing it', () => {
|
||||
expect(reconciliationFailureText('some_new_code')).toBe(reconciliationMessages.generic)
|
||||
expect(reconciliationFailureText('some_new_code')).not.toContain('some_new_code')
|
||||
expect(reconciliationStageText('E1')).toBe(reconciliationMessages.stageGeneric)
|
||||
})
|
||||
|
||||
it('uses the request code, not the raw server message', () => {
|
||||
const error = new ReconciliationRequestError('remote_unavailable', 500, 'remote_unavailable')
|
||||
expect(reconciliationErrorText(error)).toBe(reconciliationMessages.remoteFailed)
|
||||
expect(reconciliationErrorText(error)).not.toContain('remote_unavailable')
|
||||
})
|
||||
|
||||
it('treats a missing address or key as an unconfigured test binding', () => {
|
||||
expect(isTestBindingMissing(snapshot({ base_url: 'https://test.example', key_configured: true }))).toBe(false)
|
||||
expect(isTestBindingMissing(snapshot({ base_url: '', key_configured: true }))).toBe(true)
|
||||
expect(isTestBindingMissing(snapshot({ base_url: 'https://test.example', key_configured: false }))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { KBBindingSnapshot } from './knowledgeBaseBindings'
|
||||
import { ReconciliationRequestError } from './reconciliationApi'
|
||||
|
||||
// 页面只认这几句人话:错误码属于接口契约,不能直接进 DOM。所有出口
|
||||
// (顶部条、操作区、批次行、阶段、两个抽屉)都从这里取,避免同一原因
|
||||
// 在不同位置各写一句后漂移。
|
||||
export const reconciliationMessages = {
|
||||
notEnabled: '导入对账未启用,请联系管理员开启',
|
||||
bindingMissing: '系统设置 → 知识库绑定:测试环境未配置',
|
||||
runtimeKeyMissing: '未配置知识库绑定或绑定不可用:请到「系统设置 → 知识库绑定」填写测试环境地址与 Key',
|
||||
runtimeKeyForbidden: '当前 Key 缺少平台运行时读权限:请在 WeKnora 授权 system_runtime_read',
|
||||
runtimeUnreachable: '连不上 WeKnora 或运行时读失败:请检查「系统设置 → 知识库绑定」中的地址与网络',
|
||||
runInProgress: '该测试知识库已有对账批次在运行,请等本轮结束后再试',
|
||||
stateChanged: '记录状态已变化,请刷新后重试',
|
||||
remoteFailed: '测试知识库连接失败:请检查系统设置 → 知识库绑定中的测试环境地址与 Key',
|
||||
remoteKBMissing: '所选测试知识库在 WeKnora 中已不存在(可能已被删除),请改选当前绑定的测试库',
|
||||
queueUnavailable: '对账任务队列不可用,请联系管理员',
|
||||
ledgerUnavailable: '台账读取失败,请稍后重试或联系管理员',
|
||||
overlapCheckFailed: '无法确认整库作业状态,请稍后重试',
|
||||
scanFailed: '对账扫描失败,请稍后重试或联系管理员',
|
||||
previousCountsFailed: '读取上一批对账结果失败,请稍后重试',
|
||||
completeFailed: '保存对账结果失败,请稍后重试或联系管理员',
|
||||
generic: '对账操作失败,请稍后重试或联系管理员',
|
||||
stageGeneric: '其他原因',
|
||||
} as const
|
||||
|
||||
const failureMessages: Record<string, string> = {
|
||||
reconciliation_not_configured: reconciliationMessages.notEnabled,
|
||||
reconciliation_failed: reconciliationMessages.generic,
|
||||
reconciliation_remote_failed: reconciliationMessages.remoteFailed,
|
||||
remote_kb_missing: reconciliationMessages.remoteKBMissing,
|
||||
remote_unavailable: reconciliationMessages.remoteFailed,
|
||||
remote_scan_failed: reconciliationMessages.remoteFailed,
|
||||
remote_confirm_failed: reconciliationMessages.remoteFailed,
|
||||
runtime_read_unavailable: reconciliationMessages.runtimeKeyMissing,
|
||||
runtime_key_forbidden: reconciliationMessages.runtimeKeyForbidden,
|
||||
runtime_unreachable: reconciliationMessages.runtimeUnreachable,
|
||||
reconciliation_run_in_progress: reconciliationMessages.runInProgress,
|
||||
reconciliation_state_changed: reconciliationMessages.stateChanged,
|
||||
queue_unavailable: reconciliationMessages.queueUnavailable,
|
||||
ledger_unavailable: reconciliationMessages.ledgerUnavailable,
|
||||
overlap_check_failed: reconciliationMessages.overlapCheckFailed,
|
||||
scan_failed: reconciliationMessages.scanFailed,
|
||||
previous_counts_failed: reconciliationMessages.previousCountsFailed,
|
||||
complete_failed: reconciliationMessages.completeFailed,
|
||||
}
|
||||
|
||||
// 未知码不回显原文:英文码是内部契约,用户只需要知道「失败了、接下来做什么」。
|
||||
export function reconciliationFailureText(code: string): string {
|
||||
return failureMessages[code] ?? reconciliationMessages.generic
|
||||
}
|
||||
|
||||
// 阶段码来自上游,可能是任意值;已知平台码照样翻译,未知只给「其他原因」。
|
||||
export function reconciliationStageText(code: string): string {
|
||||
return failureMessages[code] ?? reconciliationMessages.stageGeneric
|
||||
}
|
||||
|
||||
export function reconciliationErrorText(error: unknown): string {
|
||||
if (error instanceof ReconciliationRequestError) {
|
||||
return reconciliationFailureText(error.code)
|
||||
}
|
||||
// 本地抛出的校验错误是中文;真正未知的错误也不要把英文原文塞进页面。
|
||||
if (error instanceof Error && error.message) return error.message
|
||||
return reconciliationMessages.generic
|
||||
}
|
||||
|
||||
// 与 kbbinding.Resolve 的 fail-closed 语义对齐:地址或密钥任一缺失,
|
||||
// 运行时读与对账远端都会失败,页面应先说「测试环境未配置」。
|
||||
export function isTestBindingMissing(snapshot: KBBindingSnapshot): boolean {
|
||||
return !snapshot.test.base_url.trim() || !snapshot.test.key_configured
|
||||
}
|
||||
+255
-162
@@ -1,11 +1,13 @@
|
||||
/* 发布管理:按已确认稿的布局与色系(浅底、青绿主色、白色圆角面板)。 */
|
||||
/* 发布管理:沿用全站工作台视觉(styles.css 的钴蓝 + 中性灰 token)。
|
||||
以前这一页自带一套青绿色并用 !important 压过全局按钮,看起来像另一个系统;
|
||||
现在只在这里起别名,颜色一律回到全局 token,语义色(绿=完成、红=失败)也取全局。 */
|
||||
.release-targets {
|
||||
--rel-ink: #26394a;
|
||||
--rel-muted: #7b8d9a;
|
||||
--rel-line: #dce6ed;
|
||||
--rel-teal: #269e88;
|
||||
--rel-teal-dark: #228b75;
|
||||
--rel-teal-soft: #eaf8f3;
|
||||
--rel-ink: var(--ink-strong);
|
||||
--rel-muted: var(--ink-mute);
|
||||
--rel-line: var(--border-base);
|
||||
--rel-accent: var(--c-primary);
|
||||
--rel-accent-hover: var(--c-primary-hover);
|
||||
--rel-accent-soft: var(--bg-active);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
@@ -15,11 +17,13 @@
|
||||
}
|
||||
.release-targets h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.release-targets h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.rel-head {
|
||||
display: flex;
|
||||
@@ -42,27 +46,44 @@
|
||||
.release-targets button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
background: #fff;
|
||||
border: 1px solid #d6e2e8;
|
||||
border-radius: 7px;
|
||||
padding: 7px 14px;
|
||||
color: #41596b;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--r-md);
|
||||
padding: 6px 14px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.release-targets button:hover:not(:disabled) {
|
||||
background: #edf8f5;
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.release-targets button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.release-targets button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--c-focus-ring);
|
||||
}
|
||||
.rel-primary {
|
||||
background: var(--rel-teal) !important;
|
||||
border-color: var(--rel-teal) !important;
|
||||
background: var(--rel-accent) !important;
|
||||
border-color: var(--rel-accent) !important;
|
||||
color: #fff !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
.rel-primary:hover:not(:disabled) {
|
||||
background: var(--rel-accent-hover) !important;
|
||||
border-color: var(--rel-accent-hover) !important;
|
||||
}
|
||||
/* "已同步"是结论不是失效按钮:不走半透明禁用态,用完成色说清楚已经到位。 */
|
||||
.rel-primary.rel-synced,
|
||||
.rel-primary.rel-synced:disabled {
|
||||
opacity: 1;
|
||||
cursor: default;
|
||||
background: var(--c-done-bg) !important;
|
||||
border-color: var(--c-done-border) !important;
|
||||
color: var(--c-done) !important;
|
||||
}
|
||||
.rel-secondary {
|
||||
background: #fff;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.rel-tabs {
|
||||
display: flex;
|
||||
@@ -70,54 +91,63 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.rel-tab {
|
||||
width: 310px;
|
||||
width: 300px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 13px 18px !important;
|
||||
padding: 12px 16px !important;
|
||||
text-align: left;
|
||||
border-radius: 9px !important;
|
||||
border-radius: var(--r-lg) !important;
|
||||
border: 1px solid var(--rel-line) !important;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.rel-tab strong {
|
||||
font-size: 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.rel-tab.selected {
|
||||
background: var(--rel-teal-soft) !important;
|
||||
border: 2px solid var(--rel-teal) !important;
|
||||
background: var(--rel-accent-soft) !important;
|
||||
border-color: var(--rel-accent) !important;
|
||||
box-shadow: inset 0 0 0 1px var(--rel-accent);
|
||||
}
|
||||
.rel-tab.selected strong {
|
||||
color: var(--rel-accent);
|
||||
}
|
||||
.rel-pill {
|
||||
border-radius: 5px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
padding: 2px 9px;
|
||||
padding: 1px 9px;
|
||||
white-space: nowrap;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.rel-pill.green {
|
||||
color: #228368;
|
||||
background: #e6f5ef;
|
||||
border-color: #bfe6d8;
|
||||
color: var(--c-done);
|
||||
background: var(--c-done-bg);
|
||||
border-color: var(--c-done-border);
|
||||
}
|
||||
.rel-pill.blue {
|
||||
color: #387eb8;
|
||||
background: #eaf3fc;
|
||||
border-color: #c6ddf1;
|
||||
color: var(--c-run);
|
||||
background: var(--c-run-bg);
|
||||
border-color: var(--c-run-border);
|
||||
}
|
||||
.rel-pill.gray {
|
||||
color: #7c8d99;
|
||||
background: #eff3f6;
|
||||
border-color: #dde5ea;
|
||||
color: var(--c-dead);
|
||||
background: var(--c-dead-bg);
|
||||
border-color: var(--border-base);
|
||||
}
|
||||
.rel-pill.red {
|
||||
color: #b4381f;
|
||||
background: #fdecea;
|
||||
border-color: #f3c6bc;
|
||||
color: var(--c-fail);
|
||||
background: var(--c-fail-bg);
|
||||
border-color: var(--c-fail-border);
|
||||
}
|
||||
.rel-panel {
|
||||
background: #fff;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: 12px;
|
||||
padding: 20px 22px;
|
||||
border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-card);
|
||||
padding: 18px 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
.rel-between {
|
||||
@@ -129,7 +159,7 @@
|
||||
}
|
||||
.rel-panel-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
@@ -140,18 +170,18 @@
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
.rel-jobhead h2 {
|
||||
font-size: 19px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.rel-versionline {
|
||||
margin: 12px 0 0;
|
||||
color: #496579;
|
||||
font-size: 14px;
|
||||
color: var(--ink-base);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rel-versionline b {
|
||||
color: var(--rel-teal-dark);
|
||||
color: var(--rel-accent);
|
||||
}
|
||||
.rel-unknown {
|
||||
color: #9aa9b4 !important;
|
||||
color: var(--ink-faint) !important;
|
||||
font-weight: 500;
|
||||
}
|
||||
.rel-metrics {
|
||||
@@ -161,8 +191,8 @@
|
||||
margin: 16px 0 0;
|
||||
}
|
||||
.rel-metrics div {
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 9px;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.rel-metrics dt {
|
||||
@@ -173,21 +203,22 @@
|
||||
margin: 4px 0 0;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-checklist {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
gap: 22px;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 14px 0 0;
|
||||
padding: 11px 14px;
|
||||
border-radius: 9px;
|
||||
background: #f2faf6;
|
||||
padding: 12px 14px;
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
font-size: 13px;
|
||||
color: #228368;
|
||||
color: var(--c-done);
|
||||
}
|
||||
.rel-checklist .unknown {
|
||||
color: #8a9aa6;
|
||||
color: var(--ink-faint);
|
||||
}
|
||||
.rel-footnote {
|
||||
margin: 12px 0 0;
|
||||
@@ -216,8 +247,8 @@
|
||||
.rel-drawer-table th,
|
||||
.rel-parts th {
|
||||
text-align: left;
|
||||
background: #f8fafb;
|
||||
color: #8a9aa6;
|
||||
background: var(--bg-soft);
|
||||
color: var(--rel-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: 9px 12px;
|
||||
@@ -227,7 +258,7 @@
|
||||
.rel-drawer-table td,
|
||||
.rel-parts td {
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid #eef2f5;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
vertical-align: top;
|
||||
}
|
||||
.rel-table-empty {
|
||||
@@ -238,8 +269,8 @@
|
||||
}
|
||||
.rel-protection dl {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 8px 14px;
|
||||
grid-template-columns: 11.5em 1fr;
|
||||
gap: 8px 16px;
|
||||
margin: 0 0 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -249,6 +280,8 @@
|
||||
.rel-protection dd {
|
||||
margin: 0;
|
||||
color: var(--rel-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
word-break: break-all;
|
||||
}
|
||||
.rel-hint {
|
||||
margin: 0 0 10px;
|
||||
@@ -259,39 +292,39 @@
|
||||
.rel-warn {
|
||||
margin: 12px 0 0;
|
||||
font-size: 12px;
|
||||
color: #986b24;
|
||||
background: #fff8e8;
|
||||
border: 1px solid #ead7b0;
|
||||
border-radius: 7px;
|
||||
color: var(--c-warn);
|
||||
background: var(--c-warn-bg);
|
||||
border: 1px solid var(--c-warn-border);
|
||||
border-radius: var(--r-md);
|
||||
padding: 8px 10px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.rel-notice {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: #986b24;
|
||||
background: #fff8e8;
|
||||
border: 1px solid #ead7b0;
|
||||
border-radius: 8px;
|
||||
color: var(--c-warn);
|
||||
background: var(--c-warn-bg);
|
||||
border: 1px solid var(--c-warn-border);
|
||||
border-radius: var(--r-md);
|
||||
padding: 9px 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.rel-blocked {
|
||||
border: 1px solid #f3c2b8;
|
||||
background: #fff6f3;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--c-fail-border);
|
||||
background: var(--c-fail-bg);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.rel-blocked strong {
|
||||
display: block;
|
||||
color: #a03a1e;
|
||||
color: var(--c-fail);
|
||||
font-size: 13px;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
.rel-blocked p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: #7c2d12;
|
||||
color: var(--c-fail);
|
||||
}
|
||||
|
||||
/* 阶段条 */
|
||||
@@ -300,7 +333,7 @@
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
list-style: none;
|
||||
margin: 16px 0 6px;
|
||||
margin: 4px 0 8px;
|
||||
padding: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
@@ -310,11 +343,11 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 11px 12px;
|
||||
border-radius: 8px;
|
||||
background: #f5f8fa;
|
||||
border: 1px solid #e1e8ed;
|
||||
color: #8a9aa6;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
border: 1px solid var(--border-soft);
|
||||
color: var(--ink-faint);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rel-step strong {
|
||||
@@ -325,13 +358,14 @@
|
||||
font-size: 11px;
|
||||
}
|
||||
.rel-step.done {
|
||||
color: #25886b;
|
||||
background: #f0faf5;
|
||||
color: var(--c-done);
|
||||
background: var(--c-done-bg);
|
||||
border-color: var(--c-done-border);
|
||||
}
|
||||
.rel-step.live {
|
||||
color: #167f70;
|
||||
background: #e9f8f4;
|
||||
border-color: #4eb49f;
|
||||
color: var(--c-run);
|
||||
background: var(--c-run-bg);
|
||||
border-color: var(--c-run-border);
|
||||
font-weight: 700;
|
||||
}
|
||||
.rel-step-mark {
|
||||
@@ -350,22 +384,6 @@
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 仅剩的次级操作:封存测试版本 */
|
||||
.rel-seal {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
background: #fbfdfe;
|
||||
}
|
||||
.rel-seal p {
|
||||
margin: 6px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--rel-muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 同步中 */
|
||||
.rel-jobmeta {
|
||||
margin: 8px 0 0;
|
||||
@@ -374,7 +392,7 @@
|
||||
}
|
||||
.rel-progress-foot {
|
||||
margin-top: 12px;
|
||||
border-top: 1px solid #eef2f5;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
padding-top: 10px;
|
||||
font-size: 12px;
|
||||
color: var(--rel-muted);
|
||||
@@ -383,14 +401,14 @@
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
padding: 2px 4px !important;
|
||||
color: #2b7fa6 !important;
|
||||
color: var(--rel-accent) !important;
|
||||
font-size: 12px;
|
||||
}
|
||||
.rel-datacard {
|
||||
border: 1px solid #dce6ed;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 14px 16px;
|
||||
background: #fff;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.rel-datacard header {
|
||||
display: flex;
|
||||
@@ -405,19 +423,20 @@
|
||||
}
|
||||
.rel-datacount strong {
|
||||
font-size: 24px;
|
||||
color: #9aa9b4;
|
||||
color: var(--ink-faint);
|
||||
margin-right: 4px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-progress {
|
||||
height: 6px;
|
||||
border-radius: 8px;
|
||||
background: #edf1f4;
|
||||
background: var(--bg-softer);
|
||||
overflow: hidden;
|
||||
}
|
||||
.rel-progress span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--rel-teal);
|
||||
background: var(--rel-accent);
|
||||
}
|
||||
.rel-datadetail {
|
||||
margin: 10px 0 0;
|
||||
@@ -434,27 +453,27 @@
|
||||
padding: 4px 11px;
|
||||
}
|
||||
.rel-filters .chosen {
|
||||
color: #168b73;
|
||||
background: #ebf8f3;
|
||||
border-color: #a6d7c8;
|
||||
color: var(--rel-accent);
|
||||
background: var(--rel-accent-soft);
|
||||
border-color: var(--c-run-border);
|
||||
}
|
||||
.rel-log {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
background: #f9fbfc;
|
||||
border-top: 1px solid #eef2f5;
|
||||
background: var(--bg-soft);
|
||||
border-top: 1px solid var(--border-soft);
|
||||
padding: 10px 12px;
|
||||
font-size: 12px;
|
||||
color: #7b8e9c;
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
|
||||
/* 版本与快照抽屉 */
|
||||
.rel-drawer-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(20, 52, 74, 0.4);
|
||||
background: rgb(0 0 0 / 32%);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
z-index: 40;
|
||||
@@ -463,9 +482,9 @@
|
||||
width: min(1024px, 92vw);
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
border-left: 1px solid #dce6ed;
|
||||
box-shadow: -12px 0 32px rgba(19, 44, 61, 0.18);
|
||||
background: var(--bg-panel);
|
||||
border-left: 1px solid var(--rel-line);
|
||||
box-shadow: var(--shadow-float);
|
||||
padding: 22px 26px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -493,13 +512,13 @@
|
||||
margin-top: 2px;
|
||||
}
|
||||
.rel-drawer-table tr.selected td {
|
||||
background: #f4fbf8;
|
||||
background: var(--rel-accent-soft);
|
||||
}
|
||||
.rel-snapshot {
|
||||
border: 1px solid #cfe6dd;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 16px 18px;
|
||||
background: #fbfefd;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.rel-snapshot header {
|
||||
display: flex;
|
||||
@@ -515,9 +534,9 @@
|
||||
margin: 12px 0;
|
||||
}
|
||||
.rel-snapshot-grid div {
|
||||
border: 1px solid #e2eef7;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-panel);
|
||||
padding: 9px 11px;
|
||||
}
|
||||
.rel-snapshot-grid dt {
|
||||
@@ -534,12 +553,12 @@
|
||||
.rel-parts summary {
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: #2b7fa6;
|
||||
color: var(--rel-accent);
|
||||
}
|
||||
.rel-parts table {
|
||||
margin-top: 8px;
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
overflow: hidden;
|
||||
}
|
||||
.rel-drawer-actions {
|
||||
@@ -548,12 +567,12 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.rel-danger {
|
||||
border-color: #e7b4a8 !important;
|
||||
color: #b4381f !important;
|
||||
border-color: var(--c-fail-border) !important;
|
||||
color: var(--c-fail) !important;
|
||||
}
|
||||
.rel-drawer-foot {
|
||||
margin-top: auto;
|
||||
border-top: 1px solid #eef2f5;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
padding-top: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -602,7 +621,7 @@
|
||||
margin: 2px 0 0;
|
||||
font-style: normal;
|
||||
font-size: 11px;
|
||||
color: var(--rel-muted, #7b8d9a);
|
||||
color: var(--ink-faint);
|
||||
}
|
||||
|
||||
.rel-scope-note {
|
||||
@@ -617,13 +636,13 @@
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.rel-drawer-kinds div {
|
||||
border: 1px solid var(--rel-line, #dce6ed);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-md);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
.rel-drawer-kinds dt {
|
||||
font-size: 11px;
|
||||
color: var(--rel-muted, #7b8d9a);
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
.rel-drawer-kinds dd {
|
||||
margin: 3px 0 0;
|
||||
@@ -645,12 +664,12 @@
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
border-bottom: 1px dashed var(--rel-line, #dce6ed);
|
||||
border-bottom: 1px dashed var(--rel-line);
|
||||
padding: 4px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.rel-maintenance-rows span {
|
||||
color: var(--rel-muted, #7b8d9a);
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
.rel-maintenance-rows b {
|
||||
font-variant-numeric: tabular-nums;
|
||||
@@ -687,9 +706,9 @@
|
||||
padding: 4px 10px;
|
||||
}
|
||||
.rel-history-filters button.active {
|
||||
color: #168b73;
|
||||
background: #ebf8f3;
|
||||
border-color: #a6d7c8;
|
||||
color: var(--rel-accent);
|
||||
background: var(--rel-accent-soft);
|
||||
border-color: var(--c-run-border);
|
||||
}
|
||||
.rel-history-pager {
|
||||
display: flex;
|
||||
@@ -706,33 +725,44 @@
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-size: 11px;
|
||||
background: #f7fafc;
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 7px;
|
||||
background: var(--bg-soft);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
/* 发布管理精简版:一个状态卡 + 一个主按钮,其余收进折叠区。 */
|
||||
.rel-status {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
gap: 16px;
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.rel-scope-state {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
/* 四格状态是一条从测试到生产的链:用竖分隔线排成一行,不再各自加框。 */
|
||||
.rel-status-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 14px;
|
||||
gap: 14px 0;
|
||||
margin: 0;
|
||||
}
|
||||
.rel-status-grid div {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 10px 12px;
|
||||
background: var(--card);
|
||||
padding: 2px 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
.rel-status-grid > div:first-child {
|
||||
padding-left: 0;
|
||||
}
|
||||
.rel-status-grid > div + div {
|
||||
border-left: 1px solid var(--border-soft);
|
||||
}
|
||||
.rel-status-grid dt {
|
||||
font-size: 12px;
|
||||
color: var(--muted-foreground);
|
||||
color: var(--ink-mute);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.rel-status-grid dd {
|
||||
@@ -740,23 +770,30 @@
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
word-break: break-all;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-status-grid small {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
color: var(--muted-foreground);
|
||||
color: var(--ink-mute);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-status-grid .rel-cell-action {
|
||||
margin: 4px 0 0 -4px;
|
||||
}
|
||||
.rel-status-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
.rel-next {
|
||||
flex: 1 1 320px;
|
||||
margin: 0;
|
||||
color: var(--muted-foreground);
|
||||
color: var(--ink-mute);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rel-next span {
|
||||
@@ -764,27 +801,83 @@
|
||||
margin-right: 8px;
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: var(--foreground);
|
||||
background: var(--bg-active);
|
||||
color: var(--rel-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 折叠区统一成一种样式:卡片 + 自绘箭头,取代浏览器默认的小三角。 */
|
||||
.rel-check,
|
||||
.rel-advanced {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 4px 16px 12px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 0 18px;
|
||||
background: var(--bg-panel);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.rel-check summary,
|
||||
.rel-advanced summary {
|
||||
.rel-check > summary,
|
||||
.rel-advanced > summary {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
padding: 10px 0;
|
||||
padding: 13px 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.rel-check > summary::-webkit-details-marker,
|
||||
.rel-advanced > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.rel-check > summary::before,
|
||||
.rel-advanced > summary::before {
|
||||
content: '';
|
||||
flex: none;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-right: 1.5px solid var(--ink-mute);
|
||||
border-bottom: 1.5px solid var(--ink-mute);
|
||||
transform: rotate(-45deg);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
.rel-check[open] > summary::before,
|
||||
.rel-advanced[open] > summary::before {
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.rel-check[open],
|
||||
.rel-advanced[open] {
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
.rel-check .rel-gate,
|
||||
.rel-check .rel-checklist {
|
||||
margin: 6px 0 10px;
|
||||
}
|
||||
/* 恢复验证是嵌在检查区里的子块:给它统一行距,按钮不再贴着上面的报告折叠。 */
|
||||
.rel-verification {
|
||||
margin-top: 14px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
.rel-verification > * + * {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.rel-verification > p.rel-hint {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.rel-advanced > * + * {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 放在文件末尾:要压过上面同优先级的桌面规则。 */
|
||||
@media (max-width: 760px) {
|
||||
.rel-status-grid div,
|
||||
.rel-status-grid > div:first-child {
|
||||
padding: 0;
|
||||
}
|
||||
.rel-status-grid > div + div {
|
||||
border-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user