Merge pull request 'fix: 补齐切片撤销与舍弃交互修复及验证护栏' (#50) from codex/dev-verification-guardrails-20261016 into codex/oct15-feedback-pr-20261015
Some checks failed
web-ci / checks (push) Has been cancelled
web-ci / checks (pull_request) Has been cancelled

Reviewed-on: #50
This commit is contained in:
longtao.wu 2026-10-17 14:58:33 +08:00
commit 10b0dddd34
35 changed files with 1286 additions and 37 deletions

View File

@ -28,3 +28,15 @@ jobs:
- run: npm run format:check
- run: npm run test:go:gate
- run: npm run test:frontend:gate
if: always()
- run: npx playwright install --with-deps chromium
if: ${{ !cancelled() }}
- run: npm run test:browser:editing
if: ${{ !cancelled() }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: verification-logs
path: local-data/test-results/
if-no-files-found: warn
retention-days: 14

View File

@ -0,0 +1,29 @@
# Development verification guardrails
Status: resolved
Implement the four approved retrospective improvements: inspect the actual local
Vite→API source/version chain; install and verify existing Husky hooks; run the
real E/confirmation/undo/redo interaction in CI; retain raw baseline-gate logs
and structured results. Reuse existing lint, Go/frontend baseline gates,
Playwright, workbench fixture and annotation-history coordinator. No production
business behavior, customer data, release policy, deployment, push or PR change.
Do not clear the user's live page/history or stop existing servers to install
these tools. Exercise scripts with isolated subprocesses/fixtures. Browser
fixtures are synthetic; API legacy-undo contracts remain covered by Go CI.
Verification: npm run lint and build:web passed; frontend baseline gate passed
with 13 known failures against 14 baseline entries and no new failures. Three
new subprocess integration tests passed, including an actual blocked temporary
Git commit, log retention for known/new/crashed runners, and stale API detection.
CUA passed discard/reset/legacy-empty and E→truncate→Enter→undo/redo in normal
and focused modes. Actual 5176 status reports its checkout and API 3005 and
correctly refuses missing API metadata and dirty source. Hooks are active.
CI launcher/workflow is wired but has not run on the remote runner. Browser
persistence is synthetic; no new backend changes require a Go suite rerun.
Evidence: local-data/dev-guardrails-{lint,build,frontend-gate}.log and automatic
local-data/test-results/frontend-* logs in this worktree; browser screenshot in
main repo local-data/verification/dev-guardrails-20261016/editing-history.png.

View 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.

View File

@ -0,0 +1,63 @@
# Legacy editable task slice undo
Status: resolved
Baseline52dcb53a. User reports repeated slice_edit_restoration_unavailable;
real handler diagnostic reproduced normal edit200, undo409 with missing workflow,
and undo200 when only phase=annotate was added. Existing client keeps history on
failed write, so repeated undo retries the same rejected snapshot.
Honor ADR0001/0007: owned editable first-pass/rework tasks may undo persisted
structure edits in the same task/phase. Infer legacy readiness only from current
server-owned partition/generation evidence when sliceWorkflow is absent; do not
accept a client-invented phase or mutate old records to fabricate completion.
Explicit incomplete workflow, queued/running/failed jobs, pending submission,
review ownership/stage and version/frame/coverage/archive guards remain enforced.
No schema migration, bulk backfill, online writes, push, PR or deployment.
Verify real HTTP undo/redo/CAS and local snapshot replica, keep unrelated root
changes intact. Previous production deployment approval is consumed.
## Answer
The restoration endpoint required an explicit slice/annotate workflow phase;
the application endpoint already allowed pre-workflow records. Diagnostics and
permanent regression cases reproduce edit200 → undo409 on unchanged legacy
record; adding only phase changed undo to200 before the fix.
Restoration now retains explicit phase/initial-slice behavior, and for absent
workflow recognizes a valid server-owned slice partition backed by existing
materialization/revision evidence, or a complete non-full-video action partition
using existing confirmation readiness. Generation evidence also allows partially
edited and all-discarded tracks. Evidence is read before decoding the incoming
snapshot; the client cannot manufacture eligibility. No workflow marker is
written. Explicit incomplete workflow remains rejected. Queued/running/processing
and failed workflow/jobs are blocked consistently with the edit-application
endpoint. Existing ownership/stage, pending submission, CAS, frame/coverage,
status and canonical discard archive validation is retained.
Verification:
- New HTTP regression failed before change in all4 first-pass/rework + stored
workspace/draft cases; now edit → undo → redo → undo succeeds, stale versions
reject without writes, and a new handler reads the persisted result.
- Additional16 scenarios cover generated all-discarded/partial tracks, absent
server evidence, full-video proof requirement, incomplete/failed workflow,
queued/running/processing/failed jobs, pending submission, review and nonowner.
Rejected records are compared to their actual normalized stored preimage.
- Focused API legacy confirmation/restoration/application/discard regressions
pass. Lint and Go build./... pass; full Go baseline gate rerun has70 exact
known failures and no new failures. First run had one worker concurrent claim
case failure; isolated rerun passed, worker/store/domain sources are byte
unchanged from52dcb53a. Both gate logs retained, baseline not edited.
- Actual local snapshot27018 + API3005, separate synthetic rework task
legacy-undo-20261015-task: split8→9 at version2; undo9→8/version3;
redo8→9/version4; undo9→8/version5. Fresh GET retains8 slices, original action
content unchanged, workflow marker remains absent. Existing demo not modified.
- Logs in this worktree local-data/undo-phase-fix; local replica artifacts under
main-root local-data/verification/legacy-undo-20261015 (ignored). Original local
API/processor restored after gate; updated API3005 remains for trials.
Compatibility: no new request fields/schema or production migration. Rollback
reverts legacy undo eligibility while keeping saved snapshots readable; it does
not undo customer edits. No production write, push, PR update or deployment.

View File

@ -48,6 +48,8 @@ _Avoid_:历史操作日志(本列表不展示修改前的旧版本)
**舍弃切片**:标注员明确选择不交付、以舍弃原因定义的切片类型,与使用切片名称定义的普通切片互斥。切片及其证据仍参与审核,舍弃本身不移动相邻边界。
**取消舍弃**:显式恢复为普通切片时,将整片重置为一个覆盖首尾边界的待标注动作,不恢复旧描述或无效判断;旧内容保留为审计证据。撤销/重做按对应操作快照恢复,与此显式重置分开。正常可编辑切片始终保留动作分区,语义为空以待标注动作呈现,不能成为空轨道。
## 操作含义
**删除切片**:移除一个切片划分并将其范围并入相邻切片,保持源采集的处理覆盖。

View File

@ -5,6 +5,7 @@ FROM node:22-alpine AS web-build
WORKDIR /app
COPY package*.json ./
COPY scripts/check-git-hooks.mjs ./scripts/check-git-hooks.mjs
RUN npm ci
COPY index.html metadata.json package.json tsconfig.json vite.config.ts ./

View File

@ -176,3 +176,12 @@ kill $(lsof -nP -iTCP:5173 -sTCP:LISTEN -t) 2>/dev/null; npx vite --port 5173 --
2. 删除已合入集成分支的 ticket worktree 与对应本地分支(`git worktree remove` + `branch -d`)。
3. 探针/截图证据先拷回主仓 `local-data/**/probe-out*` 再删 worktree。
4. 发布中的记录(`python3 scripts/release.py status`)若非 completed,向用户交代状态后再收。
## 10. 本地验证护栏(2026-10-16)
- 安装依赖时 `prepare` 自动安装并检查 Husky。使用 `npm ci --ignore-scripts` 后运行 `npm run hooks:install`;随时用 `npm run hooks:check` 检查。自定义 hooksPath 不会被覆盖,CI / HUSKY=0 会明确跳过。
- 启动快照 API 用 `npm run dev:api:replica`:重新编译并写入当前提交版本;有已跟踪文件改动时标记 `-dirty`。端口被占用时先核对进程归属,不自动终止旧服务。
- 打开本地页面后运行 `npm run dev:status -- http://localhost:5173`,核对 Vite 工作目录、提交、改动状态,以及代理实际返回的 API 版本。旧 Vite 没有 `/__dev/status`,需要重启对应 Vite 才能提供信息。出现 IPv4 / IPv6 多监听时分别检查 `http://127.0.0.1:5173` 和 `http://[::1]:5173`。Vite 状态接口仅开发模式存在,API 凭据不返回。
- `npm run test:frontend:gate` 和 `npm run test:go:gate` 每次保留完整 stdout、stderr 和 summary.json 到 `local-data/test-results/`;可用 `--log-dir <目录>` 指定目录。失败不会自动重跑或更新已知失败基线。CI 上传该目录,保留 14 天。
- CI 的 `npm run test:browser:editing` 启动隔离的 5188 端口合成工作台,验证 E/G 确认、取消舍弃整片重置,以及 E 修改→截断确认→Enter→撤销/重做,覆盖普通和聚焦模式。使用真实组件和历史协调器,保存回调为合成实现;后端持久化与权限仍由 Go 检查负责。CI 失败截图和 Vite 日志保存在上述目录。代理本地浏览器验证使用 `tests/browser/discard-focus-track.mjs` 导出的 CUA 驱动。

View File

@ -3,3 +3,6 @@
标注员需要撤销误切、误删以及已经保存的描述,但切片生成和送检会触发异步产物发布、当前版本替换及审核阶段流转。撤销因此限于当前任务、当前编辑阶段;已保存内容通过受当前版本与归属校验保护的写入恢复,开始生成、送检或切换任务截断历史(2026-10-13 修订:原列于截断触发项中的“重新切片”已随入口停用移除,结构编辑撤销扩展到逐片标注阶段,见 [ADR 0007](0007-inplace-slice-editing-replaces-reslice.md)),避免把普通编辑撤销扩大为媒体版本恢复或审核流程回滚。
这一取舍保留了日常纠错能力,同时要求服务端写入成功后才宣告撤销成功;首版撤销历史仅保留在当前页面会话,刷新后从后端已保存内容恢复,不恢复撤销栈。用户于 2026-09-17 的两轮设计确认中接受此边界;详细交互与验收见 [标注键盘工作流设计](../../.scratch/annotation-keyboard-workflow/spec.md)。
2026-10-15 旧任务兼容补充:缺少 `sliceWorkflow` 的历史任务,若服务端保存的完整切片分区有可靠生成记录,或非全视频任务有完整标注分区证据,可在当前标注员、当前阶段内撤销/重做。判定只读取服务端记录,不以客户端撤销快照充当证明,也不补写阶段标记。显式但不完整的工作流、生成中/失败处理任务、待完成送检和审核阶段仍禁止恢复;版本、归属、真实帧、覆盖及舍弃审计校验保持生效。

View File

@ -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)。

View File

@ -136,3 +136,13 @@ Ctrl/⌘+Enter 有三种结果:当前有草稿就保存它;其他片还有
### 专注工作页字典翻页
切片名称和动作描述字典共用自适应分页:窗口越高,每页可见条目越多,上一页/下一页、页码和总数位于搜索框下方,无需滚动寻找。按 ← / → 翻页,↑ / ↓ 选择,Enter 填入,Esc 返回。搜索框已有文字时,左右键仍移动光标;先按 ↓ 进入词条再翻页。填入词条后仍须明确保存,不会自动提交。长词条可悬停查看全文,填入后也能在编辑区查看。
## E 面板的舍弃与取消舍弃
E 打开切片重设面板;G 或按钮打开舍弃/恢复确认。选定原因后 Enter 只记入预览,
再按一次 Enter 才应用整个面板。鼠标确认和键盘确认关闭子弹层后都归还工作台焦点,
无需点击大页面;输入法、文字输入和长按 Enter 不得串成重复提交。
显式取消舍弃后整片重置为一个待标注动作,旧描述不自动恢复,邻片内容不变;
旧内容保留审计,撤销/重做按各自快照恢复。若需要切片名称,仍从项目字典选择后应用。
正常可编辑动作轨道保持连续分区;无描述以待标注区间呈现,不显示成空轨道。

View 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)
}
})
}
}

