🐛 Restore acceptance markers and consistent dashboard totals

This commit is contained in:
Codex 2026-11-10 05:21:06 -08:00
parent dfb9d7bc65
commit 77ee8b0af1
19 changed files with 516 additions and 103 deletions

View File

@ -0,0 +1,40 @@
# 平台调优问题修复验证(2026-11-10)
Base: `0040988f`,统一 `dev` 工作区;未创建新分支。用户本轮授权本地逐项修复,未授权推送、部署或客户数据回写。
## 改动范围
| 问题 | 本地处置 | 仍需确认 |
| --- | --- | --- |
| 跨接口超时、送检锁竞争 | 整合 `404e40c0` 的安全锁释放和持久化有界重试,以及 `ae52e5d4` / `1ba3a0a6` 的检索、列表读取优化 | 发布后的真实请求效果;不把健康检查当成业务验收 |
| 送检后标注疑似丢失 | 整合 `d1dc4a38`:归档失败输入、保护正式修订及返工工作区、阻断空白切片覆盖 | 历史内容未恢复;既有调查未找到完整最新快照,本轮不回写客户数据 |
| 多人均为 12.1 小时 | 原始秒数不同,已确认是一位小数舍入;保留既有展示契约 | 不作为代码缺陷修改 |
| 验收时间点打点缺失 | 转发来源、切片与时间基准;按当前切片映射;补全 mediaOnly 的标记层,复用聚合与跳转逻辑 | 发布后业务验收 |
| 看板刷新跳动 | 同查询刷新沿用更新时间行显示状态,取消重复占位;失败仍清除旧值并报错 | 发布后业务验收 |
| 跨账号汇总不同 | 选定人员/角色时统一顶部、供应商及人员归属,保留组织/供应商/本人约束 | 发布后同快照对账 |
| 18 段约 2.35 小时 | 原附件实际显示 BLF-data、首次送检 10/10–11/09、通过 1.2 小时;此前 2.49 来自另一范围,不能混为同一差额 | 原 18 段清单缺失,已请求补充;不通过调整公式凑数 |
## 已有证据
- 跨账号回归在旧实现失败(管理员选验收员得到 0),修复后单元与 API 同快照对照通过;覆盖供应商隔离、不同角色、重复通过去重。
- 刷新浏览器在旧实现位移 67.5px,修复后 0px;看板和卡片没有重新挂载。合成 API 与账号,未写客户数据。
- 验收浏览器 native / movi / movi-fractional 三模式通过:保存后标记可见、点击跳转、换片不串点、刷新/重新进入后恢复、只读和加载失败禁写。
- 界面已查看本地合成截图:验收标记、刷新中看板。正常状态无新增说明栏,错误仍可见。
- 原始记录与命令日志位于忽略目录 `local-data/`;不在此保存凭证或客户标注正文。
## 最终验证
- 整批 `npm run verify:task -- --base 0040988f --budget-seconds 1800` 记录:`local-data/test-results/verify-1794315714569782000/report.json`。初始结果 31 passed / 3 failed / 2 incomplete,且过程中修改过统计代码;该报告本身不作为“整批全绿”证据。
- 三项首次失败已分别补证:管理员任务池原命令复跑通过(`local-data/admin-pool-browser-recheck.log`);刷新测试断言修正后,位移为 0px、失败清空旧值及恢复通过(`local-data/dashboard-refresh-final.log`);切片夹具补齐媒体引用、真实 validator 校验和当前“恢复”文案后,6 类编辑/撤销恢复场景通过(`local-data/slice-phase-final.log`)。没有放宽产品校验。
- 最终统计逻辑:`go test ./internal/workforcestats ./internal/api -run TestProductionQuality -count=1` 通过(`local-data/statistics-final-tests.log`)。顶部、供应商及人员使用同一累加入口,不再复制本人归因逻辑。
- 最终统计代码另跑 `python3 scripts/test_dashboard_stability.py`:race、timing 阶段 required 全通过,skipped 为空。5000 part / 4 API handler / 121 次暖查询,p95 59ms,未触发源事实重建(`local-data/platform-fixes-final-stability.log`)。这是本地合成验证,不是生产容量承诺。
- 最终 `npm run test:browser:dashboard`:admin / manager / u1 / qc / acceptor 五角色、空数据、筛选、失败与恢复通过,无异常写入和页面错误(`local-data/platform-fixes-final-dashboard.log`)。验收三播放器模式与重载后的标记显示/导航见 `local-data/test-results/acceptance-playback-rate/report.json`。
- 数据库专项:任务池 Mongo 旧数据、权限、分页、覆盖投影、大载荷;送检恢复事件持久化与隐私;锁取消、未开始操作释放、已开始且结果未知保持保护、进程崩溃恢复及旧 worker fencing 均通过。见整批报告 13、16、17、25、30、31、32 日志。
- 81 人读取混合冒烟:975 requests / 0 errors(整批 `29.log`)。检索性能的原三轮对照沿用未修改实现的 `docs/operations/acceptance-search-v2.md` 证据;本次组合后的短冒烟不冒充完整持续容量验收。
- 按集成计划补齐格式、前端基线门禁、生产构建和启动检查;Go 门禁在最终统计重构后复跑。前端 13 个失败均在既有 14 项基线内;Go 68 个失败均在既有 70 项基线内,没有新增失败,不修改基线。日志:`local-data/platform-fixes-{format,frontend-gate,build,boot}.log`、`local-data/platform-fixes-final-go-gate.log`。
- 验证映射 tooling 22 项通过(`local-data/platform-fixes-tooling.log`)。整批 store 默认运行中被跳过的其他 opt-in / replica-set 场景保留为未覆盖,不声称全库测试全部执行;本批相关 Mongo 路径已显式开启通过。推送、公司部署、客户数据回写、120 人长期容量及生产业务验收均未进行。
- 最终源文件摘要、基线与补充日志索引:忽略目录 `local-data/platform-fixes-evidence.json`。应用源码修改后重跑相应统计单元/API、race、时延及五角色浏览器验证,未将旧运行自动当作最终证据。
## 历史内容恢复边界
既有调查见 `../submission-loss-guard/validation.md` 的 Affected capture recovery:故障送检后发生普通切片生成与前置修订清理,旧 BOS 修订不可读,未取得完整最新返工快照。保留下来的打回基线不等于用户后来改好的内容。本次交付未来提交/重试保护,不声称已恢复历史丢失内容,不将旧基线写回当前任务。

