🛡️ Prevent annotation edits in review workspaces

This commit is contained in:
d-robotics 2026-10-20 18:30:37 +08:00
parent 63560220a0
commit 86a1d7a360
16 changed files with 769 additions and 27 deletions

View File

@ -0,0 +1,26 @@
# 审核查看与原标注编辑权限核对
Type: task
Status: resolved
2026-10-20 平台调优群反馈审核员可拖动切片边界。用户要求核查同类入口并防止复发。
基线为已上线的 `63560220`,本地分支 `codex/review-authoring-guards-20261020`。
## 验收
- 质检、剪切审核、旧验收入口、最终验收、历史查看和仅媒体查看均不能修改原切片、动作、名称、舍弃状态或执行标注撤销/重做、保存及送检;普通和专注布局一致。
- 审核意见与正式决定按原权限可操作;播放、逐帧、切片和动作导航继续可用。
- 权限失效后,指针拖动和长按键停止修改,松手不补交变更;锁定审核不能经快捷键改意见。
- 页面修改回调独立核对当前查看模式、角色、阶段及任务归属,不能只靠隐藏控件。
- 服务端覆盖质检/验收角色、新旧修改接口、通用提交及返工处理入口,拒写后原数据不变。
- 用真实审核可写状态复现红灯,再验证修复;新增测试进入发布门禁,不修改已知失败基线。
## 边界
不改变业务数据协议或既有管理权限,不迁移客户数据;本次本地修改和验证不构成新部署、PR 或推送授权。
## Answer
已完成本地修复、22 组浏览器查看模式、正常标注/审核与失权正反对照,以及服务端两角色四阶段 120 次拒写验证。
类型、格式、实际生产包启动与发布工具测试通过;完整前后端套件没有新增失败。详见
[核对与修复报告](../../../docs/verification/review-authoring-20261020/report.md)。线上未部署本修复。

View File

@ -21,6 +21,12 @@ Coordinator 保留当前镜像;更新它们仍须单独审查与授权。
这是命令行防误操作流程,不是安全边界:操作者仍可以直接运行 kubectl。团队级强制执行
需后续收敛集群写权限。首版没有自动回退、自动重试、压测或自动创建测试数据。
2026-10-20 审核权限补充:发布本地检查强制运行 `test:browser:review-permissions`、
`TestReviewCannotMutateAnnotation` 及 `TestRouteSnapshot`。浏览器以可写审核意见的真实状态
验证原标注不可编辑,不得额外设置整体只读来代替;覆盖普通/专注、旧审核入口、最终验收、
历史/媒体查看、快捷键及失权手势,同时保留合法标注和审核操作的正向对照。此检查使用
本机 Vite、合成媒体和内存数据库,需要 FFmpeg 与现有 Playwright 浏览器;不访问生产。
## 授权与数据边界
- 本地 prepare/check/plan 不构成部署、PR 或客户数据写入授权。

View File

@ -20,6 +20,7 @@
["npm", "run", "lint:web"],
["npm", "run", "build:web"],
["npm", "run", "test:production:boot"],
["go", "test", "./internal/api", "-run", "TestDurableAnnotationOutbox|TestSliceRecovery", "-count=1"]
["npm", "run", "test:browser:review-permissions"],
["go", "test", "./internal/api", "-run", "TestDurableAnnotationOutbox|TestSliceRecovery|TestReviewCannotMutateAnnotation|TestRouteSnapshot", "-count=1"]
]
}

View File

@ -0,0 +1,55 @@
# 审核编辑权限核对与修复(2026-10-20)
基线为已上线 `63560220`。本地分支 `codex/review-authoring-guards-20261020`,保留主工作区已有修改。
本报告记录本地修复;未上传新镜像、部署、推送或创建 PR,未写生产客户数据。
## 发现
1. 可填写意见的质检/旧验收模式把整体 `readOnly` 保持为 false,切片拖动及悬停新增漏检审查模式。
在与生产同版的真实组件上复现了修改回调;这不是合法的播放导航。
2. 仅经字幕或审查导航进入共享组件的查看模式,还可能开放删除切片、删除动作及动作分界控件。
当前最终验收调用者已有仅媒体/只读保护;这是共享组件自身的同类缺口,不能据此声称所有生产入口已允许写库。
3. 指针拖动及长按键开始后失权,旧手势仍可能继续修改或在释放时追加编辑历史。
4. 质检、旧验收及最终验收父容器的意见快捷键未完整遵循写锁。按钮禁用不能阻止快捷键回调。
5. 旧字幕/相机夹具额外传入整体只读,掩盖了真实“意见可写、标注不可写”的状态。
本地同版服务端检查中,质检/验收账号均不能调用标注修改接口;没有证据认定客户数据已越权改写。
生产页仅观察了已有页面,不接管会话、不拖动或保存客户任务。未进行生产历史数据损坏审计。
## 修改
- 共享工作台统一将审查、仅字幕/导航及媒体查看的原标注设为只读;审核意见的可写状态独立计算。
切片/动作的增删、边界、名称/舍弃、确认/送检及历史操作继承同一约束。
- 失权时结束拖动和长按,不再继续移动或追加提交。编辑器更新及边界原语也核对权限。
- 页面回调独立检查当前模式、角色、阶段、归属和本地工作页持有权;异步/旧回调读取当前状态。
- 审核写快捷键的分类由两个工作台复用。最终验收播放器通过自身 canAct 传递意见写锁;
媒体查看始终不能修改原标注,同时保留合法批注与验收决定。
- 去掉字幕夹具中多余的只读设置,增加浏览器负向断言与正常标注/审核正向对照。
- 发布策略强制运行浏览器权限测试、服务端拒写测试及权限路由快照。补记此前已经存在的两条
delivery-index-batches 路由;既有权限期望未放宽,未改 `tests/known-failures.json`。
没有新增持久化字段、迁移、API 协议或后台处理行为;原标注和审查记录的业务契约保持不变。
## 验证
| 检查 | 结果 |
| --- | --- |
| 红灯复现 | 修复前真实审核状态可拖边界、触发原标注回调;扩展测试抓到查看模式编辑入口、失权手势和快捷键;最终验收父子容器有独立红灯记录 |
| `npm run test:browser:review-permissions` | 22 组:质检/剪切审核/旧验收的两个阶段与两种布局,加字幕/导航/历史/媒体/真实最终验收两种布局;零原标注回调、零运行错误、零外部或写请求 |
| 正向与失权对照 | 标注两个阶段仍可拖边界;质检、旧验收、真实最终验收可写意见及通过;失权后拖动、长按和意见快捷键均不再写入 |
| `TestReviewCannotMutateAnnotation` | 两个角色 × 四个阶段 × 15 个写入口,共 120 次拒写,原 HumanItem/AnnotationTask 不变;含旧接口、通用提交和返工处理 |
| 字幕、相机浏览器回归 | 通过;6 组普通相机默认/按需加载对照通过,字幕几何/跟随/开关/播放推进通过 |
| TypeScript、格式、实际生产包构建与启动 | 通过,登录页可见、零运行错误;构建仍有既有大 bundle 提示 |
| 完整前端门禁 | 13 个失败均在既有 14 项基线内,无新增失败 |
| 完整 Go 门禁 | 70 个失败均在既有 70 项基线内,无新增失败;本次拒写、路由快照及定向恢复测试另行通过 |
| 发布工具 | 37 个 unittest 通过 |
本地证据位于忽略目录 `local-data/diagnostics/review-slice-permissions-20261020/` 和
`local-data/test-results/review-authoring-permissions/`。最初受沙箱端口限制的前端运行及诊断夹具扫描失败
保留在旧日志中;修正测试环境/临时文件后按原基线门禁重跑,没有跳过断言或放宽基线。
## 实际边界
本次核对范围是标注、质检、剪切审核、最终验收及其历史/媒体查看相关入口,不是整个平台的全面渗透测试。
浏览器使用真实组件与合成数据,服务端使用真实路由和内存存储;未声称在生产完成领取、保存、审核决定或交付写测试。
修复仍需新的具体发布计划、紧邻部署授权和线上核验后才对客户生效。

