From 4d12d8cb02b846f050d924548d535b698bc77ef7 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Wed, 21 Oct 2026 13:25:33 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Persist=20drag=20edits=20through?= =?UTF-8?q?=20atomic=20archive=20application?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The quick path validated raw actions before archiving and bypassed the server slice application. Share its archive-aware validation and authoritative save with panel edits, await Enter confirmation, retain failed choices, and preserve pre-drag persisted undo. Cover both directions, recovery, and keyboard/mouse confirmation through the real page and HTTP API. --- .scratch/rework-boundary-20261021/map.md | 13 ++ .scratch/rework-boundary-20261021/spec.md | 18 ++ ...-inplace-slice-editing-replaces-reslice.md | 9 + docs/annotation-keyboard-guide.zh-CN.md | 1 + docs/verification/rework-boundary-20261021.md | 19 ++ internal/api/rework_boundary_browser_test.go | 146 ++++++++++++ src/components/CaptureAnnotationWorkbench.tsx | 63 ++++-- src/components/SliceEditConflictList.tsx | 18 +- src/lib/slice-edit-drag-quick-path.js | 10 +- src/pages/AnnotationOperations.tsx | 162 ++++++++++---- tests/browser/rework-boundary-replica.mjs | 211 ++++++++++++++++++ .../capture-annotation-workbench.test.mjs | 4 +- tests/frontend/rework-boundary.test.mjs | 74 ++++++ 13 files changed, 681 insertions(+), 67 deletions(-) create mode 100644 .scratch/rework-boundary-20261021/map.md create mode 100644 .scratch/rework-boundary-20261021/spec.md create mode 100644 docs/verification/rework-boundary-20261021.md create mode 100644 internal/api/rework_boundary_browser_test.go create mode 100644 tests/browser/rework-boundary-replica.mjs create mode 100644 tests/frontend/rework-boundary.test.mjs diff --git a/.scratch/rework-boundary-20261021/map.md b/.scratch/rework-boundary-20261021/map.md new file mode 100644 index 00000000..c874a8e7 --- /dev/null +++ b/.scratch/rework-boundary-20261021/map.md @@ -0,0 +1,13 @@ +# Wang Ziyu rework feedback + +## Notes + +11:41 Enter feedback and 11:42 discard-boundary feedback are tracked separately, with a shared failing save path. A missing Capture title alone does not establish the cause. Repair base is deployed fab5be57; delivery classification v4 work is a separate branch. + +## Decisions-so-far + +- [Resolved repair](spec.md): route shortcuts through atomic slice application, preserve kept classifications, await confirmation and retain failed choices. Existing archive authority, CAS and undo contracts are reused. + +## Fog + +Local synthetic verification is not production acceptance. No customer records were changed, and this branch has not been deployed. Historical records that users explicitly invalidated require a separate evidence-based recovery decision; this fix does not infer their intended classifications. diff --git a/.scratch/rework-boundary-20261021/spec.md b/.scratch/rework-boundary-20261021/spec.md new file mode 100644 index 00000000..aa610d97 --- /dev/null +++ b/.scratch/rework-boundary-20261021/spec.md @@ -0,0 +1,18 @@ +# Repair Wang Ziyu's discard-boundary and Enter feedback +Status: resolved + +Base: deployed fab5be57. Local changes only; no deployment, push or production writes. + +Use the existing atomic slice application for boundary edits and conflict confirmation, with server-owned archives, version checks, authoritative recovery and one persisted undo step. Keep discarded portions archived and preserve kept-side action text/status/dictionary. Explicit invalidate remains a deliberate whole-action decision. + +Enter/button confirmation must await persistence, reject duplicate writes, expose failures beside the confirmation controls, retain choices for retry and prevent cancellation while a result is pending. No outcome is inferred from the Capture title. + +Verify through the actual AnnotationOperations page and real HTTP slice API with isolated synthetic data: left/right expansion, pending/described, mouse/keyboard confirmation, fresh read, error/retry, lost response, cancel, undo/redo and first-pass/rework. Keep existing split/merge, permission and autosave contracts. + +## Answer + +The deployed drag path had bypassed the atomic slice application and validated raw pieces before server archive semantics. Both failures are now handled by the existing authoritative application/reconciliation flow. Discarded portions are archived; kept portions preserve classification. Confirmation is asynchronous with an inline failure and a duplicate/cancel guard. + +Regression command: `REWORK_BOUNDARY_BROWSER_TEST=1 go test ./internal/api -run '^TestReworkBoundaryBrowserReplica$' -count=1 -v` (local loopback and isolated MemoryStore; ffmpeg, Node dependencies and a Playwright browser required). Unit regression: `node --test tests/frontend/rework-boundary.test.mjs`. + +Details: [map](map.md), [verification](../../docs/verification/rework-boundary-20261021.md). diff --git a/docs/adr/0007-inplace-slice-editing-replaces-reslice.md b/docs/adr/0007-inplace-slice-editing-replaces-reslice.md index 79ae4646..42032e2f 100644 --- a/docs/adr/0007-inplace-slice-editing-replaces-reslice.md +++ b/docs/adr/0007-inplace-slice-editing-replaces-reslice.md @@ -16,6 +16,15 @@ - 默认“截断”在边界切开动作,进入舍弃侧的部分归档,保留侧不被整段无效化。“判无效”仍是显式的整段无效判断(两侧几何保留);清单说明影响范围,不将其作为跨保留/舍弃边界的唯一可保存选项。 - 切片重设面板与冲突清单占用右侧编辑区,普通宽屏预留侧栏,窄屏进入正常文档流,避免遮挡视频;替代早期“锚到分界处”的浮卡位置规则。帧号输入及单帧步进不变;Shift+方向键仍为 0.5 秒粗调。 +## 2026-10-21:拖拽与冲突清单应用路径补齐 + +这是 10-19 边界归档语义的入口补齐,不新增分类或舍弃状态。 + +- 拖拽释放、快捷边界调整、拆分及删除的快捷应用,与 E 面板共用服务端切片原子应用;前端对归档后的活动动作作包含校验,但发送原始分割动作,由服务端维护归档、版本检查与审计。 +- 一次拖动及其确认只记录一条持久化历史,撤销基线为拖动前工作区。正常侧保留原描述、状态和分类信息;显式“判无效”的语义不变。 +- Enter 和按钮均等待权威保存结果;保存中禁用重复应用、处置选择及取消,错误在清单内显示并保留选择。响应丢失时通过原应用编号回读确认。成功后清理已合入保存的编辑器草稿,避免用旧几何覆盖新工作区。 +- 不批量修改已保存、送检或交付数据;现有权限、阶段锁、历史数据恢复接口保持有效。 + ## 背景 返修中要改切片结构只能"重新切片":清空全部动作标注、整单退回切片阶段,代价高且不可审计(旧文案"请先返回重新切片"即两把阶段锁的报错)。同时旧 D2 规则在拖动边界穿过动作时自动拆两段标"待核对"——该状态不在服务端白名单(pending/described/invalid)内,不处置则保存被堵死。本决策来自 24 项已拍板裁决(Q1:a–Q8:a、R2-Q1–Q8、R3-1–R3-4)。 diff --git a/docs/annotation-keyboard-guide.zh-CN.md b/docs/annotation-keyboard-guide.zh-CN.md index 869f2517..ad0836af 100644 --- a/docs/annotation-keyboard-guide.zh-CN.md +++ b/docs/annotation-keyboard-guide.zh-CN.md @@ -100,6 +100,7 @@ Ctrl/⌘+Z 可连续撤销,Ctrl/⌘+Shift+Z 可重做。最多保留最近 100 - **被边界穿过的动作**(三选条目):`1` 截断(动作在边界处分成两段,各段保留原状态)/`2` 挪片(段迁入对面切片保留原状态,让出的空当自动生成显式无效段)/`3` 判无效(整段截断几何全部转无效)。 - **恰好贴边的有效动作**(两选条目):`1` 跟随伸缩(默认)/`2` 保持原边界。贴边的无效动作不成条目,自动跟随伸缩(零打扰)。 - 清单键位:`↑/↓` 在条目间移动(回绕);`1/2/3` 选当前条目处置,选完自动跳下一条未决;`Enter` 应用(未决条目按默认——三选截断、两选跟随——批量处理);`Esc` 取消整个待应用改动集。不支持部分应用。 +- Enter 或按钮确认后显示“正在保存…”,等待完成再继续;保存期间不能重复应用或取消。失败原因显示在清单内,原选择保留,可核对后重试。 - 清单打开期间其它键不响应,其它边界改动也被冻结;一次只决一件事。 - 无论怎么选,时间轴覆盖永不缺口、动作/无效两轨永不重叠;自动生成的无效段与手工无效动作完全同形,可编辑、可撤销。 diff --git a/docs/verification/rework-boundary-20261021.md b/docs/verification/rework-boundary-20261021.md new file mode 100644 index 00000000..a9a98916 --- /dev/null +++ b/docs/verification/rework-boundary-20261021.md @@ -0,0 +1,19 @@ +# Rework boundary and Enter repair — 2026-10-21 + +Base: deployed `fab5be57`. Implementation is local, on `codex/rework-boundary-20261021`. + +The quick drag path previously ran raw action containment validation and local draft save, bypassing the server archive application. The fix validates the archive preview and sends original action pieces through the existing atomic application. Enter and mouse confirmation await authoritative persistence. A failed save retains choices and shows its error beside the controls; pending saves block duplicate application and cancellation. Persisted undo uses the pre-drag snapshot, and successful quick edits clear frozen drafts. + +## Regression evidence + +- The new unit regression against pristine `fab5be57` source fails all four left/right × pending/described cases with “舍弃片段不能包含当前有效标注”. Against the fix, all five tests pass, including rejection of an unsupported action status hidden in a discard interval. +- All 26 focused frontend checks pass. +- The real AnnotationOperations page is served by Vite and driven in headless Edge, against actual Go HTTP handlers and an isolated MemoryStore. Synthetic video, hardware timestamps and IMU data exercise frame validation. No customer or snapshot database is used. All 10 browser scenarios pass with zero page errors. Browser assertions cover left/right expansion, pending/described, first-pass/rework, button/Enter, persisted reload, visible failure/retry, delayed-save duplicate and cancel guards, lost-response reconciliation, persisted undo/redo, and Escape cancellation. +- Focused Go archive/application/restoration/legacy/permission contracts pass. No backend business contract or database migration is introduced. +- TypeScript, full frontend baseline gate, frontend/API/worker builds and production-bundle browser boot pass. The frontend gate retains 13 exact failures already registered in `tests/known-failures.json`; no new failure and no baseline change. These are unrelated navigation/project/automation source-shape assertions; the production-shell assertion is now passing. + +Run the browser regression with `REWORK_BOUNDARY_BROWSER_TEST=1 go test ./internal/api -run '^TestReworkBoundaryBrowserReplica$' -count=1 -v`. It needs local ffmpeg, npm dependencies and a Playwright browser (Edge by default, or BROWSER_EXECUTABLE). Evidence is written under untracked `local-data/test-results/rework-boundary/`. The pristine unit comparison is in its `baseline/result.log`; the final frontend summary lists exact existing failures and full logs. + +## Compatibility and limits + +The existing endpoints, domain statuses, permission checks, archive authority, CAS and response-loss recovery remain in use. Other workflows and the separate delivery-format work are not included. This prevents future inadvertent invalidation through the affected shortcut; it does not reconstruct classifications already explicitly changed by a user. Production rollout and customer acceptance remain outstanding. diff --git a/internal/api/rework_boundary_browser_test.go b/internal/api/rework_boundary_browser_test.go new file mode 100644 index 00000000..bb699937 --- /dev/null +++ b/internal/api/rework_boundary_browser_test.go @@ -0,0 +1,146 @@ +package api + +import ( + "context" + "droboticflow/internal/config" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "droboticflow/internal/domain" +) + +// Actual page -> actual HTTP handler -> isolated memory store. Neither a +// production endpoint nor the local snapshot database is reachable here. +func TestReworkBoundaryBrowserReplica(t *testing.T) { + if os.Getenv("REWORK_BOUNDARY_BROWSER_TEST") != "1" { + t.Skip("local browser opt-in") + } + f := continuousFixture(t) + reason := dispositionFixturePayload(t, f) + if err := f.store.UpsertOrganizationPlugin(f.ctx, domain.OrganizationPluginRecord{OrganizationID: domain.DefaultOrganizationID, PluginID: "annotation-qa", Enabled: true, Config: defaultAnnotationPluginConfig()}); err != nil { + t.Fatal(err) + } + reset := func(side, status string, round int) error { + var before []domain.SliceSegment + d := domain.SliceSegment{ID: "d", Start: 0, End: 5, DeliveryDisposition: "discard", DiscardReason: "相机被遮挡", DiscardReasonLabelID: reason.ReasonLabelID, DiscardReasonVersion: reason.ReasonVersion} + k := domain.SliceSegment{ID: "k", Name: "测试切片", Start: 5, End: 10} + if side == "right" { + k.Start, k.End = 0, 5 + d.Start, d.End = 5, 10 + before = []domain.SliceSegment{k, d} + } else { + before = []domain.SliceSegment{d, k} + } + a := domain.AnnotationSegment{ID: "a", Start: k.Start, End: k.End, Status: status} + if status == "invalid" { + a.IsInvalid = true + a.Description = "无效片段" + } + if status == "described" { + a.Description = "合成有效动作" + } + item := f.item + item.ReviewRound = round + actions := []domain.AnnotationSegment{a} + item.Subject.Payload = map[string]any{"sliceWorkflow": map[string]any{"status": "completed", "phase": "annotate"}, "annotationWorkspace": map[string]any{"userId": f.annotator.ID, "savedAt": nowISO(), "sliceSegments": before, "segments": actions, "statuses": map[string]string{"k": "pending", "d": "discarded"}}} + return f.store.UpsertHumanItem(f.ctx, item) + } + root := t.TempDir() + 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 + f.task.SourceDurationSeconds = 10 + f.task.CoverageEndSecond = 10 + pts := "timestamp_us\n" + for i := 0; i < 100; i++ { + pts += fmt.Sprintf("%d\n", 1000000+i*100000) + } + bindings := []domain.NodeInputBinding{} + 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 { + t.Fatalf("video: %v: %s", err, out) + } + timestamps := filepath.Join(root, side+"_pts.csv") + if err := os.WriteFile(timestamps, []byte(pts), 0600); err != nil { + t.Fatal(err) + } + port := "fullLeftVideos" + if side == "right" { + port = "fullRightVideos" + } + bindings = append(bindings, domain.NodeInputBinding{TargetPortID: port, Artifacts: []domain.ExecutionArtifact{{ID: side + "-video", Name: side + ".mp4", Path: video, Data: map[string]any{"collectionId": "capture"}}}}, domain.NodeInputBinding{TargetPortID: side + "Timestamps", Artifacts: []domain.ExecutionArtifact{{ID: side + "-pts", Name: side + "_pts.csv", Path: timestamps, Data: map[string]any{"collectionId": "capture"}}}}) + } + imu := "timestamp_us,x,y,z,type\n" + for i := 0; i < 100; i++ { + stamp := 1000000 + i*100000 + imu += fmt.Sprintf("%d,1,2,3,accel\n%d,4,5,6,gyro\n", stamp, stamp) + } + imuPath := filepath.Join(root, "imu.csv") + if err := os.WriteFile(imuPath, []byte(imu), 0600); err != nil { + 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 { + t.Fatal(err) + } + if err := f.store.UpsertAnnotationTask(f.ctx, f.task); err != nil { + t.Fatal(err) + } + if err := reset("left", "described", 1); err != nil { + t.Fatal(err) + } + 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" { + renderJSON(w, 200, map[string]any{"user": sanitizeUser(&f.annotator), "organization": domain.OrganizationRecord{ID: domain.DefaultOrganizationID, Status: domain.OrganizationStatusActive}}) + return + } + if r.URL.Path == "/__boundary/reset" { + round := 1 + if r.URL.Query().Get("round") == "0" { + round = 0 + } + if err := reset(r.URL.Query().Get("side"), r.URL.Query().Get("status"), round); err != nil { + renderError(w, 500, err) + return + } + renderJSON(w, 200, map[string]any{"ok": true}) + return + } + if r.URL.Path == "/__boundary/state" { + item, _ := f.store.GetHumanItem(r.Context(), f.item.ID) + renderJSON(w, 200, item) + return + } + if r.Method != "GET" && r.Method != "HEAD" && !strings.HasSuffix(r.URL.Path, "/slice-edit-applications") && !strings.HasSuffix(r.URL.Path, "/slice-edit-restorations") && !strings.HasSuffix(r.URL.Path, "/drafts") { + renderJSON(w, 403, map[string]string{"error": "fixture write not permitted"}) + return + } + r.AddCookie(&http.Cookie{Name: csrfCookieName, Value: "boundary-local-csrf"}) + r.Header.Set(csrfHeaderName, "boundary-local-csrf") + r = r.WithContext(context.WithValue(r.Context(), authContextKey{}, &authenticatedPrincipal{User: f.annotator, Organization: domain.OrganizationRecord{ID: domain.DefaultOrganizationID, Status: domain.OrganizationStatusActive}})) + handler.ServeHTTP(w, r) + })) + defer server.Close() + ctx, cancel := context.WithTimeout(t.Context(), 4*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, "node", "tests/browser/rework-boundary-replica.mjs") + cmd.Dir = "../.." + cmd.Env = append(os.Environ(), "REWORK_BOUNDARY_API="+server.URL) + out, err := cmd.CombinedOutput() + t.Log(string(out)) + if err != nil { + t.Fatal(fmt.Errorf("browser: %w", err)) + } +} diff --git a/src/components/CaptureAnnotationWorkbench.tsx b/src/components/CaptureAnnotationWorkbench.tsx index 2429f338..c2620a55 100644 --- a/src/components/CaptureAnnotationWorkbench.tsx +++ b/src/components/CaptureAnnotationWorkbench.tsx @@ -1,5 +1,5 @@ +import { checkSliceEditResolution } from "../lib/slice-edit-drag-quick-path.js"; import { formatAnnotationTime } from "../lib/annotation-time.js"; -import { previewSliceEditDispositions } from "../lib/slice-edit-dispositions.js"; import { userErrorMessage } from "../lib/user-error-message.js"; import { reviewCommandRequiresWrite, reviewShortcut, reviewShortcutHelp } from "../lib/review-shortcuts.js"; import type { ReviewViewingProps, ReviewViewingController, ReviewPosition, ReviewNavigation } from "./review-viewing"; @@ -79,12 +79,10 @@ import { } from "../lib/annotation-shortcuts.js"; import { applyConflictListChoice, conflictListFocusStep } from "../lib/slice-edit-conflict-list.js"; import { - assertActionsCoveredByExactlyOneSlice, resolveSliceEditConflicts, restoreSliceEditWorkspace, scanSliceEditConflicts, snapshotSliceEditWorkspace, - validateActionStatuses, } from "../lib/slice-edit-conflict.js"; import type { SliceEditAutoFollow, SliceEditChoice, SliceEditConflictEntry } from "../lib/slice-edit-conflict-types"; import { @@ -236,7 +234,7 @@ type Props = ReviewViewingProps & { editor?: SliceEditor | null; revealAnnotation?: { id: string; start: number }; } | null; - onSplitSlice?: (sliceIndex: number, at: number) => string | undefined; + onSplitSlice?: (sliceIndex: number, at: number) => string | undefined | Promise; onDeleteSlice?: (sliceIndex: number) => void; onMergeSliceBoundary?: (sliceId: string, direction: "shrink" | "expand") => void; /** @@ -269,8 +267,11 @@ type Props = ReviewViewingProps & { beforeSlices?: SliceSegment[]; afterSlices?: SliceSegment[]; } | null; - onSliceEditQuickConflictApply?: (decisions: Partial>) => string | undefined | void; + onSliceEditQuickConflictApply?: ( + decisions: Partial>, + ) => string | undefined | void | Promise; onSliceEditQuickConflictCancel?: () => void; + sliceEditAppliedRevision?: number; onConfirmSlices?: () => void; canConfirmSlices?: boolean; onConfirmAnnotations?: ( @@ -405,6 +406,7 @@ export function CaptureAnnotationWorkbench({ sliceEditQuickConflict = null, onSliceEditQuickConflictApply, onSliceEditQuickConflictCancel, + sliceEditAppliedRevision, onAnnotationEdit, onAnnotationDraftEdit, onHistoryCommand, @@ -1807,13 +1809,7 @@ export function CaptureAnnotationWorkbench({ // Enter 落库前自检(03 引擎的 Go 守卫前端镜像):状态白名单 + 「动作完整落在 // 恰好一个切片」(ADR 0007 / T3 钉死)。逐片无缝铺满校验刻意不跑——标注相草稿 // 允许留空缺口(词汇表「保存进度」),那是提交守卫而非结构改动守卫。 - const preview = previewSliceEditDispositions(panel.snapshot.slices, resolution.slices, resolution.actions, { - resetRestoredActions: true, - }); - const issues = [ - ...validateActionStatuses(preview.actions), - ...assertActionsCoveredByExactlyOneSlice(preview.actions, preview.slices), - ]; + const issues = checkSliceEditResolution(resolution, { baseSlices: panel.snapshot.slices }); if (issues.length) { setError(`切片改动未通过提交自检:${issues[0].message};尚未应用,请调整选择或按 Esc 回退。`); return; @@ -1913,24 +1909,49 @@ export function CaptureAnnotationWorkbench({ // 票 05:清单 Enter/Esc 按来源分发——quick(拖动释放/悬停+)交回页面(落定产 // 物/回退快照;成功时返回焦点切片 id 供选中),panel 维持 04 面板自己的流 // (commitSliceEditPanel / cancelSliceEditPanel)。键盘分发与清单按钮共用本组助手。 - const applySliceEditConflictList = (decisions: Partial>) => { + // A quick edit can succeed without a conflict list. Its frozen drafts are + // already in the authoritative workspace; never replay their old geometry. + useEffect(() => { + if (!sliceEditAppliedRevision) return; + setEditingAnnotation(null); + setParkedEditors({}); + setEndSelection(null); + onDraftsChange?.([]); + }, [sliceEditAppliedRevision]); + const quickConflictApplyingRef = useRef(false); + const [quickConflictApplying, setQuickConflictApplying] = useState(false); + const applySliceEditConflictList = async (decisions: Partial>) => { if (!sliceEditConflictList) return; if (sliceEditConflictList.source === "quick") { - const applied = onSliceEditQuickConflictApply?.(decisions); - if (typeof applied === "string" && applied) setSelectedSliceId(applied); + if (saving || readOnly || quickConflictApplyingRef.current) return; + quickConflictApplyingRef.current = true; + setQuickConflictApplying(true); + setError(""); + try { + const applied = await onSliceEditQuickConflictApply?.(decisions); + if (typeof applied === "string") { + if (applied) setSelectedSliceId(applied); + focusWorkbench(); + } + } catch (cause) { + setError(userErrorMessage(cause) || "切片改动保存失败,选择和预览已保留,请核对后重试。"); + } finally { + quickConflictApplyingRef.current = false; + setQuickConflictApplying(false); + } return; } commitSliceEditPanel(decisions); }; const cancelSliceEditConflictList = () => { - if (!sliceEditConflictList) return; + if (!sliceEditConflictList || saving || quickConflictApplyingRef.current) return; if (sliceEditConflictList.source === "quick") { onSliceEditQuickConflictCancel?.(); return; } cancelSliceEditPanel(); }; - const insertSlice = (index: number, time: number) => { + const insertSlice = async (index: number, time: number) => { // R2-Q7:a 全局解锁:悬停"+"新增分界在 annotate 相同样可用。 if (readOnly || isQualityReview || saving || (phase !== "slice" && phase !== "annotate")) return; // R2-Q5/R2-Q3:面板或冲突清单打开期间悬停"+"锁定(结构改动统一走单一处置入口)。 @@ -1949,7 +1970,7 @@ export function CaptureAnnotationWorkbench({ setError(""); pausePlayback(); setReviewPlayback(false); - const nextSelectedSliceId = onSplitSlice?.(index, point); + const nextSelectedSliceId = await onSplitSlice?.(index, point); if (nextSelectedSliceId) setSelectedSliceId(nextSelectedSliceId); setSplitPreview(null); seek(point); @@ -3111,6 +3132,10 @@ export function CaptureAnnotationWorkbench({ // Enter 按默认应用、Esc 取消整个待应用改动集;播放族 "pass" 放行给全局表 // (视频是参照物),J/K "locked" 给提示,其余键整体吞掉(面板键不生效)。 if (sliceEditConflictList && phase === "annotate") { + if (saving || quickConflictApplyingRef.current) { + event.preventDefault(); + return; + } const command = sliceEditConflictListShortcut( { key: event.key, @@ -6605,6 +6630,8 @@ export function CaptureAnnotationWorkbench({ {sliceEditConflictList && phase === "annotate" ? ( { */ export function SliceEditConflictList({ entries, + saving = false, + error = "", decisions, focus, autoFollows, @@ -49,6 +51,8 @@ export function SliceEditConflictList({ afterSlices = [], }: { entries: SliceEditConflictEntry[]; + saving?: boolean; + error?: string; decisions: Partial>; focus: number; autoFollows?: SliceEditAutoFollow[]; @@ -79,7 +83,9 @@ export function SliceEditConflictList({ style={style} >
- 切片调整 · {entries.length} 个动作受影响 + + {entries.length ? `切片调整 · ${entries.length} 个动作受影响` : "保存切片改动"} + 未决 {undecided} · Enter 应用(未决按默认) · Esc 取消
@@ -102,6 +108,11 @@ export function SliceEditConflictList({ {autoFollowHint} · 无效动作贴边不成条目,按区间语义随新边界自动伸缩
) : null} + {error ? ( +
+ {error} +
+ ) : null}
{entries.map((entry, index) => { const active = index === activeIndex; @@ -139,6 +150,7 @@ export function SliceEditConflictList({
diff --git a/src/lib/slice-edit-drag-quick-path.js b/src/lib/slice-edit-drag-quick-path.js index 654cb713..899c6560 100644 --- a/src/lib/slice-edit-drag-quick-path.js +++ b/src/lib/slice-edit-drag-quick-path.js @@ -1,3 +1,4 @@ +import { previewSliceEditDispositions } from "./slice-edit-dispositions.js"; // 拖动快路径释放决策(票 05,spec §2 R2-Q3「拖动确认时机」):拖动边界手柄松手(或 // 悬停+拆分等结构快捷入口落点)时,把「基线结构 → 预览结构」交给 03 引擎——clean // 则直接给出可落库产物(快路径保持快:不进面板、不按 Enter;贴边无效动作的自动跟随 @@ -32,11 +33,16 @@ export function planSliceEditDragRelease({ baseSlices, pendingSlices, actions }) * 「动作完整落在恰好一个切片」(ADR 0007 / T3 钉死)。逐片无缝铺满刻意不进自检—— * 标注相草稿允许语义留空,铺满是提交守卫而非结构改动守卫。 * @param {{ actions: Array, slices: Array }} resolution resolveSliceEditConflicts 产物 + * @param {{baseSlices?: Array}} options 基线切片;检查归档后的活动动作,但原始状态仍须合法。 + * 服务端接收原始分割动作,在原子应用中维护归档;此处预览不代替服务端校验。 * @returns {Array} issues;空数组 = 通过 */ -export function checkSliceEditResolution(resolution) { +export function checkSliceEditResolution(resolution, { baseSlices } = {}) { + const preview = baseSlices + ? previewSliceEditDispositions(baseSlices, resolution.slices, resolution.actions, { resetRestoredActions: true }) + : resolution; return [ ...validateActionStatuses(resolution.actions), - ...assertActionsCoveredByExactlyOneSlice(resolution.actions, resolution.slices), + ...assertActionsCoveredByExactlyOneSlice(preview.actions, preview.slices), ]; } diff --git a/src/pages/AnnotationOperations.tsx b/src/pages/AnnotationOperations.tsx index a462f3b3..7a7ba530 100644 --- a/src/pages/AnnotationOperations.tsx +++ b/src/pages/AnnotationOperations.tsx @@ -152,6 +152,7 @@ import { autosaveSegmentsWithDrafts, sliceEditSessionFlushEdge, workbenchDraftsFingerprint, + sliceEditActionsWithDrafts, } from "../lib/annotation-autosave.js"; import { useAnnotationAutosave } from "../hooks/useAnnotationAutosave"; import { getActionErrorMessage, recoverableGatewayStatus } from "../lib/action-errors.js"; @@ -229,10 +230,14 @@ type SliceEditSnapshot = { // 落定时整段手势 + 处置合并为一条可撤销历史(与旧处置卡同款承诺)。 // 票 06 起 slice 相提交式挪动(←/→ 与 Shift+←/→)同走此管线(单一处置入口)。 type SliceEditQuickConflict = { + taskId: string; entries: SliceEditConflictEntry[]; autoFollows?: SliceEditAutoFollow[]; baseSlices: SliceSegment[]; baseSegments: AnnotationSegment[]; + actions: AnnotationSegment[]; + draftsFingerprint: string; + hasUnfinishedDrafts: boolean; pendingSlices: SliceSegment[]; operation: Omit; anchorTime: number; @@ -814,6 +819,8 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const sliceDragEditRef = useRef<{ before: SliceEditSnapshot; after?: SliceEditSnapshot } | null>(null); // 票 05:结构快捷入口的冲突清单待决集(03 引擎条目);非空即冻结其它边界改动。 const [sliceEditQuickConflict, setSliceEditQuickConflict] = useState(null); + const sliceEditQuickApplyingRef = useRef(null); + const [sliceEditAppliedRevision, setSliceEditAppliedRevision] = useState(0); const [historyReveal, setHistoryReveal] = useState<{ sliceId: string; time: number; @@ -2895,7 +2902,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: combinedSubmissionLocked || annotationMutationScopeRef.current.busy() || sliceEditSessionOpen || - Boolean(sliceEditQuickConflict), + Boolean(sliceEditQuickConflict) || + Boolean(sliceDragEditRef.current) || + Boolean(sliceEditQuickApplyingRef.current), buildSaveContext: () => { const item = detailRef.current?.humanItem; if (!item || !detailRef.current?.task) return null; @@ -3213,6 +3222,17 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: location: { sliceId, time: time ?? sliceSegments.find((slice) => slice.id === sliceId)?.start ?? 0 }, }); + const quickSliceEditActionSnapshot = (baseSegments: AnnotationSegment[]) => { + const prepared = sliceEditActionsWithDrafts(baseSegments, workbenchDrafts); + return { + taskId: detail?.task.id || "", + baseSegments, + actions: prepared.actions as AnnotationSegment[], + draftsFingerprint: workbenchDraftsFingerprint(workbenchDrafts), + hasUnfinishedDrafts: prepared.unresolved.length > 0, + }; + }; + const beginSliceBoundaryEdit = (sliceId: string) => { if (!annotationAuthoringRef.current) return; // 冲突清单开着时不接受新的边界拖动:一次只决一件事(待决快照不被打穿)。 @@ -3224,7 +3244,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: // 状态白名单 +「动作完整落在恰好一个切片」(与 04 面板 Enter 同一管线);有冲突弹 // 04 同款冲突清单(同一键盘模型),Enter 落定、Esc 整体回退本次拖动(R1-Q4 不支持 // 部分应用)。旧三选卡不再承接拖动释放(06 票删除旧卡与非拖动调用方)。 - const finishSliceBoundaryEdit = () => { + const finishSliceBoundaryEdit = async () => { const edit = sliceDragEditRef.current; sliceDragEditRef.current = null; if (!annotationAuthoringRef.current) return; @@ -3238,7 +3258,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const prompt: SliceEditQuickConflict = { entries: [], baseSlices: edit.before.slices, - baseSegments: edit.before.segments, + ...quickSliceEditActionSnapshot(edit.before.segments), pendingSlices: sliceSegments, operation: { type: "adjust", @@ -3252,7 +3272,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const plan = planSliceEditDragRelease({ baseSlices: prompt.baseSlices, pendingSlices: prompt.pendingSlices, - actions: prompt.baseSegments, + actions: prompt.actions, }); if (plan.kind === "conflict") { sliceDragEditRef.current = edit; // 清单落定时继续并入这条拖动编辑的历史(Esc 回退基线同源) @@ -3263,13 +3283,13 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: }); return; } - // 无冲突:立即生效(快路径保持快)。暂不可落库(保存锁等)或自检失败时按旧快 - // 路径收尾——几何停在释放位、手势照常入历史,绝不留半途结构;用户可重拖或撤销。 - sliceDragEditRef.current = edit; // applySliceChange 以拖动前快照为历史基线(一条可撤销历史) - const outcome = applySliceEditQuickResolution(prompt, plan.resolution); + // 无冲突也等待服务端原子保存;失败保留清单供重试或取消。 + sliceDragEditRef.current = edit; // 持久化历史以拖动前快照为基线 + const outcome = await applySliceEditQuickResolution(prompt, plan.resolution); + if (detailRef.current?.task.id !== prompt.taskId) return; sliceDragEditRef.current = null; if (outcome === "applied") return; - recordSliceDragEdit(edit); + setSliceEditQuickConflict(prompt); return; } recordSliceDragEdit(edit); @@ -3336,22 +3356,27 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: }; // —— 票 05(spec §2 R2-Q3):结构快捷入口的冲突清单落定/回退 —— - // 清单 Enter 与无冲突快路径共用的落库原语:解析产物过 Go 守卫前端镜像自检 → - // applySliceChange 原子落库(拖动来源以 sliceDragEditRef 的拖动前快照为历史基线, - // 整段手势 + 处置合并为一条可撤销历史)。返回 "applied" = 已收尾(含无变化早退, - // 几何已在预览位、手势照常入历史);"blocked" = 暂不可落库或期间外部改动——调用 - // 方保留清单供重试或 Esc,不写任何东西。 - const applySliceEditQuickResolution = ( + // 清单与无冲突快捷操作共享服务端原子应用:归档预览自检后发送原始动作, + // 等待权威工作区确认。失败保留清单与选择;拖动前快照作为一条持久化撤销历史。 + const applySliceEditQuickResolution = async ( prompt: SliceEditQuickConflict, resolution: { slices: SliceSegment[]; actions: AnnotationSegment[] }, ) => { - if (!annotationAuthoringRef.current) return "blocked"; - if (segments !== prompt.baseSegments) { - // 清单期间工作区被其它编辑改动:宁可拦下也不覆盖(旧处置卡同款承诺)。 + if ( + !annotationAuthoringRef.current || + sliceEditQuickApplyingRef.current || + detailRef.current?.task.id !== prompt.taskId + ) + return "blocked"; + if (segments !== prompt.baseSegments || prompt.draftsFingerprint !== workbenchDraftsFingerprint(workbenchDrafts)) { setError("处置期间工作区发生了其它修改,请按 Esc 关闭清单后重试。"); return "blocked"; } - const issues = checkSliceEditResolution(resolution); + if (prompt.hasUnfinishedDrafts) { + setError("仍有描述尚未确认结束点,请按 Esc 返回完成区间后再调整切片;草稿会保留。"); + return "blocked"; + } + const issues = checkSliceEditResolution(resolution, { baseSlices: prompt.baseSlices }); if (issues.length) { setError(`切片改动未通过提交自检:${issues[0].message};请按 Esc 取消本次改动。`); return "blocked"; @@ -3360,13 +3385,51 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: setError("当前状态暂不能应用切片改动,请稍后重试,或按 Esc 取消。"); return "blocked"; } - const changed = applySliceChange( - resolution.slices as SliceSegment[], - prompt.operation, - resolution.actions as AnnotationSegment[], - ); - if (prompt.dragEdit) recordSliceDragEdit(prompt.dragEdit); - return "applied"; // changed=false 为「无变化」早退:以当前状态收尾这条拖动历史 + const before = prompt.dragEdit?.before ?? { + ...sliceEditSnapshot(prompt.focusSliceId, prompt.anchorTime), + slices: prompt.baseSlices, + segments: prompt.baseSegments, + }; + let nextActions = resolution.actions; + // Preserve the existing cancel-cut rule: merged regions return to pending. + if (prompt.operation.type === "merge" || prompt.operation.type === "delete") { + const changed = resolution.slices.filter( + (slice) => + slice.sourceIds?.length && + prompt.baseSlices.some((old) => old.id === slice.id && (old.start !== slice.start || old.end !== slice.end)), + ); + nextActions = nextActions.filter( + (action) => !changed.some((slice) => action.start < slice.end && action.end > slice.start), + ); + } + if ( + JSON.stringify(resolution.slices) === JSON.stringify(prompt.baseSlices) && + JSON.stringify(nextActions) === JSON.stringify(prompt.baseSegments) + ) { + if (prompt.dragEdit) setSliceOperations(prompt.dragEdit.before.operations); + return "applied"; + } + const operations = [...before.operations, { ...prompt.operation, before: before.slices, after: resolution.slices }]; + const taskId = detail?.task.id; + sliceEditQuickApplyingRef.current = prompt; + try { + // Send raw split pieces, not the client archive preview. The server owns + // canonical archives, CAS, audit and recovery for every entry point. + const workspace = await persistSliceEditApplication( + resolution.slices, + nextActions, + prompt.focusSliceId, + true, + operations, + before, + ); + if (!workspace || detailRef.current?.task.id !== taskId) return "blocked"; + setWorkbenchDrafts([]); + setSliceEditAppliedRevision((revision) => revision + 1); + return "applied"; + } finally { + if (sliceEditQuickApplyingRef.current === prompt) sliceEditQuickApplyingRef.current = null; + } }; // 票 05:传给工作台的清单条目视图。useMemo 固定引用——工作台的播种 effect 依赖 @@ -3388,7 +3451,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: // 冲突清单 Enter(R2-Q2):未决条目按默认落定(03 引擎 resolver 语义),产物过自检 // 后原子落库;拖动来源整段手势 + 处置合并为一条可撤销历史。失败保留清单(重试/Esc)。 // 成功时返回焦点切片 id 供工作台选中(拆分来源为新片;拖动来源为被拖片)。 - const handleSliceEditQuickConflictApply = (decisions: Partial>) => { + const handleSliceEditQuickConflictApply = async (decisions: Partial>) => { if (!annotationAuthoringRef.current) return; const prompt = sliceEditQuickConflict; if (!prompt) return; @@ -3396,14 +3459,14 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const resolveInput = { baseSlices: prompt.baseSlices, pendingSlices: prompt.pendingSlices, - actions: prompt.baseSegments, + actions: prompt.actions, choices: decisions, }; const resolution = resolveSliceEditConflicts(resolveInput) as { slices: SliceSegment[]; actions: AnnotationSegment[]; }; - if (applySliceEditQuickResolution(prompt, resolution) !== "applied") return; + if ((await applySliceEditQuickResolution(prompt, resolution)) !== "applied") return; sliceDragEditRef.current = null; setSliceEditQuickConflict(null); setError(""); @@ -3413,6 +3476,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: // 冲突清单 Esc(R2-Q3/R1-Q4):拖动来源整段回退到拖动前快照(边界回原位、不留 // 历史);拆分等未落库来源直接丢弃(改动从未发生)。 const handleSliceEditQuickConflictCancel = () => { + if (sliceEditQuickApplyingRef.current || saving) return; const prompt = sliceEditQuickConflict; if (!prompt) return; setSliceEditQuickConflict(null); @@ -3439,7 +3503,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: } }; - const adjustSlice = (id: string, field: "start" | "end", value: number) => { + const adjustSlice = async (id: string, field: "start" | "end", value: number) => { if (!annotationAuthoringRef.current) return; // 冲突清单开着时冻结其它边界改动,防止待决快照被打穿。 if (sliceEditQuickConflict) return; @@ -3481,7 +3545,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const prompt: SliceEditQuickConflict = { entries: [], baseSlices: sliceSegments, - baseSegments: segments, + ...quickSliceEditActionSnapshot(segments), pendingSlices: next, operation: { type: "adjust", segmentIds: affected, at: value }, anchorTime: value, @@ -3491,7 +3555,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const plan = planSliceEditDragRelease({ baseSlices: prompt.baseSlices, pendingSlices: prompt.pendingSlices, - actions: prompt.baseSegments, + actions: prompt.actions, }); if (plan.kind === "conflict") { setSliceEditQuickConflict({ @@ -3501,10 +3565,14 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: }); return; } - applySliceEditQuickResolution(prompt, plan.resolution); + if ( + (await applySliceEditQuickResolution(prompt, plan.resolution)) !== "applied" && + detailRef.current?.task.id === prompt.taskId + ) + setSliceEditQuickConflict(prompt); }; - const splitSlice = (index: number, requestedAt = annotationPlayheadRef.current) => { + const splitSlice = async (index: number, requestedAt = annotationPlayheadRef.current) => { if (!annotationAuthoringRef.current) return; const current = sliceSegments[index]; if (!current) return; @@ -3533,7 +3601,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const prompt: SliceEditQuickConflict = { entries: [], baseSlices: sliceSegments, - baseSegments: segments, + ...quickSliceEditActionSnapshot(segments), pendingSlices: split.slices, operation: { type: "split", segmentIds: [current.id], at }, anchorTime: at, @@ -3543,7 +3611,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const plan = planSliceEditDragRelease({ baseSlices: prompt.baseSlices, pendingSlices: prompt.pendingSlices, - actions: prompt.baseSegments, + actions: prompt.actions, }); if (plan.kind === "conflict") { setSliceEditQuickConflict({ @@ -3553,7 +3621,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: }); return; // 未应用:不选中新片(Enter 落定后经回调返回焦点片) } - return applySliceEditQuickResolution(prompt, plan.resolution) === "applied" ? split.selectedSliceId : undefined; + if ((await applySliceEditQuickResolution(prompt, plan.resolution)) === "applied") return split.selectedSliceId; + if (detailRef.current?.task.id === prompt.taskId) setSliceEditQuickConflict(prompt); + return undefined; }; const mergeSlice = (index: number) => { @@ -3565,7 +3635,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: if (merged) applySliceChange(merged.slices, { type: "merge", segmentIds: [current.id, nextItem.id] }); }; - const deleteSlice = (index: number) => { + const deleteSlice = async (index: number) => { if (!annotationAuthoringRef.current) return; const target = sliceSegments[index]; const merged = target ? cancelSlicePartition(sliceSegments, index) : null; @@ -3576,7 +3646,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const prompt: SliceEditQuickConflict = { entries: [], baseSlices: sliceSegments, - baseSegments: segments, + ...quickSliceEditActionSnapshot(segments), pendingSlices: merged.slices, operation: { type: "delete", segmentIds: [target.id] }, anchorTime: target.start, @@ -3586,7 +3656,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const plan = planSliceEditDragRelease({ baseSlices: prompt.baseSlices, pendingSlices: prompt.pendingSlices, - actions: prompt.baseSegments, + actions: prompt.actions, }); if (plan.kind === "conflict") { setSliceEditQuickConflict({ @@ -3596,7 +3666,11 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: }); return; } - applySliceEditQuickResolution(prompt, plan.resolution); + if ( + (await applySliceEditQuickResolution(prompt, plan.resolution)) !== "applied" && + detailRef.current?.task.id === prompt.taskId + ) + setSliceEditQuickConflict(prompt); }; const updateSliceName = (id: string, name: string) => { @@ -3727,11 +3801,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: focusSliceId: string, recordHistory = true, restoredOperations = sliceOperations, + historyBefore?: SliceEditSnapshot, ) => { if (!annotationAuthoringRef.current) return null; if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return null; const taskId = detail.task.id; - const before = sliceEditSnapshot(focusSliceId); + const before = historyBefore ?? sliceEditSnapshot(focusSliceId); const token = await beginAnnotationMutation(taskId); if (!token) return null; const applicationId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`; @@ -3742,7 +3817,7 @@ 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(before.slices, nextSlices, { resetRestoredActions: recordHistory, restoredActions: nextSegments, }), @@ -7642,6 +7717,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: sliceEditQuickConflict={sliceEditQuickConflictView} onSliceEditQuickConflictApply={handleSliceEditQuickConflictApply} onSliceEditQuickConflictCancel={handleSliceEditQuickConflictCancel} + sliceEditAppliedRevision={sliceEditAppliedRevision} onSliceEditSessionChange={setSliceEditSessionOpen} onApplySliceEdit={async (nextSlices, nextSegments, focusSliceId) => Boolean(await persistSliceEditApplication(nextSlices, nextSegments, focusSliceId)) diff --git a/tests/browser/rework-boundary-replica.mjs b/tests/browser/rework-boundary-replica.mjs new file mode 100644 index 00000000..de8b596c --- /dev/null +++ b/tests/browser/rework-boundary-replica.mjs @@ -0,0 +1,211 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { chromium } from "playwright"; +import { createServer } from "vite"; +const api = process.env.REWORK_BOUNDARY_API; +assert.match(api, /^http:\/\/127\.0\.0\.1:\d+$/); +const out = path.resolve("local-data/test-results/rework-boundary"); +fs.mkdirSync(out, { recursive: true }); +const server = await createServer({ + server: { host: "127.0.0.1", port: 5202, strictPort: true, proxy: { "/api": { target: api, changeOrigin: true } } }, +}); +let browser, + page, + fault = "", + releaseSave; +const report = { cases: [], pageErrors: [], writes: [] }; +const taskURL = + "http://127.0.0.1:5202/plugins/annotation-qa/workflows/all/work?projectId=draft-project&taskId=draft-task"; +const read = async () => (await (await fetch(api + "/__boundary/state")).json()).subject.payload.annotationWorkspace; +const waitFor = async (check) => { + for (let n = 0; n < 80; n++) { + if (await check()) return; + await new Promise((r) => setTimeout(r, 50)); + } + assert.fail("server state did not settle"); +}; +try { + await server.listen(); + browser = await chromium.launch({ + executablePath: process.env.BROWSER_EXECUTABLE || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + headless: true, + args: ["--no-proxy-server"], + }); + const ctx = await browser.newContext({ viewport: { width: 1600, height: 1100 }, serviceWorkers: "block" }); + page = await ctx.newPage(); + page.setDefaultTimeout(12000); + page.on("pageerror", (e) => report.pageErrors.push(e.message)); + page.on("request", (r) => { + if (!["GET", "HEAD"].includes(r.method())) + report.writes.push({ method: r.method(), path: new URL(r.url()).pathname }); + }); + await page.route("**/*", async (route) => { + const req = route.request(), + u = new URL(req.url()); + if (u.hostname !== "127.0.0.1") return route.abort(); + if (u.pathname.includes("/worker-api/")) return route.fulfill({ json: { status: "ok" } }); + if (req.method() === "POST" && u.pathname.endsWith("/slice-edit-applications")) { + const mode = fault; + fault = ""; + if (mode === "reject") return route.fulfill({ status: 503, json: { error: "合成保存失败,请重试" } }); + if (mode === "delay") + await new Promise((resolve) => { + releaseSave = resolve; + }); + if (mode === "lost") { + await route.fetch(); + return route.abort("failed"); + } + } + return route.continue(); + }); + const load = async () => { + await page.goto(taskURL, { waitUntil: "domcontentloaded" }); + await page.getByRole("button", { name: "继续工作", exact: true }).click(); + await page + .getByTestId("capture-annotation-workbench") + .getByRole("button", { name: "拖动切片边界", exact: true }) + .first() + .waitFor(); + }; + const reset = async (side = "left", status = "described", round = 1) => { + assert.equal((await fetch(`${api}/__boundary/reset?side=${side}&status=${status}&round=${round}`)).status, 200); + await load(); + }; + const list = () => page.getByTestId("slice-edit-conflict-list"); + const drag = async (side = "left") => { + const handle = page + .getByTestId("capture-annotation-workbench") + .getByRole("button", { name: "拖动切片边界", exact: true }) + .first(); + const box = await handle.boundingBox(); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + box.width / 2 + (side === "left" ? 100 : -100), box.y + box.height / 2, { steps: 8 }); + await page.mouse.up(); + await list().waitFor(); + }; + const confirm = async (keyboard = false) => { + if (keyboard) { + await list().click({ position: { x: 15, y: 15 } }); + await page.keyboard.press("Enter"); + } else await list().getByTestId("slice-edit-conflict-apply").click(); + await list().waitFor({ state: "hidden" }); + }; + const assertSaved = async (side, status) => { + const w = await read(), + k = w.sliceSegments.find((s) => s.id === "k"), + d = w.sliceSegments.find((s) => s.id === "d"); + assert.equal(w.segments.length, 1); + assert.equal(w.segments[0].status, status); + assert.equal(w.segments[0].description || "", status === "described" ? "合成有效动作" : ""); + assert.ok(!w.segments[0].isInvalid); + assert.equal(d.discardedAnnotations.length, 1); + assert.equal(d.discardedAnnotations[0].status, status); + if (side === "left") { + assert.equal(k.start, 6); + assert.equal(d.end, 6); + assert.equal(w.segments[0].start, 6); + } else { + assert.equal(k.end, 4); + assert.equal(d.start, 4); + assert.equal(w.segments[0].end, 4); + } + }; + for (const side of ["left", "right"]) + for (const status of ["pending", "described"]) { + await reset(side, status, status === "pending" ? 0 : 1); + await drag(side); + await confirm(status === "described"); + await assertSaved(side, status); + await load(); + await assertSaved(side, status); + report.cases.push( + `${side} ${status}: ${status === "described" ? "Enter/rework" : "button/first-pass"}, archive and reload`, + ); + } + await reset("left", "invalid", 0); + const cleanHandle = page + .getByTestId("capture-annotation-workbench") + .getByRole("button", { name: "拖动切片边界", exact: true }) + .first(); + const cleanBox = await cleanHandle.boundingBox(); + await page.mouse.move(cleanBox.x + cleanBox.width / 2, cleanBox.y + cleanBox.height / 2); + await page.mouse.down(); + await page.mouse.move(cleanBox.x + cleanBox.width / 2 - 100, cleanBox.y + cleanBox.height / 2, { steps: 8 }); + await page.mouse.up(); + await waitFor(async () => (await read()).sliceSegments.find((s) => s.id === "d").end === 4); + assert.equal(await list().count(), 0); + report.cases.push("conflict-free drag persists without an extra confirmation"); + await reset(); + await drag(); + fault = "reject"; + await list().getByTestId("slice-edit-conflict-apply").click(); + await list().getByRole("alert").filter({ hasText: "合成保存失败" }).waitFor(); + assert.equal((await read()).sliceSegments.find((s) => s.id === "d").end, 5); + await confirm(true); + await assertSaved("left", "described"); + report.cases.push("failed write visible, choices retained, Enter retry"); + await reset(); + await drag(); + fault = "delay"; + const count = () => report.writes.filter((r) => r.path.endsWith("/slice-edit-applications")).length; + const before = count(); + await list().getByTestId("slice-edit-conflict-apply").click(); + await page.getByRole("button", { name: "正在保存…", exact: true }).waitFor(); + assert.equal(await list().getByRole("button", { name: "Esc 取消", exact: true }).isDisabled(), true); + await page.keyboard.press("Enter"); + await page.keyboard.press("Escape"); + assert.equal(count(), before + 1); + assert.equal(await list().isVisible(), true); + await waitFor(() => Boolean(releaseSave)); + releaseSave(); + releaseSave = null; + await list().waitFor({ state: "hidden" }); + await assertSaved("left", "described"); + report.cases.push("pending save blocks repeat Enter and cancellation"); + await reset(); + await drag(); + fault = "lost"; + await confirm(true); + await assertSaved("left", "described"); + report.cases.push("lost response reconciled against authoritative API"); + await page.getByRole("button", { name: "撤销", exact: true }).click(); + await waitFor(async () => (await read()).sliceSegments.find((s) => s.id === "d").end === 5); + let restored = await read(); + assert.equal(restored.segments.length, 1); + assert.equal(restored.segments[0].start, 5); + assert.equal(restored.segments[0].description, "合成有效动作"); + // Existing history intentionally throttles accepted commands to one per second. + await page.waitForTimeout(1100); + await page.getByRole("button", { name: "重做", exact: true }).click(); + await waitFor(async () => (await read()).sliceSegments.find((s) => s.id === "d").end === 6); + await assertSaved("left", "described"); + report.cases.push("persisted undo/redo restores original action and archive"); + await reset(); + await drag(); + await page.keyboard.press("Escape"); + await list().waitFor({ state: "hidden" }); + assert.equal((await read()).sliceSegments.find((s) => s.id === "d").end, 5); + report.cases.push("Escape cancels preview without server write"); + assert.deepEqual(report.pageErrors, []); + console.log(JSON.stringify(report)); +} catch (e) { + if (page) { + await page.screenshot({ path: path.join(out, "failure.png"), fullPage: true }).catch(() => {}); + fs.writeFileSync( + path.join(out, "failure-body.txt"), + await page + .locator("body") + .innerText() + .catch(() => ""), + ); + } + throw e; +} finally { + releaseSave?.(); + fs.writeFileSync(path.join(out, "report.json"), JSON.stringify(report, null, 2)); + await browser?.close(); + await server.close(); +} diff --git a/tests/frontend/capture-annotation-workbench.test.mjs b/tests/frontend/capture-annotation-workbench.test.mjs index ed1c8925..8b14b915 100644 --- a/tests/frontend/capture-annotation-workbench.test.mjs +++ b/tests/frontend/capture-annotation-workbench.test.mjs @@ -173,7 +173,7 @@ test("slice reconfig panel: E opens the preview panel with Enter/Esc, locks bypa workbench.indexOf("const applySliceEditPanel ="), ); assert.match(commit, /resolveSliceEditConflicts\(/); - assert.match(commit, /assertActionsCoveredByExactlyOneSlice/); + assert.match(commit, /checkSliceEditResolution\(resolution, \{ baseSlices: panel\.snapshot\.slices \}\)/); assert.match(commit, /onApplySliceEdit\?\.\(/, "应用经页面侧原子落库回调"); // 面板与清单组件、常显提示、红块高亮、播放族放行(seam ③ 表 + 分发)。 assert.match(sliceEditPanel, /data-testid="slice-edit-panel-hint"/); @@ -236,7 +236,7 @@ test("drag quick path: releases route through the 03 engine into the 04 conflict ); assert.ok(quickHelpers.indexOf("const applySliceEditQuickResolution =") >= 0, "落库原语存在"); assert.match(quickHelpers, /checkSliceEditResolution\(/, "落库前 Go 守卫前端镜像自检(T3)"); - assert.match(quickHelpers, /applySliceChange\(/, "原子落库(一条可撤销历史)"); + assert.match(quickHelpers, /await persistSliceEditApplication\(/, "服务端原子归档及一条可撤销历史"); assert.match(quickHelpers, /segments !== prompt\.baseSegments/, "清单期间外部改动宁可拦下"); assert.match(quickHelpers, /resolveSliceEditConflicts\(/, "清单 Enter 未决按默认落定"); const cancel = quickHelpers.slice( diff --git a/tests/frontend/rework-boundary.test.mjs b/tests/frontend/rework-boundary.test.mjs new file mode 100644 index 00000000..1f3b6cff --- /dev/null +++ b/tests/frontend/rework-boundary.test.mjs @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { resolveSliceEditConflicts } from "../../src/lib/slice-edit-conflict.js"; +import { checkSliceEditResolution } from "../../src/lib/slice-edit-drag-quick-path.js"; +import { previewSliceEditDispositions } from "../../src/lib/slice-edit-dispositions.js"; + +for (const side of ["left", "right"]) + for (const status of ["pending", "described"]) { + test(`default truncate archives ${side} discard expansion and preserves ${status} kept classification`, () => { + const d = { id: "d", start: 0, end: 5, deliveryDisposition: "discard" }; + const k = { id: "k", start: 5, end: 10 }; + if (side === "right") { + d.start = 5; + d.end = 10; + k.start = 0; + k.end = 5; + } + const baseSlices = side === "left" ? [d, k] : [k, d]; + const boundary = side === "left" ? 6 : 4; + const pendingSlices = baseSlices.map((s, i) => ({ + ...s, + ...(i === 0 ? { end: boundary } : { start: boundary }), + })); + const dictionary = { + id: "frozen", + kind: "action", + version: 3, + name: "Original classification", + tags: ["frozen-tag"], + }; + const action = { + id: "a", + start: k.start, + end: k.end, + status, + description: status === "described" ? "Original description" : "", + labelId: "frozen-label", + label: "Original classification", + phrases: ["frozen-phrase"], + source: "manual", + dictionary, + }; + const result = resolveSliceEditConflicts({ baseSlices, pendingSlices, actions: [action], choices: {} }); + assert.deepEqual(checkSliceEditResolution(result, { baseSlices }), []); + const preview = previewSliceEditDispositions(baseSlices, result.slices, result.actions); + assert.equal(preview.actions.length, 1); + assert.equal(preview.actions[0].status, status); + assert.equal(preview.actions[0].description, action.description); + assert.equal(preview.actions[0].labelId, action.labelId); + assert.equal(preview.actions[0].label, action.label); + assert.deepEqual(preview.actions[0].phrases, action.phrases); + assert.equal(preview.actions[0].source, action.source); + assert.deepEqual(preview.actions[0].dictionary, dictionary); + assert.equal(preview.actions[0].isInvalid, undefined); + const archived = preview.slices.find((s) => s.id === "d").discardedAnnotations; + assert.equal(archived.length, 1); + assert.deepEqual(archived[0].dictionary, dictionary); + }); + } +test("invalid source states cannot be hidden in the discard preview", () => { + const baseSlices = [ + { id: "d", start: 0, end: 5, deliveryDisposition: "discard" }, + { id: "k", start: 5, end: 10 }, + ]; + const slices = [ + { ...baseSlices[0], end: 6 }, + { ...baseSlices[1], start: 6 }, + ]; + const issues = checkSliceEditResolution( + { slices, actions: [{ id: "a", start: 5, end: 6, status: "unsupported" }] }, + { baseSlices }, + ); + assert.ok(issues.some((i) => i.code === "action_annotation_incomplete")); +});