View File

@ -22,7 +22,7 @@
新增 `/api/dashboard/production-quality`;原统计 API 默认语义不变。新接口使用已有共享快照,权限每次从当前身份限制,参数不能扩大组织、供应商或本人范围。默认两类列表各 5 条;CSV 使用相同筛选和快照,导出完整人员结果。昨日及近六天同样按各日首次提交批次计算最新质量结果。
生产时长按 part 去重,人员审查数据时长也表示处理过的去重 part 数据量,不是操作次数或实际工时;原工作记录接口的逐次审查工作量不变。各角色按自身负责的记录展示。可交付时长额外要求当前验收通过,且对应当前 release partition 的正式交付包已有 manifest digest;不把所有验收通过直接等同可交付。
生产时长按 part 去重,人员审查数据时长也表示处理过的去重 part 数据量,不是操作次数或实际工时;原工作记录接口的逐次审查工作量不变。各角色按自身负责的记录展示。选定人员及角色后,顶部与供应商汇总复用该人员的角色归属口径,与本人看板和人员明细一致;管理员筛选不改变服务端组织、供应商及本人权限边界。可交付时长额外要求当前验收通过,且对应当前 release partition 的正式交付包已有 manifest digest;不把所有验收通过直接等同可交付。
沿用 120 秒快照更新机制,实时状态意为不截止在所选日期终点,并非逐秒更新保证。列表不读取视频、草稿、切片正文或意见正文;新意见事实只读取 ID、作用域、归属和误报标记。供应商、人员和总览共用请求内审核记录整理结果,无跨请求权限缓存,无新索引或迁移。

View File