View File

@ -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

View File

@ -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 {

View File

@ -0,0 +1,157 @@
package api
import (
"encoding/json"
"net/http"
"testing"
"droboticflow/internal/domain"
)
func TestLegacySliceEditUndoRedoAfterSuccessfulEdit(t *testing.T) {
for _, rework := range []bool{false, true} {
for _, key := range []string{"annotationWorkspace", "annotationDraft"} {
t.Run(map[bool]string{false: "first-pass", true: "rework"}[rework]+"/"+key, func(t *testing.T) {
f := continuousFixture(t)
item := f.item
item.CurrentRevision = 1
if rework {
item.ReviewRound = 1
task := f.task
task.Status = domain.AnnotationTaskStatusRework
if err := f.store.UpsertAnnotationTask(f.ctx, task); err != nil {
t.Fatal(err)
}
}
delete(item.Subject.Payload, "sliceWorkflow")
original := []domain.SliceSegment{{ID: "whole", Name: "测试切片", Start: 0, End: 10}}
split := []domain.SliceSegment{{ID: "left", Name: "测试切片", Start: 0, End: 5}, {ID: "right", Name: "测试切片", Start: 5, End: 10}}
actions := []domain.AnnotationSegment{{ID: "a", Start: 0, End: 5, Status: "pending"}, {ID: "b", Start: 5, End: 10, Status: "described", Description: "保留描述"}}
item.Subject.Payload[key] = map[string]any{"sliceSegments": original, "segments": actions}
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
body := combinedAnnotationDraftInput{Version: item.Version, SliceSegments: split, Segments: actions}
r := f.request("POST", path+"/slice-edit-applications", f.annotator, sliceEditApplicationInput{ApplicationID: "legacy-split", combinedAnnotationDraftInput: body})
if r.Code != 200 {
t.Fatalf("edit %d %s", r.Code, r.Body.String())
}
var response struct {
Item domain.HumanItemRecord `json:"item"`
Workspace combinedAnnotationDraftInput `json:"workspace"`
}
if err := json.Unmarshal(r.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
for _, target := range [][]domain.SliceSegment{original, split, original} {
body.Version = response.Item.Version
body.SliceSegments = target
r = f.request("POST", path+"/slice-edit-restorations", f.annotator, body)
if r.Code != 200 {
t.Fatalf("undo/redo %d %s", r.Code, r.Body.String())
}
if err := json.Unmarshal(r.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if len(response.Workspace.SliceSegments) != len(target) || len(response.Workspace.Segments) != 2 || response.Workspace.Segments[1].Description != "保留描述" {
t.Fatal("snapshot or actions lost")
}
if response.Item.Subject.Payload["sliceWorkflow"] != nil {
t.Fatal("legacy restore invented workflow")
}
// A lost response cannot be retried with the old version and overwrite the new state.
stale := f.request("POST", path+"/slice-edit-restorations", f.annotator, body)
if stale.Code != http.StatusConflict {
t.Fatalf("stale accepted %d", stale.Code)
}
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
if saved.Version != response.Item.Version {
t.Fatal("stale changed version")
}
f.handler = NewHandler(f.store, nil)
}
})
}
}
}
func TestLegacySliceUndoUsesStoredEvidenceAndKeepsSafetyGuards(t *testing.T) {
for _, scenario := range []string{"all-discarded-generated", "partial-generated", "client-only-evidence", "no-actions-no-generation", "full-video-no-generation", "explicit-missing-phase", "explicit-materializing", "workflow-failed", "job-queued", "job-running", "job-processing", "job-failed", "explicit-phase-job-failed", "submission", "review-stage", "nonowner"} {
t.Run(scenario, func(t *testing.T) {
f := continuousFixture(t)
item := f.item
item.CurrentRevision = 1
delete(item.Subject.Payload, "sliceWorkflow")
slices := []domain.SliceSegment{{ID: "whole", Name: "测试切片", Start: 0, End: 10}}
actions := []domain.AnnotationSegment{{ID: "a", Start: 0, End: 10, Status: "pending"}}
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions}
want := http.StatusConflict
switch scenario {
case "all-discarded-generated":
slices[0].DeliveryDisposition = "discard"
slices[0].DiscardReason = "历史舍弃"
actions = nil
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions}
item.Subject.Payload["materialization"] = map[string]any{"status": "completed", "revision": 1, "artifactId": "server-generated", "runId": f.task.RunID}
want = 200
case "partial-generated":
actions = actions[:1]
actions[0].End = 4
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions}
item.Subject.Payload["materialization"] = map[string]any{"status": "completed", "revision": 1, "artifactId": "server-generated", "runId": f.task.RunID}
want = 200
case "client-only-evidence":
delete(item.Subject.Payload, "annotationWorkspace")
case "no-actions-no-generation":
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices}
case "full-video-no-generation":
task := f.task
task.SourceIsFullVideo = true
if err := f.store.UpsertAnnotationTask(f.ctx, task); err != nil {
t.Fatal(err)
}
case "explicit-missing-phase":
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed"}
case "explicit-materializing":
item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "materializing"}
case "workflow-failed":
item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "annotate", "status": "failed"}
case "job-queued", "job-running", "job-processing", "job-failed":
item.ProcessingJob = &domain.AnnotationProcessingJob{Status: scenario[4:]}
case "explicit-phase-job-failed":
item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "annotate"}
item.ProcessingJob = &domain.AnnotationProcessingJob{Status: "failed"}
case "submission":
item.PendingCombinedSubmissionID = "pending"
case "review-stage":
item.CurrentStageID = domain.FanyuV58StageQualityReview
case "nonowner":
item.AssignedUserID = f.admin.ID
}
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
storedBefore, err := f.store.GetHumanItem(f.ctx, item.ID)
if err != nil {
t.Fatal(err)
}
before, _ := json.Marshal(storedBefore)
r := f.request("POST", "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/slice-edit-restorations", f.annotator, combinedAnnotationDraftInput{Version: item.Version, SliceSegments: slices, Segments: actions})
if r.Code != want {
t.Fatalf("want %d got %d %s", want, r.Code, r.Body.String())
}
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
if want == 200 {
if saved.Version != item.Version+1 || saved.Subject.Payload["sliceWorkflow"] != nil {
t.Fatal("restore failed or invented workflow")
}
} else {
after, _ := json.Marshal(saved)
if string(before) != string(after) {
t.Fatal("rejected restore mutated server state")
}
}
})
}
}