View File

@ -0,0 +1,76 @@
package api
import (
"net/http"
"reflect"
"testing"
"droboticflow/internal/domain"
)
// A claimed review task is writable for opinions, not for its source annotations.
// Exercise the real router with valid CSRF and an assignee, not anonymous requests.
func TestReviewCannotMutateAnnotation(t *testing.T) {
for _, role := range []domain.UserRole{domain.UserRoleQualityReviewer, domain.UserRoleAcceptanceReviewer} {
for _, stage := range []string{"annotation_combined", "quality_review", "prepackage_acceptance", "acceptance"} {
t.Run(string(role)+"/"+stage, func(t *testing.T) {
f := continuousFixture(t)
user := f.reviewer
user.Role = role
if err := f.store.UpsertUser(f.ctx, user); err != nil {
t.Fatal(err)
}
item := f.item
item.CurrentStageID = stage
item.AssignedUserID = user.ID
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
before, _ := f.store.GetHumanItem(f.ctx, item.ID)
beforeTask, _ := f.store.GetAnnotationTask(f.ctx, f.task.ID)
base := "/api/plugins/annotation-qa/tasks/" + f.task.ID
legacy := "/api/annotation-tasks/" + f.task.ID
for _, endpoint := range []struct{ method, path string }{
{http.MethodPut, base + "/drafts"},
{http.MethodPost, base + "/annotation-confirmations"},
{http.MethodPost, base + "/slice-edit-applications"},
{http.MethodPost, base + "/slice-edit-restorations"},
{http.MethodPost, base + "/slice-dispositions"},
{http.MethodPost, base + "/slice-confirmations"},
{http.MethodPost, base + "/slice-reset"},
{http.MethodPost, base + "/slice-revisions"},
{http.MethodPost, base + "/revisions"},
{http.MethodPost, base + "/combined-submissions"},
{http.MethodPost, legacy + "/slice-revisions"},
{http.MethodPost, legacy + "/revisions"},
{http.MethodPost, legacy + "/combined-submissions"},
{http.MethodPut, "/api/human-items/" + item.ID + "/rework-handling"},
} {
body := map[string]any{
"version": item.Version, "applicationId": "forbidden-review-edit",
"sliceSegments": []map[string]any{{"id": "s", "start": 0, "end": 5}},
"segments": []map[string]any{{"id": "a", "start": 0, "end": 5, "description": "forged"}},
"role": "annotator",
}
response := f.request(endpoint.method, endpoint.path, user, body)
if response.Code != http.StatusForbidden {
t.Fatalf("%s %s: got %d, want 403", endpoint.method, endpoint.path, response.Code)
}
}
// The generic human-loop submission route must not provide an
// alternative way to submit annotations from a review stage/role.
response := f.request(http.MethodPost, "/api/human-items/"+item.ID+"/submissions", user, map[string]any{
"version": item.Version, "revision": 2, "submissionRef": "forged-review-submission",
})
if response.Code != http.StatusForbidden && response.Code != http.StatusConflict {
t.Fatalf("generic annotation submission: got %d, want 403/409", response.Code)
}
after, _ := f.store.GetHumanItem(f.ctx, item.ID)
afterTask, _ := f.store.GetAnnotationTask(f.ctx, f.task.ID)
if !reflect.DeepEqual(before, after) || !reflect.DeepEqual(beforeTask, afterTask) {
t.Fatal("denied review request changed persisted annotations or task state")
}
})
}
}
}

View File