@ -76,7 +76,24 @@ func TestProductionQualityAPISelectionPaginationExportAndPermissions(t *testing.
if !strings.Contains(exported.Header().Get("Content-Type"), "text/csv") || !strings.Contains(exported.Body.String(), "首轮通过率") {
t.Fatal("export contract")
}
_ = outputReady(t, f, strings.Replace(url, "role=annotation", "role=quality", 1), f.reviewer)
reviewURL := strings.Replace(url, "role=annotation", "role=quality", 1)
self := outputReady(t, f, reviewURL, f.reviewer)
var selfBody struct{ Totals workforcestats.OutputTotals }
if e := json.Unmarshal(self.Body.Bytes(), &selfBody); e != nil {
t.Fatal(e)
}
selected := outputReady(t, f, reviewURL+"&userId="+f.reviewer.ID+"&snapshotId="+body.Snapshot.ID, f.admin)
var selectedBody struct {
Totals workforcestats.OutputTotals
People outputPage[workforcestats.ProductionPerson]
}
if e := json.Unmarshal(selected.Body.Bytes(), &selectedBody); e != nil {
t.Fatal(e)
}
if selfBody.Totals.Submitted.Count != 1 || selectedBody.Totals.Submitted.Count != 1 || selectedBody.People.Total != 1 || *selectedBody.Totals.Submitted.Seconds != *selfBody.Totals.Submitted.Seconds {
t.Fatal("selected reviewer summary differs from self on same snapshot")
}
invalid := f.request("GET", url+"&snapshotId=invalid", f.annotator, nil)
if invalid.Code != 409 {
t.Fatalf("snapshot %d", invalid.Code)

View File

@ -31,12 +31,13 @@ func TestSlicePhaseBrowserReplica(t *testing.T) {
reset := func(status, shape string) error {
before := []domain.SliceSegment{{ID: "first", Start: 0, End: 10}}
item := f.item
item.Subject.ArtifactID = "left-video"
item.ReviewRound = 0
actions := []domain.AnnotationSegment{{ID: "pending-first", Start: 0, End: 10, Status: "pending"}}
if status == "empty" {
actions = []domain.AnnotationSegment{}
}
item.Subject.Payload = map[string]any{"sliceWorkflow": map[string]any{"status": "editing", "phase": "slice"}, "annotationWorkspace": map[string]any{"userId": f.annotator.ID, "savedAt": nowISO(), "sliceSegments": before, "segments": actions, "statuses": map[string]string{"first": "pending"}}}
item.Subject.Payload = map[string]any{"rightArtifactId": "right-video", "sliceWorkflow": map[string]any{"status": "editing", "phase": "slice"}, "annotationWorkspace": map[string]any{"userId": f.annotator.ID, "savedAt": nowISO(), "sliceSegments": before, "segments": actions, "statuses": map[string]string{"first": "pending"}}}
if status == "draft" {
item.Subject.Payload["annotationDraft"] = map[string]any{"userId": f.annotator.ID, "savedAt": time.Now().Add(time.Second).UTC().Format(time.RFC3339Nano), "savedVersion": item.Version, "sliceSegments": before, "segments": actions, "statuses": map[string]string{"first": "pending"}}
item.Subject.Payload["annotationWorkspace"].(map[string]any)["segments"] = []domain.AnnotationSegment{}
@ -68,6 +69,9 @@ func TestSlicePhaseBrowserReplica(t *testing.T) {
f.task.SourceVideo = "/api/runs/" + f.task.RunID + "/artifacts/left-video/content"
f.task.RightSourceVideo = "/api/runs/" + f.task.RunID + "/artifacts/right-video/content"
f.task.NodeID = "human"
f.task.SourceVideo = "/api/runs/" + f.task.RunID + "/artifacts/left-video/content"
f.task.RightSourceVideo = "/api/runs/" + f.task.RunID + "/artifacts/right-video/content"
f.task.NodeID = "human"
f.task.ArtifactID = "left-video"
f.task.RightArtifactID = "right-video"
f.task.SourceIsFullVideo = true
@ -78,6 +82,7 @@ func TestSlicePhaseBrowserReplica(t *testing.T) {
pts += fmt.Sprintf("%d\n", 1000000+i*100000)
}
bindings := []domain.NodeInputBinding{}
mediaArtifacts := []domain.ExecutionArtifact{}
for _, side := range []string{"left", "right"} {
video := filepath.Join(root, side+".mp4")
if out, err := exec.Command("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=navy:s=160x90:r=10:d=10", "-c:v", "libx264", "-pix_fmt", "yuv420p", video).CombinedOutput(); err != nil {
@ -87,6 +92,7 @@ func TestSlicePhaseBrowserReplica(t *testing.T) {
if err := os.WriteFile(timestamps, []byte(pts), 0600); err != nil {
t.Fatal(err)
}
mediaArtifacts = append(mediaArtifacts, domain.ExecutionArtifact{ID: side + "-video", Name: side + ".mp4", Path: video, Type: domain.PortTypeVideo})
port := "fullLeftVideos"
if side == "right" {
port = "fullRightVideos"
@ -103,7 +109,7 @@ func TestSlicePhaseBrowserReplica(t *testing.T) {
t.Fatal(err)
}
bindings = append(bindings, domain.NodeInputBinding{TargetPortID: "imu", Artifacts: []domain.ExecutionArtifact{{ID: "imu", Name: "imu.csv", Path: imuPath, Data: map[string]any{"collectionId": "capture"}}}})
if err := f.store.UpsertRun(f.ctx, domain.RunRecord{ID: f.task.RunID, OrganizationID: f.task.OrganizationID, ProjectID: f.task.ProjectID, WorkflowID: f.task.WorkflowID, NodeExecutions: []domain.NodeExecutionRecord{{NodeID: f.task.NodeID, InputBindings: bindings}}}); err != nil {
if err := f.store.UpsertRun(f.ctx, domain.RunRecord{ID: f.task.RunID, OrganizationID: f.task.OrganizationID, ProjectID: f.task.ProjectID, WorkflowID: f.task.WorkflowID, Artifacts: mediaArtifacts, NodeExecutions: []domain.NodeExecutionRecord{{NodeID: f.task.NodeID, InputBindings: bindings}}}); err != nil {
t.Fatal(err)
}
if err := f.store.UpsertAnnotationTask(f.ctx, f.task); err != nil {
@ -112,6 +118,35 @@ func TestSlicePhaseBrowserReplica(t *testing.T) {
if err := reset("pending", ""); err != nil {
t.Fatal(err)
}
// The slice phase requires the real validator's admission evidence, unlike
// an already materialized rework fixture. Process only isolated synthetic media.
t.Setenv("ANNOTATION_PROCESSOR_ROLE", "validation")
validationCtx, stopValidation := context.WithTimeout(t.Context(), 30*time.Second)
validationDone := make(chan error, 1)
go func() {
validationDone <- RunAnnotationProcessor(validationCtx, f.store, config.AppConfig{WorkspaceMountPath: root}, 1, false)
}()
var validationStatus string
for validationCtx.Err() == nil {
job, e := f.store.GetAnnotationIndexJob(validationCtx, f.task.ID)
if e != nil {
stopValidation()
<-validationDone
t.Fatal(e)
}
if job != nil {
validationStatus = job.Status
if job.Status == "completed" || job.Status == "failed" {
break
}
}
time.Sleep(20 * time.Millisecond)
}
stopValidation()
<-validationDone
if validationStatus != "completed" {
t.Fatalf("synthetic source validation did not complete: %s", validationStatus)
}
handler := NewHandlerWithConfig(f.store, nil, config.AppConfig{WorkspaceMountPath: root})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/auth/me" {

View File

@ -88,21 +88,34 @@ func BuildProductionQuality(d OutputDataset, q OutputQuery) ProductionQualityRep
}
}
}
selfSums := make([]outputAccumulator, 4)
selectedSums := make([]outputAccumulator, 4)
selectedVendorSums := map[string][]outputAccumulator{}
supplierMembers := map[string]map[string]map[string]bool{}
for key, parts := range participants {
sums := make([]outputAccumulator, 4)
selected := (q.MatchUser || q.UserID != "") && (q.ReportRole == "" || key.role == q.ReportRole)
if selected && selectedVendorSums[key.supplier] == nil {
selectedVendorSums[key.supplier] = make([]outputAccumulator, 4)
}
add := func(stage int, p OutputPartFact) {
sums[stage].add(p.ID, p.Seconds)
if selected {
selectedSums[stage].add(p.ID, p.Seconds)
selectedVendorSums[key.supplier][stage].add(p.ID, p.Seconds)
}
}
personDelivery := outputAccumulator{}
for index := range parts {
p := d.Parts[index]
sums[0].add(p.ID, p.Seconds)
add(0, p)
if p.Deliverable && p.Stages[2] != nil && key.role == OutputRoleAnnotation && p.Stages[2].User == key.user && p.Stages[2].Supplier == key.supplier {
personDelivery.add(p.ID, p.Seconds)
}
if key.role == OutputRoleAnnotation {
for stage := 1; stage < 4; stage++ {
if f := p.Stages[stage]; f != nil && f.User == key.user && f.Supplier == key.supplier {
sums[stage].add(p.ID, p.Seconds)
add(stage, p)
}
}
} else {
@ -114,39 +127,15 @@ func BuildProductionQuality(d OutputDataset, q OutputQuery) ProductionQualityRep
}
if owner == key.user {
if latest.Decision == "approved" {
sums[2].add(p.ID, p.Seconds)
add(2, p)
} else {
sums[3].add(p.ID, p.Seconds)
}
}
}
}
}
if q.MatchUser && key.role == q.ReportRole {
for index := range parts {
p := d.Parts[index]
selfSums[0].add(p.ID, p.Seconds)
if key.role == OutputRoleAnnotation {
for stage := 1; stage < 4; stage++ {
if f := p.Stages[stage]; f != nil && f.User == key.user {
selfSums[stage].add(p.ID, p.Seconds)
}
}
} else if last, ok := latestAcceptance[index]; ok {
owner := last.TargetUser
if key.role == OutputRoleAcceptance {
owner = last.User
}
if owner == key.user {
if last.Decision == "approved" {
selfSums[2].add(p.ID, p.Seconds)
} else {
selfSums[3].add(p.ID, p.Seconds)
add(3, p)
}
}
}
}
}
row := ProductionPerson{Deliverable: personDelivery.metric(), ID: key.user, Name: d.Users[key.user], SupplierID: key.supplier, SupplierName: d.Suppliers[key.supplier], Role: key.role, Totals: OutputTotals{sums[0].metric(), sums[1].metric(), sums[2].metric(), sums[3].metric()}}
if v, ok := quality[key.role+"\x00"+key.supplier+"\x00"+key.user]; ok {
row.Quality = &v
@ -177,6 +166,14 @@ func BuildProductionQuality(d OutputDataset, q OutputQuery) ProductionQualityRep
if a := vendorDelivery[id]; a != nil {
dm = a.metric()
}
if q.MatchUser || q.UserID != "" {
sums := selectedVendorSums[id]
if sums == nil {
sums = make([]outputAccumulator, 4)
}
supplierTotals[id] = OutputTotals{sums[0].metric(), sums[1].metric(), sums[2].metric(), sums[3].metric()}
}
result.Suppliers = append(result.Suppliers, ProductionSupplier{Deliverable: dm, ID: id, Name: d.Suppliers[id], Totals: supplierTotals[id], Members: counts, Quality: supplierQuality[id]})
}
sort.Slice(result.Suppliers, func(i, j int) bool { return result.Suppliers[i].ID < result.Suppliers[j].ID })
@ -184,8 +181,8 @@ func BuildProductionQuality(d OutputDataset, q OutputQuery) ProductionQualityRep
a, b := result.People[i], result.People[j]
return a.Role+"\x00"+a.SupplierID+"\x00"+a.ID < b.Role+"\x00"+b.SupplierID+"\x00"+b.ID
})
if q.MatchUser && q.ReportRole != "" {
result.Totals = OutputTotals{selfSums[0].metric(), selfSums[1].metric(), selfSums[2].metric(), selfSums[3].metric()}
if q.MatchUser || q.UserID != "" {
result.Totals = OutputTotals{selectedSums[0].metric(), selectedSums[1].metric(), selectedSums[2].metric(), selectedSums[3].metric()}
}
attachQualityComparisons(&result, original, q)
return result

View File

@ -78,3 +78,42 @@ func TestProductionQualityTotalsMatchLegacyForSelectedCohort(t *testing.T) {
}
}
}
func TestProductionQualitySelectedReviewerMatchesSelf(t *testing.T) {
now := time.Date(2026, 11, 10, 0, 0, 0, 0, time.UTC)
seconds := 900.0
d := OutputDataset{AsOf: now, Users: map[string]string{"ac": "AC", "qc": "QC"}, Suppliers: map[string]string{"v": "V"}, Parts: []OutputPartFact{
{ID: "part", Project: "p", Seconds: &seconds, Stages: [4]*OutputStageFact{{At: "2026-11-09T00:00:00Z", User: "annotator", Supplier: "v"}, nil, {At: "2026-11-09T02:00:00Z", User: "annotator", Supplier: "v"}, nil}},
}, Work: []OutputWorkFact{
{Part: 0, Role: OutputRoleQuality, User: "qc", Supplier: "v", At: "2026-11-09T01:00:00Z", Decision: "approved"},
{Part: 0, Role: OutputRoleAcceptance, User: "ac", Supplier: "v", TargetUser: "qc", At: "2026-11-09T02:00:00Z", Decision: "approved"},
{Part: 0, Role: OutputRoleAcceptance, User: "ac", Supplier: "v", TargetUser: "qc", At: "2026-11-09T03:00:00Z", Decision: "approved"},
}}
for _, person := range []struct{ user, role string }{{"ac", OutputRoleAcceptance}, {"qc", OutputRoleQuality}} {
q := OutputQuery{From: now.AddDate(0, 0, -2), To: now, Location: time.UTC, ReportRole: person.role, MatchUser: true, ScopeUserID: person.user}
self := BuildProductionQuality(d, q)
assertOutputSeconds(t, self.Totals.Acceptance, 1, 900)
q.MatchUser = false
q.ScopeUserID = ""
q.UserID = person.user
admin := BuildProductionQuality(d, q)
if !reflect.DeepEqual(admin.Totals, self.Totals) {
t.Fatalf("selected %s totals differ: admin=%+v self=%+v", person.role, admin.Totals, self.Totals)
}
if len(admin.Suppliers) != 1 || !reflect.DeepEqual(admin.Suppliers[0].Totals, self.Totals) {
t.Fatal("selected supplier summary differs from person")
}
q.MatchSupplier = true
q.ScopeSupplierID = "v"
vendor := BuildProductionQuality(d, q)
if !reflect.DeepEqual(vendor.Totals, self.Totals) {
t.Fatal("vendor selected reviewer differs")
}
q.ScopeSupplierID = "foreign"
assertOutputSeconds(t, BuildProductionQuality(d, q).Totals.Acceptance, 0, 0)
q.MatchUser = true
q.ScopeUserID = "foreign"
q.MatchSupplier = false
assertOutputSeconds(t, BuildProductionQuality(d, q).Totals.Acceptance, 0, 0)
}
}

View File

@ -118,12 +118,14 @@
"^src/hooks/useReviewDraft\\.ts$",
"^src/lib/(review-caption-preferences\\.js|review-navigation\\.js|review-opinions\\.ts)$",
"^src/styles/review-captions\\.css$",
"^tests/browser/review-caption-recovery\\.mjs$"
"^tests/browser/review-caption-recovery\\.mjs$",
"^src/lib/acceptance-workspace\\.js$"
],
"frontend": [
"tests/frontend/review-target-interaction.test.mjs",
"tests/frontend/review-caption-preferences.test.mjs",
"tests/frontend/review-captions.test.mjs"
"tests/frontend/review-captions.test.mjs",
"tests/frontend/acceptance-workspace.test.mjs"
],
"go": {},
"task": [
@ -422,6 +424,10 @@
"SOURCE_ADMISSION_LOCAL_MONGO": "1"
},
"tests": true
},
{
"argv": ["node", "tests/browser/dashboard-refresh.mjs"],
"tests": true
}
],
"warnings": ["统计/查询改动须额外记录同数据规模的性能对照;完整 120 人容量另行验收。"]
@ -524,6 +530,8 @@
"^internal/store/human_event_recovery.*\\.go$",
"^docs/operations/submission-recovery.*\\.md$",
"^internal/api/annotation_submission_(busy_test|retry)\\.go$",
"^internal/api/slice_phase_browser_test\\.go$",
"^tests/browser/slice-phase-replica\\.mjs$",
"^internal/store/(account_mutation_lock|supplier_project_stripes|submission_lock_contention).*\\.go$"
],
"frontend": [

View File

@ -3166,6 +3166,66 @@ export function CaptureAnnotationWorkbench({
);
}
const renderTimestampOpinionMarkers = (start: number, end: number, offset = 0) =>
isReviewViewing &&
reviewTimestampOpinions &&
reviewTimestampOpinions.length > 0 && (
<div
aria-label="时间点意见标记"
className="absolute inset-x-0 top-0 z-20 h-4"
onPointerDown={(e) => e.stopPropagation()}
>
{(() => {
// §4.3:点位标记不涂红父切片;近邻聚合,重叠可展开选择。
const span = Math.max(end - start, 0.001);
const sorted = [...reviewTimestampOpinions].sort((a, b) => a.atSeconds - b.atSeconds);
const clusters: { key: string; opinions: typeof sorted; left: number }[] = [];
for (const opinion of sorted) {
const left = Math.min(100, Math.max(0, ((opinion.atSeconds + offset - start) / span) * 100));
const last = clusters[clusters.length - 1];
if (last && Math.abs(last.left - left) < 0.8) last.opinions.push(opinion);
else clusters.push({ key: opinion.id, opinions: [opinion], left });
}
return clusters.map((cluster) => (
<div key={cluster.key} className="absolute top-0" style={{ left: `${cluster.left}%` }}>
<button
type="button"
aria-label={`时间点意见 ${cluster.opinions.length > 1 ? `${cluster.opinions.length} 条` : cluster.opinions[0].text.slice(0, 12)}`}
title={cluster.opinions.map((o) => `${formatTime(o.atSeconds)} ${o.text}`).join("\n")}
onClick={(e) => {
e.stopPropagation();
if (cluster.opinions.length > 1)
setOpinionMarkerOpen(opinionMarkerOpen === cluster.key ? null : cluster.key);
else reviewController.seekTime(cluster.opinions[0].atSeconds);
}}
className="-translate-x-1/2 rounded-full border border-orange-500 bg-orange-400 px-1 text-[9px] font-bold leading-3 text-white shadow"
>
{cluster.opinions.length > 1 ? cluster.opinions.length : "•"}
</button>
{cluster.opinions.length > 1 && opinionMarkerOpen === cluster.key && (
<div className="absolute left-0 top-4 z-30 max-h-24 w-44 overflow-auto rounded border border-orange-300 bg-white p-1 text-left text-[10px] shadow-lg dark:border-orange-700 dark:bg-[#151619]">
{cluster.opinions.map((o) => (
<button
key={o.id}
type="button"
onClick={(e) => {
e.stopPropagation();
setOpinionMarkerOpen(null);
reviewController.seekTime(o.atSeconds);
}}
className="block w-full truncate rounded px-1 py-0.5 text-left text-slate-600 hover:bg-orange-50 dark:text-slate-300 dark:hover:bg-orange-950/30"
>
{formatTime(o.atSeconds)} {o.text}
</button>
))}
</div>
)}
</div>
));
})()}
</div>
);
return (
<section
ref={workbenchRef}
@ -4424,6 +4484,15 @@ export function CaptureAnnotationWorkbench({
<div
className={cn("capture-timeline-editor border-y border-slate-200", mediaOnly ? "px-2 py-1" : "px-5 py-3")}
>
{mediaOnly && isReviewViewing && !!reviewTimestampOpinions?.length && (
<div className="relative h-4" onPointerDown={(event) => event.stopPropagation()}>
{renderTimestampOpinionMarkers(
totalProgress ? 0 : clipStart,
totalProgress?.duration ?? clipEnd,
totalProgress?.offset ?? 0,
)}
</div>
)}
<input
type="range"
aria-label={totalProgress ? "总视频播放位置" : "Capture 播放位置"}
@ -4598,65 +4667,7 @@ export function CaptureAnnotationWorkbench({
}}
>
<div className="absolute inset-x-0 top-4 h-px bg-slate-200" />
{isReviewViewing && reviewTimestampOpinions && reviewTimestampOpinions.length > 0 && (
<div
aria-label="时间点意见标记"
className="absolute inset-x-0 top-0 z-20 h-4"
onPointerDown={(e) => e.stopPropagation()}
>
{(() => {
// §4.3:点位标记不涂红父切片;近邻聚合,重叠可展开选择。
const span = Math.max(sliceTimelineEnd - sliceTimelineStart, 0.001);
const sorted = [...reviewTimestampOpinions].sort((a, b) => a.atSeconds - b.atSeconds);
const clusters: { key: string; opinions: typeof sorted; left: number }[] = [];
for (const opinion of sorted) {
const left = Math.min(
100,
Math.max(0, ((opinion.atSeconds - sliceTimelineStart) / span) * 100),
);
const last = clusters[clusters.length - 1];
if (last && Math.abs(last.left - left) < 0.8) last.opinions.push(opinion);
else clusters.push({ key: opinion.id, opinions: [opinion], left });
}
return clusters.map((cluster) => (
<div key={cluster.key} className="absolute top-0" style={{ left: `${cluster.left}%` }}>
<button
type="button"
aria-label={`时间点意见 ${cluster.opinions.length > 1 ? `${cluster.opinions.length} 条` : cluster.opinions[0].text.slice(0, 12)}`}
title={cluster.opinions.map((o) => `${formatTime(o.atSeconds)} ${o.text}`).join("\n")}
onClick={(e) => {
e.stopPropagation();
if (cluster.opinions.length > 1)
setOpinionMarkerOpen(opinionMarkerOpen === cluster.key ? null : cluster.key);
else reviewController.seekTime(cluster.opinions[0].atSeconds);
}}
className="-translate-x-1/2 rounded-full border border-orange-500 bg-orange-400 px-1 text-[9px] font-bold leading-3 text-white shadow"
>
{cluster.opinions.length > 1 ? cluster.opinions.length : "•"}
</button>
{cluster.opinions.length > 1 && opinionMarkerOpen === cluster.key && (
<div className="absolute left-0 top-4 z-30 max-h-24 w-44 overflow-auto rounded border border-orange-300 bg-white p-1 text-left text-[10px] shadow-lg dark:border-orange-700 dark:bg-[#151619]">
{cluster.opinions.map((o) => (
<button
key={o.id}
type="button"
onClick={(e) => {
e.stopPropagation();
setOpinionMarkerOpen(null);
reviewController.seekTime(o.atSeconds);
}}
className="block w-full truncate rounded px-1 py-0.5 text-left text-slate-600 hover:bg-orange-50 dark:text-slate-300 dark:hover:bg-orange-950/30"
>
{formatTime(o.atSeconds)} {o.text}
</button>
))}
</div>
)}
</div>
));
})()}
</div>
)}
{renderTimestampOpinionMarkers(sliceTimelineStart, sliceTimelineEnd)}
{reworkActive && reworkEmphasis && reworkEmphasis.markers.length > 0 && (
<div
aria-label="返工时间点意见标记"

View File

@ -22,6 +22,7 @@ import { apiFetch } from "../services/api/client";
import { buildAPIURL } from "../services/api/base-url.js";
import {
acceptanceActions,
acceptanceTimestampOpinions,
acceptanceViewStatus,
acceptanceSliceCountLabel,
acceptanceChecks,
@ -101,6 +102,7 @@ export function FinalAcceptanceWorkspace({
onReviewProblemEdit,
onReviewProblemDelete,
onReviewEscape,
reviewTimestampOpinions,
reviewProblemPanel,
reviewTracePanel,
}: Props) {
@ -755,6 +757,7 @@ export function FinalAcceptanceWorkspace({
viewportSuspended={viewportSuspended}
browserReadyMedia={!active.sourceIndex}
reviewCaption={reviewCaption}
reviewTimestampOpinions={acceptanceTimestampOpinions(groups, active.id, reviewTimestampOpinions)}
totalProgress={
fullVideoWindow
? {

View File

@ -282,6 +282,7 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
</div>
);
const totals = data?.totals;
const reviewSummary = personal ? defaultRole !== "annotation" : !!query.userId && query.role !== "annotation";
return (
<section className="pq-dashboard" aria-label="生产与质量看板">
<header>
@ -418,17 +419,17 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
{data && (
<p className="text-xs text-slate-500">
更新于 {formatCompactDateTime(data.snapshot.asOf, timeZone)}
{(data.snapshot.stale || data.snapshot.refreshing) && " · 正在更新"}
{(busy || data.snapshot.stale || data.snapshot.refreshing) && <span role="status"> · 正在更新</span>}
</p>
)}
{busy && (
{busy && !data && (
<div role="status" className="pq-loading">
加载中…
</div>
)}
<div className={`pq-cards${personal && defaultRole !== "annotation" ? " pq-cards-review" : ""}`}>
{[
[personal && defaultRole !== "annotation" ? "审查视频时长" : "提交视频时长", totals?.submitted],
[reviewSummary ? "审查视频时长" : "提交视频时长", totals?.submitted],
["质检通过时长", totals?.quality],
["最终验收通过时长", totals?.acceptance],
["可交付时长", data?.deliverable],

View File

@ -26,6 +26,9 @@ export type ReviewPosition = {
discarded?: boolean;
};
export type ReviewTimestampOpinion = {
sourceItemId?: string;
sliceId?: string;
timeBasis?: "capture-seconds" | "slice-seconds";
id: string;
atSeconds: number;
text: string;

View File

@ -198,3 +198,22 @@ export function acceptanceChecks(entries, groups, loading, error) {
});
return { filesReady, coverageReady };
}
// Acceptance media uses a slice-relative clock; persisted opinions retain their
// source and original clock. Never clamp a different slice's opinion to an edge.
export function acceptanceTimestampOpinions(groups, activeId, opinions = []) {
const active = groups.find((group) => group.id === activeId);
if (!active) return [];
const sliceId = active.entry.finalSlices?.[active.index - 1]?.id;
if (!sliceId) return [];
const sourceId = active.entry.sourceHumanItemId;
const ambiguous = groups.filter((group) => group.entry.finalSlices?.[group.index - 1]?.id === sliceId).length > 1;
return opinions.flatMap((opinion) => {
if (opinion.sliceId !== sliceId || (opinion.sourceItemId ? opinion.sourceItemId !== sourceId : ambiguous))
return [];
if (!["slice-seconds", "capture-seconds"].includes(opinion.timeBasis)) return [];
const at = opinion.atSeconds - (opinion.timeBasis === "capture-seconds" ? active.start : 0);
if (!Number.isFinite(at) || at < 0 || at > active.end - active.start) return [];
return [{ ...opinion, atSeconds: at, timeBasis: "slice-seconds" }];
});
}

View File

@ -7716,6 +7716,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
onReviewTimestampJump={reviewDraft.jumpTimestampProblem}
reviewTimestampOpinions={reviewDraft.timestampProblems.map((p) => ({
id: p.id,
sourceItemId: p.sourceItemId,
sliceId: p.sliceId,
timeBasis: p.timeBasis,
atSeconds: p.atSeconds ?? 0,
text: p.text,
}))}
@ -8177,6 +8180,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
onReviewTimestampJump={reviewDraft.jumpTimestampProblem}
reviewTimestampOpinions={reviewDraft.timestampProblems.map((p) => ({
id: p.id,
sourceItemId: p.sourceItemId,
sliceId: p.sliceId,
timeBasis: p.timeBasis,
atSeconds: p.atSeconds ?? 0,
text: p.text,
}))}

View File

@ -343,14 +343,28 @@ try {
assert.equal(draft.problems.length, 1);
const problem = draft.problems[0];
assert.equal(problem.scope, "timestamp");
await page.getByLabel("时间点意见标记", { exact: true }).waitFor();
assert.equal(await page.getByRole("button", { name: "时间点意见 时间点固定在当前画面", exact: true }).count(), 1);
assert.equal(problem.timeBasis, "slice-seconds");
assert.equal(problem.sourceItemId, "synthetic-source");
assert.equal(problem.sliceId, "slice-000002");
assert(firstAnchor.includes(problem.atSeconds.toFixed(3)), "saved timestamp must equal frozen editor anchor");
const marker = page.getByRole("button", { name: "时间点意见 时间点固定在当前画面", exact: true });
await marker.click();
await page.waitForFunction((value) => {
const slider = document.querySelector('input[aria-label="总视频播放位置"]');
return slider && Math.abs(Number(slider.value) - (8 + value)) < 0.15;
}, problem.atSeconds);
await page.screenshot({ path: `${out}/${engine}-timestamp-marker.png`, fullPage: true });
await page.getByLabel("字幕位置").selectOption("top");
await page.waitForFunction(() => document.querySelectorAll('[data-caption-placement="top"]').length === 2);
await page.getByRole("button", { name: "下一片", exact: true }).click();
await page.getByTestId("acceptance-discard-evidence").waitFor();
assert.equal(
await page.getByLabel("时间点意见标记", { exact: true }).count(),
0,
"another slice must not inherit markers",
);
await assertRate(1.5);
await page.waitForFunction(
(offset) =>
@ -377,6 +391,13 @@ try {
"top",
"caption placement persists across remount/reload",
);
await page.getByRole("button", { name: "下一片", exact: true }).click();
await page.getByLabel("时间点意见标记", { exact: true }).waitFor();
assert.equal(
await page.getByRole("button", { name: "时间点意见 时间点固定在当前画面", exact: true }).count(),
1,
"saved marker survives reload and slice navigation",
);
await page.goto(`${base}/__acceptance_playback_rate?readonly=1`);
await sliceCard.waitFor();
assert(await sliceCard.isDisabled(), "read-only viewers cannot enter edit mode");

View File

@ -0,0 +1,156 @@
import { createServer } from "vite";
import { chromium } from "playwright";
import { browserExecutableOptions } from "../../scripts/lib/browser-executable.mjs";
import assert from "node:assert/strict";
import fs from "node:fs/promises";
const out = process.env.DASHBOARD_TEST_OUTPUT || "local-data/test-results/dashboard-refresh";
await fs.mkdir(out, { recursive: true });
const server = await createServer({
configFile: "tests/browser/vite.platform-feedback.config.ts",
server: { host: "127.0.0.1", port: 0 },
cacheDir: out + "/vite-cache",
plugins: [
{
name: "dashboard-diagnostic-fixture",
enforce: "pre",
async transform(code, id) {
if (id.endsWith("/tests/browser/fixtures/acceptance-playback-rate.tsx"))
return await fs.readFile("tests/browser/fixtures/dashboard-refresh.tsx", "utf8");
},
},
],
});
let browser;
try {
await server.listen();
const origin = server.resolvedUrls.local[0].replace(/\/$/, "");
browser = await chromium.launch({ ...browserExecutableOptions(), headless: true, args: ["--no-proxy-server"] });
const page = await browser.newPage({ viewport: { width: 1500, height: 1000 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const user = {
id: "synthetic-ac",
name: "Synthetic acceptor",
role: "acceptance_reviewer",
status: "active",
supplierId: "synthetic-v",
};
const metric = { count: 1, seconds: 3600 };
const totals = {
submitted: metric,
quality: { count: 0, seconds: 0 },
acceptance: metric,
rework: { count: 0, seconds: 0 },
};
let fail = false;
let slow = false,
reads = 0;
await page.route("**/api/**", async (route) => {
const path = new URL(route.request().url()).pathname;
if (!path.startsWith("/api/")) return route.continue();
if (path === "/api/auth/me")
return route.fulfill({ json: { user, organization: { id: "synthetic-org", name: "Synthetic" } } });
if (path === "/api/dashboard/production-quality") {
reads++;
if (slow) await new Promise((resolve) => setTimeout(resolve, 1200));
if (fail) return route.fulfill({ status: 503, json: { error: "看板加载失败,请重试" } });
const body = {
snapshot: { id: "synthetic-snapshot", asOf: new Date().toISOString(), stale: false, refreshing: false },
audienceScope: "self",
from: "2026-09-10",
to: "2026-11-10",
totals,
deliverable: { count: 0, seconds: 0 },
quality: [],
suppliers: { items: [], total: 0, page: 1, pageSize: 5 },
people: {
items: [
{
id: user.id,
name: user.name,
supplierId: user.supplierId,
supplierName: "Synthetic",
role: "acceptance",
totals,
deliverable: { count: 0, seconds: 0 },
quality: null,
},
],
total: 1,
page: 1,
pageSize: 5,
},
projects: [],
supplierOptions: [],
users: [],
};
return route.fulfill({ json: body });
}
return route.fulfill({ json: { items: [] } });
});
await page.route("**/dashboard-flicker-repro", async (route) =>
route.fulfill({
contentType: "text/html",
body: `<html><body><div id="root"></div><script type="module">import RefreshRuntime from '/@react-refresh';RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>type=>type;window.__vite_plugin_react_preamble_installed__=true;</script><script type="module" src="/tests/browser/fixtures/acceptance-playback-rate.tsx"></script></body></html>`,
}),
);
await page.goto(origin + "/dashboard-flicker-repro");
await page
.getByRole("heading", { name: "我的批次质量", exact: true })
.waitFor({ timeout: 15000 })
.catch(async (e) => {
console.log(JSON.stringify({ errors, body: (await page.locator("body").innerText()).slice(0, 1200) }));
throw e;
});
await page.waitForFunction(
() => document.querySelectorAll(".pq-cards>div").length === 3 && !document.querySelector(".pq-loading"),
);
const before = await page.locator(".pq-cards").boundingBox();
await page.evaluate(() => {
window.__diagnosticDashboardNode = document.querySelector(".pq-dashboard");
window.__diagnosticCardsNode = document.querySelector(".pq-cards");
});
await page.screenshot({ path: out + "/before.png" });
slow = true;
await page.getByRole("button", { name: "刷新", exact: true }).click();
await page.getByRole("status").filter({ hasText: "正在更新" }).waitFor();
const during = await page.locator(".pq-cards").boundingBox();
const report = {
sameDashboardNode: await page.evaluate(
() => window.__diagnosticDashboardNode === document.querySelector(".pq-dashboard"),
),
sameCardsNode: await page.evaluate(() => window.__diagnosticCardsNode === document.querySelector(".pq-cards")),
beforeY: before.y,
duringY: during.y,
shiftPixels: during.y - before.y,
dashboardInstances: await page.locator(".pq-dashboard").count(),
cardCount: await page.locator(".pq-cards>div").count(),
reads,
errors,
};
await page.screenshot({ path: out + "/during.png" });
await fs.writeFile(out + "/result.json", JSON.stringify(report, null, 2));
console.log(JSON.stringify(report));
assert.equal(report.errors.length, 0);
assert(Math.abs(report.shiftPixels) < 1, "Refresh must not move the existing dashboard cards");
await page.getByRole("status").waitFor({ state: "hidden" });
fail = true;
await page.getByRole("button", { name: "刷新", exact: true }).click();
await page.getByRole("alert").filter({ hasText: "看板加载失败" }).waitFor();
assert.equal(
await page.locator(".pq-cards strong").filter({ hasText: "1" }).count(),
0,
"failed refresh clears stale metric values",
);
await page.screenshot({ path: out + "/error.png" });
fail = false;
slow = false;
await page.getByRole("button", { name: "刷新", exact: true }).click();
await page.getByRole("alert").waitFor({ state: "hidden" });
await page.waitForFunction(
() => document.querySelector(".pq-cards strong")?.textContent?.replace(/\s/g, "") === "1小时",
);
} finally {
await browser?.close();
await server.close();
}

View File

@ -60,6 +60,7 @@ function App() {
});
return (
<FinalAcceptanceWorkspace
reviewTimestampOpinions={review.timestampProblems.map((p) => ({ ...p, atSeconds: p.atSeconds ?? 0 }))}
onReviewPositionChange={review.onPosition}
onReviewController={review.onController}
onReviewNavigate={review.onNavigate}

View File

@ -0,0 +1,10 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { UserProvider } from "/src/context/UserContext";
import { ProductionQualityDashboard } from "/src/components/ProductionQualityDashboard";
import "/src/index.css";
createRoot(document.getElementById("root")!).render(
<UserProvider>
<ProductionQualityDashboard timeZone="Asia/Shanghai" />
</UserProvider>,
);

View File

@ -12,6 +12,7 @@ assert.match(api, /^http:\/\/127\.0\.0\.1:\d+$/);
fs.mkdirSync(root, { recursive: true });
const server = await createServer({
root: source,
configFile: "tests/browser/vite.platform-feedback.config.ts",
server: { host: "127.0.0.1", port: 5204, strictPort: true, proxy: { "/api": { target: api, changeOrigin: true } } },
});
let browser, page;
@ -85,7 +86,7 @@ try {
await page.waitForTimeout(500);
assert.equal(await del.count(), 1);
await page.waitForTimeout(1100);
await page.getByRole("button", { name: "重做", exact: true }).click();
await page.getByRole("button", { name: "恢复", exact: true }).click();
await del.nth(1).waitFor();
assert.equal(await del.count(), 2);
await page.reload();
@ -127,7 +128,7 @@ try {
await page.waitForTimeout(500);
assert.deepEqual(await labels(), before);
await page.waitForTimeout(1100);
await page.getByRole("button", { name: "重做", exact: true }).click();
await page.getByRole("button", { name: "恢复", exact: true }).click();
await page.waitForTimeout(500);
assert.deepEqual(await labels(), after);
assert.equal((await state()).segments.length >= 2, true);
@ -141,7 +142,7 @@ try {
await page.waitForTimeout(500);
assert.deepEqual(await labels(), after);
await page.waitForTimeout(1100);
await page.getByRole("button", { name: "重做", exact: true }).click();
await page.getByRole("button", { name: "恢复", exact: true }).click();
await page.waitForTimeout(500);
assert.equal(await bench.getByRole("button", { name: "删除切片", exact: true }).count(), 1);
report.cases.push({ scenario: "pending-delete-undo-redo" });

View File

@ -2,6 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import {
acceptanceActions,
acceptanceTimestampOpinions,
acceptanceSliceName,
acceptanceChecks,
acceptanceFrameTimes,
@ -201,3 +202,47 @@ test("discarded acceptance slices use the frozen reason, preserving legacy fallb
"原片名",
);
});
test("acceptance markers retain source identity and map only the active slice clock", () => {
const entryA = { sourceHumanItemId: "source-A", finalSlices: [{ id: "same-id", start: 8, end: 16 }] };
const entryB = { sourceHumanItemId: "source-B", finalSlices: [{ id: "same-id", start: 20, end: 28 }] };
const groups = [
{ id: "A", entry: entryA, index: 1, start: 8, end: 16 },
{ id: "B", entry: entryB, index: 1, start: 20, end: 28 },
];
const opinions = [
{
id: "local",
sourceItemId: "source-A",
sliceId: "same-id",
timeBasis: "slice-seconds",
atSeconds: 2,
text: "local",
},
{
id: "capture",
sourceItemId: "source-A",
sliceId: "same-id",
timeBasis: "capture-seconds",
atSeconds: 11,
text: "capture",
},
{ id: "other", sourceItemId: "source-B", sliceId: "same-id", timeBasis: "slice-seconds", atSeconds: 2 },
{ id: "ambiguous", sliceId: "same-id", timeBasis: "slice-seconds", atSeconds: 2 },
{ id: "bad-clock", sourceItemId: "source-A", sliceId: "same-id", atSeconds: 2 },
{ id: "outside", sourceItemId: "source-A", sliceId: "same-id", timeBasis: "slice-seconds", atSeconds: 9 },
];
assert.deepEqual(
acceptanceTimestampOpinions(groups, "A", opinions).map((p) => [p.id, p.atSeconds]),
[
["local", 2],
["capture", 3],
],
);
assert.deepEqual(
acceptanceTimestampOpinions(groups, "B", opinions).map((p) => p.id),
["other"],
);
assert.deepEqual(acceptanceTimestampOpinions(groups, "missing", opinions), []);
assert.equal(acceptanceTimestampOpinions([groups[0]], "A", [opinions[3]])[0].id, "ambiguous");
});