Compare commits

...

4 Commits

Author SHA1 Message Date
姚章浩 90901a4458 feat(qa-ops): 默认本周快捷查询并全量展示固定字段
build / build (push) Successful in 1m1s
新增本周直接查询按钮,所选范围自动分批读取并校验总数、重复与游标完整性;删除手动加载更多,固定展示完整字段,空列不隐藏,不伪造译文或评估。

验证:全量、固定列及本周入口回归先红后绿;完整make verify通过,前端273通过;真实只读源浏览器默认及快捷查询均639条全部唯一展示,14必需字段按序,右侧字段可达、手机无外溢、JS异常0。无新增迁移或源库写入。
2026-10-18 16:32:16 +08:00
姚章浩 3566f208e0 feat(qa-ops): 增加北京时间自然周年份与周次筛选
build / build (push) Successful in 1m8s
按确认口径展示周次及起止日期,处理跨年、52/53周和本周截至当前。保留自定义时间及查询操作,固定UTC+8边界,不改后端源查询。

验证:目标日期、非法53周、北京时间解析、本周截止及渲染回归均先红后绿;前端266通过,完整make verify成功;洛杉矶时区真实浏览器核对查询UTC边界、切年、自定义和390px布局通过,JS异常0。
2026-10-18 16:10:24 +08:00
姚章浩 2ea2111420 fix(web): 保留代理端口以修复同源质量查询误拒绝
build / build (push) Successful in 1m1s
Nginx 使用原始 Host 和端口转发,不修改后端跨站防护。补充无 Fetch Metadata 的 LAN/Tailscale 同源和异源、异端口、转发头伪造回归。

验证:配置回归先因丢失端口失败后通过;HTTP竞态、真实隔离Nginx正反例及完整make verify均通过。部署前真实入口无Metadata为403,同源Metadata对照可过;源库及人工复核无写入。
2026-10-18 15:45:09 +08:00
姚章浩 828c2c5fa0 feat(qa-ops): 按确认口径补齐质量比例与分母明细
build / build (push) Successful in 1m6s
使用完整筛选范围的当前有效结论计算覆盖率和正确率,人工优先,失效与对应待确认/未评估/不计入排除;零分母返回null,界面展示原始分子分母和排除构成,前端拒绝不守恒或比例不一致的响应。