@ -1,7 +1,7 @@
# Generated by TestRouteSnapshot; see routes_snapshot_test.go.
# access: reach = endpoint reached; otherwise the status the middleware chain returned.
global=[diagnosticTrace,middleware.(*Compressor).Handler-fm,(*server).invalidateDashboardCachesOnWrite-fm,(*server).apiTokenAuth-fm,(*server).sessionAuth-fm,(*server).csrfProtection-fm,(*server).projectDeletionWriteGuard-fm,(*server).supplierDeletionWriteGuard-fm,(*server).acceptanceAccessCache-fm,annotationReadCache]
routes=366
routes=368
DELETE /api/admin/organizations/{id} | mw=[(*server).requireSuperAdmin-fm] | (*server).handleAdminOrganizationsDelete-fm | anon=401 token=401 super=reach admin=403 supplier=403 annotator=403 quality=403 acceptance=403
DELETE /api/admin/users/{id} | mw=[(*server).requireSuperAdmin-fm] | (*server).handleAdminUserDelete-fm | anon=401 token=401 super=reach admin=403 supplier=403 annotator=403 quality=403 acceptance=403
DELETE /api/database/collections/{name} | mw=[(*server).requireBusinessRole.1] | (*server).handleDatabaseCollectionDelete-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403
@ -51,6 +51,7 @@ GET /api/database/collections/{name}/documents | mw=[(*server).requireBusinessRo
GET /api/database/collections/{name}/indexes | mw=[(*server).requireBusinessRole.1] | (*server).handleDatabaseCollectionIndexes-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403
GET /api/delivery-downloads/manifest | mw=[] | (*server).handleDeliveryDownloadManifest-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
GET /api/delivery-downloads/projects | mw=[] | (*server).handleDeliveryDownloadProjects-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
GET /api/delivery-index-batches | mw=[] | (*server).handleDeliveryIndexBatch-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
GET /api/delivery-packages | mw=[] | (*server).handleDeliveryPackagesList-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
GET /api/delivery-packages/{id} | mw=[] | (*server).handleDeliveryPackageGet-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
GET /api/delivery-packages/{id}/artifacts/{artifactId}/content | mw=[] | (*server).handleDeliveryPackageArtifactContent-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
@ -223,6 +224,7 @@ POST /api/data-operations/backfill | mw=[(*server).requireBusinessRole.1] | (*se
POST /api/database/collections | mw=[(*server).requireBusinessRole.1] | (*server).handleDatabaseCollectionCreate-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403
POST /api/database/collections/{name}/documents | mw=[(*server).requireBusinessRole.1] | (*server).handleDatabaseDocumentCreate-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403
POST /api/database/collections/{name}/indexes | mw=[(*server).requireBusinessRole.1] | (*server).handleDatabaseCollectionIndexCreate-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403
POST /api/delivery-index-batches | mw=[] | (*server).handleDeliveryIndexBatch-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach
POST /api/delivery-packages/{id}/claim | mw=[(*server).requireBusinessRole.1] | (*server).handleDeliveryPackageClaim-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=reach acceptance=reach
POST /api/delivery-packages/{id}/decisions | mw=[(*server).requireBusinessRole.1] | (*server).handleDeliveryPackageDecision-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=reach acceptance=reach
POST /api/delivery-packages/{id}/release | mw=[(*server).requireBusinessRole.1] | (*server).handleDeliveryPackageRelease-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=reach acceptance=reach

View File

@ -80,6 +80,7 @@
"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",
"test:browser:review-permissions": "node tests/browser/review-authoring-permissions.mjs",
"test:production:boot": "node tests/browser/run-production-boot.mjs"
},
"dependencies": {

View File

@ -1,7 +1,7 @@
import { formatAnnotationTime } from "../lib/annotation-time.js";
import { previewSliceEditDispositions } from "../lib/slice-edit-dispositions.js";
import { userErrorMessage } from "../lib/user-error-message.js";
import { reviewShortcut, reviewShortcutHelp } from "../lib/review-shortcuts.js";
import { reviewCommandRequiresWrite, reviewShortcut, reviewShortcutHelp } from "../lib/review-shortcuts.js";
import type { ReviewViewingProps, ReviewViewingController, ReviewPosition, ReviewNavigation } from "./review-viewing";
import { ReviewCaptionDetails, ReviewVideoCaption, type ReviewCaption } from "./ReviewCaptions";
import { reviewCaptionAtTime } from "../lib/review-captions.js";
@ -442,7 +442,12 @@ export function CaptureAnnotationWorkbench({
}: Props) {
const isReviewViewing = isQualityReview || Boolean(providedReviewCaption) || Boolean(reviewNavigation);
const timelineReady = frameTimelineStatus === "ready";
const readOnly = providedReadOnly || !timelineReady || (isQualityReview && reviewWriteLocked);
// Reviewing may allow opinions and decisions, never annotation authoring.
// Keep this invariant here so pointer, keyboard and legacy viewing paths agree.
const reviewReadOnly = providedReadOnly || !timelineReady || reviewWriteLocked;
const readOnly = providedReadOnly || !timelineReady || isReviewViewing || mediaOnly;
const reviewWritableRef = useRef(!reviewReadOnly);
reviewWritableRef.current = !reviewReadOnly;
// Editable continuous tracks expose explicit pending intervals, including
// legacy empty workspaces; frozen review records and loading states stay raw.
const segments = useMemo(
@ -483,6 +488,8 @@ export function CaptureAnnotationWorkbench({
const saveInFlightRef = useRef(false);
const [descriptionSaving, setDescriptionSaving] = useState(false);
const saving = externalSaving || descriptionSaving;
const annotationWritableRef = useRef(!readOnly && !saving);
annotationWritableRef.current = !readOnly && !saving;
const focusWorkbench = () => workbenchRef.current?.focus({ preventScroll: true });
const focusDescriptionEditor = () => descriptionEditorRef.current?.focus({ preventScroll: true });
const leftVideoRef = useRef<HTMLVideoElement>(null);
@ -922,6 +929,7 @@ export function CaptureAnnotationWorkbench({
}, [editingAnnotation?.id, selectedSlice?.id, reviewComment]);
const saveSegmentQAComment = () => {
if (reviewReadOnly) return;
if (reviewWriteLocked || !selectedSlice || !editingAnnotation) return;
const segIndex = annotationSegments.findIndex((s) => s.id === editingAnnotation.id);
const sliceLabel = selectedSlice.name || `切片 ${selectedSliceIndex + 1}`;
@ -971,6 +979,7 @@ export function CaptureAnnotationWorkbench({
};
const deleteSegmentQAComment = (targetSliceLabel?: string, targetSegIdx?: number, targetTimeRange?: string) => {
if (reviewReadOnly) return;
if (reviewWriteLocked) return;
const { segmentComments: currentList, generalComment } = parseSegmentCommentsFromText(reviewComment || "");
const nextList = currentList.filter((c) => {
@ -1500,6 +1509,7 @@ export function CaptureAnnotationWorkbench({
};
const updateSliceBoundaryAt = (index: number, time: number, preview = false) => {
if (readOnly || saving) return;
const current = slices[index];
const following = slices[index + 1];
if (!current || !following) return;
@ -1518,6 +1528,7 @@ export function CaptureAnnotationWorkbench({
* 的提交式管线:无冲突立即生效/有冲突弹 04 清单/Esc=挪动未发生),与 slice 相
* ←/→ 的既有路径同一条。 */
const coarseNudgeSliceBoundary = (direction: -1 | 1) => {
if (readOnly || saving) return;
if (phase !== "annotate" || slices.length < 2 || selectedDiscarded) return;
let index = selectedBoundary?.index;
if (index == null || index < 0 || index >= slices.length - 1)
@ -1560,7 +1571,7 @@ export function CaptureAnnotationWorkbench({
};
const updateSliceDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
if (!sliceDragRef.current || !sliceTrackRef.current) return;
if (readOnly || saving || !sliceDragRef.current || !sliceTrackRef.current) return;
const { index, gesture } = sliceDragRef.current;
// Keep the gesture scale fixed as the edge changes the visible page range.
// Global adjacent-frame limits below permit motion past the visible edge.
@ -1571,7 +1582,7 @@ export function CaptureAnnotationWorkbench({
const releaseSliceDrag = () => {
if (!sliceDragRef.current) return;
sliceDragRef.current = null;
onSliceBoundaryEditEnd?.();
if (!readOnly && !saving) onSliceBoundaryEditEnd?.();
transport.finishScrub();
focusWorkbench();
};
@ -1604,6 +1615,7 @@ export function CaptureAnnotationWorkbench({
return index >= 0 && index < pendingSlices.length - 1 ? "end" : index > 0 ? "start" : "end";
};
const openSliceEditPanel = (targetSlice?: SliceSegment) => {
if (readOnly || saving) return;
// D1(rework-ux-adjust 04):单切片任务同样直开面板——面板内 C 可加边界,旧的
// 「仅一个切片」toast 分支整体删除;目标缺省为当前选中片(E 路径),J/K 联动
// 传入意见锚定的切片。
@ -1842,6 +1854,7 @@ export function CaptureAnnotationWorkbench({
focusWorkbench();
};
const applySliceEditPanel = () => {
if (readOnly || saving) return;
const panel = sliceEditPanel;
if (!panel) return;
if (!continuousActions && editingAnnotation) {
@ -1963,6 +1976,7 @@ export function CaptureAnnotationWorkbench({
};
const updateEditingAnnotation = (patch: Partial<AnnotationSegment>) => {
if (readOnly || saving) return;
if (
!editingAnnotation ||
Object.entries(patch).every(([key, value]) => editingAnnotation[key as keyof AnnotationSegment] === value)
@ -1979,6 +1993,7 @@ export function CaptureAnnotationWorkbench({
};
const editAnnotationBoundary = (field: "start" | "end", time: number) => {
if (readOnly || saving) return;
if (!editingAnnotation || !selectedSlice || !Number.isFinite(time)) return;
if (continuousActions) {
if (outstandingDrafts.some((draft) => draft.sliceId === selectedSlice.id)) {
@ -2386,7 +2401,7 @@ export function CaptureAnnotationWorkbench({
};
const updateAnnotationBoundaryDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
if (selectingEnd) return;
if (readOnly || saving || selectingEnd) return;
if (!annotationBoundaryDragRef.current) {
if (annotationTrackRef.current) {
const point = pointForEvent(
@ -2437,7 +2452,12 @@ export function CaptureAnnotationWorkbench({
if (!annotationBoundaryDragRef.current) return;
const edit = annotationBoundaryDragRef.current;
annotationBoundaryDragRef.current = null;
if (edit.after && JSON.stringify(edit.before.segments) !== JSON.stringify(edit.after.segments))
if (
!readOnly &&
!saving &&
edit.after &&
JSON.stringify(edit.before.segments) !== JSON.stringify(edit.after.segments)
)
onAnnotationEdit?.(edit.before, edit.after);
setSelectedAnnotationBoundary(null);
transport.finishScrub();
@ -2936,8 +2956,16 @@ export function CaptureAnnotationWorkbench({
stopBoundaryHold();
}, [selectedSlice.id, editingAnnotation?.id]);
useEffect(() => {
if (viewportSuspended || saving || showDictionary || stageConfirmation) stopBoundaryHold();
}, [viewportSuspended, saving, showDictionary, stageConfirmation]);
if (readOnly || viewportSuspended || saving || showDictionary || stageConfirmation) stopBoundaryHold();
if (readOnly || saving) {
const scrubbing = Boolean(sliceDragRef.current || annotationBoundaryDragRef.current);
sliceDragRef.current = null;
annotationBoundaryDragRef.current = null;
if (scrubbing) transport.finishScrub();
setSplitPreview(null);
setAnnotationSplitPreview(null);
}
}, [readOnly, viewportSuspended, saving, showDictionary, stageConfirmation]);
const startBoundaryHold = (direction: -1 | 1) => {
if (!continuousActions || !canEdit || !exactFrames || boundaryHoldRef.current) return;
if (outstandingDrafts.some((draft) => draft.sliceId === selectedSlice.id)) {
@ -2964,8 +2992,8 @@ export function CaptureAnnotationWorkbench({
stopped = true;
clearTimeout(timer);
clearInterval(interval);
if (phase === "slice") onSliceBoundaryEditEnd?.();
else if (nextSegments !== segments)
if (phase === "slice" && annotationWritableRef.current) onSliceBoundaryEditEnd?.();
else if (phase !== "slice" && annotationWritableRef.current && nextSegments !== segments)
onAnnotationEdit?.(before, {
...before,
segments: nextSegments,
@ -2976,6 +3004,10 @@ export function CaptureAnnotationWorkbench({
};
const move = (count: number) => {
if (stopped) return;
if (!annotationWritableRef.current) {
finish();
return;
}
const active = document.activeElement;
if (
!workbenchRef.current?.contains(active) ||
@ -3229,6 +3261,7 @@ export function CaptureAnnotationWorkbench({
);
if (!command) return;
event.preventDefault();
if (reviewReadOnly && reviewCommandRequiresWrite(command)) return;
if (command === "escape") {
onReviewEscape?.();
reviewController.focus();
@ -3686,7 +3719,7 @@ export function CaptureAnnotationWorkbench({
) : isQualityReview ? (
<div className="flex items-center gap-2">
<span className="rounded-md bg-blue-500/10 px-3 py-1 text-xs font-semibold text-blue-600 dark:bg-blue-500/20 dark:text-blue-400">
质检审核模式{readOnly ? "(只读查看)" : ""}
质检审核模式{reviewReadOnly ? "(只读查看)" : ""}
</span>
</div>
) : (
@ -4319,7 +4352,7 @@ export function CaptureAnnotationWorkbench({
<button
type="button"
className="inline-flex items-center gap-2 rounded-lg border border-orange-400 bg-orange-50 px-3 py-2 text-sm font-semibold text-orange-800 shadow-sm hover:bg-orange-100 dark:bg-orange-950/40 dark:text-orange-200"
disabled={reviewWriteLocked}
disabled={reviewReadOnly}
onClick={() => {
if (reviewProblemPanel) {
onReviewProblem?.({ ...reviewPosition, actionId: null }, "slice");
@ -4692,6 +4725,7 @@ export function CaptureAnnotationWorkbench({
) : null}
</div>
{(phase === "slice" || phase === "annotate") &&
!readOnly &&
index < (sliceEditPanel ? sliceEditPanel.pendingSlices.length : slices.length) - 1 ? (
<button
type="button"
@ -5764,7 +5798,7 @@ export function CaptureAnnotationWorkbench({
</div>
{/* QA inline commenting panel */}
{!readOnly || reviewWriteLocked ? (
{!reviewReadOnly || reviewWriteLocked ? (
<div className="rounded-lg border border-rose-200 bg-rose-50/50 p-3 dark:border-rose-900/40 dark:bg-rose-950/20 space-y-2.5">
<div className="flex items-center justify-between">
<label className="text-xs font-bold text-rose-800 dark:text-rose-200 flex items-center gap-1">
@ -5778,7 +5812,7 @@ export function CaptureAnnotationWorkbench({
<textarea
aria-label="当前动作问题备注"
disabled={reviewWriteLocked}
disabled={reviewReadOnly}
rows={3}
value={qaDraftComment}
onChange={(e) => setQaDraftComment(e.target.value)}
@ -5790,7 +5824,7 @@ export function CaptureAnnotationWorkbench({
{qaCommentForThis ? (
<button
type="button"
disabled={reviewWriteLocked}
disabled={reviewReadOnly}
onClick={() => {
deleteSegmentQAComment(
currentSliceLabel,
@ -5817,7 +5851,7 @@ export function CaptureAnnotationWorkbench({
</button>
<button
type="button"
disabled={reviewWriteLocked}
disabled={reviewReadOnly}
onClick={() => {
saveSegmentQAComment();
setEditingAnnotation(null);
@ -6190,7 +6224,7 @@ export function CaptureAnnotationWorkbench({
</button>
</div>
) : null}
{isQualityReview && !readOnly ? (
{isQualityReview && !reviewReadOnly ? (
<>
<div className="flex items-center gap-2 text-xs text-slate-500 dark:text-gray-400">
<span>
@ -6259,6 +6293,7 @@ export function CaptureAnnotationWorkbench({
type="button"
className="ml-4 text-orange-600"
onClick={() => {
if (reviewReadOnly) return;
const parsed = parseSegmentCommentsFromText(reviewComment || "");
const notes = parsed.segmentComments.filter(
(c) =>
@ -6399,7 +6434,7 @@ export function CaptureAnnotationWorkbench({
)}
</footer>
)}
{showRejectModal ? (
{showRejectModal && !reviewReadOnly ? (
<div
role="dialog"
aria-modal="true"
@ -6480,7 +6515,9 @@ export function CaptureAnnotationWorkbench({
onProblemSliceIdsChange?.([selectedSlice.id]);
}
setShowRejectModal(false);
setTimeout(() => onReject?.(), 50);
setTimeout(() => {
if (reviewWritableRef.current) onReject?.();
}, 50);
}}
className="rounded-lg bg-red-600 px-5 py-2 text-xs font-bold text-white shadow-sm hover:bg-red-700 disabled:opacity-50"
>

View File

@ -1,7 +1,7 @@
import { userErrorMessage } from "../lib/user-error-message.js";
import { stripTaskOpinionLines } from "../lib/task-scope-visibility.js";
import { AcceptanceSourceOpinions } from "./AcceptanceSourceOpinions";
import { reviewShortcut } from "../lib/review-shortcuts.js";
import { reviewCommandRequiresWrite, reviewShortcut } from "../lib/review-shortcuts.js";
import type { ReviewViewingProps, ReviewViewingController, ReviewPosition } from "./review-viewing";
import { ReviewCaptionDetails } from "./ReviewCaptions";
import { reviewCaptionAtTime } from "../lib/review-captions.js";
@ -553,6 +553,7 @@ export function FinalAcceptanceWorkspace({
);
if (!command) return;
event.preventDefault();
if (!canAct && reviewCommandRequiresWrite(command)) return;
if (command === "escape") {
onReviewEscape?.();
finalController.focus();
@ -703,7 +704,7 @@ export function FinalAcceptanceWorkspace({
? "loading"
: "ready"
}
readOnly
reviewWriteLocked={!canAct || saving}
videoSource={memberURL(left.id)}
rightVideoSource={memberURL(right.id)}
clipStart={0}

View File

@ -1,4 +1,17 @@
/** Review owns viewing commands only; editing shortcuts never enter this dispatch. */
const writeCommands = new Set([
"problem",
"save-note",
"edit-problem",
"delete-problem",
"rework-verdict-resolved",
"rework-verdict-unresolved",
]);
export function reviewCommandRequiresWrite(command) {
return writeCommands.has(command);
}
const macPlatform = () =>
typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || "");

View File

@ -2799,6 +2799,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
const currentAnnotationMutationContext = annotationMutationContextRef.current.current;
const beginAnnotationMutation = async (taskId: string) => {
if (!annotationAuthoringRef.current) return null;
if (workPage && (!workSession.active || !workSession.owns())) return null;
const currentContext = currentAnnotationMutationContext();
++bufferReadEpochRef.current;
@ -2847,6 +2848,21 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
selectedHumanItem.assignedUserId === currentUser?.id &&
["claimed", "in_progress"].includes(selectedHumanItem.status),
);
const annotationAuthoring =
(workspaceMode === "clip" || workspaceMode === "annotate") &&
taskPoolView !== "reviewed" &&
(role === "annotator" || isManager) &&
(selectedClaimedByMe || isManager) &&
!["pending_quality", "pending_acceptance", "accepted"].includes(detail?.task.status || "") &&
(!detail?.humanItem ||
["annotation_combined", "split_annotation", "cut_adjustment", "semantic_annotation"].includes(
detail.humanItem.currentStageId,
)) &&
(!workPage || (workSession.active && workSession.owns()));
// Callbacks can outlive a render or pointer gesture. Check the current view
// again before changing annotations, independently of child control visibility.
const annotationAuthoringRef = useRef(annotationAuthoring);
annotationAuthoringRef.current = annotationAuthoring;
// A01 标注草稿自动保存:D1 触发(换片/20s 空闲/页面隐藏)、D4 草稿归并、D2 冲突横幅。
const [draftConflictAuthoritative, setDraftConflictAuthoritative] = useState<AnnotationTaskDetail | null>(null);
// 验收修复 C:切片重设面板会话标记——面板打开期间暂停草稿自动保存(快照引用
@ -2861,6 +2877,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
detail && annotationBaselineRef.current && annotationFingerprint !== annotationBaselineRef.current,
);
const autosaveEnabled = Boolean(
annotationAuthoring &&
selectedClaimedByMe &&
detail?.humanItem?.currentStageId === "annotation_combined" &&
(combinedEditorPhase === "slice" || combinedEditorPhase === "annotate"),
@ -3040,6 +3057,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
: "切分与标注队列";
const addSegment = () => {
if (!annotationAuthoringRef.current) return;
if (!detail) return;
const label = selectedLabels.find((item) => item.id === segmentDraft.labelId);
const next = normalizeAnnotationSegments(
@ -3069,6 +3087,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
const updateSegments = useCallback(
(next: AnnotationSegment[]) => {
if (!annotationAuthoringRef.current) return;
setSegments(next);
setSliceStatuses(
deriveSliceStatuses(sliceSegments, next, sliceStatuses) as Record<
@ -3085,6 +3104,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
return confirmed && confirmed.taskId === detailRef.current?.task.id ? structuredClone(confirmed.workspace) : null;
};
const recordAnnotationEdit = (before: AnnotationEditState, after: AnnotationEditState) => {
if (!annotationAuthoringRef.current) return;
if (saving || combinedSubmissionLocked || annotationMutationScopeRef.current.busy() || !selectedClaimedByMe) return;
const persisted = confirmedAnnotationWorkspace();
if (!persisted) return;
@ -3100,6 +3120,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
before?: AnnotationEditState,
restoring?: AnnotationEditSnapshot["persisted"],
) => {
if (!annotationAuthoringRef.current) return false;
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked) return false;
const taskId = detail.task.id;
let submittedVersion = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
@ -3193,6 +3214,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
});
const beginSliceBoundaryEdit = (sliceId: string) => {
if (!annotationAuthoringRef.current) return;
// 冲突清单开着时不接受新的边界拖动:一次只决一件事(待决快照不被打穿)。
if (sliceEditQuickConflict) return;
sliceDragEditRef.current = { before: sliceEditSnapshot(sliceId) };
@ -3205,6 +3227,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
const finishSliceBoundaryEdit = () => {
const edit = sliceDragEditRef.current;
sliceDragEditRef.current = null;
if (!annotationAuthoringRef.current) return;
if (!edit?.after) return;
const draggedId = edit.before.location.sliceId;
const beforeSlice = edit.before.slices.find((item) => item.id === draggedId);
@ -3252,6 +3275,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
recordSliceDragEdit(edit);
};
const recordSliceDragEdit = (edit: { before: SliceEditSnapshot; after?: SliceEditSnapshot }) => {
if (!annotationAuthoringRef.current) return;
const before = annotationWorkspaceFingerprint(edit.before.slices, [], edit.before.segments, edit.before.statuses);
const after = edit.after
? annotationWorkspaceFingerprint(edit.after.slices, [], edit.after.segments, edit.after.statuses)
@ -3265,6 +3289,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
operation: Omit<SliceOperation, "before" | "after">,
candidateSegments = segments,
) => {
if (!annotationAuthoringRef.current) return false;
if (!exactFrameEditing) {
setError("统一帧范围尚未就绪,暂不能修改切片。");
return false;
@ -3320,6 +3345,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
prompt: SliceEditQuickConflict,
resolution: { slices: SliceSegment[]; actions: AnnotationSegment[] },
) => {
if (!annotationAuthoringRef.current) return "blocked";
if (segments !== prompt.baseSegments) {
// 清单期间工作区被其它编辑改动:宁可拦下也不覆盖(旧处置卡同款承诺)。
setError("处置期间工作区发生了其它修改,请按 Esc 关闭清单后重试。");
@ -3363,6 +3389,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
// 后原子落库;拖动来源整段手势 + 处置合并为一条可撤销历史。失败保留清单(重试/Esc)。
// 成功时返回焦点切片 id 供工作台选中(拆分来源为新片;拖动来源为被拖片)。
const handleSliceEditQuickConflictApply = (decisions: Partial<Record<string, SliceEditChoice>>) => {
if (!annotationAuthoringRef.current) return;
const prompt = sliceEditQuickConflict;
if (!prompt) return;
// 经由具名输入绕开 JSDoc 推断的窄参数类型(引擎实现源是 JS + JSDoc,家族同款)。
@ -3389,6 +3416,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
const prompt = sliceEditQuickConflict;
if (!prompt) return;
setSliceEditQuickConflict(null);
if (!annotationAuthoringRef.current) {
sliceDragEditRef.current = null;
return;
}
setError("");
const edit = prompt.dragEdit;
if (!edit) return;
@ -3409,6 +3440,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const adjustSlice = (id: string, field: "start" | "end", value: number) => {
if (!annotationAuthoringRef.current) return;
// 冲突清单开着时冻结其它边界改动,防止待决快照被打穿。
if (sliceEditQuickConflict) return;
const index = sliceSegments.findIndex((item) => item.id === id);
@ -3473,6 +3505,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const splitSlice = (index: number, requestedAt = annotationPlayheadRef.current) => {
if (!annotationAuthoringRef.current) return;
const current = sliceSegments[index];
if (!current) return;
if (requestedAt <= current.start + 0.001 || requestedAt >= current.end - 0.001) {
@ -3524,6 +3557,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const mergeSlice = (index: number) => {
if (!annotationAuthoringRef.current) return;
const current = sliceSegments[index];
const nextItem = sliceSegments[index + 1];
if (!current || !nextItem) return;
@ -3532,6 +3566,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const deleteSlice = (index: number) => {
if (!annotationAuthoringRef.current) return;
const target = sliceSegments[index];
const merged = target ? cancelSlicePartition(sliceSegments, index) : null;
if (!target || !merged) return;
@ -3565,6 +3600,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const updateSliceName = (id: string, name: string) => {
if (!annotationAuthoringRef.current) return;
if (!exactFrameEditing || saving || combinedSubmissionLocked || annotationMutationScopeRef.current.busy()) return;
const slice = sliceSegments.find((item) => item.id === id);
if (!slice || slice.deliveryDisposition === "discard" || slice.name === name) return;
@ -3582,6 +3618,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
restorePreviousName = false,
restoreNameFromVersion?: number,
) => {
if (!annotationAuthoringRef.current) return false;
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return false;
const previousSlice = sliceSegments.find((slice) => slice.id === sliceId);
if (!previousSlice) return false;
@ -3691,6 +3728,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
recordHistory = true,
restoredOperations = sliceOperations,
) => {
if (!annotationAuthoringRef.current) return null;
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return null;
const taskId = detail.task.id;
const before = sliceEditSnapshot(focusSliceId);
@ -3781,6 +3819,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const restorePersistedSliceEdit = async (snapshot: SliceEditSnapshot) => {
if (!annotationAuthoringRef.current) return null;
// Ticket 07(spec §3.5):结构编辑已在标注相解锁(票 02),持久化切片编辑的
// 撤销/重做在标注相也要经服务端快照恢复;物化/质检等阶段仍拒绝。
if (!detail?.humanItem || !selectedClaimedByMe || !["slice", "annotate"].includes(combinedEditorPhase)) return null;
@ -3852,6 +3891,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const restoreEdit = async (direction: "undo" | "redo") => {
if (!annotationAuthoringRef.current) return;
if (
!exactFrameEditing ||
!selectedClaimedByMe ||
@ -3935,6 +3975,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const alignCurrentSliceBoundaries = () => {
if (!annotationAuthoringRef.current) return;
if (
!detail ||
!exactFrameEditing ||
@ -4061,6 +4102,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const confirmSlicesAndMaterialize = async () => {
if (!annotationAuthoringRef.current) return;
if ((detail?.humanItem?.subject.payload?.sliceWorkflow as { status?: string } | undefined)?.status === "failed") {
if (annotationDirty) setError("请先保存当前编辑,再按已保存内容重试切片。");
else await retryFailedSlices();
@ -4150,6 +4192,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
// 票 06:首标「重新切片」提交(f980696f~1 取回)——经权威变更核对管线写
// resetSlices,未知结果驻留待核对;成功后回确认切片阶段并重建基线指纹。
const resetToSliceEditing = async () => {
if (!annotationAuthoringRef.current) return;
if (
!detail?.humanItem ||
!selectedClaimedByMe ||
@ -4238,6 +4281,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const submitSliceRevision = async () => {
if (!annotationAuthoringRef.current) return;
if (!detail || sliceSegments.length === 0) return;
setSaving(true);
setError("");
@ -4260,6 +4304,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const submitRevision = async () => {
if (!annotationAuthoringRef.current) return;
if (!detail || segments.length === 0) return;
setSaving(true);
setError("");
@ -4278,6 +4323,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const submitCombined = async () => {
if (!annotationAuthoringRef.current) return;
// Preserve explicit blank actions; only structural and in-flight edits block handoff.
if (
!detail?.humanItem ||
@ -4423,6 +4469,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
}, [combinedSubmissionProcessing, detail?.task.id, loadProject, setDetail]);
const toggleSliceUsability = (sliceId: string, usable: boolean) => {
if (!annotationAuthoringRef.current) return;
const target = sliceSegments.find((slice) => slice.id === sliceId);
if (!target) return;
if (!usable) {
@ -4461,6 +4508,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const confirmSliceEmpty = (sliceId: string) => {
if (!annotationAuthoringRef.current) return;
const target = sliceSegments.find((slice) => slice.id === sliceId);
if (!target) return;
const hasEvents = segments.some((segment) => segment.start >= target.start && segment.end <= target.end);
@ -4479,10 +4527,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
};
const resetSliceCompletion = (sliceId: string) => {
if (!annotationAuthoringRef.current) return;
setSliceStatuses((current) => ({ ...current, [sliceId]: "pending" }));
};
const rejectAnnotationInput = async () => {
if (!annotationAuthoringRef.current) return;
if (!detail || !reviewComment.trim()) {
setError("拒绝输入必须填写原因。");
return;
@ -7421,12 +7471,17 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
}
onReworkSkipToggle={
reworkEmphasisEligible && !saving && !combinedSubmissionLocked && !reworkEmphasisData.saving
? (opinionId, skipped) => void reworkEmphasisData.toggleSkip(opinionId, skipped)
? (opinionId, skipped) => {
if (annotationAuthoringRef.current)
void reworkEmphasisData.toggleSkip(opinionId, skipped);
}
: undefined
}
onDraftsChange={setWorkbenchDrafts}
onSelectedSliceChange={() => autosave.notifySliceSwitch()}
onAnnotationDraftEdit={() => editHistoryRef.current.invalidateRedo()}
onAnnotationDraftEdit={() => {
if (annotationAuthoringRef.current) editHistoryRef.current.invalidateRedo();
}}
adaptiveLayout={adaptiveSliceLayout}
focusedLayout={focusedStageLayout || reviewFocused}
viewportSuspended={viewportPaused || showResliceWarning}
@ -7476,6 +7531,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
: statusLabels[detail.task.status] || "只读查看"
}
readOnly={
((workspaceMode === "clip" || workspaceMode === "annotate") && !annotationAuthoring) ||
taskPoolView === "reviewed" ||
(workspaceMode === "annotate" &&
(detail.task.status === "pending_quality" ||

View File

@ -70,7 +70,7 @@ createRoot(document.getElementById("root")!).render(
isQualityReview={mode === "quality"}
browserReadyMedia
continuousActions
readOnly
readOnly={mode === "annotation"}
onChange={noop}
/>
),

View File

@ -0,0 +1,10 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="root"></div>
<script type="module" src="./review-authoring-permissions.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,188 @@
import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { CaptureAnnotationWorkbench } from "/src/components/CaptureAnnotationWorkbench";
import { FinalAcceptanceWorkspace } from "/src/components/FinalAcceptanceWorkspace";
import "/src/index.css";
import "/src/styles/review-workspace.css";
const params = new URLSearchParams(location.search);
const mode = params.get("mode") || "quality";
const phase = params.get("phase") === "slice" ? "slice" : "annotate";
const focused = params.get("focused") === "true";
const originalSlices = [
{ id: "s1", name: "合成切片一", start: 0, end: 4 },
{ id: "s2", name: "合成切片二", start: 4, end: 8 },
];
const originalActions = [
{ id: "a1", start: 0, end: 2, description: "原始动作一", status: "described" },
{ id: "a2", start: 2, end: 4, description: "原始动作二", status: "described" },
{ id: "a3", start: 4, end: 8, description: "原始动作三", status: "described" },
];
function Fixture() {
const [locked, setLocked] = useState(mode === "history");
const [reviewLocked, setReviewLocked] = useState(false);
const [slices, setSlices] = useState(originalSlices);
const [actions, setActions] = useState(originalActions);
const [authoring, setAuthoring] = useState<string[]>([]);
const [review, setReview] = useState<string[]>([]);
const [comment, setComment] = useState("");
const record = (name: string) => setAuthoring((events) => [...events, name]);
const note = (name: string) => setReview((events) => [...events, name]);
useEffect(() => {
const lock = (event: KeyboardEvent) => {
if (event.key === "F8") setLocked(true);
if (event.key === "F9") setReviewLocked(true);
};
window.addEventListener("keydown", lock);
return () => window.removeEventListener("keydown", lock);
}, []);
return (
<main className="annotation-operations-page" data-review-focused={focused || undefined}>
<output data-testid="permission-observation">
{JSON.stringify({ locked, reviewLocked, authoring, review, slices, actions })}
</output>
{mode === "final-acceptance" ? (
<FinalAcceptanceWorkspace
item={{
id: "synthetic-acceptance",
version: 1,
status: "claimed",
processingProfile: "raw_human",
subject: {
payload: {
items: [
{
materialization: {
artifactId: "mat",
revision: 1,
manifestSha256: "fixture",
sliceCount: 2,
coverage: { contiguous: true, gapMicroseconds: 0, overlapMicroseconds: 0 },
},
finalSlices: originalSlices,
},
],
},
},
}}
mine={!locked}
writeLocked={reviewLocked}
saving={false}
focusedLayout={focused}
draft={{ headpose: "include", handpose: "include", exclusionReason: "" }}
comment={comment}
onDraftChange={() => note("acceptance-draft")}
onCommentChange={setComment}
onApprove={() => note("approve")}
onReject={() => note("reject")}
onReviewProblem={() => note("problem")}
onReviewSave={() => note("save-note")}
onReviewProblemEdit={() => note("edit-problem")}
onReviewProblemDelete={() => note("delete-problem")}
/>
) : (
<CaptureAnnotationWorkbench
taskId="synthetic-permission-task"
phase={phase}
focusedLayout={focused}
readOnly={locked}
isQualityReview={mode === "quality" || mode === "clip-quality" || mode === "acceptance"}
reviewMode={mode === "acceptance" ? "acceptance" : "quality"}
reviewWriteLocked={reviewLocked}
reviewCaption={
mode === "caption" ? { kind: "described", text: "原始动作一", sliceText: "合成切片一" } : undefined
}
reviewNavigation={
mode === "navigation"
? {
actions,
selectedActionId: null,
onSelectAction: () => {},
sliceIndex: 0,
sliceCount: 2,
onNavigateSlice: () => {},
}
: undefined
}
mediaOnly={mode === "media"}
slices={slices}
segments={actions}
statuses={{ s1: "labeled", s2: "labeled" }}
continuousActions
clipStart={0}
clipEnd={8}
frameTimelineStatus="ready"
frameBoundaries={Array.from({ length: 81 }, (_, i) => i / 10)}
videoSource="/__capture-workbench-mock.mp4"
browserReadyMedia
reviewComment={comment}
onReviewCommentChange={(value) => {
setComment(value);
note("comment");
}}
onReviewProblem={() => note("problem")}
onReviewSave={() => note("save-note")}
onReviewProblemEdit={() => note("edit-problem")}
onReviewProblemDelete={() => note("delete-problem")}
onReviewReworkVerdict={() => note("verdict")}
onReviewReworkNavigate={() => note("navigate-opinion")}
onApprove={() => note("approve")}
onReject={() => note("reject")}
onChange={(next) => {
record("actions");
setActions(next);
}}
onDraftsChange={(drafts) => {
if (drafts.length) record("drafts");
}}
onSliceBoundaryChange={(id, field, value) => {
record("slice-boundary");
setSlices((old) =>
old.map((slice, index) =>
slice.id === id
? { ...slice, [field]: value }
: index === 1 && field === "end"
? { ...slice, start: value }
: slice,
),
);
}}
onSliceBoundaryEditStart={() => record("slice-drag-start")}
onSliceBoundaryEditEnd={() => record("slice-drag-end")}
onSliceNameChange={() => record("slice-name")}
onSliceDispositionChange={async () => {
record("disposition");
return true;
}}
onSplitSlice={() => {
record("split-slice");
return "new";
}}
onDeleteSlice={() => record("delete-slice")}
onMergeSliceBoundary={() => record("merge-slice")}
onApplySliceEdit={async () => {
record("apply-slice");
return true;
}}
onAnnotationEdit={() => record("action-history")}
onAnnotationDraftEdit={() => record("action-draft")}
onHistoryCommand={() => record("history")}
onSaveProgress={async () => {
record("save-progress");
return true;
}}
onConfirmSlices={() => record("confirm-slices")}
onConfirmAnnotations={async () => {
record("confirm-actions");
return true;
}}
onSubmitTask={() => record("submit")}
canSubmitTask
canConfirmSlices
/>
)}
</main>
);
}
createRoot(document.getElementById("root")!).render(<Fixture />);

View File

@ -145,7 +145,6 @@ function Preview() {
continuousActions
focusedLayout={focused}
isQualityReview
readOnly
cameraDefault="left"
cameraPreferenceKey="local-caption-overlay-preview"
reviewReworkEmphasis={notes ? emphasis : null}

View File

@ -0,0 +1,271 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { chromium } from "playwright";
import { createServer } from "vite";
const out = path.resolve("local-data/test-results/review-authoring-permissions");
fs.mkdirSync(out, { recursive: true });
const media = path.join(out, "synthetic.mp4");
assert.equal(
spawnSync("ffmpeg", [
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"color=c=black:s=160x90:r=10",
"-t",
"8",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
media,
]).status,
0,
);
process.env.CAPTURE_WORKBENCH_MOCK_VIDEO = media;
const server = await createServer({
configFile: "tests/browser/vite.platform-feedback.config.ts",
server: { host: "127.0.0.1", port: 5194, strictPort: true },
});
let browser;
const report = { cases: [], errors: [], failures: [], unexpectedRequests: [] };
const check = (condition, message) => {
if (!condition) report.failures.push(message);
};
try {
await server.listen();
const origin = "http://127.0.0.1:5194";
browser = await chromium.launch({
...(process.env.BROWSER_EXECUTABLE ? { executablePath: process.env.BROWSER_EXECUTABLE } : {}),
headless: true,
args: ["--no-proxy-server"],
});
const page = await browser.newPage({ viewport: { width: 1600, height: 1100 }, serviceWorkers: "block" });
page.setDefaultTimeout(12000);
page.on("pageerror", (e) => report.errors.push(e.message));
await page.route("**/*", async (route) => {
const req = route.request(),
u = new URL(req.url()),
p = decodeURIComponent(u.pathname);
if (u.origin !== origin || req.method() !== "GET") {
report.unexpectedRequests.push({ method: req.method(), path: p });
return route.abort();
}
if (p.startsWith("/api/")) {
if (p.endsWith("/members"))
return route.fulfill({
json: {
items: [1, 2].flatMap((i) =>
[
"left.mp4",
"right.mp4",
"left_pts.csv",
"right_pts.csv",
"imu.csv",
"annotation.json",
"synchronized-slice.json",
].map((name) => ({
id: `${i}-${name}`,
name,
group: `slices/slice-${String(i).padStart(6, "0")}`,
sizeBytes: 100,
contentAvailable: true,
})),
),
total: 14,
offset: 0,
limit: 200,
truncated: false,
recognized: true,
},
});
if (p.includes("annotation.json"))
return route.fulfill({
json: {
descriptions: [
{ id: "a1", clipStartMs: 0, clipEndMs: 2000, description: "原始动作一" },
{ id: "a2", clipStartMs: 2000, clipEndMs: 4000, description: "原始动作二" },
],
},
});
if (p.includes("synchronized-slice.json"))
return route.fulfill({
json: {
window: { startTimestampUs: 0, endTimestampUs: 4000000 },
boundaryContract: "hardware-frame-v1",
boundarySeconds: Array.from({ length: 41 }, (_, i) => i / 10),
left: { pts: { rowCount: 40 } },
},
});
if (p.endsWith(".csv/content"))
return route.fulfill({
contentType: "text/csv",
body: "clip_time_ms\n" + Array.from({ length: 40 }, (_, i) => i * 100).join("\n"),
});
if (p.endsWith(".mp4/content")) return route.fulfill({ contentType: "video/mp4", body: fs.readFileSync(media) });
return route.fulfill({ json: { items: [] } });
}
return route.continue();
});
const observe = () => page.getByTestId("permission-observation").textContent().then(JSON.parse);
const open = async (mode, focused, phase = "annotate") => {
await page.goto(
`${origin}/tests/browser/fixtures/review-authoring-permissions.html?mode=${mode}&focused=${focused}&phase=${phase}`,
);
await page.getByTestId("capture-annotation-workbench").waitFor();
};
const drag = async (handle) => {
await handle.scrollIntoViewIfNeeded();
const b = await handle.boundingBox();
await page.mouse.move(b.x + b.width / 2, b.y + b.height / 2);
await page.mouse.down();
await page.mouse.move(b.x + b.width / 2 + 60, b.y + b.height / 2, { steps: 5 });
await page.mouse.up();
};
for (const mode of [
"quality",
"clip-quality",
"acceptance",
"caption",
"navigation",
"history",
"media",
"final-acceptance",
]) {
for (const focused of [false, true]) {
for (const phase of ["quality", "clip-quality", "acceptance"].includes(mode)
? ["slice", "annotate"]
: ["annotate"]) {
await open(mode, focused, phase);
const bench = page.getByTestId("capture-annotation-workbench");
const before = await observe();
const handle = bench.getByRole("button", { name: "拖动切片边界", exact: true });
const enabled = (await handle.count()) ? await handle.first().isEnabled() : false;
if (enabled) await drag(handle.first());
const sliceBlock = bench.locator("[data-slice-id='s1'] .capture-slice-block");
if (await sliceBlock.count()) {
await sliceBlock.hover();
check(
(await bench.getByTestId("slice-insert-button").count()) === 0,
`${mode}/${focused}: slice insertion leaked`,
);
}
for (const name of ["删除切片", "拖动动作分界", "删除此动作"]) {
for (const control of await bench.getByRole("button", { name, exact: true }).all())
check(!(await control.isEnabled()), `${mode}/${focused}: enabled ${name}`);
}
for (const key of ["e", "c", "n", "d", "Backspace", "Control+z", "Control+Shift+z", "Shift+ArrowRight"])
await bench.press(key);
const action = bench.getByTestId("annotation-description-block").first();
if (await action.count()) await action.dblclick();
for (const control of await bench.getByRole("textbox", { name: "动作描述", exact: true }).all()) {
check(
(await control.getAttribute("readonly")) !== null || !(await control.isEnabled()),
`${mode}/${focused}: editable description exposed`,
);
}
const after = await observe();
check(
!enabled &&
after.authoring.length === 0 &&
JSON.stringify(before.slices) === JSON.stringify(after.slices) &&
JSON.stringify(before.actions) === JSON.stringify(after.actions),
`${mode}/${focused}: review changed annotations`,
);
report.cases.push({ mode, focused, phase, boundaryEnabled: enabled, authoringCallbacks: after.authoring });
}
}
}
for (const mode of ["quality", "acceptance", "final-acceptance"]) {
await open(mode, false);
const bench = page.getByTestId("capture-annotation-workbench");
const scope = mode === "final-acceptance" ? page.getByTestId("final-acceptance-workspace") : bench;
const approve = scope.getByRole("button", { name: mode === "quality" ? "审核通过" : "验收通过", exact: true });
if (mode === "final-acceptance")
await page.waitForFunction(() => {
const button = [...document.querySelectorAll("button")].find((b) => b.textContent.trim() === "验收通过");
return button && !button.disabled;
});
check(
(await approve.isVisible()) && (await approve.isEnabled()),
`${mode}: review decision disabled by annotation lock`,
);
await approve.click();
await bench.press("f");
await bench.press("Control+Enter");
check(
(await observe()).review.includes("approve") && (await observe()).review.includes("save-note"),
`${mode}: review writes unavailable`,
);
await bench.press("F9");
await page.waitForFunction(
() => JSON.parse(document.querySelector('[data-testid="permission-observation"]').textContent).reviewLocked,
);
const before = await observe();
for (const key of ["f", "Control+Enter", "Enter", "Shift+Delete", "1", "2"]) await bench.press(key);
const after = await observe();
check(JSON.stringify(before.review) === JSON.stringify(after.review), `${mode}: locked review shortcuts wrote`);
if (mode === "final-acceptance") {
await scope.press("f");
await scope.press("Control+Enter");
await scope.press("Shift+Delete");
check(
JSON.stringify(before.review) === JSON.stringify((await observe()).review),
"final acceptance parent bypassed write lock",
);
}
}
for (const phase of ["slice", "annotate"]) {
await open("annotation", false, phase);
const bench = page.getByTestId("capture-annotation-workbench"),
handle = bench.getByRole("button", { name: "拖动切片边界", exact: true }).first();
assert(await handle.isEnabled(), "positive authoring control must be editable");
await drag(handle);
check((await observe()).authoring.includes("slice-boundary"), `${phase}: author boundary editing regressed`);
await handle.scrollIntoViewIfNeeded();
const b = await handle.boundingBox();
await page.mouse.move(b.x + b.width / 2, b.y + b.height / 2);
await page.mouse.down();
await page.keyboard.press("F8");
await page.waitForFunction(
() => JSON.parse(document.querySelector('[data-testid="permission-observation"]').textContent).locked,
);
const before = await observe();
await page.mouse.move(b.x + b.width / 2 + 90, b.y + b.height / 2, { steps: 5 });
await page.mouse.up();
check(
JSON.stringify(before.authoring) === JSON.stringify((await observe()).authoring),
`${phase}: active drag survived permission loss`,
);
}
await open("annotation", false, "slice");
const bench = page.getByTestId("capture-annotation-workbench");
await bench.press("Escape");
await page.keyboard.down("Shift");
await page.keyboard.down("ArrowRight");
const held = await observe();
check(held.authoring.includes("slice-boundary"), "positive held boundary key did not move");
await page.keyboard.press("F8");
await page.waitForFunction(
() => JSON.parse(document.querySelector('[data-testid="permission-observation"]').textContent).locked,
);
await page.keyboard.up("ArrowRight");
await page.keyboard.up("Shift");
check(
JSON.stringify(held.authoring) === JSON.stringify((await observe()).authoring),
"held boundary key committed after permission loss",
);
check(report.errors.length === 0, "browser runtime errors");
check(report.unexpectedRequests.length === 0, "unexpected network writes");
console.log(JSON.stringify(report));
assert.deepEqual(report.failures, []);
} finally {
fs.writeFileSync(path.join(out, "report.json"), JSON.stringify(report, null, 2));
await browser?.close();
await server.close();
}