View File

@ -35,24 +35,34 @@ func (s *server) handleSliceEditRestoration(w http.ResponseWriter, r *http.Reque
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
busy := false
if job := item.ProcessingJob; job != nil {
busy = job.Status == "queued" || job.Status == "running" || job.Status == "processing"
busy = job.Status == "queued" || job.Status == "running" || job.Status == "processing" || job.Status == "failed"
}
// Newly claimed captures have no workflow until the first generation. They
// are editable, but an incomplete workflow or generated media is not enough
// evidence to infer slicing after the phase field has been lost.
// Explicit workflow markers stay authoritative. For pre-workflow records,
// use server-owned persisted evidence, never the incoming undo snapshot.
initialSlice := len(workflow) == 0 && item.CurrentRevision == 0 && len(mapValue(item.Subject.Payload["materialization"])) == 0 && item.ProcessingJob == nil
// Ticket 07 (spec §3.5): in-place structure edits also happen in the
// annotate pass (unlocked by ticket 02), so their undo/redo replays there
// too. Materializing/processing states still refuse — a snapshot write
// must never race a generation.
editablePhase := func() bool {
switch stringValue(workflow["phase"]) {
case "slice", "annotate":
return true
phase := stringValue(workflow["phase"])
editablePhase := phase == "slice" || phase == "annotate" || initialSlice
blocked := busy
switch stringValue(workflow["status"]) {
case "processing", "running", "materializing", "queued", "failed":
blocked = true
}
if !editablePhase && !blocked && item.Subject.Payload["sliceWorkflow"] == nil {
storedSlices := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(item)["sliceSegments"])
if len(storedSlices) > 0 && len(validateSliceSegments(storedSlices, *task)) == 0 && len(validateCompleteSliceCoverage(storedSlices, *task)) == 0 {
// Generation evidence also covers all-discarded or partially edited
// tracks, which need not satisfy final annotation confirmation yet.
editablePhase, err = s.hasLegacyAnnotationGenerationEvidence(r.Context(), *task, item)
if err == nil && !editablePhase && !task.SourceIsFullVideo {
editablePhase, err = s.legacyAnnotationConfirmationReady(r.Context(), *task, item)
}
if err != nil {
renderError(w, 500, err)
return
}
}
return initialSlice
}()
if !editablePhase || stringValue(workflow["status"]) == "processing" || stringValue(workflow["status"]) == "running" || stringValue(workflow["status"]) == "materializing" || stringValue(workflow["status"]) == "queued" || busy {
}
if !editablePhase || blocked {
renderJSON(w, 409, map[string]string{"code": "slice_edit_restoration_unavailable", "error": "仅可在可编辑的切片或标注阶段撤销或重做切片"})
return
}

View File

@ -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 {

View File

@ -10,7 +10,7 @@
"dev:worker": "go run ./cmd/worker",
"dev:drosync-coordinator": "go run ./cmd/drosync-coordinator",
"dev:web": "vite",
"prepare": "husky",
"prepare": "node scripts/check-git-hooks.mjs --install",
"build": "npm run build:web && npm run build:go",
"build:web": "vite build",
"build:go": "mkdir -p build && go build -o build/droboticflow-api ./cmd/api && go build -o build/droboticflow-worker ./cmd/worker && go build -o build/drosync-coordinator ./cmd/drosync-coordinator",
@ -74,7 +74,12 @@
"acceptance:drosync-poc": "python3 scripts/drosync-poc-acceptance.py",
"acceptance:drosync-capacity": "python3 scripts/drosync-capacity-acceptance.py",
"acceptance:xplatform": "python3 scripts/xplatform-live-acceptance.py",
"acceptance:poc-operator-workflows": "./scripts/poc-operator-workflow-acceptance.sh"
"acceptance:poc-operator-workflows": "./scripts/poc-operator-workflow-acceptance.sh",
"hooks:check": "node scripts/check-git-hooks.mjs",
"hooks:install": "node scripts/check-git-hooks.mjs --install",
"dev:status": "node scripts/local/check-dev-stack.mjs",
"dev:api:replica": "bash scripts/local/start-replica-api.sh",
"test:browser:editing": "node tests/browser/run-editing-regression.mjs"
},
"dependencies": {
"@tailwindcss/vite": "^4.1.14",

View File

@ -0,0 +1,31 @@
#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { accessSync, constants, existsSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
try {
if (process.env.CI || process.env.HUSKY === "0" || !existsSync(resolve(root, ".git"))) {
console.log("Git hooks: skipped (CI, HUSKY=0, or exported source)");
} else {
let configured = "";
try {
configured = execFileSync("git", ["config", "--get", "core.hooksPath"], { cwd: root, encoding: "utf8" }).trim();
} catch {}
if (process.argv.includes("--install")) {
if (configured && resolve(root, configured) !== resolve(root, ".husky/_"))
throw Error("Custom hooksPath detected; left unchanged");
execFileSync(process.execPath, [resolve(root, "node_modules/husky/bin.js")], { cwd: root, stdio: "inherit" });
configured = execFileSync("git", ["config", "--get", "core.hooksPath"], { cwd: root, encoding: "utf8" }).trim();
}
if (resolve(root, configured) !== resolve(root, ".husky/_"))
throw Error("core.hooksPath must resolve to this checkout's .husky/_");
for (const name of [".husky/_/pre-commit"]) accessSync(resolve(root, name), constants.X_OK);
accessSync(resolve(root, ".husky/_/h"), constants.R_OK);
accessSync(resolve(root, ".husky/pre-commit"), constants.R_OK);
console.log(`Git hooks: active in ${root}`);
}
} catch (error) {
console.error(`Git hooks unavailable: ${error.message}. Run npm run hooks:install in this checkout.`);
process.exitCode = 1;
}

View File

@ -15,9 +15,9 @@
// the package whose `FAIL\t<pkg>` block marker closes them).
import { spawn } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { dirname, join, resolve } from "node:path";
const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
const baselinePath = join(repoRoot, "tests", "known-failures.json");
@ -78,6 +78,11 @@ function parseGoFailures(output) {
}
async function main() {
const logOption = process.argv.indexOf("--log-dir");
if (logOption >= 0 && (!process.argv[logOption + 1] || process.argv[logOption + 1].startsWith("--"))) {
console.error("--log-dir requires a directory path");
process.exit(2);
}
const baselineFile = JSON.parse(readFileSync(baselinePath, "utf8"));
const known = new Set(baselineFile[suite] ?? []);
if (known.size === 0 && !update) {
@ -90,9 +95,44 @@ async function main() {
? await run("npm", ["run", "--silent", "test:frontend"])
: await run("npm", ["run", "--silent", "test"]);
// Preserve every invocation, including crashes and runs which pass only
// because failures are known. No automatic retries or baseline mutation.
const option = logOption;
const logDir = resolve(
option >= 0
? process.argv[option + 1]
: join(
repoRoot,
"local-data/test-results",
`${suite}-${new Date().toISOString().replaceAll(":", "-")}-${process.pid}`,
),
);
mkdirSync(logDir, { recursive: true, mode: 0o700 });
writeFileSync(join(logDir, "stdout.log"), result.out, { mode: 0o600 });
writeFileSync(join(logDir, "stderr.log"), result.err, { mode: 0o600 });
console.log(`Full test output: ${logDir}`);
const failures =
suite === "frontend" ? parseFrontendFailures(result.out + result.err) : parseGoFailures(result.out + result.err);
const fresh = [...failures].filter((id) => !known.has(id));
const fixed = [...known].filter((id) => !failures.has(id));
writeFileSync(
join(logDir, "summary.json"),
JSON.stringify(
{
suite,
at: new Date().toISOString(),
exitCode: result.code,
failures: [...failures],
newFailures: fresh,
fixed,
updateRequested: update,
},
null,
2,
) + "\n",
{ mode: 0o600 },
);
const runnerCrashed = result.code === null;
const noFailuresParsed = failures.size === 0 && result.code !== 0;
if (runnerCrashed || noFailuresParsed) {
@ -108,12 +148,11 @@ async function main() {
return;
}
const fresh = [...failures].filter((id) => !known.has(id));
const fixed = [...known].filter((id) => !failures.has(id));
if (fresh.length > 0) {
console.error(`NEW ${suite} failures (${fresh.length}) not in tests/known-failures.json:`);
for (const id of fresh) console.error(` + ${id}`);
// Put a bounded diagnostic tail in CI output; full streams remain on disk.
console.error((result.out + result.err).slice(-4000));
process.exit(1);
}
if (fixed.length > 0) {

View File

@ -0,0 +1,39 @@
import { execFileSync } from "node:child_process";
export function localDevStatusPlugin(apiTarget) {
let root;
return {
name: "local-development-status",
apply: "serve",
configResolved(config) {
root = config.root;
},
configureServer(server) {
server.middlewares.use("/__dev/status", (req, res, next) => {
if (req.url !== "/" || req.method !== "GET") return next();
const git = (...args) =>
execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
try {
const target = new URL(apiTarget);
target.username = "";
target.password = "";
target.search = "";
target.hash = "";
res.setHeader("Content-Type", "application/json");
res.setHeader("Cache-Control", "no-store");
res.end(
JSON.stringify({
root,
commit: git("rev-parse", "HEAD"),
dirty: Boolean(git("status", "--porcelain", "--untracked-files=no")),
apiTarget: target.origin,
}),
);
} catch {
res.statusCode = 503;
res.end('{"error":"development source metadata unavailable"}');
}
});
},
};
}

View File

@ -0,0 +1,43 @@
#!/usr/bin/env node
import { execFileSync } from "node:child_process";
const origin = new URL(process.argv[2] || "http://localhost:5173");
if (
!["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) ||
origin.protocol !== "http:" ||
origin.username ||
origin.password
)
throw Error("Use a loopback HTTP development URL");
const get = async (path) => {
const response = await fetch(new URL(path, origin), { redirect: "error", signal: AbortSignal.timeout(5000) });
if (!response.ok) throw Error(`${path}: HTTP ${response.status}`);
return response.json();
};
try {
const [frontend, api] = await Promise.all([get("/__dev/status"), get("/api/health")]);
const expected = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
const issues = [];
if (frontend.commit !== expected) issues.push("Frontend is from another commit");
if (!api.buildCommit) issues.push("API has no buildCommit; restart through npm run dev:api:replica");
else if (api.buildCommit !== expected) issues.push("API is from another commit");
if (frontend.dirty)
issues.push("Frontend source has uncommitted changes; commit comparison alone cannot prove the running build");
if (api.status !== "ok") issues.push("API is not healthy");
console.log(
JSON.stringify(
{
url: origin.origin,
expectedCommit: expected,
frontend,
api: { status: api.status, commit: api.buildCommit, buildTime: api.buildTime },
issues,
},
null,
2,
),
);
if (issues.length) process.exitCode = 1;
} catch (error) {
console.error(`Local stack check failed: ${error.message}`);
process.exitCode = 1;
}

View File

@ -0,0 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT_DIR"
source scripts/local/env-local-snapshot.sh
export DROBOTICFLOW_DATABASE_BOOTSTRAP=verify-existing
export ANNOTATION_PROCESSOR_MODE=external
# Recompile before assigning the version; never stamp an existing stale binary.
export DROBOTICFLOW_BUILD_COMMIT="$(git rev-parse HEAD)"
if ! git diff --quiet HEAD --; then
export DROBOTICFLOW_BUILD_COMMIT="${DROBOTICFLOW_BUILD_COMMIT}-dirty"
fi
export DROBOTICFLOW_BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
exec go run ./cmd/api

View File

@ -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),

View File

@ -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

View File

@ -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) };
}

View File

@ -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({

View File

@ -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;

View File

@ -0,0 +1,81 @@
// 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;
}
// Same driver runs through CUA locally and a Playwright adapter in CI.
// The fixture mounts the real workbench, resolver and history coordinator;
// server persistence/legacy-state contracts run separately in the Go gate.
export async function runEditingHistoryRegression(tab, origin) {
assert.ok(["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname));
const results = [];
for (const focused of [false, true]) {
await tab.goto(origin + "/tests/browser/fixtures/discard-focus-track.html" + (focused ? "?focused" : ""));
await tab.playwright.getByTestId("capture-annotation-workbench").waitFor({ state: "visible" });
const read = async () => JSON.parse(await tab.playwright.getByTestId("slice-state").innerText());
const original = await read();
await tab.pressKey(null, "e");
await tab.playwright.getByRole("button", { name: "尾帧前移2帧", exact: true }).click();
await tab.playwright.getByRole("button", { name: "Enter 应用", exact: true }).click();
await tab.playwright.getByTestId("slice-edit-conflict-list").waitFor({ state: "visible" });
await tab.playwright.getByRole("button", { name: /1 截断/ }).click();
await tab.pressKey(null, "Return");
await tab.playwright.getByTestId("slice-edit-panel").waitFor({ state: "hidden" });
const edited = await read();
assert.equal(edited[0].end, 3.8);
await tab.pressKey(null, "ctrl+z");
assert.deepEqual(await read(), original);
await tab.playwright.getByTestId("history-ready").waitFor({ state: "visible" });
await tab.pressKey(null, "ctrl+shift+z");
assert.deepEqual(await read(), edited);
results.push({ focused, conflictConfirmation: "passed", undo: "passed", redo: "passed" });
}
return results;
}

View 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>

View File

@ -0,0 +1,82 @@
import React, { useEffect, useRef, 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 { createAnnotationHistory } from "/src/lib/annotation-history.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);
const history = useRef(createAnnotationHistory());
const [cooldown, setCooldown] = useState(false);
useEffect(() => {
if (!cooldown) return;
const timer = setTimeout(() => setCooldown(false), 1100);
return () => clearTimeout(timer);
}, [cooldown]);
return (
<div className="annotation-operations-page">
<p role="status" data-testid="apply-count">
已应用 {count} 次
</p>
{!cooldown && <span data-testid="history-ready">历史操作就绪</span>}
<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 });
history.current.record({ before: { slices, actions }, after: { slices: p.slices, actions: p.actions } });
history.current.markPersisted();
setSlices(p.slices);
setActions(p.actions);
setCount((v) => v + 1);
return true;
}}
onHistoryCommand={async (direction) => {
await history.current[direction](async (snapshot) => {
setSlices(snapshot.slices);
setActions(snapshot.actions);
return true;
});
setCooldown(true);
}}
onConfirmAnnotations={() => true}
onConfirmSlices={() => {}}
onSubmitTask={() => {}}
onReturnToPool={() => {}}
/>
<pre data-testid="slice-state">{JSON.stringify(slices)}</pre>
<pre data-testid="track-state">{JSON.stringify(actions)}</pre>
</div>
);
}
createRoot(document.getElementById("root")!).render(<Harness />);

View File

@ -0,0 +1,52 @@
// CI-only browser launcher. Local agent interactions use the exported CUA driver.
import { chromium } from "playwright";
import { spawn } from "node:child_process";
import { mkdirSync, openSync, closeSync } from "node:fs";
import { runDiscardFocusTrackRegression, runEditingHistoryRegression } from "./discard-focus-track.mjs";
const output = "local-data/test-results/browser-editing";
mkdirSync(output, { recursive: true });
const log = openSync(output + "/vite.log", "w");
// Refuse an occupied port before starting, so a stale fixture cannot be reused.
const { createServer } = await import("node:net");
await new Promise((resolve, reject) => {
const probe = createServer();
probe.once("error", reject);
probe.listen(5188, "127.0.0.1", () => probe.close(resolve));
});
const server = spawn(
process.execPath,
["node_modules/vite/bin/vite.js", "--host", "127.0.0.1", "--port", "5188", "--strictPort"],
{ stdio: ["ignore", log, log] },
);
const origin = "http://127.0.0.1:5188";
let browser, page;
try {
const deadline = Date.now() + 20000;
while (true) {
try {
if ((await fetch(origin, { signal: AbortSignal.timeout(1000) })).ok) break;
} catch {}
if (server.exitCode !== null || Date.now() > deadline)
throw Error("Synthetic Vite fixture server unavailable; inspect vite.log");
await new Promise((done) => setTimeout(done, 200));
}
browser = await chromium.launch({ headless: true });
page = await browser.newPage();
page.setDefaultTimeout(8000);
const keyMap = { Return: "Enter", "ctrl+z": "Control+z", "ctrl+shift+z": "Control+Shift+z" };
const tab = {
goto: (url) => page.goto(url),
playwright: page,
pressKey: (_element, key) => page.keyboard.press(keyMap[key] || key),
};
console.log(JSON.stringify(await runDiscardFocusTrackRegression(tab, origin)));
console.log(JSON.stringify(await runEditingHistoryRegression(tab, origin)));
} catch (error) {
if (page) await page.screenshot({ path: output + "/failure.png", fullPage: true }).catch(() => {});
console.error(error);
process.exitCode = 1;
} finally {
await browser?.close();
server.kill("SIGTERM");
closeSync(log);
}

View File

@ -0,0 +1,126 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, copyFileSync, cpSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { spawnSync } from "node:child_process";
import { createServer } from "node:http";
import { spawn } from "node:child_process";
const root = resolve(".");
const run = (file, args, cwd, env = {}) =>
spawnSync(process.execPath, [file, ...args], {
cwd,
encoding: "utf8",
env: { ...process.env, CI: "", HUSKY: "", ...env },
});
test("missing Husky wrappers are detected and installation produces a working pre-commit hook", () => {
const dir = mkdtempSync(join(tmpdir(), "hook-guard-"));
try {
mkdirSync(join(dir, "scripts"));
mkdirSync(join(dir, ".husky"));
mkdirSync(join(dir, "node_modules"));
copyFileSync(join(root, "scripts/check-git-hooks.mjs"), join(dir, "scripts/check-git-hooks.mjs"));
cpSync(join(root, "node_modules/husky"), join(dir, "node_modules/husky"), { recursive: true });
spawnSync("git", ["init", "-q"], { cwd: dir });
writeFileSync(join(dir, ".husky/pre-commit"), "echo hook-was-executed\nexit 1\n");
const script = join(dir, "scripts/check-git-hooks.mjs");
assert.equal(run(script, [], dir).status, 1);
assert.equal(run(script, ["--install"], dir).status, 0);
assert.equal(run(script, [], dir).status, 0);
const hook = spawnSync(
"git",
[
"-c",
"user.name=Fixture",
"-c",
"user.email=fixture@example.invalid",
"commit",
"--allow-empty",
"-m",
"fixture",
],
{ cwd: dir, encoding: "utf8", env: { ...process.env, HUSKY: "" } },
);
assert.notEqual(hook.status, 0);
assert.match(hook.stdout + hook.stderr, /hook-was-executed/);
spawnSync("git", ["config", "core.hooksPath", "custom-hooks"], { cwd: dir });
assert.equal(run(script, ["--install"], dir).status, 1);
assert.equal(
spawnSync("git", ["config", "--get", "core.hooksPath"], { cwd: dir, encoding: "utf8" }).stdout.trim(),
"custom-hooks",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("baseline gate keeps raw output for known failures, novel failures and runner crashes", () => {
const dir = mkdtempSync(join(tmpdir(), "baseline-logs-"));
try {
for (const name of ["scripts", "tests", "bin"]) mkdirSync(join(dir, name));
copyFileSync(join(root, "scripts/check-test-baseline.mjs"), join(dir, "scripts/check-test-baseline.mjs"));
const baseline = JSON.stringify({ frontend: ["fixture.test.mjs :: known"], go: ["fixture :: TestKnown"] });
writeFileSync(join(dir, "tests/known-failures.json"), baseline);
for (const [name, output, expected] of [
["known", "test at tests/frontend/fixture.test.mjs:1:1\n✖ known (1ms)\nassertion-details", 0],
["new", "test at tests/frontend/fixture.test.mjs:1:1\n✖ novel (1ms)\nnovel-assertion-details", 1],
["crash", "runner failed before producing tests", 1],
]) {
writeFileSync(
join(dir, "bin/npm"),
"#!/usr/bin/env node\nprocess.stdout.write(" +
JSON.stringify(output) +
'); process.stderr.write("stderr-details"); process.exit(1);\n',
{ mode: 0o755 },
);
const logDir = join(dir, name);
const result = run(join(dir, "scripts/check-test-baseline.mjs"), ["frontend", "--log-dir", logDir], dir, {
PATH: join(dir, "bin") + ":" + process.env.PATH,
});
assert.equal(result.status, expected, result.stderr);
assert.equal(readFileSync(join(logDir, "stdout.log"), "utf8"), output);
assert.equal(readFileSync(join(logDir, "stderr.log"), "utf8"), "stderr-details");
const summary = JSON.parse(readFileSync(join(logDir, "summary.json"), "utf8"));
assert.equal(summary.exitCode, 1);
assert.equal(summary.updateRequested, false);
assert.equal(readFileSync(join(dir, "tests/known-failures.json"), "utf8"), baseline);
}
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("local stack check rejects a missing or stale API version and accepts matching source", async () => {
const commit = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim();
let apiCommit = "";
const server = createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(
JSON.stringify(
req.url === "/__dev/status"
? { commit, dirty: false, root, apiTarget: "http://127.0.0.1:3001" }
: { status: "ok", buildCommit: apiCommit },
),
);
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
const url = "http://127.0.0.1:" + server.address().port;
const command = () =>
new Promise((done) => {
const child = spawn(process.execPath, ["scripts/local/check-dev-stack.mjs", url], { cwd: root });
let output = "";
child.stdout.on("data", (x) => (output += x));
child.on("close", (code) => done({ code, output }));
});
try {
assert.equal((await command()).code, 1);
apiCommit = "old-source";
assert.equal((await command()).code, 1);
apiCommit = commit;
const result = await command();
assert.equal(result.code, 0, result.output);
} finally {
await new Promise((done) => server.close(done));
}
});

View File

@ -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)) {

View 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;
}
}
});

View File

@ -1,3 +1,4 @@
import { localDevStatusPlugin } from "./scripts/lib/local-dev-status.mjs";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { createReadStream, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
@ -16,6 +17,7 @@ export default defineConfig(() => {
return {
plugins: [
react(),
localDevStatusPlugin(proxyTargets.api),
tailwindcss(),
{
name: "capture-workbench-local-video",