forked from longtao.wu/droboticflow
🐛 Fix discard confirmation focus and reset restored action tracks
This commit is contained in:
parent
3472c021de
commit
52dcb53a8c
81
.scratch/discard-focus-track-20261015/spec.md
Normal file
81
.scratch/discard-focus-track-20261015/spec.md
Normal file
@ -0,0 +1,81 @@
|
||||
# Discard confirmation focus and continuous action tracks
|
||||
|
||||
Status: resolved
|
||||
|
||||
Baseline: PR49 candidate3472c021; deployed application2071b0a2. User reports
|
||||
E-panel G/click discard → Enter confirmation leaves keyboard focus such that
|
||||
Enter cannot apply without clicking the workbench, and cancelling discard can
|
||||
leave an empty action track. Reproduce actual nested dialog/panel keyboard flow
|
||||
and archive/restore/partition chain before choosing fixes.
|
||||
|
||||
Keep two-step confirmation deliberate (the confirming key must not also submit),
|
||||
restore keyboard ownership after child UI closes, cover click and keyboard,
|
||||
manual/dictionary reasons, cancellation, repeat/IME and busy/failed writes.
|
||||
No kept editable slice may have an empty continuous action track. Preserve
|
||||
neighboring slices and history. User confirmed: explicit cancellation resets the whole slice to one pending
|
||||
action. Do not restore old descriptions; retain original audit evidence.
|
||||
Undo/redo remain snapshot operations rather than explicit cancellation.
|
||||
|
||||
Compatibility: existing task/draft/archive/action states and server CAS/role/frame
|
||||
validation; historical formal records are not bulk-mutated. Initial slice phase,
|
||||
discard evidence and genuine loading/error states are not invented action data.
|
||||
Use local synthetic fixtures; no deployment, production mutations, push or PR
|
||||
update is included in this request. Leave unrelated root changes untouched.
|
||||
|
||||
|
||||
## Answer
|
||||
|
||||
Root causes:
|
||||
|
||||
- Closing the focused child reason UI removes its DOM node. Focus falls to BODY,
|
||||
outside the workbench-scoped keyboard dispatcher, so the next Enter is lost.
|
||||
Restore confirmation also did not take initial focus, allowing its Enter to
|
||||
bypass confirmation. Both child entry and exit now have explicit focus ownership.
|
||||
- Preview restored archives without completing partitions; missing/empty/invalid
|
||||
old archives could produce an empty kept track. Explicit restore now resets
|
||||
that slice in preview and on the server, and editable continuous tracks fill
|
||||
pending gaps using the existing partition helper.
|
||||
|
||||
Compatibility:
|
||||
|
||||
- Optional `resetToPending` on direct and E-application disposition commands;
|
||||
accepted only for a discarded → keep transition, before CAS. Clients without
|
||||
this flag preserve archived descriptions; empty archives now seed pending.
|
||||
- UI explicit restore sends the flag; undo/redo target snapshots retain existing
|
||||
history semantics and replay pending-reset snapshots without reviving old text.
|
||||
- Neighbor actions, private restore evidence, CAS, roles, dictionary and frame
|
||||
validation remain enforced. No persisted schema migration or bulk record update.
|
||||
- Frontend and API must be released together: older APIs ignore the new request
|
||||
field and would restore archived descriptions. Rolling back both components
|
||||
preserves prior evidence but reverts explicit restore behavior.
|
||||
|
||||
Verification (2026-10-15):
|
||||
|
||||
- Red loops: real component E/G/Enter left activeElement=BODY and application
|
||||
count at zero on next Enter; three empty-archive preview cases and first-pass/
|
||||
rework HTTP reset cases failed before implementation.
|
||||
- Focused frontend partition/conflict/panel tests: 40 passed; review navigation
|
||||
regression: 11 passed after adding the standard layout-effect hook to its
|
||||
DOM-free test harness.
|
||||
- CUA real-component normal/focused layout: reason Enter consumes only child
|
||||
confirmation, next Enter applies; restore confirmation then application works;
|
||||
empty legacy editable track shows one full pending action. Mouse reason
|
||||
confirmation → Enter and Esc cancellation also verified.
|
||||
- Server focused tests cover first-pass/rework, empty old archives, durable
|
||||
handler reload, invalid reset without CAS, audit retention and undo/redo.
|
||||
- Full baseline gates: frontend 13 existing failures (14 known), Go 70 existing
|
||||
failures (70 known), no new failures. Two old empty-restore expectations were
|
||||
updated to require a pending interval while retaining array and audit checks.
|
||||
- Lint, format check, Web/API/Worker/coordinator builds passed. Existing large
|
||||
bundle warning remains.
|
||||
- Actual local snapshot replica: API 3005 + Vite 5176, separate synthetic task
|
||||
`discard-focus-track-20261015-task`, review round 1. E → G → reason Enter →
|
||||
Enter persisted discard without clicking the page. E → G → Enter → Enter
|
||||
reset six described actions in [30,60] to exactly one pending action. Browser
|
||||
reload retained it; read-only Mongo comparison confirmed neighbor actions
|
||||
unchanged, six original archived descriptions retained, original demo item
|
||||
still version 46. Dedicated item advanced version 1 → 3.
|
||||
- Local artifacts (ignored): main root
|
||||
`local-data/verification/discard-focus-track-20261015/`; test logs under this
|
||||
worktree `local-data/discard-focus-track/`. No production writes, push, PR
|
||||
update or deployment performed. Original local API/processor restored healthy.
|
||||
@ -48,6 +48,8 @@ _Avoid_:历史操作日志(本列表不展示修改前的旧版本)
|
||||
|
||||
**舍弃切片**:标注员明确选择不交付、以舍弃原因定义的切片类型,与使用切片名称定义的普通切片互斥。切片及其证据仍参与审核,舍弃本身不移动相邻边界。
|
||||
|
||||
**取消舍弃**:显式恢复为普通切片时,将整片重置为一个覆盖首尾边界的待标注动作,不恢复旧描述或无效判断;旧内容保留为审计证据。撤销/重做按对应操作快照恢复,与此显式重置分开。正常可编辑切片始终保留动作分区,语义为空以待标注动作呈现,不能成为空轨道。
|
||||
|
||||
## 操作含义
|
||||
|
||||
**删除切片**:移除一个切片划分并将其范围并入相邻切片,保持源采集的处理覆盖。
|
||||
|
||||
@ -3,6 +3,13 @@
|
||||
日期:2026-10-13
|
||||
状态:已接受(三轮 grill 共 24 项用户裁决全票通过后实施,spec 见 `.scratch/inplace-slice-editing/spec.md`)
|
||||
|
||||
## 2026-10-15 取消舍弃裁决更新
|
||||
|
||||
用户明确选择:显式取消舍弃后,整片重置为一个待标注动作,不恢复旧描述。
|
||||
此规则替代下文“恢复舍弃则动作还原”的显式恢复行为;旧内容与舍弃证据保留,
|
||||
撤销/重做仍按操作快照恢复。前后端共同保证正常可编辑切片不出现空动作轨道;
|
||||
旧空归档恢复也补齐整片待标注。已正式送检/审核记录不批量追改。
|
||||
|
||||
## 背景
|
||||
|
||||
返修中要改切片结构只能"重新切片":清空全部动作标注、整单退回切片阶段,代价高且不可审计(旧文案"请先返回重新切片"即两把阶段锁的报错)。同时旧 D2 规则在拖动边界穿过动作时自动拆两段标"待核对"——该状态不在服务端白名单(pending/described/invalid)内,不处置则保存被堵死。本决策来自 24 项已拍板裁决(Q1:a–Q8:a、R2-Q1–Q8、R3-1–R3-4)。
|
||||
|
||||
@ -136,3 +136,13 @@ Ctrl/⌘+Enter 有三种结果:当前有草稿就保存它;其他片还有
|
||||
### 专注工作页字典翻页
|
||||
|
||||
切片名称和动作描述字典共用自适应分页:窗口越高,每页可见条目越多,上一页/下一页、页码和总数位于搜索框下方,无需滚动寻找。按 ← / → 翻页,↑ / ↓ 选择,Enter 填入,Esc 返回。搜索框已有文字时,左右键仍移动光标;先按 ↓ 进入词条再翻页。填入词条后仍须明确保存,不会自动提交。长词条可悬停查看全文,填入后也能在编辑区查看。
|
||||
|
||||
## E 面板的舍弃与取消舍弃
|
||||
|
||||
E 打开切片重设面板;G 或按钮打开舍弃/恢复确认。选定原因后 Enter 只记入预览,
|
||||
再按一次 Enter 才应用整个面板。鼠标确认和键盘确认关闭子弹层后都归还工作台焦点,
|
||||
无需点击大页面;输入法、文字输入和长按 Enter 不得串成重复提交。
|
||||
|
||||
显式取消舍弃后整片重置为一个待标注动作,旧描述不自动恢复,邻片内容不变;
|
||||
旧内容保留审计,撤销/重做按各自快照恢复。若需要切片名称,仍从项目字典选择后应用。
|
||||
正常可编辑动作轨道保持连续分区;无描述以待标注区间呈现,不显示成空轨道。
|
||||
|
||||
137
internal/api/discard_reset_pending_test.go
Normal file
137
internal/api/discard_reset_pending_test.go
Normal file
@ -0,0 +1,137 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
)
|
||||
|
||||
func TestExplicitDiscardRestoreResetsWholeSliceToPending(t *testing.T) {
|
||||
for _, rework := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "first-pass", true: "rework"}[rework], func(t *testing.T) {
|
||||
f := continuousFixture(t)
|
||||
reason := dispositionFixturePayload(t, f)
|
||||
slices := []domain.SliceSegment{{ID: "a", Name: "测试切片", Start: 0, End: 5}, {ID: "b", Name: "测试切片", Start: 5, End: 10}}
|
||||
actions := []domain.AnnotationSegment{{ID: "described", Start: 0, End: 2, Status: "described", Description: "saved original"}, {ID: "invalid", Start: 2, End: 5, Status: "invalid", IsInvalid: true}, {ID: "neighbor", Start: 5, End: 10, Status: "pending"}}
|
||||
item := f.item
|
||||
if rework {
|
||||
item.ReviewRound = 1
|
||||
}
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed", "phase": "annotate"}
|
||||
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions}
|
||||
if e := f.store.UpsertHumanItem(f.ctx, item); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
proposed := append([]domain.SliceSegment(nil), slices...)
|
||||
proposed[0].DeliveryDisposition = "discard"
|
||||
input := sliceEditApplicationInput{ApplicationID: "discard", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: item.Version, SliceSegments: proposed, Segments: actions}, Dispositions: []sliceDispositionInput{{SliceID: "a", Disposition: "discard", ReasonLabelID: reason.ReasonLabelID, ReasonVersion: reason.ReasonVersion}}}
|
||||
endpoint := "/api/plugins/annotation-qa/tasks/" + f.task.ID + "/slice-edit-applications"
|
||||
r := f.request("POST", endpoint, f.annotator, input)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("discard %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
var got struct {
|
||||
Item domain.HumanItemRecord `json:"item"`
|
||||
Workspace combinedAnnotationDraftInput `json:"workspace"`
|
||||
}
|
||||
if e := json.Unmarshal(r.Body.Bytes(), &got); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
restore := map[string]any{"applicationId": "restore-pending", "version": got.Item.Version, "sliceSegments": slices, "segments": actions[2:], "dispositions": []map[string]any{{"sliceId": "a", "disposition": "keep", "resetToPending": true}}}
|
||||
r = f.request("POST", endpoint, f.annotator, restore)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("restore %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
if e := json.Unmarshal(r.Body.Bytes(), &got); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(got.Workspace.Segments) != 2 {
|
||||
t.Fatalf("explicit restore must reset to one full pending action plus unchanged neighbor, got %+v", got.Workspace.Segments)
|
||||
}
|
||||
var own []domain.AnnotationSegment
|
||||
for _, a := range got.Workspace.Segments {
|
||||
if a.Start < 5 {
|
||||
own = append(own, a)
|
||||
}
|
||||
}
|
||||
if len(own) != 1 || own[0].Start != 0 || own[0].End != 5 || own[0].Status != "pending" || own[0].Description != "" || own[0].IsInvalid {
|
||||
t.Fatalf("not a full pending interval: %+v", own)
|
||||
}
|
||||
f.handler = NewHandler(f.store, nil)
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
if len(decodeMaterializationValue[domain.AnnotationSegment](annotationWorkspacePayload(saved)["segments"])) != 2 {
|
||||
t.Fatal("reset not durable")
|
||||
}
|
||||
if len(decodeMaterializationValue[sliceRestoreEvidence](saved.Subject.Payload[sliceRestoreEvidenceKey])) == 0 {
|
||||
t.Fatal("audit recovery evidence lost")
|
||||
}
|
||||
|
||||
// Reject a reset command on an already-kept slice without any CAS.
|
||||
restore["version"] = got.Item.Version
|
||||
restore["applicationId"] = "illegal-reset-kept"
|
||||
bad := f.request("POST", endpoint, f.annotator, restore)
|
||||
if bad.Code != 400 {
|
||||
t.Fatalf("reset kept slice accepted: %d %s", bad.Code, bad.Body.String())
|
||||
}
|
||||
unchanged, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
if unchanged.Version != got.Item.Version {
|
||||
t.Fatal("invalid reset changed the record")
|
||||
}
|
||||
// Undo/redo of the restore must never resurrect old descriptions.
|
||||
input.ApplicationID = "undo-restore"
|
||||
input.Version = got.Item.Version
|
||||
input.Segments = got.Workspace.Segments
|
||||
r = f.request("POST", endpoint, f.annotator, input)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("undo restore %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if len(got.Workspace.SliceSegments[0].DiscardedAnnotations) != 2 {
|
||||
t.Fatal("undo lost original archived evidence")
|
||||
}
|
||||
restore["version"] = got.Item.Version
|
||||
restore["applicationId"] = "redo-restore-pending"
|
||||
r = f.request("POST", endpoint, f.annotator, restore)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("redo reset %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if len(got.Workspace.Segments) != 2 {
|
||||
t.Fatal("redo resurrected archived descriptions")
|
||||
}
|
||||
for _, a := range got.Workspace.Segments {
|
||||
if a.Start < 5 && (a.Start != 0 || a.End != 5 || a.Status != "pending" || a.Description != "") {
|
||||
t.Fatalf("redo not pending: %+v", a)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscardRestoreEmptyArchiveNeverCreatesEmptyTrack(t *testing.T) {
|
||||
for _, reset := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "legacy-client", true: "explicit-reset"}[reset], func(t *testing.T) {
|
||||
f := continuousFixture(t)
|
||||
dispositionFixturePayload(t, f)
|
||||
item := f.item
|
||||
discarded := domain.SliceSegment{ID: "a", Start: 0, End: 10, DeliveryDisposition: "discard", DiscardReason: "legacy"}
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed", "phase": "annotate"}
|
||||
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": []domain.SliceSegment{discarded}, "segments": []domain.AnnotationSegment{}}
|
||||
f.store.UpsertHumanItem(f.ctx, item)
|
||||
kept := discarded
|
||||
kept.DeliveryDisposition = "keep"
|
||||
kept.Name = "测试切片"
|
||||
in := sliceEditApplicationInput{ApplicationID: "empty-restore", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: item.Version, SliceSegments: []domain.SliceSegment{kept}}, Dispositions: []sliceDispositionInput{{SliceID: "a", Disposition: "keep", ResetToPending: reset}}}
|
||||
r := f.request("POST", "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-applications", f.annotator, in)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("restore %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
actions := decodeMaterializationValue[domain.AnnotationSegment](annotationWorkspacePayload(saved)["segments"])
|
||||
if len(actions) != 1 || actions[0].Start != 0 || actions[0].End != 10 || actions[0].Status != "pending" {
|
||||
t.Fatalf("empty restored track: %+v", actions)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -352,6 +352,7 @@ type sliceDispositionInput struct {
|
||||
ReasonVersion int `json:"reasonVersion"`
|
||||
ReasonNote string `json:"reasonNote"`
|
||||
RestorePreviousName bool `json:"restorePreviousName,omitempty"`
|
||||
ResetToPending bool `json:"resetToPending,omitempty"`
|
||||
RestoreNameFromVersion int `json:"restoreNameFromVersion,omitempty"`
|
||||
}
|
||||
|
||||
@ -494,6 +495,10 @@ func (s *server) prepareSliceDisposition(w http.ResponseWriter, r *http.Request,
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
before := slices[idx]
|
||||
if body.ResetToPending && (body.Disposition != "keep" || !before.IsDiscarded()) {
|
||||
renderValidationError(w, validationIssue{Field: "resetToPending", Message: "只能在明确取消舍弃时重置待标注区间"})
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
restoredName := ""
|
||||
if body.RestorePreviousName || body.RestoreNameFromVersion != 0 {
|
||||
var found bool
|
||||
@ -576,6 +581,25 @@ func (s *server) prepareSliceDisposition(w http.ResponseWriter, r *http.Request,
|
||||
} else {
|
||||
if before.IsDiscarded() {
|
||||
restored := restoredDiscardAnnotations(before)
|
||||
if body.ResetToPending || len(restored) == 0 {
|
||||
// Explicit restore starts fresh; legacy empty archives still need
|
||||
// a real pending partition. Original evidence remains server-owned.
|
||||
keptSlice := before
|
||||
keptSlice.DeliveryDisposition = "keep"
|
||||
restored = fillPendingActionGaps([]domain.SliceSegment{keptSlice}, nil)
|
||||
}
|
||||
if body.ResetToPending {
|
||||
outside := []domain.AnnotationSegment{}
|
||||
for _, action := range segments {
|
||||
if action.End <= before.Start || action.Start >= before.End {
|
||||
outside = append(outside, action)
|
||||
} else if action.Start < before.Start || action.End > before.End {
|
||||
renderValidationError(w, validationIssue{Field: "segments", Message: "动作跨越切片边界,不能取消舍弃"})
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
}
|
||||
segments = outside
|
||||
}
|
||||
used := map[string]bool{}
|
||||
for _, a := range segments {
|
||||
used[a.ID] = true
|
||||
|
||||
@ -83,13 +83,25 @@ func TestSliceRestoreEmptyAnnotationsReturnsJSONArray(t *testing.T) {
|
||||
if e := json.Unmarshal(r.Body.Bytes(), &wire); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if string(wire.Workspace["segments"]) != "[]" {
|
||||
if raw := string(wire.Workspace["segments"]); len(raw) == 0 || raw[0] != '[' {
|
||||
t.Fatalf("%s returned segments=%s; browser progress.filter requires an array", action, wire.Workspace["segments"])
|
||||
}
|
||||
var got struct {
|
||||
Workspace combinedAnnotationDraftInput `json:"workspace"`
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if action == "discard" && len(got.Workspace.Segments) != 0 {
|
||||
t.Fatal("discard retained active annotations")
|
||||
}
|
||||
if action == "keep" {
|
||||
if len(got.Workspace.Segments) != 1 {
|
||||
t.Fatal("empty archive restore must create one pending interval")
|
||||
}
|
||||
pending := got.Workspace.Segments[0]
|
||||
if pending.Start != 3 || pending.End != 7 || pending.Status != "pending" || pending.Description != "" {
|
||||
t.Fatalf("restore did not create a full pending interval: %+v", pending)
|
||||
}
|
||||
}
|
||||
body.combinedAnnotationDraftInput = got.Workspace
|
||||
body.Version = wire.Item.Version
|
||||
if wire.Item.AssignedUserID != f.annotator.ID || wire.Item.CurrentStageID != f.item.CurrentStageID {
|
||||
|
||||
@ -88,8 +88,12 @@ func TestSliceResetKeepsPartitionWithoutRevivingArchivedActions(t *testing.T) {
|
||||
t.Fatalf("restore after reset: %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
item, workspace = readSliceRestoration(t, f)
|
||||
if len(workspace.Segments) != 0 {
|
||||
t.Fatal("reset descriptions revived from old discard archive")
|
||||
if len(workspace.Segments) != 1 {
|
||||
t.Fatal("restore after reset must create one pending interval")
|
||||
}
|
||||
pending := workspace.Segments[0]
|
||||
if pending.Start != 3 || pending.End != 7 || pending.Status != "pending" || pending.Description != "" || pending.IsInvalid {
|
||||
t.Fatalf("reset revived archived judgment instead of a pending interval: %+v", pending)
|
||||
}
|
||||
history, _ := item.Subject.Payload["sliceDispositionHistory"].([]any)
|
||||
if len(history) < 2 {
|
||||
|
||||
@ -6,9 +6,9 @@ import type { ReviewViewingProps, ReviewViewingController, ReviewPosition, Revie
|
||||
import { ReviewVideoCaption, ReviewCaptionDetails, type ReviewCaption, usePictureBox } from "./ReviewCaptions";
|
||||
import { reviewCaptionAtTime } from "../lib/review-captions.js";
|
||||
import { DiscardReasonFields, type DiscardReasonChoice } from "./DiscardReasonFields";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { cancelActionPartition, lastActionFrame, moveActionBoundary } from "../lib/action-frame-boundary.js";
|
||||
import { actionJudgment } from "../lib/continuous-actions.js";
|
||||
import { actionJudgment, completeActionPartitions } from "../lib/continuous-actions.js";
|
||||
import { adjacentAnnotation } from "../lib/annotation-list-navigation.js";
|
||||
import { WorkspaceDictionaryPanel } from "./WorkspaceDictionaryPanel";
|
||||
import { SliceNameDictionaryPicker } from "./SliceNameDictionaryPicker";
|
||||
@ -331,7 +331,7 @@ export function CaptureAnnotationWorkbench({
|
||||
clipEnd,
|
||||
sourceIsFullVideo = false,
|
||||
slices,
|
||||
segments,
|
||||
segments: providedSegments,
|
||||
labels = [],
|
||||
discardReasons = [],
|
||||
discardReasonsLoading = false,
|
||||
@ -435,6 +435,15 @@ export function CaptureAnnotationWorkbench({
|
||||
const isReviewViewing = isQualityReview || Boolean(providedReviewCaption) || Boolean(reviewNavigation);
|
||||
const timelineReady = frameTimelineStatus === "ready";
|
||||
const readOnly = providedReadOnly || !timelineReady || (isQualityReview && reviewWriteLocked);
|
||||
// Editable continuous tracks expose explicit pending intervals, including
|
||||
// legacy empty workspaces; frozen review records and loading states stay raw.
|
||||
const segments = useMemo(
|
||||
() =>
|
||||
continuousActions && phase === "annotate" && !readOnly && !isReviewViewing
|
||||
? (completeActionPartitions(slices, providedSegments) as AnnotationSegment[])
|
||||
: providedSegments,
|
||||
[continuousActions, phase, readOnly, isReviewViewing, slices, providedSegments],
|
||||
);
|
||||
const workbenchRef = useRef<HTMLElement>(null);
|
||||
const suspendedDialogsRef = useRef<HTMLDialogElement[] | null>(null);
|
||||
const descriptionInputRef = useRef<HTMLTextAreaElement>(null);
|
||||
@ -585,6 +594,16 @@ export function CaptureAnnotationWorkbench({
|
||||
} | null>(null);
|
||||
// 面板内 G 的舍弃原因草稿(预览,不落库;确认后随 Enter 一并应用)。
|
||||
const [sliceEditDiscardDraft, setSliceEditDiscardDraft] = useState<SliceEditPanelDiscardDraft | null>(null);
|
||||
const discardDraftWasOpenRef = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
const closed = discardDraftWasOpenRef.current && !sliceEditDiscardDraft;
|
||||
discardDraftWasOpenRef.current = Boolean(sliceEditDiscardDraft);
|
||||
// Removing the focused child dialog sends focus to BODY. Reclaim it after
|
||||
// the DOM commit, without stealing a deliberate focus on another control.
|
||||
if (closed && sliceEditPanel && document.activeElement === document.body)
|
||||
workbenchRef.current?.focus({ preventScroll: true });
|
||||
}, [sliceEditDiscardDraft, sliceEditPanel]);
|
||||
|
||||
// R2-Q5 旁路锁定提示:面板/清单打开期间按 J/K、拖手柄、点其它切片时的可见反馈
|
||||
// (短暂停留后自动消失,复用 E 提示的恒定占位槽渲染)。
|
||||
const [sliceEditLocked, setSliceEditLocked] = useState(false);
|
||||
@ -1720,7 +1739,9 @@ export function CaptureAnnotationWorkbench({
|
||||
// Enter 落库前自检(03 引擎的 Go 守卫前端镜像):状态白名单 + 「动作完整落在
|
||||
// 恰好一个切片」(ADR 0007 / T3 钉死)。逐片无缝铺满校验刻意不跑——标注相草稿
|
||||
// 允许留空缺口(词汇表「保存进度」),那是提交守卫而非结构改动守卫。
|
||||
const preview = previewSliceEditDispositions(panel.snapshot.slices, resolution.slices, resolution.actions);
|
||||
const preview = previewSliceEditDispositions(panel.snapshot.slices, resolution.slices, resolution.actions, {
|
||||
resetRestoredActions: true,
|
||||
});
|
||||
const issues = [
|
||||
...validateActionStatuses(preview.actions),
|
||||
...assertActionsCoveredByExactlyOneSlice(preview.actions, preview.slices),
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { AnnotationLabelRecord, SliceSegment } from "../types";
|
||||
import { formatAnnotationTime } from "../lib/annotation-time.js";
|
||||
import { DiscardReasonFields, type DiscardReasonChoice } from "./DiscardReasonFields";
|
||||
@ -78,6 +78,14 @@ export function SliceEditPanel({
|
||||
const [startDraft, setStartDraft] = useState("");
|
||||
const [endDraft, setEndDraft] = useState("");
|
||||
const dictionaryTriggerRef = useRef<HTMLButtonElement>(null);
|
||||
const dispositionPreviewRef = useRef<HTMLDivElement>(null);
|
||||
const dispositionPreviewOpen = Boolean(discard.draft);
|
||||
useLayoutEffect(() => {
|
||||
// Both discard reasons and restore confirmation own their first Enter.
|
||||
// The nested dictionary may subsequently focus its search input.
|
||||
if (dispositionPreviewOpen) dispositionPreviewRef.current?.focus({ preventScroll: true });
|
||||
}, [dispositionPreviewOpen]);
|
||||
|
||||
const boundaryValue = (field: "start" | "end") =>
|
||||
exactFrames ? String(frameIndexOf(target[field])) : String(Number(target[field].toFixed(3)));
|
||||
useEffect(() => {
|
||||
@ -290,6 +298,10 @@ export function SliceEditPanel({
|
||||
|
||||
{discard.draft ? (
|
||||
<div
|
||||
ref={dispositionPreviewRef}
|
||||
tabIndex={-1}
|
||||
role="group"
|
||||
aria-label="切片用途预览确认"
|
||||
className="rounded border border-orange-300 bg-orange-50/50 p-2 dark:border-orange-700 dark:bg-orange-950/20"
|
||||
onKeyDown={(event) => {
|
||||
// 弹层自有键:Esc 关草稿(一层一层退),Ctrl/⌘+Enter 确认——镜像既有舍弃弹窗。
|
||||
@ -320,7 +332,9 @@ export function SliceEditPanel({
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
{!discard.draft.discard && <p className="my-1.5 text-xs">恢复后请核对原有描述,再按现有流程提交审核。</p>}
|
||||
{!discard.draft.discard && (
|
||||
<p className="my-1.5 text-xs">恢复后整片重置为一个待标注动作;原有内容保留在历史中。</p>
|
||||
)}
|
||||
{discard.draft.discard && (
|
||||
<DiscardReasonFields
|
||||
workspace
|
||||
|
||||
@ -1,9 +1,15 @@
|
||||
import { completeActionPartitions } from "./continuous-actions.js";
|
||||
|
||||
const discarded = (slice) => slice?.deliveryDisposition === "discard";
|
||||
const parent = (before, slice) =>
|
||||
before.find((old) => old.id === slice.id) || before.find((old) => slice.sourceIds?.includes(old.id));
|
||||
|
||||
/** Explicit policy commands for one atomic panel application (including undo). */
|
||||
export function sliceEditDispositionCommands(before = [], after = []) {
|
||||
export function sliceEditDispositionCommands(
|
||||
before = [],
|
||||
after = [],
|
||||
{ resetRestoredActions = false, restoredActions = [] } = {},
|
||||
) {
|
||||
const commands = [];
|
||||
for (const slice of after) {
|
||||
const old = parent(before, slice);
|
||||
@ -19,6 +25,21 @@ export function sliceEditDispositionCommands(before = [], after = []) {
|
||||
commands.push({
|
||||
sliceId: slice.id,
|
||||
disposition: discarded(slice) ? "discard" : "keep",
|
||||
...(!discarded(slice) &&
|
||||
discarded(old) &&
|
||||
(resetRestoredActions ||
|
||||
restoredActions.some(
|
||||
(action) =>
|
||||
action.start === slice.start &&
|
||||
action.end === slice.end &&
|
||||
action.status === "pending" &&
|
||||
!action.description?.trim() &&
|
||||
!action.isInvalid &&
|
||||
restoredActions.filter((candidate) => candidate.start < slice.end && candidate.end > slice.start).length ===
|
||||
1,
|
||||
))
|
||||
? { resetToPending: true }
|
||||
: {}),
|
||||
reason: slice.discardReason,
|
||||
reasonLabelId: slice.discardReasonLabelId,
|
||||
reasonVersion: slice.discardReasonVersion,
|
||||
@ -43,8 +64,13 @@ export function sliceEditDispositionCommands(before = [], after = []) {
|
||||
|
||||
/** Preview the same archive/restore shape used by the server, without mutation.
|
||||
* Raw resolver actions are still sent to the server so it owns audit evidence. */
|
||||
export function previewSliceEditDispositions(before = [], after = [], actions = []) {
|
||||
const nextActions = actions.filter(
|
||||
export function previewSliceEditDispositions(
|
||||
before = [],
|
||||
after = [],
|
||||
actions = [],
|
||||
{ resetRestoredActions = false } = {},
|
||||
) {
|
||||
let nextActions = actions.filter(
|
||||
(action) => !after.some((slice) => discarded(slice) && action.start >= slice.start && action.end <= slice.end),
|
||||
);
|
||||
const slices = after.map((slice) => {
|
||||
@ -58,7 +84,9 @@ export function previewSliceEditDispositions(before = [], after = [], actions =
|
||||
...actions.filter((action) => action.start >= slice.start && action.end <= slice.end),
|
||||
],
|
||||
};
|
||||
if (discarded(old)) {
|
||||
if (discarded(old) && resetRestoredActions) {
|
||||
nextActions = nextActions.filter((action) => action.end <= slice.start || action.start >= slice.end);
|
||||
} else if (discarded(old)) {
|
||||
for (const action of old.discardedAnnotations || []) {
|
||||
const start = Math.max(action.start, slice.start),
|
||||
end = Math.min(action.end, slice.end);
|
||||
@ -68,5 +96,5 @@ export function previewSliceEditDispositions(before = [], after = [], actions =
|
||||
}
|
||||
return slice;
|
||||
});
|
||||
return { slices, actions: nextActions };
|
||||
return { slices, actions: completeActionPartitions(slices, nextActions) };
|
||||
}
|
||||
|
||||
@ -3467,6 +3467,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
version: token.version,
|
||||
sliceId,
|
||||
disposition,
|
||||
...(recordHistory && disposition === "keep" ? { resetToPending: true } : {}),
|
||||
restorePreviousName,
|
||||
...(restorePreviousName && restoreNameFromVersion ? { restoreNameFromVersion } : {}),
|
||||
...reason,
|
||||
@ -3559,7 +3560,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
segments: nextSegments,
|
||||
operations: restoredOperations,
|
||||
statuses: deriveSliceStatuses(nextSlices, nextSegments, sliceStatuses) as typeof sliceStatuses,
|
||||
dispositions: sliceEditDispositionCommands(sliceSegments, nextSlices),
|
||||
dispositions: sliceEditDispositionCommands(sliceSegments, nextSlices, {
|
||||
resetRestoredActions: recordHistory,
|
||||
restoredActions: nextSegments,
|
||||
}),
|
||||
};
|
||||
try {
|
||||
const result = await settleAuthoritativeMutation({
|
||||
|
||||
@ -60,6 +60,7 @@ export const annotationOperationsApi = {
|
||||
sliceId: string;
|
||||
disposition: "keep" | "discard";
|
||||
restorePreviousName?: boolean;
|
||||
resetToPending?: boolean;
|
||||
restoreNameFromVersion?: number;
|
||||
reason?: string;
|
||||
reasonLabelId?: string;
|
||||
@ -243,6 +244,7 @@ export const annotationOperationsApi = {
|
||||
dispositions: {
|
||||
sliceId: string;
|
||||
disposition: string;
|
||||
resetToPending?: boolean;
|
||||
reason?: string;
|
||||
reasonLabelId?: string;
|
||||
reasonVersion?: number;
|
||||
|
||||
51
tests/browser/discard-focus-track.mjs
Normal file
51
tests/browser/discard-focus-track.mjs
Normal file
@ -0,0 +1,51 @@
|
||||
// Run through the Codex CUA tab binding, not a second browser driver:
|
||||
// await runDiscardFocusTrackRegression(tab, "http://127.0.0.1:5176")
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
export async function runDiscardFocusTrackRegression(tab, origin) {
|
||||
assert.ok(["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname));
|
||||
const fixture = origin + "/tests/browser/fixtures/discard-focus-track.html";
|
||||
const results = [];
|
||||
for (const focused of [false, true]) {
|
||||
await tab.goto(fixture + (focused ? "?focused" : ""));
|
||||
await tab.playwright.getByTestId("capture-annotation-workbench").waitFor({ state: "visible" });
|
||||
await tab.pressKey(null, "e");
|
||||
await tab.pressKey(null, "g");
|
||||
await tab.playwright.getByRole("button", { name: "测试原因", exact: true }).click();
|
||||
await tab.pressKey(null, "Return");
|
||||
assert.match(await tab.playwright.getByTestId("apply-count").innerText(), /0/);
|
||||
assert.equal(
|
||||
await tab.playwright.evaluate(
|
||||
() => document.activeElement?.closest('[data-testid="capture-annotation-workbench"]') !== null,
|
||||
),
|
||||
true,
|
||||
);
|
||||
await tab.pressKey(null, "Return");
|
||||
assert.match(await tab.playwright.getByTestId("apply-count").innerText(), /1/);
|
||||
// Restore confirmation must consume its own Enter before panel application.
|
||||
await tab.pressKey(null, "e");
|
||||
await tab.pressKey(null, "g");
|
||||
await tab.pressKey(null, "Return");
|
||||
assert.match(await tab.playwright.getByTestId("apply-count").innerText(), /1/);
|
||||
assert.equal(await tab.playwright.getByTestId("slice-edit-panel").count(), 1);
|
||||
await tab.pressKey(null, "Return");
|
||||
assert.match(await tab.playwright.getByTestId("apply-count").innerText(), /2/);
|
||||
const actions = JSON.parse(await tab.playwright.getByTestId("track-state").innerText());
|
||||
const own = actions.filter((a) => a.start < 4);
|
||||
assert.equal(own.length, 1);
|
||||
assert.deepEqual([own[0].start, own[0].end, own[0].status, own[0].description], [0, 4, "pending", ""]);
|
||||
assert.equal(actions.find((a) => a.id === "a2").end, 8);
|
||||
results.push({
|
||||
focused,
|
||||
keyboardDiscardApply: "passed",
|
||||
keyboardRestoreApply: "passed",
|
||||
fullPendingTrack: "passed",
|
||||
});
|
||||
}
|
||||
await tab.goto(fixture + "?empty");
|
||||
const list = tab.playwright.getByRole("listbox", { name: "动作区间", exact: true });
|
||||
assert.match(await list.innerText(), /待标注/);
|
||||
assert.match(await list.innerText(), /00:00.000.*00:04.000/s);
|
||||
results.push({ legacyEmptyEditableTrack: "filled" });
|
||||
return results;
|
||||
}
|
||||
11
tests/browser/fixtures/discard-focus-track.html
Normal file
11
tests/browser/fixtures/discard-focus-track.html
Normal file
@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>切片焦点与轨道回归</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/tests/browser/fixtures/discard-focus-track.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
62
tests/browser/fixtures/discard-focus-track.tsx
Normal file
62
tests/browser/fixtures/discard-focus-track.tsx
Normal file
@ -0,0 +1,62 @@
|
||||
import React, { useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { CaptureAnnotationWorkbench } from "/src/components/CaptureAnnotationWorkbench";
|
||||
import { previewSliceEditDispositions } from "/src/lib/slice-edit-dispositions.js";
|
||||
import "/src/index.css";
|
||||
const query = new URLSearchParams(location.search);
|
||||
function Harness() {
|
||||
const [slices, setSlices] = useState([
|
||||
{ id: "s1", name: "测试切片", start: 0, end: 4 },
|
||||
{ id: "s2", name: "相邻切片", start: 4, end: 8 },
|
||||
]);
|
||||
const [actions, setActions] = useState(
|
||||
query.has("empty")
|
||||
? []
|
||||
: [
|
||||
{ id: "a1", start: 0, end: 4, status: "pending", description: "", label: "", labelId: "", source: "manual" },
|
||||
{ id: "a2", start: 4, end: 8, status: "pending", description: "", label: "", labelId: "", source: "manual" },
|
||||
],
|
||||
);
|
||||
const [count, setCount] = useState(0);
|
||||
return (
|
||||
<div className="annotation-operations-page">
|
||||
<p role="status" data-testid="apply-count">
|
||||
已应用 {count} 次
|
||||
</p>
|
||||
<CaptureAnnotationWorkbench
|
||||
taskId="focus-synthetic"
|
||||
videoSource=""
|
||||
clipStart={0}
|
||||
clipEnd={8}
|
||||
sourceIsFullVideo
|
||||
slices={slices}
|
||||
segments={actions}
|
||||
statuses={{ s1: "pending", s2: "pending" }}
|
||||
phase="annotate"
|
||||
initialSliceId="s1"
|
||||
frameTimelineStatus="ready"
|
||||
frameBoundaries={Array.from({ length: 81 }, (_, i) => i / 10)}
|
||||
continuousActions
|
||||
focusedLayout={query.has("focused")}
|
||||
reworkNotice={{ stageName: "返工", reviewRound: 1 }}
|
||||
labels={[]}
|
||||
discardReasons={[{ id: "reason", name: "测试原因", version: 1 }]}
|
||||
sliceDictionary={[{ id: "name", name: "测试切片" }]}
|
||||
onChange={setActions}
|
||||
onApplySliceEdit={async (next, segments) => {
|
||||
const p = previewSliceEditDispositions(slices, next, segments, { resetRestoredActions: true });
|
||||
setSlices(p.slices);
|
||||
setActions(p.actions);
|
||||
setCount((v) => v + 1);
|
||||
return true;
|
||||
}}
|
||||
onConfirmAnnotations={() => true}
|
||||
onConfirmSlices={() => {}}
|
||||
onSubmitTask={() => {}}
|
||||
onReturnToPool={() => {}}
|
||||
/>
|
||||
<pre data-testid="track-state">{JSON.stringify(actions)}</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
createRoot(document.getElementById("root")!).render(<Harness />);
|
||||
@ -46,6 +46,10 @@ export function reviewSeekHarness(overrides = {}) {
|
||||
useCallback(fn, deps) {
|
||||
return hooks.useMemo(() => fn, deps);
|
||||
},
|
||||
// This transport seam has no DOM layout; both effect phases flush after refs.
|
||||
useLayoutEffect(fn, deps) {
|
||||
hooks.useEffect(fn, deps);
|
||||
},
|
||||
useEffect(fn, deps) {
|
||||
const i = cursor++;
|
||||
if (!slots[i] || !equal(slots[i].deps, deps)) {
|
||||
|
||||
90
tests/frontend/slice-edit-restore-track.test.mjs
Normal file
90
tests/frontend/slice-edit-restore-track.test.mjs
Normal file
@ -0,0 +1,90 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { previewSliceEditDispositions, sliceEditDispositionCommands } from "../../src/lib/slice-edit-dispositions.js";
|
||||
|
||||
for (const archive of [undefined, [], [{ id: "stale", start: 0, end: 0, status: "pending" }]]) {
|
||||
test(`restoring a slice without recoverable actions yields one full pending interval (${JSON.stringify(archive)})`, () => {
|
||||
const discarded = {
|
||||
id: "restored",
|
||||
start: 2,
|
||||
end: 8,
|
||||
deliveryDisposition: "discard",
|
||||
discardedAnnotations: archive,
|
||||
};
|
||||
const neighbor = { id: "neighbor", start: 8, end: 10 };
|
||||
const action = { id: "neighbor-action", start: 8, end: 10, status: "described", description: "preserve" };
|
||||
const input = structuredClone({ discarded, neighbor, action });
|
||||
const result = previewSliceEditDispositions(
|
||||
[discarded, neighbor],
|
||||
[{ ...discarded, deliveryDisposition: "keep" }, neighbor],
|
||||
[action],
|
||||
);
|
||||
const restored = result.actions.filter((a) => a.start >= 2 && a.end <= 8);
|
||||
assert.equal(restored.length, 1, "a kept editable slice must never have an empty action track");
|
||||
assert.deepEqual([restored[0].start, restored[0].end, restored[0].status], [2, 8, "pending"]);
|
||||
assert.ok(restored[0].id, "the pending interval needs a stable identity");
|
||||
assert.equal(restored[0].description || "", "");
|
||||
assert.deepEqual(
|
||||
result.actions.find((a) => a.id === action.id),
|
||||
action,
|
||||
);
|
||||
assert.deepEqual({ discarded, neighbor, action }, input);
|
||||
});
|
||||
}
|
||||
|
||||
test("explicit restore resets mixed archived judgments; undo retains the archive path and redo retains pending", () => {
|
||||
const archive = [
|
||||
{ id: "old-described", start: 0, end: 2, status: "described", description: "original" },
|
||||
{ id: "old-invalid", start: 2, end: 4, status: "invalid", isInvalid: true },
|
||||
];
|
||||
const before = [
|
||||
{ id: "a", start: 0, end: 4, deliveryDisposition: "discard", discardedAnnotations: archive },
|
||||
{ id: "b", start: 4, end: 8 },
|
||||
];
|
||||
const after = before.map((slice) => (slice.id === "a" ? { ...slice, deliveryDisposition: "keep" } : slice));
|
||||
const neighbor = { id: "other", start: 4, end: 8, status: "pending" };
|
||||
const explicit = previewSliceEditDispositions(before, after, [neighbor], { resetRestoredActions: true });
|
||||
const own = explicit.actions.filter((a) => a.start < 4);
|
||||
assert.equal(own.length, 1);
|
||||
assert.deepEqual([own[0].start, own[0].end, own[0].status], [0, 4, "pending"]);
|
||||
assert.equal(own[0].description, "");
|
||||
assert.equal(own[0].isInvalid, undefined);
|
||||
assert.deepEqual(before[0].discardedAnnotations, archive);
|
||||
assert.equal(sliceEditDispositionCommands(before, after, { resetRestoredActions: true })[0].resetToPending, true);
|
||||
assert.equal(sliceEditDispositionCommands(before, after)[0].resetToPending, undefined);
|
||||
assert.equal(
|
||||
sliceEditDispositionCommands(before, after, { restoredActions: explicit.actions })[0].resetToPending,
|
||||
true,
|
||||
);
|
||||
const historical = previewSliceEditDispositions(before, after, [neighbor]);
|
||||
assert.deepEqual(
|
||||
historical.actions.filter((a) => a.start < 4),
|
||||
archive,
|
||||
);
|
||||
assert.equal(
|
||||
sliceEditDispositionCommands(before, after, { restoredActions: historical.actions })[0].resetToPending,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test("kept editable partitions never become empty through repeated discard/restore cycles", () => {
|
||||
let slices = [
|
||||
{ id: "a", start: 0, end: 4 },
|
||||
{ id: "b", start: 4, end: 8 },
|
||||
];
|
||||
let actions = [];
|
||||
for (let cycle = 0; cycle < 10; cycle++) {
|
||||
for (const disposition of ["discard", "keep"]) {
|
||||
const next = slices.map((s) => (s.id === "a" ? { ...s, deliveryDisposition: disposition } : s));
|
||||
const result = previewSliceEditDispositions(slices, next, actions, { resetRestoredActions: true });
|
||||
for (const s of result.slices.filter((s) => s.deliveryDisposition !== "discard")) {
|
||||
const own = result.actions.filter((a) => a.start >= s.start && a.end <= s.end);
|
||||
assert.equal(own.length, 1);
|
||||
assert.equal(own[0].start, s.start);
|
||||
assert.equal(own[0].end, s.end);
|
||||
}
|
||||
slices = result.slices;
|
||||
actions = result.actions;
|
||||
}
|
||||
}
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user