验证:make verify退出码0,Go658及前端257通过,91项声明可选集成跳过;隔离PG、三包竞态及合成/真实只读源浏览器验证通过。无新增迁移,不接AI模型,不改绩效,不写源库;本批未推送或部署,8088运行版保持0.1.21。
2026-10-18 02:00:31 +08:00
23 changed files with 876 additions and 72 deletions
+9 -1
View File
@@ -4,8 +4,14 @@
### Added
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。仅提供数量,不接 AI 模型、不定义质量率或绩效分母、不回写 DobotAI 原问答。
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
@@ -31,6 +37,8 @@
### Fixed
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
+1 -1
View File
@@ -101,7 +101,7 @@
},
"/api/v1/qa-ops/usage/people": {"post": {"tags": ["QA operations"], "operationId": "queryQAOperationsMonthlyPeople", "summary": "按北京时间自然月列出当前名册人员的2.0用量(含零记录),仅管理员,不返回原始员工标识,不作为在职/考核名单", "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "完整名册缺失或目录/区域版本变化,请同步/重新查询,不返回伪零"}}, "description": "只读查询,不写治理库或生产库;姓名筛选置于 JSON 请求体,不进入 URL;整名册指标不随人员筛选变化。第2页起须带首页目录、区域版本及 end 截止。", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "required": ["month"], "properties": {"month": {"type": "string", "pattern": "^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$"}, "cutoff": {"type": "string", "format": "date-time"}, "region": {"type": "string", "enum": ["国内工业", "APAC", "EMEA", "America", "unassigned", "cross_region"]}, "department_id": {"type": "string"}, "activity": {"type": "string", "enum": ["all", "used", "zero"]}, "search": {"type": "string", "maxLength": 100}, "page": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 30}, "directory_id": {"type": "string"}, "revision_id": {"type": "string"}}}}}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-usage-read"]}}]}},
"/api/v1/qa-ops/usage": {"get": {"tags": ["QA operations"], "operationId": "getQAOperationsUsage", "summary": "完整筛选范围内按当前通讯录和区域版本回看2.0问答使用;固定租户、管理员访问,不输出绩效结论", "parameters": [{"name": "start", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "end", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "keyword", "in": "query", "schema": {"type": "string", "maxLength": 200}}], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}}}},
"/api/v1/qa-ops/quality/query": {"post": {"operationId": "queryQAQualityCounts", "summary": "按完整时间/原问题字面关键词读取指纹及规则命中元数据并留档统计,原文仅在读取问答/复核时采集;不计算质量率,最多5000条", "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"start": {"type": "string", "format": "date-time"}, "end": {"type": "string", "format": "date-time"}, "keyword": {"type": "string", "maxLength": 200}}, "required": ["start", "end"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
"/api/v1/qa-ops/quality/query": {"post": {"operationId": "queryQAQualityCounts", "summary": "按完整筛选范围读取指纹/规则元数据并留档统计,最多5000条;summary.rates 返回 quality-rates-human-first-v1、原始分子/分母、百分比与分母构成。覆盖率=covered/(covered+uncovered+partial),正确率=covered_correct/(covered_correct+covered_incorrect);失效/不计入/相应待确认与未评估排除,零分母percent=null。原文仅在读取问答/复核时采集", "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"start": {"type": "string", "format": "date-time"}, "end": {"type": "string", "format": "date-time"}, "keyword": {"type": "string", "maxLength": 200}}, "required": ["start", "end"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
"/api/v1/qa-ops/records/{id}/reviews": {"post": {"operationId": "saveQAQualityReview", "summary": "治理库追加人工复核,登录身份审计,源端只读,输入/复核乐观锁和nonce幂等;正确时根因为空,不计入须说明原因", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"input_hash": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "input_epoch": {"type": "integer", "minimum": 1}, "base_revision": {"type": "integer", "minimum": 0}, "nonce": {"type": "string", "pattern": "^[A-Za-z0-9_-]{16,128}$"}, "fields": {"type": "object", "additionalProperties": false, "properties": {"coverage": {"type": "string", "enum": ["covered", "uncovered", "partial", "pending", "excluded"]}, "correctness": {"type": "string", "enum": ["correct", "incorrect", "pending"]}, "product_category": {"type": "string", "maxLength": 128}, "problem_type": {"type": "string", "maxLength": 128}, "root_cause": {"type": "string", "maxLength": 2000}, "exclusion_reason": {"type": "string", "maxLength": 2000}}, "required": ["coverage", "correctness"]}, "reason": {"type": "string", "minLength": 1, "maxLength": 4000}}, "required": ["input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
"/api/v1/qa-ops/records/{id}/quality/history": {"get": {"operationId": "listQAQualityHistory", "summary": "按当前固定租户查询不可变复检/人工历史,分别倒序分页,各20条", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "review_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}, {"name": "check_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
"/api/v1/qa-ops/records/{id}/quality/inputs/{epoch}": {"get": {"operationId": "getQAQualityInputSnapshot", "summary": "管理员读取已采集的历史质量输入快照,不另存人员关联/反馈字段;元数据留档但未采集原文返回409,不编造空快照", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "epoch", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "该输入版本仅有指纹/规则元数据、原文未采集"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
+2 -2
View File
@@ -14,7 +14,7 @@ server {
set $api_upstream http://api:8080;
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
@@ -22,7 +22,7 @@ server {
location = /health {
set $health_upstream http://api:8080;
proxy_pass $health_upstream/health;
proxy_set_header Host $host;
proxy_set_header Host $http_host;
}
# 带内容哈希的构建产物:可以长期缓存(换版本必然换文件名);旧哈希文件已被新构建替换
@@ -0,0 +1,62 @@
package httpapi
import (
"net/http/httptest"
"os"
"regexp"
"testing"
)
// HTTP LAN/tailnet origins may omit Fetch Metadata. nginx must preserve the
// external authority including its port so Origin can be checked without it.
func TestQAProxyPreservesBrowserAuthority(t *testing.T) {
config, err := os.ReadFile("../../deploy/nginx.conf")
if err != nil {
t.Fatal(err)
}
hosts := regexp.MustCompile(`(?m)^\s*proxy_set_header\s+Host\s+([^;]+);`).FindAllStringSubmatch(string(config), -1)
if len(hosts) < 2 {
t.Fatal("API and health proxy Host directives must both be explicit")
}
for _, host := range hosts {
if host[1] != "$http_host" {
t.Fatalf("proxy drops browser authority/port: got %q, want $http_host", host[1])
}
}
}
func TestQAIntentWithoutFetchMetadataChecksExactAuthority(t *testing.T) {
for _, tc := range []struct {
name, host, origin, forwarded, site, intent string
allowed bool
}{
{"LAN same authority", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "", "qa-quality", true},
{"tailnet same authority", "100.92.49.78:8088", "http://100.92.49.78:8088", "", "", "qa-quality", true},
{"proxy stripped port", "192.168.50.134", "http://192.168.50.134:8088", "", "", "qa-quality", false},
{"foreign origin", "192.168.50.134:8088", "http://foreign.invalid:8088", "", "", "qa-quality", false},
{"different port", "192.168.50.134:8088", "http://192.168.50.134:8089", "", "", "qa-quality", false},
{"forwarded header cannot grant", "192.168.50.134:8088", "http://foreign.invalid:8088", "foreign.invalid:8088", "", "qa-quality", false},
{"opaque origin", "192.168.50.134:8088", "null", "", "", "qa-quality", false},
{"explicit cross site", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "cross-site", "qa-quality", false},
{"missing intent", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "http://"+tc.host+"/api/v1/qa-ops/quality/query", nil)
req.Header.Set("Origin", tc.origin)
req.Header.Set("X-Governance-Action", tc.intent)
if tc.forwarded != "" {
req.Header.Set("X-Forwarded-Host", tc.forwarded)
}
if tc.site != "" {
req.Header.Set("Sec-Fetch-Site", tc.site)
}
rec := httptest.NewRecorder()
if got := authorizeQAIntent(rec, req, "qa-quality"); got != tc.allowed {
t.Fatalf("authorized=%v want %v, HTTP=%d", got, tc.allowed, rec.Code)
}
if !tc.allowed && rec.Code != 403 {
t.Fatalf("rejected authority should be 403, got %d", rec.Code)
}
})
}
}
+8
View File
@@ -117,6 +117,14 @@ func TestQAQualityDetailListAndWholeScopeCounts(t *testing.T) {
if w.Code != 200 || !strings.Contains(w.Body.String(), `"unreviewed":2`) || source.scopeCalls != 1 || source.tenant != "fixed" || store.calls < 2 {
t.Fatal("quality summary estimated from page instead of scope", w.Code, w.Body.String())
}
var counts struct {
Data struct {
Summary qaopsquality.Summary `json:"summary"`
} `json:"data"`
}
if json.Unmarshal(w.Body.Bytes(), &counts) != nil || counts.Data.Summary.Rates.Coverage.Denominator != 2 || counts.Data.Summary.Rates.Coverage.Numerator != 0 || counts.Data.Summary.Rates.Correctness.Percent != nil {
t.Fatal("confirmed quality metrics were not computed for the whole scope")
}
store.fail = true
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
if w.Code != 503 || !strings.Contains(w.Body.String(), "quality_unavailable") {
+1 -1
View File
@@ -104,7 +104,7 @@ func Project(hash string, epoch, revision int64, automatic Check, review *Review
return view
}
func Summarize(views map[string]View) Summary {
result := Summary{Total: len(views)}
result := Summary{Total: len(views), Rates: ComputeRates(views)}
for _, v := range views {
switch v.State {
case "reviewed":
+7 -6
View File
@@ -64,12 +64,13 @@ type History struct {
NextCheck int64 `json:"next_check"`
}
type Summary struct {
Total int `json:"total"`
Reviewed int `json:"reviewed"`
Unreviewed int `json:"unreviewed"`
Stale int `json:"stale"`
PendingConfirmation int `json:"pending_confirmation"`
RuleUncovered int `json:"rule_uncovered"`
Rates Rates `json:"rates"`
Total int `json:"total"`
Reviewed int `json:"reviewed"`
Unreviewed int `json:"unreviewed"`
Stale int `json:"stale"`
PendingConfirmation int `json:"pending_confirmation"`
RuleUncovered int `json:"rule_uncovered"`
}
type Receipt struct {
View View `json:"view"`
+72
View File
@@ -0,0 +1,72 @@
package qaopsquality
type Rate struct {
Numerator int `json:"numerator"`
Denominator int `json:"denominator"`
Percent *float64 `json:"percent"`
}
type RateBreakdown struct {
Covered int `json:"covered"`
Uncovered int `json:"uncovered"`
Partial int `json:"partial"`
Pending int `json:"pending"`
Unassessed int `json:"unassessed"`
Excluded int `json:"excluded"`
Stale int `json:"stale"`
CoveredCorrect int `json:"covered_correct"`
CoveredIncorrect int `json:"covered_incorrect"`
CoveredPending int `json:"covered_pending"`
CoveredUnassessed int `json:"covered_unassessed"`
}
type Rates struct {
PolicyVersion string `json:"policy_version"`
Coverage Rate `json:"coverage"`
Correctness Rate `json:"correctness"`
Breakdown RateBreakdown `json:"breakdown"`
}
func ComputeRates(views map[string]View) Rates {
out := Rates{PolicyVersion: "quality-rates-human-first-v1"}
b := &out.Breakdown
for _, v := range views {
if v.State == "stale" {
b.Stale++
continue
}
switch v.Effective.Coverage {
case "covered":
b.Covered++
switch v.Effective.Correctness {
case "correct":
b.CoveredCorrect++
case "incorrect":
b.CoveredIncorrect++
case "pending":
b.CoveredPending++
default:
b.CoveredUnassessed++
}
case "uncovered":
b.Uncovered++
case "partial":
b.Partial++
case "pending":
b.Pending++
case "excluded":
b.Excluded++
default:
b.Unassessed++
}
}
out.Coverage = makeRate(b.Covered, b.Covered+b.Uncovered+b.Partial)
out.Correctness = makeRate(b.CoveredCorrect, b.CoveredCorrect+b.CoveredIncorrect)
return out
}
func makeRate(numerator, denominator int) Rate {
r := Rate{Numerator: numerator, Denominator: denominator}
if denominator > 0 {
p := 100 * float64(numerator) / float64(denominator)
r.Percent = &p
}
return r
}
+44
View File
@@ -0,0 +1,44 @@
package qaopsquality
import (
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"math"
"strings"
"testing"
)
func TestQualityRatesUseEffectiveCurrentConclusionsAndExplicitDenominators(t *testing.T) {
views := map[string]View{}
for i, fields := range []Fields{{Coverage: "covered", Correctness: "correct"}, {Coverage: "covered", Correctness: "incorrect"}, {Coverage: "covered", Correctness: "pending"}, {Coverage: "uncovered"}, {Coverage: "partial", Correctness: "correct"}, {Coverage: "pending", Correctness: "correct"}, {}, {Coverage: "excluded", Correctness: "pending"}, {Coverage: "covered", Correctness: "correct"}, {Coverage: "covered"}} {
state := "reviewed"
if i == 3 || i == 6 {
state = "unreviewed"
}
if i == 8 {
state = "stale"
}
views[string(rune('a'+i))] = View{State: state, Effective: fields, Automatic: Check{Result: dobotaiops.CheckAnswerCoverage("暂无已发布")}}
}
r := ComputeRates(views)
if r.PolicyVersion != "quality-rates-human-first-v1" || r.Coverage.Numerator != 4 || r.Coverage.Denominator != 6 || r.Correctness.Numerator != 1 || r.Correctness.Denominator != 2 {
t.Fatal("effective decisions, partial or exclusion scopes incorrect", r)
}
if r.Coverage.Percent == nil || math.Abs(*r.Coverage.Percent-100*float64(4)/6) > 1e-10 || r.Correctness.Percent == nil || *r.Correctness.Percent != 50 {
t.Fatal("ratio value disagrees with raw counts")
}
b := r.Breakdown
if b.Covered+b.Uncovered+b.Partial+b.Pending+b.Unassessed+b.Excluded+b.Stale != len(views) || b.CoveredCorrect+b.CoveredIncorrect+b.CoveredPending+b.CoveredUnassessed != b.Covered {
t.Fatal("denominator breakdown not conserved")
}
if got := Summarize(views); got.Rates.Coverage.Denominator != 6 {
t.Fatal("scope summary did not consume the one shared calculation")
}
}
func TestQualityRatesEmptyScopeHasNullPercent(t *testing.T) {
r := ComputeRates(map[string]View{})
raw, _ := json.Marshal(r)
if r.Coverage.Percent != nil || r.Correctness.Percent != nil || strings.Count(string(raw), `"percent":null`) != 2 {
t.Fatal("zero denominator fabricated zero or full rate")
}
}
+26 -3
View File
@@ -50,17 +50,40 @@ const props = {
}
describe('QA operations workbench', () => {
it('shows populated columns in required order and keeps false/downvotes visible', () => {
it('shows all required columns even when empty and keeps false/downvotes visible', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
expect(html).toContain('原始问题')
expect(html.indexOf('AI答案')).toBeLessThan(html.indexOf('是否覆盖'))
expect(html.indexOf('是否正确')).toBeLessThan(html.indexOf('提问时间'))
expect(html).toContain('否(点踩)')
expect(html).toContain('是否正确')
expect(html).not.toContain('<th>部门</th>')
expect(html).not.toContain('<th>产品分类</th>')
expect(html).toContain('<th>部门</th>')
expect([...html.matchAll(/<th>(.*?)<\/th>/g)].slice(0, 14).map((match) => match[1])).toEqual([
'中文问题',
'AI答案',
'是否覆盖',
'是否正确',
'产品分类',
'问题类型',
'根因分析',
'提问时间',
'提问人',
'原始问题',
'语言',
'流程触发人员信息',
'部门',
'区域',
])
expect(html).toContain('<th>产品分类</th>')
expect(html).not.toContain('<script>not executable</script>')
})
it('never shows a load-more control for the all-records table', () => {
const html = renderToStaticMarkup(
<QAOperationsView {...props} page={{ ...page, total: 2, has_more: true, next_cursor: 'next' }} />
)
expect(html).not.toContain('加载更多')
expect(html).not.toContain('空列按整个筛选结果隐藏')
})
it('distinguishes an unavailable source from a successful empty query', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} page={null} error="只读源不可用" />)
expect(html).toContain('role="alert"')
+55 -54
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import type { FormEvent } from 'react'
import { useOptionalAuth } from './auth'
import { fetchQARecord, fetchQARecords, fetchQAStatus, mergeQAPages, qaCellValue, qaColumns } from './qaOps'
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
import './qaOps.css'
import { QARegions } from './QARegions'
@@ -10,6 +10,8 @@ import { QAMonthly } from './QAMonthly'
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
import { qualityLabels } from './qaQuality'
import { usageLabels } from './qaUsage'
import { QAWeekPicker } from './QAWeekPicker'
import { currentQAWeek, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
interface ViewProps {
onQualitySaved?: (record: QARecord) => void
@@ -23,7 +25,7 @@ interface ViewProps {
detailError: string | null
onSelect: (id: string) => void
onCloseDetail: () => void
onLoadMore: () => void
progress?: { loaded: number; total: number }
onRetry: () => void
}
const stateLabels = { disabled: '未配置', unavailable: '连接不可用', blocked: '接入被阻断', connected: '已连接' }
@@ -42,14 +44,18 @@ const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', unc
export function QAOperationsView(props: ViewProps) {
const page = props.page
const columns = qaColumns.filter(({ key }) => page?.columns.includes(key))
const columns = qaColumns
const detail = props.detail
const showDrawer = Boolean(detail || props.detailLoading || props.detailError)
return (
<section className="qa-ops-results" aria-label="问答记录">
<div className="qa-ops-result-bar">
<span>
{props.loading ? '正在读取…' : page ? `共 ${page.total} 条 · 已显示 ${page.items.length} 条` : '尚未读取问答'}
{props.loading
? `正在读取全部问答…${props.progress ? `(${props.progress.loaded} / ${props.progress.total})` : ''}`
: page
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
: '尚未读取问答'}
</span>
<span className="qa-ops-source">
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
@@ -132,14 +138,8 @@ export function QAOperationsView(props: ViewProps) {
) : null}
{page ? (
<footer className="qa-ops-page-bar">
<span>本次读取:{stamp(page.as_of)} · 空列按整个筛选结果隐藏</span>
{page.has_more ? (
<button type="button" onClick={props.onLoadMore} disabled={props.loading}>
{props.loading ? '读取中…' : '加载更多'}
</button>
) : page.items.length > 0 ? (
<span>已显示全部</span>
) : null}
<span>本次读取:{stamp(page.as_of)} · 固定显示完整字段,左右滚动查看;— 表示暂无数据</span>
<span>{page.items.length === page.total ? '已全部展示' : '全量读取尚未完成'}</span>
</footer>
) : null}
{showDrawer ? (
@@ -290,12 +290,10 @@ export function QAOperationsView(props: ViewProps) {
)
}
function localInput(value: Date): string {
return new Date(value.getTime() - value.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
}
function initialDraft() {
const end = new Date()
return { start: localInput(new Date(end.getTime() - 7 * 24 * 3600_000)), end: localInput(end), keyword: '' }
const current = currentQAWeek()
const { year, week, start, end } = qaWeekQueryRange(current.year, current.week)
return { year, week: week as number | null, start, end, keyword: '' }
}
export function QAOperations() {
@@ -314,16 +312,15 @@ export function QAOperations() {
const [detail, setDetail] = useState<QARecord | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState<string | null>(null)
const generation = useRef(0)
const [progress, setProgress] = useState<{ loaded: number; total: number } | undefined>()
const detailRequest = useRef<AbortController | null>(null)
const moreRequest = useRef<AbortController | null>(null)
const returnFocus = useRef<HTMLElement | null>(null)
useEffect(() => {
if (!canRead || query) return
setQuery({
start: new Date(draft.start).toISOString(),
end: new Date(draft.end).toISOString(),
start: qaDateTimeToISO(draft.start),
end: qaDateTimeToISO(draft.end),
keyword: draft.keyword,
cursor: '',
})
@@ -333,18 +330,16 @@ export function QAOperations() {
if (!query || !canRead) return
if (view !== 'records') {
setLoading(false)
moreRequest.current?.abort()
detailRequest.current?.abort()
setDetail(null)
return
}
const controller = new AbortController()
generation.current += 1
moreRequest.current?.abort()
detailRequest.current?.abort()
setLoading(true)
setError(null)
setPage(null)
setProgress(undefined)
setDetail(null)
setDetailError(null)
setDetailLoading(false)
@@ -353,7 +348,9 @@ export function QAOperations() {
.catch(() => {
if (!controller.signal.aborted) setStatus(null)
})
void fetchQARecords(query, controller.signal)
void fetchAllQARecords(query, controller.signal, (loaded, total) => {
if (!controller.signal.aborted) setProgress({ loaded, total })
})
.then((result) => {
if (!controller.signal.aborted) setPage(result)
})
@@ -369,7 +366,6 @@ export function QAOperations() {
useEffect(
() => () => {
detailRequest.current?.abort()
moreRequest.current?.abort()
},
[]
)
@@ -377,10 +373,11 @@ export function QAOperations() {
const submit = (event: FormEvent) => {
event.preventDefault()
try {
const start = new Date(draft.start),
end = new Date(draft.end)
if (!(start < end)) throw new Error('开始时间必须早于结束时间')
setQuery({ start: start.toISOString(), end: end.toISOString(), keyword: draft.keyword, cursor: '' })
const start = qaDateTimeToISO(draft.start),
end = qaDateTimeToISO(draft.end)
if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间')
if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围')
setQuery({ start, end, keyword: draft.keyword, cursor: '' })
} catch (reason) {
setError(reason instanceof Error ? reason.message : '时间格式无效')
}
@@ -409,25 +406,6 @@ export function QAOperations() {
setDetailLoading(false)
returnFocus.current?.focus()
}
const loadMore = async () => {
if (!query || !page?.has_more || loading) return
const currentGeneration = generation.current
const controller = new AbortController()
moreRequest.current = controller
setLoading(true)
setError(null)
try {
const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal)
if (!controller.signal.aborted && currentGeneration === generation.current) {
setPage(mergeQAPages(page, result))
}
} catch (reason) {
if (!controller.signal.aborted && currentGeneration === generation.current)
setError(reason instanceof Error ? reason.message : '翻页失败')
} finally {
if (!controller.signal.aborted && currentGeneration === generation.current) setLoading(false)
}
}
return (
<section className="qa-ops" aria-label="问答运营">
<header className="qa-ops-header">
@@ -470,22 +448,45 @@ export function QAOperations() {
) : (
<>
<form className="qa-ops-query" onSubmit={submit}>
{view === 'records' ? (
<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: '',
})
}}
onChange={(year, week) => {
setDraft((old) => {
if (week === null) return { ...old, year, week }
const { start, end } = qaWeekQueryRange(year, week)
return { ...old, year, week, start, end }
})
}}
/>
) : null}
<label>
开始时间
开始时间(北京时间)
<input
type="datetime-local"
required
value={draft.start}
onChange={(event) => setDraft({ ...draft, start: event.target.value })}
onChange={(event) => setDraft({ ...draft, start: event.target.value, week: null })}
/>
</label>
<label>
结束时间(不含)
结束时间(北京时间,不含)
<input
type="datetime-local"
required
value={draft.end}
onChange={(event) => setDraft({ ...draft, end: event.target.value })}
onChange={(event) => setDraft({ ...draft, end: event.target.value, week: null })}
/>
</label>
<label className="qa-ops-keyword">
@@ -543,7 +544,7 @@ export function QAOperations() {
}}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
progress={progress}
onRetry={() => setRevision((value) => value + 1)}
/>
)}
+53
View File
@@ -41,3 +41,56 @@ describe('manual quality operations', () => {
expect(ok).toContain('AI 评估未接入')
})
})
it('displays approved rates with raw denominators and exclusions', () => {
const html = renderToStaticMarkup(
<QAQualitySummaryView data={parseQualitySummary(summaryFixture)} error="" loading={false} onRefresh={() => {}} />
)
for (const value of [
'知识覆盖率',
'回答正确率',
'50.0%',
'100.0%',
'分子',
'分母',
'排除',
'部分覆盖',
'quality-rates-human-first-v1',
])
expect(html).toContain(value)
expect(html).not.toContain('不计算比例')
})
it('does not turn zero denominators into 0% or 100%', () => {
const v = parseQualitySummary(structuredClone(summaryFixture))
v.summary = {
total: 0,
reviewed: 0,
unreviewed: 0,
stale: 0,
pending_confirmation: 0,
rule_uncovered: 0,
rates: {
policy_version: 'quality-rates-human-first-v1',
coverage: { numerator: 0, denominator: 0, percent: null },
correctness: { numerator: 0, denominator: 0, percent: null },
breakdown: {
covered: 0,
uncovered: 0,
partial: 0,
pending: 0,
unassessed: 0,
excluded: 0,
stale: 0,
covered_correct: 0,
covered_incorrect: 0,
covered_pending: 0,
covered_unassessed: 0,
},
},
} as typeof v.summary
const html = renderToStaticMarkup(
<QAQualitySummaryView data={parseQualitySummary(v)} error="" loading={false} onRefresh={() => {}} />
)
expect(html).toContain('暂无可计算数据')
expect(html).not.toContain('0.0%')
})
+40 -1
View File
@@ -421,8 +421,47 @@ export function QAQualitySummaryView({ data, loading, error, onRefresh }: Summar
待重新核对 {data.summary.stale} · 人工待确认 {data.summary.pending_confirmation} · 规则命中未覆盖{' '}
{data.summary.rule_uncovered}
</p>
<div className="qa-quality-rates" aria-label="质量比例">
{(
[
['知识覆盖率', data.summary.rates.coverage],
['回答正确率', data.summary.rates.correctness],
] as const
).map(([label, rate]) => (
<div key={label}>
<strong>
{label}:{rate.percent === null ? '暂无可计算数据' : `${rate.percent.toFixed(1)}%`}
</strong>
<p>
分子 {rate.numerator} / 分母 {rate.denominator};排除 {data.summary.total - rate.denominator} 条
</p>
</div>
))}
</div>
<details className="qa-ops-organization">
<summary>查看比例口径和分母构成</summary>
<p>
覆盖分母:已覆盖 {data.summary.rates.breakdown.covered} + 未覆盖 {data.summary.rates.breakdown.uncovered}{' '}
+ 部分覆盖 {data.summary.rates.breakdown.partial};部分覆盖不计完全覆盖。
</p>
<p>
覆盖分母排除:待确认 {data.summary.rates.breakdown.pending}、未评估{' '}
{data.summary.rates.breakdown.unassessed}、不计入 {data.summary.rates.breakdown.excluded}、待重新核对{' '}
{data.summary.rates.breakdown.stale}。
</p>
<p>
正确性分母仅含已覆盖且判断明确:正确 {data.summary.rates.breakdown.covered_correct} + 错误{' '}
{data.summary.rates.breakdown.covered_incorrect};已覆盖中的待确认{' '}
{data.summary.rates.breakdown.covered_pending}、未评估 {data.summary.rates.breakdown.covered_unassessed}{' '}
不计入,其余未覆盖/部分覆盖等记录也不计入。
</p>
<p>
当前有效人工结论优先;精确规则命中的未覆盖可进入覆盖分母,但不证明回答错误。失效记录暂不参与两项比例,原始问答运行成功也不代表答案正确。
</p>
<p className="qa-ops-muted">统计规则:{data.summary.rates.policy_version}</p>
</details>
<p className="qa-ops-muted">
AI 评估未接入;人工待确认是已复核中的子集,规则命中可与人工结论不同。不计算比例。读取:{stamp(data.as_of)}
AI 评估未接入;人工待确认是已复核中的子集,规则命中可与人工结论不同。读取:{stamp(data.as_of)}
</p>
</>
) : !error && !loading ? (
+27
View File
@@ -0,0 +1,27 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { QAWeekPicker } from './QAWeekPicker'
describe('QA week picker', () => {
it('offers a one-click current-week shortcut', () => {
const html = renderToStaticMarkup(<QAWeekPicker year={2026} week={40} onChange={vi.fn()} />)
expect(html).toContain('>本周</button>')
})
it('shows a year and numbered weeks with visible inclusive date ranges', () => {
const html = renderToStaticMarkup(<QAWeekPicker year={2026} week={40} onChange={vi.fn()} />)
expect(html).toContain('aria-label="年份"')
expect(html).toContain('2026年')
expect(html).toContain('aria-label="周次"')
expect(html).toContain('value="40" selected=""')
expect(html).toContain('第40周(09-28 到 10-04)')
expect(html).toContain('第53周(2026-12-28 到 2027-01-03)')
expect(html).toContain('北京时间')
expect(html).toContain('周一至周日')
})
it('preserves custom range mode and does not offer invalid week 53', () => {
const html = renderToStaticMarkup(<QAWeekPicker year={2027} week={null} onChange={vi.fn()} />)
expect(html).toContain('value="" selected=""')
expect(html).toContain('自定义时间')
expect(html).not.toContain('第53周')
})
})
+56
View File
@@ -0,0 +1,56 @@
import { currentQAWeek, qaWeek, qaWeeksInYear } from './qaWeeks'
interface Props {
year: number
week: number | null
onChange: (year: number, week: number | null) => void
onCurrentWeek?: () => void
}
export function QAWeekPicker({ year, week, onChange, onCurrentWeek }: Props) {
const currentYear = currentQAWeek().year
const firstYear = Math.min(currentYear - 5, year)
const lastYear = Math.max(currentYear + 1, year)
return (
<div className="qa-week-picker" role="group" aria-label="按周选择">
<label>
年份
<select
aria-label="年份"
value={year}
onChange={(event) => {
const nextYear = Number(event.target.value)
onChange(nextYear, Math.min(week ?? 1, qaWeeksInYear(nextYear)))
}}
>
{Array.from({ length: lastYear - firstYear + 1 }, (_, i) => firstYear + i)
.reverse()
.map((value) => (
<option key={value} value={value}>
{value}年
</option>
))}
</select>
</label>
<label>
周次
<select
aria-label="周次"
value={week ?? ''}
onChange={(event) => onChange(year, event.target.value === '' ? null : Number(event.target.value))}
>
<option value="">自定义时间</option>
{Array.from({ length: qaWeeksInYear(year) }, (_, i) => i + 1).map((value) => (
<option key={value} value={value}>
{qaWeek(year, value).label}
</option>
))}
</select>
</label>
<button className="qa-week-current" type="button" onClick={onCurrentWeek}>
本周
</button>
<span className="qa-ops-muted">北京时间 · 周一至周日 · 本周截至当前</span>
</div>
)
}
+88
View File
@@ -0,0 +1,88 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchAllQARecords } from './qaOps'
const row = (id: string) => ({
id,
status: 'succeeded',
question: '明确合成问题',
answer: '明确合成答案',
asked_at: '2026-10-14T03:00:00Z',
time_source: 'request_message.created_at',
asker: '合成夹具',
trigger_person: '',
department: '',
region: '',
references: [],
media: [],
source_coverage: { verdict: '', reason_code: '', evaluator_version: '' },
feedback: { asker_value: '', up: 0, down: 0 },
coverage: { state: 'pending', rule_version: 'fixture-rule' },
})
const page = (ids: string[], total: number, cursor = '') => ({
items: ids.map(row),
columns: [],
total,
has_more: Boolean(cursor),
next_cursor: cursor,
as_of: '2026-10-14T04:00:00Z',
})
const query = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T08:00:00Z', keyword: '%_原文', cursor: 'stale-cursor' }
const respond = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 })
afterEach(() => vi.unstubAllGlobals())
describe('all QA records without manual pagination', () => {
it('rejects incomplete, duplicate, drifting and cycling batches', async () => {
const cases = [
[page(['a'], 2)],
[page(['a'], 2, 'n'), page(['a'], 2)],
[page(['a'], 2, 'n'), page(['b'], 3)],
[page(['a'], 3, 'n'), page(['b'], 3, 'n')],
]
for (const pages of cases) {
const fetcher = vi.fn()
pages.forEach((data) => fetcher.mockResolvedValueOnce(respond(data)))
vi.stubGlobal('fetch', fetcher)
await expect(fetchAllQARecords(query)).rejects.toThrow()
}
})
it('surfaces a later source failure instead of returning the first batch', async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce(respond(page(['a'], 2, 'n')))
.mockResolvedValueOnce(new Response(JSON.stringify({ error: '明确合成源不可用' }), { status: 503 }))
vi.stubGlobal('fetch', fetcher)
await expect(fetchAllQARecords(query)).rejects.toThrow('明确合成源不可用')
})
it('accepts a genuinely empty complete scope', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(respond(page([], 0))))
expect((await fetchAllQARecords(query)).items).toEqual([])
})
it('does not start or continue requests after cancellation', async () => {
const controller = new AbortController()
controller.abort()
const fetcher = vi.fn().mockResolvedValue(respond(page([], 0)))
vi.stubGlobal('fetch', fetcher)
await expect(fetchAllQARecords(query, controller.signal)).rejects.toMatchObject({ name: 'AbortError' })
expect(fetcher).not.toHaveBeenCalled()
})
it('reads every transport batch and verifies final count before returning', async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce(respond(page(['a', 'b'], 3, 'next')))
.mockResolvedValueOnce(respond(page(['c'], 3)))
vi.stubGlobal('fetch', fetcher)
const progress = vi.fn()
const result = await fetchAllQARecords(query, undefined, progress)
expect(result.items.map((r) => r.id)).toEqual(['a', 'b', 'c'])
expect(result.has_more).toBe(false)
expect(result.total).toBe(3)
expect(progress.mock.calls).toEqual([
[2, 3],
[3, 3],
])
const urls = fetcher.mock.calls.map((call) => new URL(String(call[0]), 'http://localhost'))
expect(urls.map((url) => url.searchParams.get('cursor'))).toEqual(['', 'next'])
expect(
urls.every((url) => url.searchParams.get('limit') === '100' && url.searchParams.get('keyword') === query.keyword)
).toBe(true)
})
})
+43 -1
View File
@@ -163,7 +163,8 @@
color: var(--ink-mute);
font-size: 12px;
}
.qa-ops-query input {
.qa-ops-query input,
.qa-week-picker select {
min-height: 36px;
min-width: 0;
padding: 7px 10px;
@@ -172,6 +173,24 @@
border-radius: var(--r-sm);
background: var(--bg-panel);
}
.qa-week-picker {
display: flex;
flex-wrap: wrap;
align-items: end;
flex-basis: 100%;
min-width: 0;
gap: 12px;
}
.qa-week-picker label {
min-width: 0;
}
.qa-week-picker select {
max-width: 100%;
font: inherit;
}
.qa-week-picker > span {
padding-bottom: 8px;
}
.qa-ops-keyword {
flex: 1;
min-width: 170px;
@@ -183,8 +202,17 @@
background: var(--c-run);
border: 1px solid var(--c-run);
}
.qa-ops-query .qa-week-current {
color: var(--ink-strong);
background: var(--bg-panel);
border-color: var(--border-strong);
}
.qa-ops-query .qa-week-current:hover {
background: var(--bg-soft);
}
.qa-ops button:focus-visible,
.qa-ops input:focus-visible,
.qa-ops select:focus-visible,
.qa-ops-table-scroll:focus-visible {
outline: 2px solid var(--c-run);
outline-offset: 2px;
@@ -394,3 +422,17 @@
grid-template-columns: 100px 1fr;
}
}
.qa-quality-rates {
display: flex;
flex-wrap: wrap;
gap: 12px 32px;
margin: 12px 0;
}
.qa-quality-rates > div {
min-width: 0;
overflow-wrap: anywhere;
}
.qa-quality-rates p {
margin: 4px 0 0;
}
+34 -1
View File
@@ -259,6 +259,35 @@ export async function fetchQARecords(query: QAQuery, signal?: AbortSignal): Prom
})
return parseQARecordPage(await getPayload(`/api/v1/qa-ops/records?${parameters}`, signal))
}
export async function fetchAllQARecords(
query: QAQuery,
signal?: AbortSignal,
onProgress?: (loaded: number, total: number) => void
): Promise<QARecordPage> {
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
let page = await fetchQARecords({ ...query, cursor: '', limit: 100 }, signal)
const total = page.total
const ids = new Set(page.items.map((item) => item.id))
const cursors = new Set<string>()
onProgress?.(ids.size, total)
while (page.has_more) {
if (signal?.aborted) throw new DOMException('读取已取消', 'AbortError')
const cursor = page.next_cursor
if (cursors.has(cursor) || ids.size >= total) throw new Error('全量读取游标异常,请重新查询')
cursors.add(cursor)
const next = await fetchQARecords({ ...query, cursor, limit: 100 }, signal)
if (next.total !== total) throw new Error('查询总数已变化,请重新查询,未将部分记录当作全部结果')
for (const item of next.items) {
if (ids.has(item.id)) throw new Error('全量读取出现重复记录,请重新查询')
ids.add(item.id)
}
page = mergeQAPages(page, next)
onProgress?.(ids.size, total)
}
if (ids.size !== total) throw new Error('全量读取数量不完整,请重试,未将部分记录当作全部结果')
return page
}
export async function fetchQARecord(id: string, signal?: AbortSignal): Promise<QARecord> {
return parseQARecord(await getPayload(`/api/v1/qa-ops/records/${encodeURIComponent(id)}`, signal))
}
@@ -283,6 +312,9 @@ export async function fetchQAStatus(signal?: AbortSignal): Promise<QAStatus> {
}
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (column === 'question_chinese')
return item.question_chinese || (/\p{Script=Han}/u.test(item.question) ? item.question : '待翻译')
if (column === 'language') return item.language || '未识别'
const f = item.quality?.effective
if (f) {
if (column === 'coverage')
@@ -309,6 +341,7 @@ export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (item.feedback.up || item.feedback.down) return `其他人:赞 ${item.feedback.up} / 踩 ${item.feedback.down}`
return null
}
if (column === 'asked_at') return new Date(item.asked_at).toLocaleString('zh-CN', { hour12: false })
if (column === 'asked_at')
return new Date(item.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
return item[column] || null
}
+26 -1
View File
@@ -40,7 +40,32 @@ export const qualityFixture = {
effective: fields,
}
export const summaryFixture = {
summary: { total: 3, reviewed: 1, unreviewed: 1, stale: 1, pending_confirmation: 0, rule_uncovered: 2 },
summary: {
total: 3,
reviewed: 1,
unreviewed: 1,
stale: 1,
pending_confirmation: 0,
rule_uncovered: 2,
rates: {
policy_version: 'quality-rates-human-first-v1',
coverage: { numerator: 1, denominator: 2, percent: 50 },
correctness: { numerator: 1, denominator: 1, percent: 100 },
breakdown: {
covered: 1,
uncovered: 1,
partial: 0,
pending: 0,
unassessed: 0,
excluded: 0,
stale: 1,
covered_correct: 1,
covered_incorrect: 0,
covered_pending: 0,
covered_unassessed: 0,
},
},
},
start: '2026-10-14T00:00:00Z',
end: '2026-10-15T00:00:00Z',
keyword: '',
+23
View File
@@ -49,3 +49,26 @@ describe('quality evidence contracts', () => {
).toHaveLength(1)
})
})
describe('confirmed quality rate contract', () => {
it('retains raw counts, null rates, scope breakdown and policy version', () => {
const result = parseQualitySummary(summaryFixture)
expect(result.summary.rates.coverage.numerator).toBe(1)
expect(result.summary.rates.coverage.denominator).toBe(2)
expect(result.summary.rates.correctness.percent).toBe(100)
})
it('rejects invalid or inconsistent numerator, denominator, percent and category sums', () => {
for (const change of [
(r: any) => (r.coverage.numerator = 3),
(r: any) => (r.coverage.denominator = 3),
(r: any) => (r.coverage.percent = 99),
(r: any) => (r.breakdown.stale = 0),
(r: any) => (r.correctness.percent = null),
(r: any) => (r.policy_version = 'unknown'),
]) {
const v = structuredClone(summaryFixture)
change(v.summary.rates)
expect(() => parseQualitySummary(v)).toThrow()
}
})
})
+75
View File
@@ -45,6 +45,29 @@ export interface QualitySnapshot {
created_at: string
payload: { id: string; question: string; answer: string; status: string; references: unknown; media: unknown }
}
export interface QualityRate {
numerator: number
denominator: number
percent: number | null
}
export interface QualityRates {
policy_version: 'quality-rates-human-first-v1'
coverage: QualityRate
correctness: QualityRate
breakdown: {
covered: number
uncovered: number
partial: number
pending: number
unassessed: number
excluded: number
stale: number
covered_correct: number
covered_incorrect: number
covered_pending: number
covered_unassessed: number
}
}
export interface QualitySummary {
summary: {
total: number
@@ -53,6 +76,7 @@ export interface QualitySummary {
stale: number
pending_confirmation: number
rule_uncovered: number
rates: QualityRates
}
start: string
end: string
@@ -195,6 +219,56 @@ export function parseQAQuality(value: unknown): QAQuality {
for (const key of Object.keys(expected) as (keyof QualityFields)[]) if (expected[key] !== effective[key]) return bad()
return { input_hash, input_epoch, revision, state: state as QAQuality['state'], automatic, latest_review, effective }
}
function qualityRate(value: unknown): QualityRate {
const v = obj(value),
numerator = num(v.numerator),
denominator = num(v.denominator)
if (numerator > denominator) return bad()
if (denominator === 0) {
if (v.percent !== null) return bad()
return { numerator, denominator, percent: null }
}
if (
typeof v.percent !== 'number' ||
!Number.isFinite(v.percent) ||
v.percent < 0 ||
v.percent > 100 ||
Math.abs(v.percent - (100 * numerator) / denominator) > 1e-8
)
return bad()
return { numerator, denominator, percent: v.percent }
}
function qualityRates(value: unknown, total: number, stale: number): QualityRates {
const v = obj(value),
r = obj(v.breakdown)
const b = {
covered: num(r.covered),
uncovered: num(r.uncovered),
partial: num(r.partial),
pending: num(r.pending),
unassessed: num(r.unassessed),
excluded: num(r.excluded),
stale: num(r.stale),
covered_correct: num(r.covered_correct),
covered_incorrect: num(r.covered_incorrect),
covered_pending: num(r.covered_pending),
covered_unassessed: num(r.covered_unassessed),
}
const coverage = qualityRate(v.coverage),
correctness = qualityRate(v.correctness)
if (
v.policy_version !== 'quality-rates-human-first-v1' ||
b.stale !== stale ||
num(b.covered + b.uncovered + b.partial + b.pending + b.unassessed + b.excluded + b.stale) !== total ||
num(b.covered_correct + b.covered_incorrect + b.covered_pending + b.covered_unassessed) !== b.covered ||
coverage.numerator !== b.covered ||
coverage.denominator !== b.covered + b.uncovered + b.partial ||
correctness.numerator !== b.covered_correct ||
correctness.denominator !== b.covered_correct + b.covered_incorrect
)
return bad()
return { policy_version: 'quality-rates-human-first-v1', coverage, correctness, breakdown: b }
}
export function parseQualitySummary(value: unknown): QualitySummary {
const v = obj(value),
s = obj(v.summary),
@@ -205,6 +279,7 @@ export function parseQualitySummary(value: unknown): QualitySummary {
stale: num(s.stale),
pending_confirmation: num(s.pending_confirmation),
rule_uncovered: num(s.rule_uncovered),
rates: qualityRates(s.rates, num(s.total), num(s.stale)),
}
const start = stamp(v.start),
end = stamp(v.end)
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest'
import { currentQAWeek, qaDateTimeToISO, qaWeek, qaWeeksInYear, qaWeekQueryRange } from './qaWeeks'
describe('QA natural-week query ranges', () => {
it('caps the in-progress week at now but leaves completed weeks intact', () => {
const now = new Date('2026-10-18T06:00:00Z')
expect(qaWeekQueryRange(2026, 42, now).end).toBe('2026-10-18T14:00')
expect(qaWeekQueryRange(2026, 40, now).end).toBe('2026-10-05T00:00')
expect(qaWeekQueryRange(2026, 53, now).start).toBe('2026-12-28T00:00')
})
it('resolves the current ISO week at the Beijing midnight boundary', () => {
expect(currentQAWeek(new Date('2026-10-18T15:59:00Z'))).toMatchObject({ year: 2026, week: 42 })
expect(currentQAWeek(new Date('2026-10-18T16:01:00Z'))).toMatchObject({ year: 2026, week: 43 })
expect(currentQAWeek(new Date('2027-01-01T12:00:00Z'))).toMatchObject({ year: 2026, week: 53 })
})
it('converts Beijing form input to UTC without relying on the browser timezone', () => {
expect(qaDateTimeToISO('2026-09-28T00:00')).toBe('2026-09-27T16:00:00.000Z')
expect(qaDateTimeToISO('2026-10-05T00:00')).toBe('2026-10-04T16:00:00.000Z')
for (const input of ['', '2026-02-30T00:00', '2026-10-04', '2026-10-04T24:00', 'invalid']) {
expect(() => qaDateTimeToISO(input)).toThrow()
}
})
it('counts only the valid weeks for each year', () => {
expect(qaWeeksInYear(2026)).toBe(53)
expect(qaWeeksInYear(2027)).toBe(52)
expect(qaWeeksInYear(2020)).toBe(53)
expect(qaWeeksInYear(2021)).toBe(52)
})
it('shows week dates inclusively and queries through the exclusive next Monday', () => {
expect(qaWeek(2026, 40)).toEqual({
year: 2026,
week: 40,
start: '2026-09-28T00:00',
end: '2026-10-05T00:00',
label: '第40周(09-28 到 10-04)',
})
})
it('rejects nonexistent weeks instead of spilling into the next year', () => {
expect(() => qaWeek(2027, 53)).toThrow()
for (const week of [0, -1, 54, 1.5, Number.NaN]) expect(() => qaWeek(2026, week)).toThrow()
for (const year of [0, 2026.5, Number.NaN]) expect(() => qaWeek(year, 1)).toThrow()
})
it('keeps the ISO week-year and shows years on crossing ranges', () => {
expect(qaWeek(2026, 1)).toMatchObject({
start: '2025-12-29T00:00',
end: '2026-01-05T00:00',
label: '第1周(2025-12-29 到 2026-01-04)',
})
expect(qaWeek(2026, 53)).toMatchObject({
start: '2026-12-28T00:00',
end: '2027-01-04T00:00',
label: '第53周(2026-12-28 到 2027-01-03)',
})
expect(qaWeek(2024, 9)).toMatchObject({ start: '2024-02-26T00:00', end: '2024-03-04T00:00' })
})
})
+67
View File
@@ -0,0 +1,67 @@
export interface QAWeek {
year: number
week: number
start: string
end: string
label: string
}
const day = 86_400_000
const dateOnly = (value: number) => new Date(value).toISOString().slice(0, 10)
export function currentQAWeek(now = new Date()): QAWeek {
const beijing = new Date(now.getTime() + 8 * 3_600_000)
beijing.setUTCHours(0, 0, 0, 0)
beijing.setUTCDate(beijing.getUTCDate() + 3 - ((beijing.getUTCDay() + 6) % 7))
const year = beijing.getUTCFullYear()
const week = Math.floor((beijing.getTime() - firstMonday(year)) / (7 * day)) + 1
return qaWeek(year, week)
}
export function qaDateTimeToISO(value: string): string {
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) throw new Error('时间格式无效')
const parsed = new Date(`${value}:00+08:00`)
if (
!Number.isFinite(parsed.getTime()) ||
new Date(parsed.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) !== value
) {
throw new Error('时间格式无效')
}
return parsed.toISOString()
}
export function qaWeekQueryRange(year: number, week: number, now = new Date()): QAWeek {
const range = qaWeek(year, week)
if (
Date.parse(qaDateTimeToISO(range.start)) < now.getTime() &&
now.getTime() < Date.parse(qaDateTimeToISO(range.end))
) {
return { ...range, end: new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) }
}
return range
}
const firstMonday = (year: number) => {
const jan4 = new Date(Date.UTC(year, 0, 4))
return jan4.getTime() - ((jan4.getUTCDay() + 6) % 7) * day
}
export function qaWeeksInYear(year: number): number {
if (!Number.isInteger(year) || year < 1900 || year > 9998) throw new Error('年份无效')
return (firstMonday(year + 1) - firstMonday(year)) / (7 * day)
}
export function qaWeek(year: number, week: number): QAWeek {
if (!Number.isInteger(week) || week < 1 || week > qaWeeksInYear(year)) throw new Error('周次无效')
const start = firstMonday(year) + (week - 1) * 7 * day
const first = dateOnly(start)
const last = dateOnly(start + 6 * day)
const crossYear = first.slice(0, 4) !== String(year) || last.slice(0, 4) !== String(year)
return {
year,
week,
start: `${first}T00:00`,
end: `${dateOnly(start + 7 * day)}T00:00`,
label: `第${week}周(${crossYear ? first : first.slice(5)} 到 ${crossYear ? last : last.slice(5)})`,
}
}