forked from longtao.wu/droboticflow
🐛 Fix October 15 annotation discard, claim and editing feedback
This commit is contained in:
parent
7aff5cf714
commit
14d6ed9c0a
@ -1,6 +1,6 @@
|
||||
# October 15 customer feedback follow-up
|
||||
|
||||
Status: claimed
|
||||
Status: resolved
|
||||
|
||||
## Acceptance
|
||||
|
||||
@ -23,3 +23,23 @@ Use the local replica (5173/3001/27018), isolated synthetic fixtures, frontend/G
|
||||
- feedback_baseline (Luna) lane: src/components/SliceEditPanel.tsx, src/components/DiscardReasonFields.tsx, src/components/WorkspaceDictionaryPanel.tsx and their targeted tests. Root supplies shared time formatter and F/D dispatcher. No global key listener.
|
||||
- claim_permissions (Luna) lane: internal/api/annotation_operations.go **handleAnnotationTaskGet only**, plus dedicated eligibility API tests. Root edits other functions in that same file; preserve both ranges. Agent does not commit or deploy.
|
||||
- All lanes read this ticket before editing. Keep file/function ownership above; report cross-lane needs to root. Only root stages and commits task changes.
|
||||
|
||||
## Implementation and compatibility
|
||||
|
||||
- The E panel applies `POST /api/plugins/annotation-qa/tasks/{id}/slice-edit-applications` with the complete workspace, explicit disposition commands, a version, and a per-application receipt ID. The server validates ownership, stage, frame boundaries, dictionaries and action containment; it prepares changes in memory and commits one CAS. Any invalid command or version conflict leaves the stored workspace unchanged.
|
||||
- Discard archives original actions, including pending/described/invalid states. Restore and persisted undo/redo use server-owned archives and merge evidence. A missing active partition in a discarded undo snapshot cannot erase the recovery archive. Continuous blank intervals after structure edits become pending actions, following the existing draft contract.
|
||||
- Ordinary draft/confirmation routes retain their explicit-disposition guard. Existing archives and stored times remain compatible. New receipt metadata is additive; there is no production migration or bulk data repair. Frontend and API must be released together for the new application endpoint.
|
||||
- Legacy G confirmation accepts a complete, valid persisted action partition without inventing a sliceWorkflow marker; full-video tasks additionally need saved generation evidence. Active/failed jobs, explicit incomplete workflows, wrong owners, pending submission and stale versions remain guarded.
|
||||
- Formal operations wait for an in-flight autosave and use its acknowledged version. Unknown write outcomes are read back before success is shown. The E panel remains open on failure and cannot cancel an application already being committed.
|
||||
- Detail responses ship `canClaim` after state recovery, using the same server eligibility calculation as the pool. The frontend renders this flag; supplier grants do not require a separate legacy project member record.
|
||||
|
||||
## Verification evidence (local only)
|
||||
|
||||
- Real local UI: E → F opens the slice dictionary; G → Enter selects the reason → Enter records the preview → Enter saves. Whole-slice discard, undo, redo and refresh preserve all 6 archived actions. The isolated `oct15-feedback-verify-task` was then submitted and reached quality review; the quality UI shows the discarded slice and its read-only original actions.
|
||||
- Real legacy local task: G persisted an invalid judgment without a workflow marker, then Undo restored the original action. A deliberately advanced synthetic version caused an E application to fail safely; the error appeared inside the panel and Esc discarded the preview.
|
||||
- Actual React autosave hook + deferred fake CAS: overlapping and sequential formal confirmations both used version 2 and confirmed successfully. Task/account lifetime guards remain in the existing hook tests.
|
||||
- Go integration tests cover first pass/rework, mixed action states, restart/readback, stale versions, a failed second command without partial writes, split/discard undo/redo, merge/archive undo, all-discarded save and submission, legacy draft confirmation, and supplier-grant detail eligibility.
|
||||
- `npm run test:go:gate`: 70 failures, all existing baseline cases; no new failures. `npm run test:frontend:gate`: 13 failures, all baseline cases (14 known). One old source-copy assertion was aligned with the already-approved continuous blank-action contract and current wording; this is not counted as a separate production fix.
|
||||
- TypeScript, script lint, Prettier, web build and `go build ./...` pass. Full `npm run lint` stops at two pre-existing unformatted files: `internal/domain/review_decision.go` and `internal/domain/review_draft.go`; both exactly match HEAD and are outside this change. Changed Go files pass gofmt.
|
||||
- Commit-hook note: the hook invokes whole-repository gofmt and is blocked by the two unchanged files above. Task-file gofmt, TypeScript and Prettier were verified separately; the local commit skips that hook without changing hook configuration.
|
||||
- Evidence is under ignored `local-data/verification/customer-feedback-20261015-new/` in the integration checkout. No company-cluster writes, push, PR update or deployment were performed for this follow-up.
|
||||
|
||||
103
internal/api/annotation_confirmation_readiness.go
Normal file
103
internal/api/annotation_confirmation_readiness.go
Normal file
@ -0,0 +1,103 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
)
|
||||
|
||||
// legacyAnnotationConfirmationReady recognizes persisted pre-workflow evidence
|
||||
// for tasks whose old records do not have sliceWorkflow. It never mutates the
|
||||
// item; the caller remains responsible for checking the submitted version.
|
||||
func (server *server) legacyAnnotationConfirmationReady(ctx context.Context, task domain.AnnotationTaskRecord, item *domain.HumanItemRecord) (bool, error) {
|
||||
if item == nil || item.PendingCombinedSubmissionID != "" {
|
||||
return false, nil
|
||||
}
|
||||
if item.ProcessingJob != nil && (item.ProcessingJob.Status == "queued" || item.ProcessingJob.Status == "running" || item.ProcessingJob.Status == "processing" || item.ProcessingJob.Status == "failed") {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if item.Subject.Payload != nil {
|
||||
if rawWorkflow, exists := item.Subject.Payload["sliceWorkflow"]; exists && rawWorkflow != nil {
|
||||
workflow := mapValue(rawWorkflow)
|
||||
return stringValue(workflow["status"]) == "completed" && stringValue(workflow["phase"]) == "annotate", nil
|
||||
}
|
||||
}
|
||||
|
||||
workspace := annotationWorkspacePayload(item)
|
||||
slices := decodeMaterializationValue[domain.SliceSegment](workspace["sliceSegments"])
|
||||
segments := decodeMaterializationValue[domain.AnnotationSegment](workspace["segments"])
|
||||
statuses := make(map[string]domain.SliceAnnotationStatus)
|
||||
for id, value := range mapValue(workspace["statuses"]) {
|
||||
if status := stringValue(value); status != "" {
|
||||
statuses[id] = domain.SliceAnnotationStatus(status)
|
||||
}
|
||||
}
|
||||
slices = (combinedAnnotationDraftInput{SliceSegments: slices, Segments: segments, Statuses: statuses}).normalizedSliceSegments()
|
||||
if len(slices) == 0 || len(segments) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
if len(validateSliceSegments(slices, task)) > 0 || len(validateCompleteSliceCoverage(slices, task)) > 0 || len(validateContinuousActions(slices, segments, false)) > 0 {
|
||||
return false, nil
|
||||
}
|
||||
seenActionIDs := make(map[string]struct{}, len(segments))
|
||||
for _, segment := range segments {
|
||||
id := strings.TrimSpace(segment.ID)
|
||||
if id == "" {
|
||||
return false, nil
|
||||
}
|
||||
if _, exists := seenActionIDs[id]; exists {
|
||||
return false, nil
|
||||
}
|
||||
seenActionIDs[id] = struct{}{}
|
||||
contained := 0
|
||||
for _, slice := range slices {
|
||||
if segment.Start >= slice.Start && segment.End <= slice.End {
|
||||
contained++
|
||||
}
|
||||
}
|
||||
if contained != 1 {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
if task.SourceIsFullVideo {
|
||||
evidence, err := server.hasLegacyAnnotationGenerationEvidence(ctx, task, item)
|
||||
if err != nil || !evidence {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (server *server) hasLegacyAnnotationGenerationEvidence(ctx context.Context, task domain.AnnotationTaskRecord, item *domain.HumanItemRecord) (bool, error) {
|
||||
if item.Subject.Payload != nil {
|
||||
materialization := mapValue(item.Subject.Payload["materialization"])
|
||||
if stringValue(materialization["status"]) == "completed" && intValue(materialization["revision"]) > 0 && stringValue(materialization["artifactId"]) != "" {
|
||||
if runID := stringValue(materialization["runId"]); runID == "" || runID == task.RunID {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slices, err := server.store.ListSliceRevisions(ctx, task.OrganizationID, task.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, revision := range slices {
|
||||
if revision.TaskID == task.ID && revision.Revision > 0 && len(revision.Segments) > 0 {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
annotations, err := server.store.ListAnnotationRevisions(ctx, task.OrganizationID, task.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, revision := range annotations {
|
||||
if revision.TaskID == task.ID && revision.Revision > 0 && len(revision.Segments) > 0 {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
200
internal/api/annotation_confirmation_readiness_test.go
Normal file
200
internal/api/annotation_confirmation_readiness_test.go
Normal file
@ -0,0 +1,200 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
)
|
||||
|
||||
func TestLegacyAnnotationConfirmationReadinessAcceptsPersistedActionPartitions(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
key string
|
||||
taskStatus domain.AnnotationTaskStatus
|
||||
}{
|
||||
{name: "first pass", key: "annotationWorkspace", taskStatus: domain.AnnotationTaskStatusPendingAnnotation},
|
||||
{name: "legacy draft fallback", key: "annotationDraft", taskStatus: domain.AnnotationTaskStatusPendingAnnotation},
|
||||
{name: "rework", key: "annotationWorkspace", taskStatus: domain.AnnotationTaskStatusRework},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
task := fixture.task
|
||||
task.Status = tc.taskStatus
|
||||
item := withLegacyActionPartition(fixture.item)
|
||||
item.Subject.Payload[tc.key] = legacyActionPartition()
|
||||
ready, err := (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, task, &item)
|
||||
if err != nil || !ready {
|
||||
t.Fatalf("legacy action partition ready=%v err=%v", ready, err)
|
||||
}
|
||||
stored, err := fixture.store.GetHumanItem(fixture.ctx, fixture.item.ID)
|
||||
if err != nil || stored == nil || stored.Version != fixture.item.Version {
|
||||
t.Fatalf("readiness check mutated persisted item: item=%#v err=%v", stored, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyAnnotationConfirmationReadinessRejectsMissingOrInvalidActions(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
segments []domain.AnnotationSegment
|
||||
}{
|
||||
{name: "no actions"},
|
||||
{name: "gap in action partition", segments: []domain.AnnotationSegment{{ID: "a", Start: 0, End: 4, Status: "pending"}}},
|
||||
{name: "crosses slice boundary", segments: []domain.AnnotationSegment{{ID: "a", Start: 0, End: 10, Status: "pending"}}},
|
||||
{name: "invalid action state", segments: []domain.AnnotationSegment{{ID: "a", Start: 0, End: 10, Status: "unknown"}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
item := withLegacyActionPartition(fixture.item)
|
||||
workspace := legacyActionPartition()
|
||||
if tc.segments == nil {
|
||||
delete(workspace, "segments")
|
||||
} else {
|
||||
workspace["segments"] = tc.segments
|
||||
}
|
||||
if tc.name == "crosses slice boundary" {
|
||||
workspace["sliceSegments"] = []domain.SliceSegment{
|
||||
{ID: "slice-1", Start: 0, End: 5, AnnotationStatus: domain.SliceAnnotationPending},
|
||||
{ID: "slice-2", Start: 5, End: 10, AnnotationStatus: domain.SliceAnnotationPending},
|
||||
}
|
||||
workspace["statuses"] = map[string]domain.SliceAnnotationStatus{"slice-1": domain.SliceAnnotationPending, "slice-2": domain.SliceAnnotationPending}
|
||||
}
|
||||
item.Subject.Payload["annotationWorkspace"] = workspace
|
||||
ready, err := (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, fixture.task, &item)
|
||||
if err != nil || ready {
|
||||
t.Fatalf("invalid legacy actions ready=%v err=%v", ready, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyAnnotationConfirmationReadinessRequiresExplicitWorkflowCompletion(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status string
|
||||
phase string
|
||||
}{
|
||||
{name: "editing", status: "editing", phase: "slice"},
|
||||
{name: "slice", status: "completed", phase: "slice"},
|
||||
{name: "failed", status: "failed", phase: "materializing"},
|
||||
{name: "processing", status: "processing", phase: "materializing"},
|
||||
{name: "queued", status: "queued", phase: "materializing"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
item := fixture.item
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": tc.status, "phase": tc.phase}
|
||||
ready, err := (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, fixture.task, &item)
|
||||
if err != nil || ready {
|
||||
t.Fatalf("workflow %s/%s ready=%v err=%v", tc.status, tc.phase, ready, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
item := fixture.item
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed", "phase": "annotate"}
|
||||
ready, err := (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, fixture.task, &item)
|
||||
if err != nil || !ready {
|
||||
t.Fatalf("completed annotation workflow ready=%v err=%v", ready, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyAnnotationConfirmationReadinessRejectsPendingSubmissionAndActiveJob(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mutate func(*domain.HumanItemRecord)
|
||||
}{
|
||||
{name: "pending submission", mutate: func(item *domain.HumanItemRecord) { item.PendingCombinedSubmissionID = "pending" }},
|
||||
{name: "queued job", mutate: func(item *domain.HumanItemRecord) {
|
||||
item.ProcessingJob = &domain.AnnotationProcessingJob{Status: "queued"}
|
||||
}},
|
||||
{name: "running job", mutate: func(item *domain.HumanItemRecord) {
|
||||
item.ProcessingJob = &domain.AnnotationProcessingJob{Status: "running"}
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
item := withLegacyActionPartition(fixture.item)
|
||||
item.Subject.Payload["annotationWorkspace"] = legacyActionPartition()
|
||||
tc.mutate(&item)
|
||||
ready, err := (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, fixture.task, &item)
|
||||
if err != nil || ready {
|
||||
t.Fatalf("blocked state ready=%v err=%v", ready, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyAnnotationConfirmationReadinessRequiresFullVideoGenerationEvidence(t *testing.T) {
|
||||
for _, evidence := range []string{"materialization", "formal revision"} {
|
||||
t.Run(evidence, func(t *testing.T) {
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
task := fixture.task
|
||||
task.SourceIsFullVideo = true
|
||||
task.SourceDurationSeconds = 10
|
||||
item := withLegacyActionPartition(fixture.item)
|
||||
item.Subject.Payload["annotationWorkspace"] = legacyActionPartition()
|
||||
ready, err := (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, task, &item)
|
||||
if err != nil || ready {
|
||||
t.Fatalf("ungenerated full-source task ready=%v err=%v", ready, err)
|
||||
}
|
||||
|
||||
if evidence == "materialization" {
|
||||
item.Subject.Payload["materialization"] = map[string]any{"status": "completed", "revision": 1, "artifactId": "materialized-legacy", "runId": task.RunID}
|
||||
} else if err := fixture.store.UpsertSliceRevision(fixture.ctx, domain.SliceRevisionRecord{
|
||||
ID: "legacy-slice-revision", OrganizationID: task.OrganizationID, TaskID: task.ID, Revision: 1,
|
||||
Segments: []domain.SliceSegment{{ID: "slice-1", Start: 0, End: 10}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ready, err = (&server{store: fixture.store}).legacyAnnotationConfirmationReady(fixture.ctx, task, &item)
|
||||
if err != nil || !ready {
|
||||
t.Fatalf("generated full-source task ready=%v err=%v", ready, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func withLegacyActionPartition(item domain.HumanItemRecord) domain.HumanItemRecord {
|
||||
if item.Subject.Payload == nil {
|
||||
item.Subject.Payload = map[string]any{}
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func legacyActionPartition() map[string]any {
|
||||
return map[string]any{
|
||||
"sliceSegments": []domain.SliceSegment{{ID: "slice-1", Start: 0, End: 10, AnnotationStatus: domain.SliceAnnotationPending}},
|
||||
"segments": []domain.AnnotationSegment{
|
||||
{ID: "action-1", Start: 0, End: 5, Status: "pending"},
|
||||
{ID: "action-2", Start: 5, End: 10, Status: "pending"},
|
||||
},
|
||||
"statuses": map[string]domain.SliceAnnotationStatus{"slice-1": domain.SliceAnnotationPending},
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyAnnotationConfirmationHTTPUsesPersistedDraftAndStillRejectsStaleWrites(t *testing.T) {
|
||||
f := continuousFixture(t)
|
||||
item := f.item
|
||||
slices := []domain.SliceSegment{{ID: "s", Name: "测试切片", Start: 0, End: 10}}
|
||||
actions := []domain.AnnotationSegment{{ID: "a", Start: 0, End: 10, Status: "pending"}}
|
||||
item.Subject.Payload["annotationDraft"] = map[string]any{"sliceSegments": slices, "segments": actions, "userId": f.annotator.ID}
|
||||
f.store.UpsertHumanItem(f.ctx, item)
|
||||
confirmed := []domain.AnnotationSegment{{ID: "a", Start: 0, End: 10, Status: "invalid", IsInvalid: true, Description: "无效片段"}}
|
||||
body := combinedAnnotationDraftInput{Version: item.Version, SliceSegments: slices, Segments: confirmed}
|
||||
endpoint := "/api/plugins/annotation-qa/tasks/" + f.task.ID + "/annotation-confirmations"
|
||||
r := f.request("POST", endpoint, f.annotator, body)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("legacy G confirmation %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
if saved.Version != item.Version+1 || saved.Subject.Payload["sliceWorkflow"] != nil {
|
||||
t.Fatal("legacy compatibility must not forge a completion marker")
|
||||
}
|
||||
r = f.request("POST", endpoint, f.annotator, body)
|
||||
if r.Code != 409 {
|
||||
t.Fatalf("stale G should conflict: %d", r.Code)
|
||||
}
|
||||
}
|
||||
@ -1024,6 +1024,21 @@ func (server *server) handleAnnotationTaskGet(writer http.ResponseWriter, reques
|
||||
sliceRevisions, revisions = currentSlices, currentAnnotations
|
||||
}
|
||||
}
|
||||
if linkedHumanItem != nil && principal != nil {
|
||||
claimable := false
|
||||
availableStatus := linkedHumanItem.Status == domain.HumanItemReady || linkedHumanItem.Status == domain.HumanItemRework || linkedHumanItem.Status == domain.HumanItemSubmitted
|
||||
if linkedHumanItem.AssignedUserID == "" && availableStatus {
|
||||
batch, batchErr := server.humanBatchForListRead(request.Context(), linkedHumanItem.BatchID)
|
||||
if batchErr != nil {
|
||||
renderError(writer, http.StatusInternalServerError, batchErr)
|
||||
return
|
||||
}
|
||||
if stage, _, found := humanStage(batch, linkedHumanItem.CurrentStageID); found {
|
||||
claimable = server.canClaimHumanItem(request.Context(), request, *linkedHumanItem, annotationRoleForHumanStage(stage))
|
||||
}
|
||||
}
|
||||
linkedHumanItem.CanClaim = &claimable
|
||||
}
|
||||
renderJSON(writer, http.StatusOK, map[string]any{"task": item, "sliceRevisions": sliceRevisions, "revisions": revisions, "reviews": reviews, "humanItem": linkedHumanItem})
|
||||
}
|
||||
|
||||
@ -1814,7 +1829,12 @@ func (server *server) handleAnnotationConfirmationCreate(writer http.ResponseWri
|
||||
if rejectPendingCombinedSubmission(writer, item) {
|
||||
return
|
||||
}
|
||||
if stringValue(sliceWorkflow["status"]) != "completed" || stringValue(sliceWorkflow["phase"]) != "annotate" {
|
||||
ready, readinessErr := server.legacyAnnotationConfirmationReady(request.Context(), *task, item)
|
||||
if readinessErr != nil {
|
||||
renderError(writer, http.StatusInternalServerError, readinessErr)
|
||||
return
|
||||
}
|
||||
if !ready {
|
||||
renderJSON(writer, http.StatusConflict, map[string]string{
|
||||
"error": "all Capture slices must be materialized before descriptions can be confirmed",
|
||||
"code": "slice_materialization_required",
|
||||
|
||||
150
internal/api/annotation_task_claim_eligibility_test.go
Normal file
150
internal/api/annotation_task_claim_eligibility_test.go
Normal file
@ -0,0 +1,150 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
)
|
||||
|
||||
func TestAnnotationTaskDetailShipsServerClaimEligibilityForSupplierGrant(t *testing.T) {
|
||||
fixture := newCombinedDraftFixture(t)
|
||||
grantReviewer := domain.UserRecord{
|
||||
ID: "grant-only-reviewer", OrganizationID: domain.DefaultOrganizationID,
|
||||
SupplierID: fixture.reviewer.SupplierID, Role: domain.UserRoleQualityReviewer,
|
||||
Status: domain.UserStatusActive,
|
||||
}
|
||||
if err := fixture.store.UpsertUser(fixture.ctx, grantReviewer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fixture.store.SetSupplierProjectAuthorization(fixture.ctx, domain.DefaultOrganizationID, fixture.task.ProjectID, grantReviewer.SupplierID, true, fixture.admin.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
batch, err := fixture.store.GetHumanBatch(fixture.ctx, fixture.item.BatchID)
|
||||
if err != nil || batch == nil {
|
||||
t.Fatalf("load batch: batch=%#v err=%v", batch, err)
|
||||
}
|
||||
batch.ProcessingProfile = domain.ProcessingProfileRawHuman
|
||||
batch.Stages = domain.DefaultFanyuV58HumanStages()
|
||||
if err := fixture.store.UpsertHumanBatch(fixture.ctx, *batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task := fixture.task
|
||||
task.SupplierID = grantReviewer.SupplierID
|
||||
task.ProcessingProfile = domain.ProcessingProfileRawHuman
|
||||
task.Status = domain.AnnotationTaskStatusPendingQuality
|
||||
if err := fixture.store.UpsertAnnotationTask(fixture.ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item := fixture.item
|
||||
item.SupplierID = grantReviewer.SupplierID
|
||||
item.ProcessingProfile = domain.ProcessingProfileRawHuman
|
||||
item.CurrentStageID = domain.FanyuV58StageQualityReview
|
||||
item.Status = domain.HumanItemReady
|
||||
item.AssignedUserID = ""
|
||||
if err := fixture.store.UpsertHumanItem(fixture.ctx, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
path := "/api/plugins/annotation-qa/tasks/" + task.ID
|
||||
read := func(user domain.UserRecord) (*http.Response, map[string]json.RawMessage, error) {
|
||||
recorder := fixture.request(http.MethodGet, path, user, nil)
|
||||
var body map[string]json.RawMessage
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
return recorder.Result(), nil, err
|
||||
}
|
||||
return recorder.Result(), body, nil
|
||||
}
|
||||
assertCanClaim := func(user domain.UserRecord, want bool) {
|
||||
t.Helper()
|
||||
response, body, err := read(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
t.Fatalf("detail status=%d body=%v", response.StatusCode, body)
|
||||
}
|
||||
var detail struct {
|
||||
HumanItem struct {
|
||||
CanClaim *bool `json:"canClaim"`
|
||||
} `json:"humanItem"`
|
||||
}
|
||||
if err := json.Unmarshal(mustJSON(t, body), &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.HumanItem.CanClaim == nil || *detail.HumanItem.CanClaim != want {
|
||||
t.Fatalf("detail humanItem.canClaim=%v want %v; response=%s", detail.HumanItem.CanClaim, want, mustJSON(t, body))
|
||||
}
|
||||
}
|
||||
|
||||
assertCanClaim(grantReviewer, true)
|
||||
|
||||
// The same active project grant does not make a task claimable once owned,
|
||||
// processing, or terminal. Detail access remains governed by the existing
|
||||
// read authorization path.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status domain.HumanItemStatus
|
||||
owner string
|
||||
}{
|
||||
{name: "assigned", status: domain.HumanItemReady, owner: grantReviewer.ID},
|
||||
{name: "processing", status: domain.HumanItemClaimed, owner: grantReviewer.ID},
|
||||
{name: "terminal", status: domain.HumanItemAccepted},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
updated := item
|
||||
updated.Status, updated.AssignedUserID = tc.status, tc.owner
|
||||
if err := fixture.store.UpsertHumanItem(fixture.ctx, updated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertCanClaim(grantReviewer, false)
|
||||
})
|
||||
}
|
||||
|
||||
// Revoke the grant while the task is unstarted and unassigned. This user
|
||||
// must lose detail access instead of receiving a claimable candidate.
|
||||
if _, err := fixture.store.SetSupplierProjectAuthorization(fixture.ctx, domain.DefaultOrganizationID, task.ProjectID, grantReviewer.SupplierID, false, fixture.admin.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := item
|
||||
if err := fixture.store.UpsertHumanItem(fixture.ctx, updated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revoked := fixture.request(http.MethodGet, path, grantReviewer, nil)
|
||||
if revoked.Code != http.StatusForbidden {
|
||||
t.Fatalf("revoked grant detail status=%d body=%s", revoked.Code, revoked.Body.String())
|
||||
}
|
||||
|
||||
// No authorization also cannot expose a detail payload with a guessed flag.
|
||||
noGrant := grantReviewer
|
||||
noGrant.ID, noGrant.SupplierID = "no-grant-reviewer", "supplier-without-task-grant"
|
||||
if err := fixture.store.UpsertSupplier(fixture.ctx, domain.SupplierRecord{ID: noGrant.SupplierID, OrganizationID: domain.DefaultOrganizationID, Name: "Unrelated supplier", Status: "active"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fixture.store.UpsertUser(fixture.ctx, noGrant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
withoutGrant := fixture.request(http.MethodGet, path, noGrant, nil)
|
||||
if withoutGrant.Code != http.StatusForbidden {
|
||||
t.Fatalf("missing grant detail status=%d body=%s", withoutGrant.Code, withoutGrant.Body.String())
|
||||
}
|
||||
|
||||
stored, err := fixture.store.GetHumanItem(fixture.ctx, item.ID)
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("load final item: item=%#v err=%v", stored, err)
|
||||
}
|
||||
if stored.Status != item.Status || stored.Version != item.Version || stored.AssignedUserID != "" {
|
||||
t.Fatalf("detail GET changed persisted item: %#v", stored)
|
||||
}
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, value any) []byte {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
@ -1533,6 +1533,7 @@ func NewHandlerWithConfig(dataStore store.Store, aiService ai.Service, appConfig
|
||||
router.Put("/api/plugins/annotation-qa/tasks/{id}/drafts", instance.handleCombinedAnnotationDraftPut)
|
||||
router.Post("/api/plugins/annotation-qa/tasks/{id}/annotation-confirmations", instance.handleAnnotationConfirmationCreate)
|
||||
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-edit-restorations", instance.handleSliceEditRestoration)
|
||||
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-edit-applications", instance.handleSliceEditApplication)
|
||||
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-dispositions", instance.handleSliceDisposition)
|
||||
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-confirmations", instance.handleSliceConfirmationCreate)
|
||||
router.Post("/api/plugins/annotation-qa/tasks/{id}/slice-reset", instance.handleSliceResetCreate)
|
||||
|
||||
@ -418,9 +418,33 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
|
||||
return
|
||||
}
|
||||
workspace, next, prepared := s.prepareSliceDisposition(w, r, task, item, p.User.ID, body)
|
||||
if !prepared {
|
||||
return
|
||||
}
|
||||
version := item.Version
|
||||
item.Version++
|
||||
item.UpdatedAt = nowISO()
|
||||
won, e := s.store.UpdateHumanItemVersioned(r.Context(), *item, version)
|
||||
if e != nil {
|
||||
renderError(w, 500, e)
|
||||
return
|
||||
}
|
||||
if !won {
|
||||
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
|
||||
return
|
||||
}
|
||||
_ = s.appendHumanEvent(r.Context(), *item, "slice_disposition_changed", p.User.ID, map[string]any{"sliceId": next.ID, "disposition": body.Disposition, "reason": next.DiscardReason, "reasonLabelId": next.DiscardReasonLabelID, "reasonVersion": next.DiscardReasonVersion, "reasonNote": next.DiscardReasonNote, "start": next.Start, "end": next.End})
|
||||
renderJSON(w, 200, map[string]any{"item": item, "workspace": workspace})
|
||||
}
|
||||
|
||||
// prepareSliceDisposition updates only this in-memory item. Callers commit one CAS
|
||||
// after every command and structure validation succeeds.
|
||||
func (s *server) prepareSliceDisposition(w http.ResponseWriter, r *http.Request, task *domain.AnnotationTaskRecord, item *domain.HumanItemRecord, actorID string, body sliceDispositionInput) (map[string]any, domain.SliceSegment, bool) {
|
||||
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
|
||||
if body.Disposition != "keep" && body.Disposition != "discard" {
|
||||
renderValidationError(w, validationIssue{Field: "disposition", Message: "用途必须为 keep 或 discard"})
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
body.Reason = strings.TrimSpace(body.Reason)
|
||||
body.ReasonNote = strings.TrimSpace(body.ReasonNote)
|
||||
@ -430,7 +454,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
reasonLabel, issues = s.resolveDiscardReason(r.Context(), item, body)
|
||||
if len(issues) > 0 {
|
||||
renderValidationError(w, issues...)
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
if reasonLabel != nil {
|
||||
body.Reason = reasonLabel.Name
|
||||
@ -447,7 +471,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
timeline, e := s.annotationFrameTimelineForTask(r.Context(), *task, "left")
|
||||
if e != nil {
|
||||
renderJSON(w, 422, map[string]string{"error": e.Error()})
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
task.CoverageStartSecond = floatValue(timeline["rangeStartSecond"])
|
||||
task.CoverageEndSecond = floatValue(timeline["rangeEndSecond"])
|
||||
@ -467,7 +491,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
if len(issues) > 0 {
|
||||
renderValidationError(w, describeSliceNameIssues(issues, slices)...)
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
before := slices[idx]
|
||||
restoredName := ""
|
||||
@ -476,7 +500,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
restoredName, found = sliceNameBeforeDiscard(item, before.ID, body.RestoreNameFromVersion)
|
||||
if body.RestoreNameFromVersion != 0 && (!found || !before.IsDiscarded() || body.Disposition != "keep") {
|
||||
renderValidationError(w, validationIssue{Field: "restoreNameFromVersion", Message: "只能恢复当前切片本轮编辑中已记录的舍弃前名称"})
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
}
|
||||
next := before
|
||||
@ -517,7 +541,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
next.DiscardReasonName = reasonLabel.Name
|
||||
}
|
||||
next.DiscardReasonNote = body.ReasonNote
|
||||
next.DiscardedByUserID = p.User.ID
|
||||
next.DiscardedByUserID = actorID
|
||||
next.DiscardedAt = nowISO()
|
||||
next.AnnotationStatus = domain.SliceAnnotationPending
|
||||
kept := []domain.AnnotationSegment{}
|
||||
@ -527,7 +551,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
archived = append(archived, a)
|
||||
} else if a.Start < next.End && a.End > next.Start {
|
||||
renderValidationError(w, validationIssue{Field: "segments", Message: "描述跨越切片边界,请先修正"})
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
} else {
|
||||
kept = append(kept, a)
|
||||
}
|
||||
@ -546,7 +570,7 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
if archiveIssues := validateDraftCombinedAnnotationEvents(next.DiscardedAnnotations, *task); len(archiveIssues) > 0 {
|
||||
renderValidationError(w, archiveIssues...)
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
segments = kept
|
||||
} else {
|
||||
@ -593,16 +617,16 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
issues = validateDraftCombinedAnnotationEvents(segments, *task)
|
||||
if len(issues) > 0 {
|
||||
renderValidationError(w, describeSliceNameIssues(issues, slices)...)
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
statuses := body.normalizedStatuses()
|
||||
statuses[next.ID] = domain.SliceAnnotationPending
|
||||
workspace := map[string]any{"sliceSegments": slices, "segments": segments, "statuses": statuses, "operations": body.normalizedOperations(), "userId": p.User.ID, "savedAt": nowISO()}
|
||||
workspace := map[string]any{"sliceSegments": slices, "segments": segments, "statuses": statuses, "operations": body.normalizedOperations(), "userId": actorID, "savedAt": nowISO()}
|
||||
if item.Subject.Payload == nil {
|
||||
item.Subject.Payload = map[string]any{}
|
||||
}
|
||||
history, _ := normalizeStructuredValue(item.Subject.Payload["sliceDispositionHistory"]).([]any)
|
||||
history = append(history, map[string]any{"sliceId": next.ID, "before": before, "after": next, "actorUserId": p.User.ID, "at": nowISO(), "itemVersion": item.Version + 1})
|
||||
history = append(history, map[string]any{"sliceId": next.ID, "before": before, "after": next, "actorUserId": actorID, "at": nowISO(), "itemVersion": item.Version + 1})
|
||||
item.Subject.Payload["sliceDispositionHistory"] = history
|
||||
item.Subject.Payload[sliceRestoreEvidenceKey] = retainedEvidence
|
||||
item.Subject.Payload[sliceArchiveEditsKey] = archiveEdits
|
||||
@ -612,21 +636,8 @@ func (s *server) handleSliceDisposition(w http.ResponseWriter, r *http.Request)
|
||||
// Frame validation can be slow; reject a dictionary change made while it ran.
|
||||
if _, issues := s.resolveDiscardReason(r.Context(), item, body); len(issues) > 0 {
|
||||
renderValidationError(w, issues...)
|
||||
return
|
||||
return nil, domain.SliceSegment{}, false
|
||||
}
|
||||
}
|
||||
version := item.Version
|
||||
item.Version++
|
||||
item.UpdatedAt = nowISO()
|
||||
won, e := s.store.UpdateHumanItemVersioned(r.Context(), *item, version)
|
||||
if e != nil {
|
||||
renderError(w, 500, e)
|
||||
return
|
||||
}
|
||||
if !won {
|
||||
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
|
||||
return
|
||||
}
|
||||
_ = s.appendHumanEvent(r.Context(), *item, "slice_disposition_changed", p.User.ID, map[string]any{"sliceId": next.ID, "disposition": body.Disposition, "reason": body.Reason, "reasonLabelId": next.DiscardReasonLabelID, "reasonVersion": next.DiscardReasonVersion, "reasonNote": next.DiscardReasonNote, "start": next.Start, "end": next.End})
|
||||
renderJSON(w, 200, map[string]any{"item": item, "workspace": workspace})
|
||||
return workspace, next, true
|
||||
}
|
||||
|
||||
325
internal/api/slice_edit_application.go
Normal file
325
internal/api/slice_edit_application.go
Normal file
@ -0,0 +1,325 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type sliceEditApplicationInput struct {
|
||||
combinedAnnotationDraftInput
|
||||
ApplicationID string `json:"applicationId"`
|
||||
Dispositions []sliceDispositionInput `json:"dispositions"`
|
||||
}
|
||||
|
||||
// A panel application is one CAS, including explicit disposition commands and
|
||||
// archive/recovery evidence. Preparation never writes the persistent item.
|
||||
func (s *server) handleSliceEditApplication(w http.ResponseWriter, r *http.Request) {
|
||||
task, err := s.getAnnotationTaskForAccess(r.Context(), chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
renderError(w, 500, err)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
renderJSON(w, 404, map[string]string{"error": "Annotation task not found"})
|
||||
return
|
||||
}
|
||||
principal, memberships, ok := s.ensureAnnotationTaskAccess(w, r, *task)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if principal == nil || principal.User.Role != domain.UserRoleAnnotator || !membershipHasRole(memberships, *task, domain.AnnotationRoleAnnotator) {
|
||||
renderJSON(w, 403, map[string]string{"error": "annotator assignment is required"})
|
||||
return
|
||||
}
|
||||
stored, ok := s.requireLegacyHumanItemClaim(w, r, *task, domain.FanyuV58StageAnnotationCombined)
|
||||
if !ok || rejectPendingCombinedSubmission(w, stored) {
|
||||
return
|
||||
}
|
||||
workflow := mapValue(stored.Subject.Payload["sliceWorkflow"])
|
||||
switch stringValue(workflow["status"]) {
|
||||
case "processing", "running", "materializing", "queued", "failed":
|
||||
renderJSON(w, 409, map[string]string{"error": "切片尚未就绪,请完成或恢复生成后再应用改动"})
|
||||
return
|
||||
}
|
||||
if job := stored.ProcessingJob; job != nil && (job.Status == "queued" || job.Status == "running" || job.Status == "processing" || job.Status == "failed") {
|
||||
renderJSON(w, 409, map[string]string{"error": "任务处理尚未就绪,请完成或恢复后再应用改动"})
|
||||
return
|
||||
}
|
||||
var body sliceEditApplicationInput
|
||||
if !decodeJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if body.ApplicationID == "" || len(body.ApplicationID) > 128 {
|
||||
renderValidationError(w, validationIssue{Field: "applicationId", Message: "缺少本次切片应用标识"})
|
||||
return
|
||||
}
|
||||
if body.Version != stored.Version {
|
||||
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
|
||||
return
|
||||
}
|
||||
item := *stored
|
||||
item.Subject.Payload = mapValue(stored.Subject.Payload)
|
||||
if item.Subject.Payload == nil {
|
||||
item.Subject.Payload = map[string]any{}
|
||||
}
|
||||
proposed := body.normalizedSliceSegments()
|
||||
ids := map[string]bool{}
|
||||
for _, slice := range proposed {
|
||||
ids[slice.ID] = true
|
||||
}
|
||||
commands := map[string]sliceDispositionInput{}
|
||||
for _, command := range body.Dispositions {
|
||||
if command.SliceID == "" || commands[command.SliceID].SliceID != "" || (command.Disposition != "keep" && command.Disposition != "discard") {
|
||||
renderValidationError(w, validationIssue{Field: "dispositions", Message: "切片用途操作无效或重复"})
|
||||
return
|
||||
}
|
||||
commands[command.SliceID] = command
|
||||
}
|
||||
originalSlices := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(&item)["sliceSegments"])
|
||||
// Undo can first restore a discarded child before rejoining it. The restore
|
||||
// remains an explicit, audited command in the same atomic application.
|
||||
for _, command := range body.Dispositions {
|
||||
if !ids[command.SliceID] {
|
||||
if command.Disposition != "keep" {
|
||||
renderValidationError(w, validationIssue{Field: "dispositions", Message: "舍弃操作必须保留目标切片"})
|
||||
return
|
||||
}
|
||||
// A deliberate cancel-cut already records both source policies and
|
||||
// archives in canonical merge evidence. Do not erase that evidence
|
||||
// by restoring the removed source before recording the merge.
|
||||
merged := false
|
||||
for _, candidate := range proposed {
|
||||
for _, source := range explicitSliceMerge(originalSlices, candidate) {
|
||||
if source.ID == command.SliceID {
|
||||
merged = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if merged {
|
||||
continue
|
||||
}
|
||||
current := annotationWorkspacePayload(&item)
|
||||
command.combinedAnnotationDraftInput = workspaceSliceEditInput(current)
|
||||
if _, _, ok := s.prepareSliceDisposition(w, r, task, &item, principal.User.ID, command); !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
previous := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(&item)["sliceSegments"])
|
||||
if len(previous) == 0 {
|
||||
revisions, e := s.store.ListSliceRevisions(r.Context(), item.OrganizationID, task.ID)
|
||||
if e != nil {
|
||||
renderError(w, 500, e)
|
||||
return
|
||||
}
|
||||
for _, rev := range revisions {
|
||||
if rev.Revision == item.CurrentRevision || len(previous) == 0 {
|
||||
previous = rev.Segments
|
||||
}
|
||||
}
|
||||
}
|
||||
previous = previousForSliceMergeUndo(&item, previous, proposed)
|
||||
// Neutralize only explicitly commanded policy changes before canonicalizing
|
||||
// geometry. Archives and audit identity always come from the saved server state.
|
||||
baseline := append([]domain.SliceSegment(nil), proposed...)
|
||||
for i, candidate := range baseline {
|
||||
if _, changed := commands[candidate.ID]; changed {
|
||||
old := domain.SliceSegment{}
|
||||
for _, saved := range previous {
|
||||
if saved.ID == candidate.ID {
|
||||
old = saved
|
||||
break
|
||||
}
|
||||
for _, id := range candidate.SourceIDs {
|
||||
if id == saved.ID {
|
||||
old = saved
|
||||
break
|
||||
}
|
||||
}
|
||||
if old.ID != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
baseline[i] = sliceEditPolicyBaseline(candidate, old)
|
||||
}
|
||||
}
|
||||
slices, issues := s.canonicalSliceDispositionState(r.Context(), &item, baseline, body.normalizedOperations())
|
||||
issues = append(issues, s.validateSliceEditFrameBounds(r, task, &item, slices, body.Segments)...)
|
||||
issues = append(issues, validateSliceSegments(slices, *task)...)
|
||||
issues = append(issues, validateCompleteSliceCoverage(slices, *task)...)
|
||||
issues = append(issues, validateDraftCombinedAnnotationEvents(body.Segments, *task)...)
|
||||
if len(issues) > 0 {
|
||||
renderValidationError(w, issues...)
|
||||
return
|
||||
}
|
||||
// Restoring an existing discarded target owns its original actions. Snapshot
|
||||
// undo can include the same actions already; do not append a second copy or
|
||||
// trust client replacements for this archived interval.
|
||||
segmentsForApplication := body.normalizedSegments()
|
||||
// Persisted undo snapshots of a discarded slice contain no active actions.
|
||||
// An explicit re-discard must archive the current server-owned actions rather
|
||||
// than treating that omission as deletion of the recovery evidence.
|
||||
savedActions := decodeMaterializationValue[domain.AnnotationSegment](annotationWorkspacePayload(&item)["segments"])
|
||||
for _, slice := range slices {
|
||||
command, exists := commands[slice.ID]
|
||||
if !exists || command.Disposition != "discard" || slice.IsDiscarded() {
|
||||
continue
|
||||
}
|
||||
hasActions := false
|
||||
for _, action := range segmentsForApplication {
|
||||
if action.Start < slice.End && action.End > slice.Start {
|
||||
hasActions = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasActions {
|
||||
for _, action := range savedActions {
|
||||
if action.Start >= slice.Start && action.End <= slice.End {
|
||||
segmentsForApplication = append(segmentsForApplication, action)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, slice := range slices {
|
||||
if command, exists := commands[slice.ID]; exists && command.Disposition == "keep" && slice.IsDiscarded() {
|
||||
retained := []domain.AnnotationSegment{}
|
||||
for _, action := range segmentsForApplication {
|
||||
if action.Start < slice.Start || action.End > slice.End {
|
||||
retained = append(retained, action)
|
||||
}
|
||||
}
|
||||
segmentsForApplication = retained
|
||||
}
|
||||
}
|
||||
workspace := map[string]any{"sliceSegments": slices, "segments": segmentsForApplication, "statuses": body.normalizedStatuses(), "operations": body.normalizedOperations(), "userId": principal.User.ID, "savedAt": nowISO()}
|
||||
item.Subject.Payload["annotationWorkspace"] = workspace
|
||||
delete(item.Subject.Payload, "annotationDraft")
|
||||
for _, command := range body.Dispositions {
|
||||
if ids[command.SliceID] {
|
||||
command.combinedAnnotationDraftInput = workspaceSliceEditInput(workspace)
|
||||
var prepared bool
|
||||
workspace, _, prepared = s.prepareSliceDisposition(w, r, task, &item, principal.User.ID, command)
|
||||
if !prepared {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
slices = decodeMaterializationValue[domain.SliceSegment](workspace["sliceSegments"])
|
||||
segments := decodeMaterializationValue[domain.AnnotationSegment](workspace["segments"])
|
||||
// A restored slice may be renamed in the same panel transaction.
|
||||
for i := range slices {
|
||||
for _, candidate := range proposed {
|
||||
if candidate.ID == slices[i].ID && !slices[i].IsDiscarded() {
|
||||
slices[i].Name = candidate.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
issues = s.validateProjectSliceNames(r.Context(), &item, slices, "draft")
|
||||
issues = append(issues, s.validateSliceEditFrameBounds(r, task, &item, slices, segments)...)
|
||||
issues = append(issues, validateDraftCombinedAnnotationEvents(segments, *task)...)
|
||||
template, e := s.store.GetAnnotationTemplate(r.Context(), task.TemplateID)
|
||||
if e != nil {
|
||||
renderError(w, 500, e)
|
||||
return
|
||||
}
|
||||
issues = append(issues, validateDraftFanyuV5CombinedSemanticSegments(segments, slices, annotationTemplateWithTaskSnapshot(template, task))...)
|
||||
if s.continuousActionsForItem(r.Context(), &item) {
|
||||
segments = fillPendingActionGaps(slices, segments)
|
||||
issues = append(issues, validateContinuousActions(slices, segments, false)...)
|
||||
}
|
||||
if len(issues) > 0 {
|
||||
renderValidationError(w, issues...)
|
||||
return
|
||||
}
|
||||
statuses := workspaceSliceEditInput(workspace).normalizedStatuses()
|
||||
if s.continuousActionsForItem(r.Context(), &item) {
|
||||
statuses = continuousSliceStatuses(slices, segments)
|
||||
}
|
||||
for i := range slices {
|
||||
slices[i].AnnotationStatus = statuses[slices[i].ID]
|
||||
}
|
||||
workspace["sliceSegments"], workspace["segments"], workspace["statuses"] = slices, segments, statuses
|
||||
item.Subject.Payload["annotationWorkspace"] = workspace
|
||||
// Recheck dictionary versions immediately before the single commit.
|
||||
for _, command := range body.Dispositions {
|
||||
if command.Disposition == "discard" {
|
||||
if _, issues := s.resolveDiscardReason(r.Context(), &item, command); len(issues) > 0 {
|
||||
renderValidationError(w, issues...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
item.Subject.Payload["lastSliceEditApplication"] = map[string]any{"id": body.ApplicationID, "actorUserId": principal.User.ID, "version": item.Version + 1}
|
||||
item.Version++
|
||||
item.UpdatedAt = nowISO()
|
||||
won, e := s.store.UpdateHumanItemVersioned(r.Context(), item, body.Version)
|
||||
if e != nil {
|
||||
renderError(w, 500, e)
|
||||
return
|
||||
}
|
||||
if !won {
|
||||
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "任务已变化,请刷新后重试"})
|
||||
return
|
||||
}
|
||||
_ = s.appendHumanEvent(r.Context(), item, "slice_edit_applied", principal.User.ID, map[string]any{"sliceCount": len(slices), "dispositionCount": len(body.Dispositions)})
|
||||
renderJSON(w, 200, map[string]any{"item": item, "workspace": workspace})
|
||||
}
|
||||
|
||||
func workspaceSliceEditInput(workspace map[string]any) combinedAnnotationDraftInput {
|
||||
statuses := map[string]domain.SliceAnnotationStatus{}
|
||||
for id, status := range mapValue(workspace["statuses"]) {
|
||||
statuses[id] = domain.SliceAnnotationStatus(stringValue(status))
|
||||
}
|
||||
return combinedAnnotationDraftInput{SliceSegments: decodeMaterializationValue[domain.SliceSegment](workspace["sliceSegments"]), Segments: decodeMaterializationValue[domain.AnnotationSegment](workspace["segments"]), Operations: decodeMaterializationValue[domain.SliceOperation](workspace["operations"]), Statuses: statuses}
|
||||
}
|
||||
|
||||
func sliceEditPolicyBaseline(candidate, old domain.SliceSegment) domain.SliceSegment {
|
||||
candidate.DeliveryDisposition = sliceDisposition(old)
|
||||
candidate.DiscardReason = old.DiscardReason
|
||||
candidate.DiscardReasonLabelID = old.DiscardReasonLabelID
|
||||
candidate.DiscardReasonVersion = old.DiscardReasonVersion
|
||||
candidate.DiscardReasonName = old.DiscardReasonName
|
||||
candidate.DiscardReasonNote = old.DiscardReasonNote
|
||||
candidate.DiscardedAt = old.DiscardedAt
|
||||
candidate.DiscardedByUserID = old.DiscardedByUserID
|
||||
candidate.DiscardedAnnotations = old.DiscardedAnnotations
|
||||
return candidate
|
||||
}
|
||||
|
||||
func (s *server) validateSliceEditFrameBounds(r *http.Request, task *domain.AnnotationTaskRecord, item *domain.HumanItemRecord, slices []domain.SliceSegment, segments []domain.AnnotationSegment) []validationIssue {
|
||||
if !task.SourceIsFullVideo && stringValue(mapValue(item.Subject.Payload["sliceWorkflow"])["boundaryContract"]) != "hardware-frame-v1" {
|
||||
return nil
|
||||
}
|
||||
timeline, err := s.annotationFrameTimelineForTask(r.Context(), *task, "left")
|
||||
if err != nil {
|
||||
return []validationIssue{{Field: "sliceSegments", Message: "无法核对切片帧边界,请稍后重试"}}
|
||||
}
|
||||
if task.SourceIsFullVideo {
|
||||
task.CoverageStartSecond = floatValue(timeline["rangeStartSecond"])
|
||||
task.CoverageEndSecond = floatValue(timeline["rangeEndSecond"])
|
||||
task.CoverageMode = "full_common_range"
|
||||
}
|
||||
grid := annotationBoundaryGrid{Seconds: timeline["boundariesSeconds"].([]float64), Timestamps: timeline["boundaryTimestampUs"].([]int64)}
|
||||
var issues []validationIssue
|
||||
resolve := func(start, end *float64, startUS, endUS *int64, field string) {
|
||||
a, ae := grid.resolve(*start)
|
||||
b, be := grid.resolve(*end)
|
||||
if ae != nil || be != nil || b <= a {
|
||||
issues = append(issues, validationIssue{Field: field, Message: "切片和动作边界必须与有效帧对齐"})
|
||||
return
|
||||
}
|
||||
*start, *end = grid.Seconds[a], grid.Seconds[b]
|
||||
*startUS, *endUS = grid.Timestamps[a], grid.Timestamps[b]
|
||||
}
|
||||
for i := range slices {
|
||||
v := &slices[i]
|
||||
resolve(&v.Start, &v.End, &v.StartTimestampUS, &v.EndTimestampUS, "sliceSegments")
|
||||
}
|
||||
for i := range segments {
|
||||
v := &segments[i]
|
||||
resolve(&v.Start, &v.End, &v.StartTimestampUS, &v.EndTimestampUS, "segments")
|
||||
}
|
||||
return issues
|
||||
}
|
||||
203
internal/api/slice_edit_application_test.go
Normal file
203
internal/api/slice_edit_application_test.go
Normal file
@ -0,0 +1,203 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"droboticflow/internal/domain"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSliceEditApplicationDiscardsAndRestoresWholeSliceAtomically(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)
|
||||
before := []domain.SliceSegment{{ID: "a", Name: "测试切片", Start: 0, End: 5}, {ID: "b", Name: "测试切片", Start: 5, End: 10}}
|
||||
actions := []domain.AnnotationSegment{{ID: "pending", Start: 0, End: 2, Status: "pending"}, {ID: "described", Start: 2, End: 4, Status: "described", Description: "synthetic action"}, {ID: "invalid", Start: 4, End: 5, Status: "invalid", IsInvalid: true, Description: "无效片段"}, {ID: "other", Start: 5, End: 10, Status: "pending"}}
|
||||
item := f.item
|
||||
item.ReviewRound = 0
|
||||
if rework {
|
||||
item.ReviewRound = 1
|
||||
}
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed", "phase": "annotate"}
|
||||
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": before, "segments": actions}
|
||||
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proposed := append([]domain.SliceSegment(nil), before...)
|
||||
proposed[0].DeliveryDisposition = "discard"
|
||||
proposed[0].DiscardReason = "相机被遮挡"
|
||||
proposed[0].DiscardedByUserID = "forged"
|
||||
cmd := sliceDispositionInput{SliceID: "a", Disposition: "discard", ReasonLabelID: reason.ReasonLabelID, ReasonVersion: reason.ReasonVersion}
|
||||
input := sliceEditApplicationInput{ApplicationID: "application-1", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: item.Version, SliceSegments: proposed, Segments: actions}, Dispositions: []sliceDispositionInput{cmd}}
|
||||
endpoint := "/api/plugins/annotation-qa/tasks/" + f.task.ID + "/slice-edit-applications"
|
||||
r := f.request(http.MethodPost, 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"`
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if got.Item.Version != item.Version+1 || len(got.Workspace.Segments) != 1 || len(got.Workspace.SliceSegments[0].DiscardedAnnotations) != 3 || got.Workspace.SliceSegments[0].DiscardedByUserID != f.annotator.ID {
|
||||
t.Fatalf("not atomic/archive-safe: %#v", got.Workspace)
|
||||
}
|
||||
// A fresh handler reads the persisted state; no process-local success illusion.
|
||||
f.handler = NewHandler(f.store, nil)
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
if saved.Version != got.Item.Version || !decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(saved)["sliceSegments"])[0].IsDiscarded() {
|
||||
t.Fatal("discard not persisted")
|
||||
}
|
||||
if stale := f.request(http.MethodPost, endpoint, f.annotator, input); stale.Code != 409 {
|
||||
t.Fatalf("stale accepted: %d", stale.Code)
|
||||
}
|
||||
restore := sliceEditApplicationInput{ApplicationID: "application-2", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: got.Item.Version, SliceSegments: before, Segments: actions}, Dispositions: []sliceDispositionInput{{SliceID: "a", Disposition: "keep"}}}
|
||||
r = f.request(http.MethodPost, endpoint, f.annotator, restore)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("restore %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if len(got.Workspace.Segments) != 4 || got.Workspace.SliceSegments[0].IsDiscarded() {
|
||||
t.Fatal("restore lost original actions")
|
||||
}
|
||||
// Redo uses the persisted discarded snapshot, which has no active
|
||||
// actions for a. Its archive must still contain all three originals.
|
||||
redo := sliceEditApplicationInput{ApplicationID: "redo", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: got.Item.Version, SliceSegments: proposed, Segments: actions[3:]}, Dispositions: []sliceDispositionInput{cmd}}
|
||||
r = f.request("POST", endpoint, f.annotator, redo)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("redo %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if len(got.Workspace.SliceSegments[0].DiscardedAnnotations) != 3 {
|
||||
t.Fatalf("redo dropped archive: %+v", got.Workspace.SliceSegments[0])
|
||||
}
|
||||
restore.Version = got.Item.Version
|
||||
r = f.request("POST", endpoint, f.annotator, restore)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("restore after redo %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
json.Unmarshal(r.Body.Bytes(), &got)
|
||||
if len(got.Workspace.Segments) != 4 {
|
||||
t.Fatal("redo/restore lost actions")
|
||||
}
|
||||
// Failure of the second command must not leave the first one applied.
|
||||
original, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
input.Version = got.Item.Version
|
||||
input.ApplicationID = "application-fail"
|
||||
input.Dispositions = append(input.Dispositions, sliceDispositionInput{SliceID: "b", Disposition: "discard", ReasonLabelID: "missing", ReasonVersion: 1})
|
||||
r = f.request(http.MethodPost, endpoint, f.annotator, input)
|
||||
if r.Code == 200 {
|
||||
t.Fatal("invalid dictionary accepted")
|
||||
}
|
||||
unchanged, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
if !reflect.DeepEqual(original, unchanged) {
|
||||
t.Fatal("partial batch survived a failed command")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliceEditApplicationRejectsUncommandedPolicyAndProcessing(t *testing.T) {
|
||||
f := continuousFixture(t)
|
||||
input := sliceEditApplicationInput{ApplicationID: "bad", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: f.item.Version, SliceSegments: []domain.SliceSegment{{ID: "s", Start: 0, End: 10, DeliveryDisposition: "discard", DiscardReason: "forged"}}}}
|
||||
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.Fatal("uncommanded discard accepted")
|
||||
}
|
||||
item := f.item
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "processing", "phase": "materializing"}
|
||||
f.store.UpsertHumanItem(f.ctx, item)
|
||||
r = f.request("POST", endpoint, f.annotator, input)
|
||||
if r.Code != 409 {
|
||||
t.Fatalf("processing %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Exercise the panel's split/discard followed by persisted undo and redo. The
|
||||
// removed discarded child must be restored explicitly before its parent rejoins.
|
||||
func TestSliceEditApplicationSplitDiscardUndoRedoAndSubmit(t *testing.T) {
|
||||
f := continuousFixture(t)
|
||||
reason := dispositionFixturePayload(t, f)
|
||||
seedCompletedMaterialization(t, f, 1)
|
||||
original := []domain.SliceSegment{{ID: "parent", Name: "测试切片", Start: 0, End: 10}}
|
||||
actions := []domain.AnnotationSegment{{ID: "left", Start: 0, End: 5, Status: "pending"}, {ID: "right", Start: 5, End: 10, Status: "pending"}}
|
||||
item, _ := f.store.GetHumanItem(f.ctx, f.item.ID)
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed", "phase": "annotate"}
|
||||
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": original, "segments": actions}
|
||||
f.store.UpsertHumanItem(f.ctx, *item)
|
||||
endpoint := "/api/plugins/annotation-qa/tasks/" + f.task.ID
|
||||
split := []domain.SliceSegment{{ID: "child-left", SourceIDs: []string{"parent"}, Start: 0, End: 5, DeliveryDisposition: "discard", DiscardReason: "相机被遮挡"}, {ID: "child-right", SourceIDs: []string{"parent"}, Name: "测试切片", Start: 5, End: 10}}
|
||||
call := func(id string, slices []domain.SliceSegment, segments []domain.AnnotationSegment, commands []sliceDispositionInput) combinedAnnotationDraftInput {
|
||||
t.Helper()
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, f.item.ID)
|
||||
r := f.request("POST", endpoint+"/slice-edit-applications", f.annotator, sliceEditApplicationInput{ApplicationID: id, combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: saved.Version, SliceSegments: slices, Segments: segments}, Dispositions: commands})
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("%s %d %s", id, r.Code, r.Body.String())
|
||||
}
|
||||
var got struct {
|
||||
Workspace combinedAnnotationDraftInput `json:"workspace"`
|
||||
}
|
||||
if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got.Workspace
|
||||
}
|
||||
discard := []sliceDispositionInput{{SliceID: "child-left", Disposition: "discard", ReasonLabelID: reason.ReasonLabelID, ReasonVersion: reason.ReasonVersion}}
|
||||
got := call("split", split, actions, discard)
|
||||
if len(got.Segments) != 1 || len(got.SliceSegments[0].DiscardedAnnotations) != 1 {
|
||||
t.Fatalf("split lost evidence: %+v", got)
|
||||
}
|
||||
got = call("undo", original, actions, []sliceDispositionInput{{SliceID: "child-left", Disposition: "keep"}})
|
||||
if len(got.SliceSegments) != 1 || len(got.Segments) != 2 || got.SliceSegments[0].IsDiscarded() {
|
||||
t.Fatalf("undo lost actions: %+v", got)
|
||||
}
|
||||
got = call("redo", split, actions, discard)
|
||||
if len(got.Segments) != 1 || len(got.SliceSegments[0].DiscardedAnnotations) != 1 {
|
||||
t.Fatal("redo failed")
|
||||
}
|
||||
// Discard the remaining half; all-discarded submissions require no active actions.
|
||||
all := append([]domain.SliceSegment(nil), got.SliceSegments...)
|
||||
all[1].DeliveryDisposition = "discard"
|
||||
got = call("discard-rest", all, got.Segments, []sliceDispositionInput{{SliceID: "child-right", Disposition: "discard", ReasonLabelID: reason.ReasonLabelID, ReasonVersion: reason.ReasonVersion}})
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, f.item.ID)
|
||||
got.Version = saved.Version
|
||||
if r := f.request("PUT", endpoint+"/drafts", f.annotator, got); r.Code != 200 {
|
||||
t.Fatalf("save progress %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
saved, _ = f.store.GetHumanItem(f.ctx, f.item.ID)
|
||||
got.Version = saved.Version
|
||||
r := f.request("POST", endpoint+"/combined-submissions", f.annotator, got)
|
||||
if r.Code != 201 && r.Code != 202 {
|
||||
t.Fatalf("submit discarded %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliceEditApplicationMergeAndUndoPreserveDiscardedSourceEvidence(t *testing.T) {
|
||||
f := continuousFixture(t)
|
||||
reason := dispositionFixturePayload(t, f)
|
||||
slices := []domain.SliceSegment{{ID: "a", Name: "测试切片", Start: 0, End: 5}, {ID: "b", Start: 5, End: 10, DeliveryDisposition: "discard", DiscardReason: "相机被遮挡", DiscardReasonLabelID: reason.ReasonLabelID, DiscardReasonVersion: reason.ReasonVersion, DiscardedAnnotations: []domain.AnnotationSegment{{ID: "archive", Start: 5, End: 10, Status: "invalid", IsInvalid: true}}}}
|
||||
actions := []domain.AnnotationSegment{{ID: "active", Start: 0, End: 5, Status: "pending"}}
|
||||
item := f.item
|
||||
item.Subject.Payload["annotationWorkspace"] = map[string]any{"sliceSegments": slices, "segments": actions}
|
||||
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "completed", "phase": "annotate"}
|
||||
f.store.UpsertHumanItem(f.ctx, item)
|
||||
endpoint := "/api/plugins/annotation-qa/tasks/" + f.task.ID + "/slice-edit-applications"
|
||||
merged := []domain.SliceSegment{{ID: "a", Start: 0, End: 10, SourceIDs: []string{"a", "b"}}}
|
||||
r := f.request("POST", endpoint, f.annotator, sliceEditApplicationInput{ApplicationID: "merge", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: item.Version, SliceSegments: merged}, Dispositions: []sliceDispositionInput{{SliceID: "b", Disposition: "keep"}}})
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("merge %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
saved, _ := f.store.GetHumanItem(f.ctx, item.ID)
|
||||
r = f.request("POST", endpoint, f.annotator, sliceEditApplicationInput{ApplicationID: "undo-merge", combinedAnnotationDraftInput: combinedAnnotationDraftInput{Version: saved.Version, SliceSegments: slices, Segments: actions}, Dispositions: []sliceDispositionInput{{SliceID: "b", Disposition: "discard", ReasonLabelID: reason.ReasonLabelID, ReasonVersion: reason.ReasonVersion}}})
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("undo merge %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
saved, _ = f.store.GetHumanItem(f.ctx, item.ID)
|
||||
got := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(saved)["sliceSegments"])
|
||||
if len(got) != 2 || len(got[1].DiscardedAnnotations) != 1 || got[1].DiscardedAnnotations[0].ID != "archive" {
|
||||
t.Fatalf("merge undo lost original archive: %+v", got)
|
||||
}
|
||||
}
|
||||
14
src/App.tsx
14
src/App.tsx
@ -1,3 +1,4 @@
|
||||
import { annotationLandingPath } from "./lib/annotation-landing.js";
|
||||
/**
|
||||
* @license
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
@ -157,6 +158,17 @@ function RoleRouteGuard({ children }: { children: React.ReactNode }) {
|
||||
return children;
|
||||
}
|
||||
|
||||
function HomeLanding() {
|
||||
const { currentUser } = useUser();
|
||||
const location = useLocation();
|
||||
const landing = annotationLandingPath(currentUser?.role);
|
||||
return landing && new URLSearchParams(location.search).get("view") !== "dashboard" ? (
|
||||
<Navigate to={landing} replace />
|
||||
) : (
|
||||
<Dashboard />
|
||||
);
|
||||
}
|
||||
|
||||
function ApplicationRoutes() {
|
||||
return (
|
||||
<Layout>
|
||||
@ -164,7 +176,7 @@ function ApplicationRoutes() {
|
||||
<Suspense fallback={<RouteFallback />}>
|
||||
<RoleRouteGuard>
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/" element={<HomeLanding />} />
|
||||
<Route path="/projects" element={<Projects />} />
|
||||
<Route path="/project/:id" element={<ProjectDetail />} />
|
||||
<Route path="/operators" element={<Operators />} />
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
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 type { ReviewViewingProps, ReviewViewingController, ReviewPosition, ReviewNavigation } from "./review-viewing";
|
||||
@ -149,6 +151,7 @@ type Props = ReviewViewingProps & {
|
||||
discardReasons?: AnnotationLabelRecord[];
|
||||
discardReasonsLoading?: boolean;
|
||||
discardReasonsAllowManual?: boolean;
|
||||
operationError?: string;
|
||||
discardReasonsError?: string;
|
||||
onRefreshDiscardReasons?: () => void;
|
||||
sliceDictionary?: { id: string; name: string }[];
|
||||
@ -235,7 +238,11 @@ type Props = ReviewViewingProps & {
|
||||
* (切片 + 冲突解析后的动作产物)作为一次原子落库交给页面侧(applySliceChange
|
||||
* 同款:一条可撤销历史 + 状态重推导)。返回 false 表示页面当前不接受改动。
|
||||
*/
|
||||
onApplySliceEdit?: (slices: SliceSegment[], segments: AnnotationSegment[], focusSliceId: string) => boolean;
|
||||
onApplySliceEdit?: (
|
||||
slices: SliceSegment[],
|
||||
segments: AnnotationSegment[],
|
||||
focusSliceId: string,
|
||||
) => boolean | Promise<boolean>;
|
||||
/**
|
||||
* 切片重设面板会话通道(验收修复 C):面板打开(true)与整体关闭(false,
|
||||
* Enter 应用或 Esc 取消)时通知页面——页面据此暂停草稿自动落盘(快照引用
|
||||
@ -291,15 +298,7 @@ type Props = ReviewViewingProps & {
|
||||
|
||||
import { annotationTimelineColors as colors } from "../lib/annotation-colors.js";
|
||||
|
||||
const formatTime = (seconds: number) => {
|
||||
// Convert once: subtracting integer seconds can turn 4.1 into a displayed
|
||||
// 04.099 through floating-point cancellation. Preserve millisecond truncation.
|
||||
const totalMilliseconds = Math.floor(Math.max(0, seconds) * 1000 + 1e-7);
|
||||
const minutes = Math.floor(totalMilliseconds / 60000);
|
||||
const wholeSeconds = Math.floor(totalMilliseconds / 1000) % 60;
|
||||
const milliseconds = totalMilliseconds % 1000;
|
||||
return `${String(minutes).padStart(2, "0")}:${String(wholeSeconds).padStart(2, "0")}.${String(milliseconds).padStart(3, "0")}`;
|
||||
};
|
||||
const formatTime = formatAnnotationTime;
|
||||
|
||||
const frameStep = 1 / 30;
|
||||
|
||||
@ -337,6 +336,7 @@ export function CaptureAnnotationWorkbench({
|
||||
discardReasons = [],
|
||||
discardReasonsLoading = false,
|
||||
discardReasonsAllowManual = false,
|
||||
operationError = "",
|
||||
discardReasonsError = "",
|
||||
onRefreshDiscardReasons,
|
||||
sliceDictionary = [],
|
||||
@ -1600,6 +1600,7 @@ export function CaptureAnnotationWorkbench({
|
||||
if (target) openSliceEditPanel(target);
|
||||
};
|
||||
const cancelSliceEditPanel = () => {
|
||||
if (saving || sliceEditApplyingRef.current) return;
|
||||
// Esc/E 整体回退:预览从未落库,丢弃预览即回到打开面板时的快照(R1-Q1);
|
||||
// D6 驻留一并清空——Esc 是显式全弃,收起驻留不允许在取消后复活。
|
||||
setSliceEditPanel(null);
|
||||
@ -1704,9 +1705,10 @@ export function CaptureAnnotationWorkbench({
|
||||
);
|
||||
if (target.deliveryDisposition !== "discard") onRefreshDiscardReasons?.();
|
||||
};
|
||||
const commitSliceEditPanel = (choices: Partial<Record<string, SliceEditChoice>>) => {
|
||||
const sliceEditApplyingRef = useRef(false);
|
||||
const commitSliceEditPanel = async (choices: Partial<Record<string, SliceEditChoice>>) => {
|
||||
const panel = sliceEditPanel;
|
||||
if (!panel) return;
|
||||
if (!panel || sliceEditApplyingRef.current) return;
|
||||
// 经由具名输入绕开 JSDoc 推断的窄参数类型(引擎实现源是 JS + JSDoc)。
|
||||
const resolveInput = {
|
||||
baseSlices: panel.snapshot.slices,
|
||||
@ -1718,19 +1720,26 @@ export function CaptureAnnotationWorkbench({
|
||||
// Enter 落库前自检(03 引擎的 Go 守卫前端镜像):状态白名单 + 「动作完整落在
|
||||
// 恰好一个切片」(ADR 0007 / T3 钉死)。逐片无缝铺满校验刻意不跑——标注相草稿
|
||||
// 允许留空缺口(词汇表「保存进度」),那是提交守卫而非结构改动守卫。
|
||||
const preview = previewSliceEditDispositions(panel.snapshot.slices, resolution.slices, resolution.actions);
|
||||
const issues = [
|
||||
...validateActionStatuses(resolution.actions),
|
||||
...assertActionsCoveredByExactlyOneSlice(resolution.actions, resolution.slices),
|
||||
...validateActionStatuses(preview.actions),
|
||||
...assertActionsCoveredByExactlyOneSlice(preview.actions, preview.slices),
|
||||
];
|
||||
if (issues.length) {
|
||||
setError(`切片改动未通过提交自检:${issues[0].message};已取消应用(可按 Esc 回退)。`);
|
||||
return;
|
||||
}
|
||||
const applied = onApplySliceEdit?.(
|
||||
resolution.slices as SliceSegment[],
|
||||
resolution.actions as AnnotationSegment[],
|
||||
panel.sliceId,
|
||||
);
|
||||
sliceEditApplyingRef.current = true;
|
||||
let applied: boolean | void;
|
||||
try {
|
||||
applied = await onApplySliceEdit?.(
|
||||
resolution.slices as SliceSegment[],
|
||||
resolution.actions as AnnotationSegment[],
|
||||
panel.sliceId,
|
||||
);
|
||||
} finally {
|
||||
sliceEditApplyingRef.current = false;
|
||||
}
|
||||
if (applied === false) {
|
||||
setError("当前状态暂不能应用切片改动,请稍后重试,或按 Esc 取消。");
|
||||
return;
|
||||
@ -3083,6 +3092,14 @@ export function CaptureAnnotationWorkbench({
|
||||
);
|
||||
else if (command === "split") panelSplitAtPlayhead();
|
||||
else if (command === "discard") panelDiscardDraftOpen();
|
||||
else if (command === "dictionary") {
|
||||
if (!sliceEditDiscardDraft)
|
||||
workbenchRef.current
|
||||
?.querySelector<HTMLButtonElement>(
|
||||
"[data-slice-edit-dictionary-trigger] button[aria-haspopup='dialog']:not(:disabled)",
|
||||
)
|
||||
?.click();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (command === "pass") {
|
||||
@ -3227,6 +3244,8 @@ export function CaptureAnnotationWorkbench({
|
||||
void onHistoryCommand?.(action);
|
||||
else if (action === "discard-dictionary") openDisposition();
|
||||
else if (action === "save") requestStageConfirmation(true);
|
||||
else if (action === "toggle-slice-edit" && phase === "annotate" && !readOnly && !isQualityReview && !mediaOnly)
|
||||
openSliceEditPanel();
|
||||
else if (canEdit) {
|
||||
if (action === "adjust-boundary") startBoundaryHold(event.key === "ArrowLeft" ? -1 : 1);
|
||||
else if (action === "coarse-nudge-boundary") coarseNudgeSliceBoundary(event.key === "ArrowLeft" ? -1 : 1);
|
||||
@ -3245,7 +3264,6 @@ export function CaptureAnnotationWorkbench({
|
||||
// 票 04(R1-Q1):E 改派切片重设面板(专注浮层 + Enter 应用/Esc 回退);旧
|
||||
// 切片编辑模式自此刻起无入口,06 票随旧横幅一并清除。rework-ux-adjust 04
|
||||
// (D1):单切片任务同样直开(面板内 C 可加边界),unavailable 提示分支删除。
|
||||
else if (action === "toggle-slice-edit" && phase === "annotate") openSliceEditPanel();
|
||||
else if (action === "new" && phase === "annotate" && sliceAligned) addAnnotation();
|
||||
else if (action === "confirm-end" && selectingEnd && editingAnnotation) confirmEndSelection();
|
||||
else if (action === "edit-description" && editingAnnotation && !selectingEnd)
|
||||
@ -3257,6 +3275,14 @@ export function CaptureAnnotationWorkbench({
|
||||
}
|
||||
}}
|
||||
>
|
||||
{!sliceEditPanel && (operationError || error) ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="sticky top-0 z-50 rounded border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-800 dark:bg-rose-950 dark:text-rose-200"
|
||||
>
|
||||
{userErrorMessage(operationError || error)}
|
||||
</div>
|
||||
) : null}
|
||||
{continuousActions && phase === "annotate" && (
|
||||
<aside className="capture-action-list" aria-label="当前切片动作列表">
|
||||
<strong>动作 · {actionListForRender.length}</strong>
|
||||
@ -3374,7 +3400,7 @@ export function CaptureAnnotationWorkbench({
|
||||
? "切片"
|
||||
: opinion.scope === "action"
|
||||
? "动作"
|
||||
: `${(opinion.atSeconds ?? 0).toFixed(2)}s`}
|
||||
: `${formatTime(opinion.atSeconds ?? 0)}`}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-words">{opinion.text}</span>
|
||||
</li>
|
||||
@ -4330,7 +4356,7 @@ export function CaptureAnnotationWorkbench({
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`时间点意见 ${cluster.opinions.length > 1 ? `${cluster.opinions.length} 条` : cluster.opinions[0].text.slice(0, 12)}`}
|
||||
title={cluster.opinions.map((o) => `${o.atSeconds.toFixed(2)}s ${o.text}`).join("\n")}
|
||||
title={cluster.opinions.map((o) => `${formatTime(o.atSeconds)} ${o.text}`).join("\n")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (cluster.opinions.length > 1)
|
||||
@ -4354,7 +4380,7 @@ export function CaptureAnnotationWorkbench({
|
||||
}}
|
||||
className="block w-full truncate rounded px-1 py-0.5 text-left text-slate-600 hover:bg-orange-50 dark:text-slate-300 dark:hover:bg-orange-950/30"
|
||||
>
|
||||
{o.atSeconds.toFixed(2)}s {o.text}
|
||||
{formatTime(o.atSeconds)} {o.text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@ -4403,7 +4429,7 @@ export function CaptureAnnotationWorkbench({
|
||||
type="button"
|
||||
aria-label={`返工时间点意见 ${cluster.opinions.length > 1 ? `${cluster.opinions.length} 条` : cluster.opinions[0].text.slice(0, 12)}`}
|
||||
title={cluster.opinions
|
||||
.map((o) => `${o.atSeconds.toFixed(2)}s${o.state === "red" ? " ⚠" : ""} ${o.text}`)
|
||||
.map((o) => `${formatTime(o.atSeconds)}${o.state === "red" ? " ⚠" : ""} ${o.text}`)
|
||||
.join("\n")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
@ -4668,7 +4694,7 @@ export function CaptureAnnotationWorkbench({
|
||||
? "切片"
|
||||
: op.scope === "action"
|
||||
? `动作${actionIndexLabel(op.actionId)}`
|
||||
: `时间点 ${(op.atSeconds ?? 0).toFixed(2)}s`}
|
||||
: `时间点 ${formatTime(op.atSeconds ?? 0)}`}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-words">{op.text}</span>
|
||||
{op.reattached && (
|
||||
@ -4744,7 +4770,7 @@ export function CaptureAnnotationWorkbench({
|
||||
<span className="font-mono text-xs text-slate-600 dark:text-gray-300">
|
||||
{formatTime(selectedSlice.start)} ~ {formatTime(selectedSlice.end)}
|
||||
<span className="ml-1 text-slate-400">
|
||||
({(selectedSlice.end - selectedSlice.start).toFixed(2)}s)
|
||||
({formatTime(selectedSlice.end - selectedSlice.start)})
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
@ -4995,7 +5021,7 @@ export function CaptureAnnotationWorkbench({
|
||||
</h3>
|
||||
<span className="font-mono text-xs text-slate-500">
|
||||
({formatTime(selectedSlice.start)} ~ {formatTime(selectedSlice.end)} · 时长{" "}
|
||||
{(selectedSlice.end - selectedSlice.start).toFixed(2)}s)
|
||||
{formatTime(selectedSlice.end - selectedSlice.start)})
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-xs flex items-center gap-1.5 text-slate-500">
|
||||
@ -5251,7 +5277,7 @@ export function CaptureAnnotationWorkbench({
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono text-[10px] text-slate-500">
|
||||
{(segment.end - segment.start).toFixed(2)}s
|
||||
{formatTime(segment.end - segment.start)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@ -5390,7 +5416,7 @@ export function CaptureAnnotationWorkbench({
|
||||
<span className="font-semibold text-white">动作 #{hoveredSegment.index + 1}</span>
|
||||
</span>
|
||||
<span className="font-mono text-xs font-semibold text-orange-300">
|
||||
{(hoveredSegment.segment.end - hoveredSegment.segment.start).toFixed(2)}s
|
||||
{formatTime(hoveredSegment.segment.end - hoveredSegment.segment.start)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1.5 flex items-center gap-2 font-mono text-[10px] text-slate-400">
|
||||
@ -5530,7 +5556,7 @@ export function CaptureAnnotationWorkbench({
|
||||
<span className="font-mono text-xs text-slate-500">
|
||||
{formatTime(editingAnnotation.start - lowerAnnotation)} ~{" "}
|
||||
{formatTime(editingAnnotation.end - lowerAnnotation)} (时长{" "}
|
||||
{(editingAnnotation.end - editingAnnotation.start).toFixed(2)}s)
|
||||
{formatTime(editingAnnotation.end - editingAnnotation.start)})
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@ -5595,7 +5621,7 @@ export function CaptureAnnotationWorkbench({
|
||||
<span className="font-mono text-xs text-slate-500">
|
||||
{formatTime(editingAnnotation.start - lowerAnnotation)} ~{" "}
|
||||
{formatTime(editingAnnotation.end - lowerAnnotation)} (时长{" "}
|
||||
{(editingAnnotation.end - editingAnnotation.start).toFixed(2)}s)
|
||||
{formatTime(editingAnnotation.end - editingAnnotation.start)})
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@ -6352,7 +6378,8 @@ export function CaptureAnnotationWorkbench({
|
||||
exactFrames={exactFrames}
|
||||
frameIndexOf={(time) => nearestFrameBoundaryIndex(frameBoundaries, time)}
|
||||
saving={Boolean(saving)}
|
||||
playheadLabel={`${currentTime.toFixed(2)}s`}
|
||||
playheadLabel={formatTime(currentTime)}
|
||||
error={operationError || error}
|
||||
onFocusBoundary={(field) =>
|
||||
setSliceEditPanel((panel) =>
|
||||
panel && panel.focusBoundary !== field ? { ...panel, focusBoundary: field } : panel,
|
||||
|
||||
@ -103,8 +103,12 @@ export function DiscardReasonFields({
|
||||
}
|
||||
onSelect={(id) => {
|
||||
const item = items.find((item) => item.id === id);
|
||||
if (item && !loading && !error) onChange({ ...value, reasonLabelId: item.id, reasonVersion: item.version });
|
||||
if (item && !loading && !error) {
|
||||
onChange({ ...value, reasonLabelId: item.id, reasonVersion: item.version });
|
||||
if (workspace) panelRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
onKeyboardSelect={() => panelRef.current?.focus()}
|
||||
onClose={onClose}
|
||||
onDismiss={() => {}}
|
||||
/>
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { formatAnnotationTime } from "../lib/annotation-time.js";
|
||||
import { userErrorMessage } from "../lib/user-error-message.js";
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import type { useReviewDraft } from "../hooks/useReviewDraft";
|
||||
@ -100,7 +101,7 @@ export function ReviewProblemPanel({ review, label, writeLocked = false, focused
|
||||
onClick={() => review.selectProblem(p)}
|
||||
className={`block w-full rounded px-1 py-0.5 text-left text-xs hover:bg-orange-50 data-review-focus:bg-rose-50 data-review-focus:font-semibold dark:hover:bg-orange-950/20 dark:data-review-focus:bg-rose-950/30${opinionKey(p) === activeTimestampKey ? " font-semibold" : ""}`}
|
||||
>
|
||||
<span className="font-mono text-slate-500">{(p.atSeconds ?? 0).toFixed(2)}s</span>{" "}
|
||||
<span className="font-mono text-slate-500">{formatAnnotationTime(p.atSeconds ?? 0)}</span>{" "}
|
||||
<span>{p.text}</span>
|
||||
</button>
|
||||
))}
|
||||
@ -122,7 +123,9 @@ export function ReviewProblemPanel({ review, label, writeLocked = false, focused
|
||||
{card.problems.length > 1 ? `${i + 1}. ` : ""}
|
||||
{p.text}
|
||||
{card.problems.length > 1 && p.scope !== "task" && (
|
||||
<span className="block text-xs text-slate-500">记录位置:{p.atSeconds.toFixed(3)} 秒</span>
|
||||
<span className="block text-xs text-slate-500">
|
||||
记录位置:{formatAnnotationTime(p.atSeconds)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { formatAnnotationTime } from "../lib/annotation-time.js";
|
||||
import type { ReworkEmphasisView, ReworkOpinionView } from "../lib/rework-emphasis-types";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
@ -94,7 +95,7 @@ export function ReworkOpinionRail({
|
||||
? `切片${sliceLabel ? ` ${sliceLabel}` : ""}`
|
||||
: opinion.scope === "action"
|
||||
? `动作${actionIndex ? ` #${actionIndex}` : ""}${sliceLabel ? ` · ${sliceLabel}` : ""}`
|
||||
: `时间点 ${(opinion.atSeconds ?? 0).toFixed(2)}s${sliceLabel ? ` · ${sliceLabel}` : ""}`;
|
||||
: `时间点 ${formatAnnotationTime(opinion.atSeconds ?? 0)}${sliceLabel ? ` · ${sliceLabel}` : ""}`;
|
||||
return (
|
||||
<div
|
||||
key={`${opinion.round}:${opinion.id}`}
|
||||
|
||||
@ -64,7 +64,7 @@ const navItems: readonly NavigationItem[] = [
|
||||
{
|
||||
icon: LayoutDashboard,
|
||||
label: "仪表盘",
|
||||
path: "/",
|
||||
path: "/?view=dashboard",
|
||||
roles: ["admin", "supplier_manager", "member", "annotator", "quality_reviewer", "acceptance_reviewer"],
|
||||
},
|
||||
{
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { formatAnnotationTime } from "../lib/annotation-time.js";
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { CSSProperties } from "react";
|
||||
import type { SliceSegment } from "../types";
|
||||
@ -7,7 +8,7 @@ import { conflictAutoFollowHint, effectiveActionStatus, sliceEditChoiceLabels }
|
||||
|
||||
const statusLabel: Record<string, string> = { pending: "待标注", described: "已描述", invalid: "无效" };
|
||||
|
||||
const seconds = (time: number) => `${Number(time).toFixed(2)}s`;
|
||||
const seconds = formatAnnotationTime;
|
||||
|
||||
const relationText = (entry: SliceEditConflictEntry) => {
|
||||
const relation = entry.relation as {
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { AnnotationLabelRecord, SliceSegment } from "../types";
|
||||
import { formatAnnotationTime } from "../lib/annotation-time.js";
|
||||
import { DiscardReasonFields, type DiscardReasonChoice } from "./DiscardReasonFields";
|
||||
import { SliceNameDictionaryPicker } from "./SliceNameDictionaryPicker";
|
||||
|
||||
export type SliceEditPanelDiscardDraft = { discard: boolean } & DiscardReasonChoice;
|
||||
|
||||
const seconds = (time: number) => `${Number(time).toFixed(2)}s`;
|
||||
|
||||
/**
|
||||
* 切片重设面板(票 04 spec §2 R1-Q1/R1-Q3/R2-Q4/R2-Q5):E 进入的专注浮层,视频与
|
||||
* 轨道仍可见。五项操作——①首尾帧数字输入 + ±1/±2 帧步进(←/→ 连续挪、Shift 粗步进
|
||||
@ -36,6 +35,7 @@ export function SliceEditPanel({
|
||||
onCancel,
|
||||
dictionary,
|
||||
discard,
|
||||
error,
|
||||
}: {
|
||||
target: SliceSegment;
|
||||
ordinal: number;
|
||||
@ -55,6 +55,7 @@ export function SliceEditPanel({
|
||||
onMerge: (side: "start" | "end") => void;
|
||||
onApply: () => void;
|
||||
onCancel: () => void;
|
||||
error?: string;
|
||||
dictionary: {
|
||||
items: { id: string; name: string }[];
|
||||
loading?: boolean;
|
||||
@ -141,7 +142,7 @@ export function SliceEditPanel({
|
||||
{focused ? "(焦点 ↑/↓ 切换)" : ""}
|
||||
</button>
|
||||
<span className="font-mono text-[10px] text-slate-500">
|
||||
{seconds(target[field])}
|
||||
{formatAnnotationTime(target[field])}
|
||||
{isFixed ? " · 采集边缘固定" : ""}
|
||||
</span>
|
||||
</div>
|
||||
@ -201,6 +202,7 @@ export function SliceEditPanel({
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
disabled={saving}
|
||||
className="rounded p-1 text-slate-400 hover:text-slate-600"
|
||||
aria-label="关闭面板(取消)"
|
||||
>
|
||||
@ -209,6 +211,15 @@ export function SliceEditPanel({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2.5 px-3 py-2.5 text-[color:var(--app-text)]">
|
||||
{error ? (
|
||||
<p
|
||||
role="alert"
|
||||
data-testid="slice-edit-panel-error"
|
||||
className="rounded bg-red-50 px-2 py-1 text-xs text-red-700 dark:bg-red-950/30 dark:text-red-300"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{boundaryRow("start")}
|
||||
{boundaryRow("end")}
|
||||
@ -257,7 +268,7 @@ export function SliceEditPanel({
|
||||
|
||||
<div className="rounded border border-slate-200 px-2.5 py-2 dark:border-[#34363b]">
|
||||
<div className="text-xs font-semibold">切片字典描述</div>
|
||||
<div className="mt-1">
|
||||
<div className="mt-1" data-slice-edit-dictionary-trigger>
|
||||
<SliceNameDictionaryPicker
|
||||
inline
|
||||
triggerRef={dictionaryTriggerRef}
|
||||
@ -283,12 +294,21 @@ export function SliceEditPanel({
|
||||
onKeyDown={(event) => {
|
||||
// 弹层自有键:Esc 关草稿(一层一层退),Ctrl/⌘+Enter 确认——镜像既有舍弃弹窗。
|
||||
event.stopPropagation();
|
||||
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
|
||||
if (event.key === "Escape" && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault();
|
||||
discard.onCancel();
|
||||
} else if ((event.ctrlKey || event.metaKey) && event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (!event.repeat && !event.nativeEvent.isComposing && reasonReady) discard.onConfirm();
|
||||
if (!event.repeat && reasonReady) discard.onConfirm();
|
||||
} else if (
|
||||
event.key === "Enter" &&
|
||||
!event.shiftKey &&
|
||||
!event.altKey &&
|
||||
!(event.target instanceof HTMLElement && event.target.matches("input, textarea, select, button"))
|
||||
) {
|
||||
event.preventDefault();
|
||||
if (!event.repeat && reasonReady) discard.onConfirm();
|
||||
}
|
||||
}}
|
||||
>
|
||||
@ -347,6 +367,7 @@ export function SliceEditPanel({
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
disabled={saving}
|
||||
className="rounded border border-slate-300 px-2.5 py-1 text-xs font-normal dark:border-[#34363b]"
|
||||
>
|
||||
Esc 取消
|
||||
|
||||
@ -10,6 +10,7 @@ export function WorkspaceDictionaryPanel({
|
||||
value,
|
||||
status,
|
||||
onSelect,
|
||||
onKeyboardSelect,
|
||||
onClose,
|
||||
onDismiss,
|
||||
embedded = false,
|
||||
@ -21,6 +22,7 @@ export function WorkspaceDictionaryPanel({
|
||||
value?: string;
|
||||
status?: ReactNode;
|
||||
onSelect: (id: string) => void;
|
||||
onKeyboardSelect?: () => void;
|
||||
onClose: () => void;
|
||||
onDismiss: () => void;
|
||||
}) {
|
||||
@ -76,7 +78,19 @@ export function WorkspaceDictionaryPanel({
|
||||
onKeyDown={(event) => {
|
||||
// Embedded discard selection leaves save shortcuts to its owning form.
|
||||
if (embedded && (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey)) return;
|
||||
const selectingFromSearch =
|
||||
event.key === "Enter" &&
|
||||
event.target === searchRef.current &&
|
||||
!event.repeat &&
|
||||
!event.nativeEvent.isComposing &&
|
||||
event.keyCode !== 229;
|
||||
const firstOption = selectingFromSearch
|
||||
? (event.currentTarget as HTMLDivElement).querySelector<HTMLButtonElement>(
|
||||
"[data-dictionary-option]:not(:disabled)",
|
||||
)
|
||||
: null;
|
||||
dictionaryKeyDown(event, onClose);
|
||||
if (firstOption) onKeyboardSelect?.();
|
||||
if (
|
||||
event.nativeEvent.isComposing ||
|
||||
event.keyCode === 229 ||
|
||||
|
||||
@ -59,7 +59,7 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
argsRef.current = args;
|
||||
|
||||
const sessionRef = useRef({ taskId: args.taskId, userId: args.userId, enabled: args.enabled });
|
||||
const inFlightRef = useRef<object | null>(null);
|
||||
const inFlightRef = useRef<{ done: Promise<boolean> } | null>(null);
|
||||
const savedDraftsFingerprintRef = useRef(EMPTY_FINGERPRINT);
|
||||
const failedAttemptRef = useRef("");
|
||||
if (
|
||||
@ -107,7 +107,13 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
return false;
|
||||
}
|
||||
const version = options.versionOverride ?? context.version;
|
||||
const request = {};
|
||||
let complete!: (saved: boolean) => void;
|
||||
const request = {
|
||||
done: new Promise<boolean>((resolve) => {
|
||||
complete = resolve;
|
||||
}),
|
||||
};
|
||||
let saved = false;
|
||||
inFlightRef.current = request;
|
||||
const keepalive = reason === "hidden" || reason === "pagehide";
|
||||
try {
|
||||
@ -127,6 +133,7 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
failedAttemptRef.current = "";
|
||||
setStatus({ session, errorNotice: "", lastSavedAt: Date.now() });
|
||||
current.onApplied({ item: response.item, workspace: response.draft, sentVersion: version });
|
||||
saved = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return false;
|
||||
@ -157,6 +164,7 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
return false;
|
||||
} finally {
|
||||
if (inFlightRef.current === request) inFlightRef.current = null;
|
||||
complete(saved && isCurrent());
|
||||
}
|
||||
},
|
||||
);
|
||||
@ -218,5 +226,10 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
dirty,
|
||||
notifySliceSwitch: notifySliceSwitchRef.current,
|
||||
flushNow: (reason: AnnotationAutosaveFlushReason, options?: { versionOverride?: number }) => flush(reason, options),
|
||||
waitForPending: async () => {
|
||||
const session = sessionRef.current;
|
||||
const saved = await (inFlightRef.current?.done ?? Promise.resolve(true));
|
||||
return saved && sessionRef.current === session;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
12
src/lib/annotation-landing.js
Normal file
12
src/lib/annotation-landing.js
Normal file
@ -0,0 +1,12 @@
|
||||
export function annotationLandingPath(role) {
|
||||
const stage = { annotator: "annotate", quality_reviewer: "quality", acceptance_reviewer: "acceptance" }[role];
|
||||
return stage ? `/plugins/annotation-qa/workflows/all/${stage}?pool=mine` : null;
|
||||
}
|
||||
|
||||
export function initialAnnotationPool({ role, workspaceMode, workPage, hasSelection, pool }) {
|
||||
if (pool === "available" || pool === "mine" || pool === "reviewed") return pool;
|
||||
if (workPage) return "mine";
|
||||
// An unclaimed deep link is a preview, not proof of ownership.
|
||||
if (hasSelection && ["quality", "clip-quality", "acceptance"].includes(workspaceMode)) return "available";
|
||||
return annotationLandingPath(role) ? "mine" : hasSelection ? "mine" : "available";
|
||||
}
|
||||
@ -135,6 +135,7 @@ export function sliceEditPanelShortcut(event, { editable = false } = {}) {
|
||||
if (lower === "e") return repeat ? "consume" : "cancel"; // E 再按关面板=取消(票 06 以此写进键位表)
|
||||
if (lower === "c") return repeat ? "consume" : "split";
|
||||
if (lower === "g") return repeat ? "consume" : "discard";
|
||||
if (lower === "f" || lower === "d") return repeat ? "consume" : "dictionary";
|
||||
// D6:J/K 放行给全局表(返工分支跳转意见;连发由返工分支自行忽略)。
|
||||
if (lower === "j" || lower === "k") return "pass";
|
||||
if (lower === "b" || lower === "v" || key === " ") return "pass";
|
||||
@ -151,6 +152,7 @@ export const sliceEditPanelShortcutHelp = [
|
||||
{ keys: "↑ / ↓", label: "在首帧与尾帧边界之间切换焦点", phases: ["annotate"], edit: true },
|
||||
{ keys: "C", label: "在播放头处拆分当前切片", phases: ["annotate"], edit: true },
|
||||
{ keys: "G", label: "舍弃当前切片(先选舍弃原因,随 Enter 一并应用)", phases: ["annotate"], edit: true },
|
||||
{ keys: "F / D", label: "打开切片名称字典,Enter 选中,Esc 返回", phases: ["annotate"], edit: true },
|
||||
{ keys: "Enter", label: "应用全部预览改动(有冲突先弹冲突清单)", phases: ["annotate"], edit: true },
|
||||
{ keys: "Esc / E", label: "取消整个待应用改动集,回退到打开面板前的结构", phases: ["annotate"], edit: true },
|
||||
{
|
||||
|
||||
9
src/lib/annotation-time.js
Normal file
9
src/lib/annotation-time.js
Normal file
@ -0,0 +1,9 @@
|
||||
/** Human-facing annotation time; API and persisted values remain seconds. */
|
||||
export function formatAnnotationTime(seconds) {
|
||||
const value = Number(seconds);
|
||||
const totalMilliseconds = Math.floor(Math.max(0, Number.isFinite(value) ? value : 0) * 1000 + 1e-7);
|
||||
const minutes = Math.floor(totalMilliseconds / 60000);
|
||||
const wholeSeconds = Math.floor(totalMilliseconds / 1000) % 60;
|
||||
const milliseconds = totalMilliseconds % 1000;
|
||||
return `${String(minutes).padStart(2, "0")}:${String(wholeSeconds).padStart(2, "0")}.${String(milliseconds).padStart(3, "0")}`;
|
||||
}
|
||||
72
src/lib/slice-edit-dispositions.js
Normal file
72
src/lib/slice-edit-dispositions.js
Normal file
@ -0,0 +1,72 @@
|
||||
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 = []) {
|
||||
const commands = [];
|
||||
for (const slice of after) {
|
||||
const old = parent(before, slice);
|
||||
if (
|
||||
discarded(old) === discarded(slice) &&
|
||||
(!discarded(slice) ||
|
||||
(old?.discardReasonLabelId === slice.discardReasonLabelId &&
|
||||
old?.discardReasonVersion === slice.discardReasonVersion &&
|
||||
old?.discardReason === slice.discardReason &&
|
||||
(old?.discardReasonNote || "") === (slice.discardReasonNote || "")))
|
||||
)
|
||||
continue;
|
||||
commands.push({
|
||||
sliceId: slice.id,
|
||||
disposition: discarded(slice) ? "discard" : "keep",
|
||||
reason: slice.discardReason,
|
||||
reasonLabelId: slice.discardReasonLabelId,
|
||||
reasonVersion: slice.discardReasonVersion,
|
||||
reasonNote: slice.discardReasonNote,
|
||||
});
|
||||
}
|
||||
// A snapshot undo may restore a discarded child and rejoin it atomically.
|
||||
for (const old of before) {
|
||||
if (
|
||||
discarded(old) &&
|
||||
!after.some(
|
||||
(slice) =>
|
||||
slice.id === old.id ||
|
||||
(discarded(slice) && (slice.sourceIds?.includes(old.id) || old.sourceIds?.includes(slice.id))),
|
||||
)
|
||||
) {
|
||||
commands.unshift({ sliceId: old.id, disposition: "keep" });
|
||||
}
|
||||
}
|
||||
return commands;
|
||||
}
|
||||
|
||||
/** 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(
|
||||
(action) => !after.some((slice) => discarded(slice) && action.start >= slice.start && action.end <= slice.end),
|
||||
);
|
||||
const slices = after.map((slice) => {
|
||||
const old = parent(before, slice);
|
||||
if (discarded(slice))
|
||||
return {
|
||||
...slice,
|
||||
name: "",
|
||||
discardedAnnotations: [
|
||||
...(old?.discardedAnnotations || []),
|
||||
...actions.filter((action) => action.start >= slice.start && action.end <= slice.end),
|
||||
],
|
||||
};
|
||||
if (discarded(old)) {
|
||||
for (const action of old.discardedAnnotations || []) {
|
||||
const start = Math.max(action.start, slice.start),
|
||||
end = Math.min(action.end, slice.end);
|
||||
if (end <= start || nextActions.some((current) => current.id === action.id)) continue;
|
||||
nextActions.push({ ...action, start, end });
|
||||
}
|
||||
}
|
||||
return slice;
|
||||
});
|
||||
return { slices, actions: nextActions };
|
||||
}
|
||||
@ -1,12 +1,23 @@
|
||||
/** Display-only wording. Never use this text to classify errors or change retry behaviour. */
|
||||
export function userErrorMessage(value, fallback = "操作暂时未完成") {
|
||||
if (value == null || value === "") return "";
|
||||
if (typeof value === "object" && Array.isArray(value.issues) && value.issues.length) {
|
||||
const messages = value.issues
|
||||
.slice(0, 3)
|
||||
.map((issue) => userErrorMessage(issue?.message, fallback))
|
||||
.filter(Boolean);
|
||||
if (messages.length) return [...new Set(messages)].join(";");
|
||||
}
|
||||
const raw = typeof value === "string" ? value : value?.message || "";
|
||||
const text = raw.trim();
|
||||
const code = typeof value === "object" ? value?.code || "" : "";
|
||||
const status = typeof value === "object" ? Number(value?.status) : 0;
|
||||
const source = `${code} ${text}`;
|
||||
const rules = [
|
||||
[
|
||||
/slice_materialization_required|all Capture slices must be materialized/i,
|
||||
"切片尚未完成生成,请先确认切片;已有标注会保留",
|
||||
],
|
||||
[/HTTP\s*(502|503|504)|Bad Gateway|Service Unavailable|Gateway Timeout/i, "系统服务暂时不可用"],
|
||||
[/APITimeoutError|网络异常,请重试/, "网络异常,请重试"],
|
||||
[/kubernetes job|container.*(?:failed|terminated)|pod.*(?:failed|evicted)/i, "后台任务运行异常"],
|
||||
|
||||
@ -1,3 +1,6 @@
|
||||
import { initialAnnotationPool } from "../lib/annotation-landing.js";
|
||||
import { sliceEditDispositionCommands } from "../lib/slice-edit-dispositions.js";
|
||||
import { formatAnnotationTime } from "../lib/annotation-time.js";
|
||||
/*
|
||||
* AnnotationOperations.tsx — region map (grep anchors, NOT line numbers; keep in sync when regions move).
|
||||
* This file is ~7k lines; navigate by anchor instead of reading end-to-end:
|
||||
@ -684,15 +687,16 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
|
||||
const [tasks, setTasks] = useState<AnnotationTaskRecord[]>([]);
|
||||
const [humanPools, setHumanPools] = useState<HumanPools>(emptyHumanPools);
|
||||
const [taskPoolView, setTaskPoolView] = useState<TaskPoolView>(() => {
|
||||
// A URL task/acceptance id is a selection, not ownership.
|
||||
if (
|
||||
!isOrganizationAdminRole(role) &&
|
||||
(workspaceMode === "quality" || workspaceMode === "clip-quality" || workspaceMode === "acceptance")
|
||||
)
|
||||
return "available";
|
||||
return workPage || requestedTaskId || requestedAcceptanceId ? "mine" : "available";
|
||||
});
|
||||
// A URL task id is a selection, not ownership; deep-link previews retain their pool.
|
||||
const defaultTaskPoolView = () =>
|
||||
initialAnnotationPool({
|
||||
role,
|
||||
workspaceMode,
|
||||
workPage,
|
||||
hasSelection: Boolean(requestedTaskId || requestedAcceptanceId),
|
||||
pool: searchParams.get("pool"),
|
||||
}) as TaskPoolView;
|
||||
const [taskPoolView, setTaskPoolView] = useState<TaskPoolView>(defaultTaskPoolView);
|
||||
const [workload, setWorkload] = useState<AnnotationWorkloadSummary>({ items: [], eventCount: 0 });
|
||||
const [rejects, setRejects] = useState<HumanReject[]>([]);
|
||||
const [deliveryPackages, setDeliveryPackages] = useState<DeliveryPackage[]>([]);
|
||||
@ -1375,7 +1379,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
setSelectedAnnotationTaskId("");
|
||||
setReviewComment("");
|
||||
setProblemSliceIds([]);
|
||||
setTaskPoolView(workPage || (blindAnnotator && (requestedTaskId || requestedAcceptanceId)) ? "mine" : "available");
|
||||
setTaskPoolView(defaultTaskPoolView());
|
||||
setDeliveryPackages([]);
|
||||
setDeliveryPackageContents({});
|
||||
}, [currentUser?.id]);
|
||||
@ -2638,7 +2642,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
}, [detail?.humanItem?.cancellationReason, isReworkTask, latestRejectReview]);
|
||||
|
||||
const currentAnnotationMutationContext = annotationMutationContextRef.current.current;
|
||||
const beginAnnotationMutation = (taskId: string) => {
|
||||
const beginAnnotationMutation = async (taskId: string) => {
|
||||
if (workPage && (!workSession.active || !workSession.owns())) return null;
|
||||
const currentContext = currentAnnotationMutationContext();
|
||||
const token = annotationMutationScopeRef.current.begin({
|
||||
@ -2649,7 +2653,15 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
++taskDetailRequestRef.current;
|
||||
setSaving(true);
|
||||
setError("");
|
||||
return token;
|
||||
const settled = await autosave.waitForPending();
|
||||
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return null;
|
||||
if (!settled) {
|
||||
annotationMutationScopeRef.current.end(token);
|
||||
setSaving(false);
|
||||
setError("自动保存结果尚未确认,当前编辑已保留;请核对提示后再操作。");
|
||||
return null;
|
||||
}
|
||||
return { ...token, version: detailRef.current?.humanItem?.version ?? 0 };
|
||||
};
|
||||
const endAnnotationMutation = (token: AnnotationMutationToken) => {
|
||||
if (annotationMutationScopeRef.current.end(token)) setSaving(false);
|
||||
@ -2732,6 +2744,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
const currentVersion = detailRef.current?.humanItem?.version ?? 0;
|
||||
if (!item || item.version < currentVersion) return;
|
||||
const savedItem = { ...item, display: item.display || detailRef.current?.humanItem?.display };
|
||||
if (detailRef.current) detailRef.current = { ...detailRef.current, humanItem: savedItem };
|
||||
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
|
||||
setHumanPools((current) => ({
|
||||
...current,
|
||||
@ -2752,6 +2765,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
const currentVersion = detailRef.current?.humanItem?.version ?? 0;
|
||||
if (!item || item.version < currentVersion) return;
|
||||
const savedItem = { ...item, display: item.display || detailRef.current?.humanItem?.display };
|
||||
if (detailRef.current) detailRef.current = { ...detailRef.current, humanItem: savedItem };
|
||||
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
|
||||
},
|
||||
});
|
||||
@ -2833,22 +2847,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
frameBoundaries,
|
||||
detail?.task.continuousActions,
|
||||
]);
|
||||
const canCurrentUserClaimItem = useCallback(
|
||||
(item: HumanItem | undefined) => {
|
||||
if (!item) return false;
|
||||
if (isManager) return true;
|
||||
if (typeof item.canClaim === "boolean") return item.canClaim;
|
||||
// F5: in the unscoped review workspace the membership fan-out is skipped,
|
||||
// so there is no local membership to check. Stay optimistic: the claim
|
||||
// button stays clickable and the server rejects unauthorized claims (a
|
||||
// 403 is surfaced as an error message).
|
||||
if (reviewOnly && !projectId) return true;
|
||||
const requiredRole = assignmentRoleForStage(item.currentStageId || "");
|
||||
const member = projectMembers.find((m) => m.userId === currentUser?.id && m.projectId === item.projectId);
|
||||
return memberCanClaim(item, member, requiredRole);
|
||||
},
|
||||
[currentUser?.id, isManager, projectMembers, reviewOnly, projectId],
|
||||
);
|
||||
const canCurrentUserClaimItem = useCallback((item: HumanItem | undefined) => item?.canClaim === true, []);
|
||||
const sliceEditorReadOnly = annotationSliceEditorReadOnly({
|
||||
workspaceMode,
|
||||
isCombinedQuality: isV5CombinedQuality,
|
||||
@ -2938,7 +2937,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
) => {
|
||||
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked) return false;
|
||||
const taskId = detail.task.id;
|
||||
const submittedVersion = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||||
let submittedVersion = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||||
const previousWorkspace = confirmedAnnotationWorkspace();
|
||||
if (!previousWorkspace) {
|
||||
setError("已保存标注尚未加载,请稍后重试。");
|
||||
@ -2961,8 +2960,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
segments: nextSegments.map((segment) => ({ ...segment, label: "", handedness: "" })),
|
||||
statuses: nextStatuses,
|
||||
};
|
||||
const token = beginAnnotationMutation(taskId);
|
||||
const token = await beginAnnotationMutation(taskId);
|
||||
if (!token) return false;
|
||||
submittedVersion = token.version;
|
||||
payload.version = submittedVersion;
|
||||
try {
|
||||
const result = await settleAuthoritativeMutation({
|
||||
scope: annotationMutationScopeRef.current,
|
||||
@ -3419,7 +3420,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return false;
|
||||
const previousSlice = sliceSegments.find((slice) => slice.id === sliceId);
|
||||
if (!previousSlice) return false;
|
||||
const version = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||||
let version = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||||
const location = { sliceId, time: annotationPlayheadRef.current };
|
||||
const snapshot = (slice: SliceSegment): DispositionEditSnapshot => ({
|
||||
kind: "disposition",
|
||||
@ -3435,13 +3436,14 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
},
|
||||
location,
|
||||
});
|
||||
const before = snapshot(previousSlice);
|
||||
const taskId = detail.task.id;
|
||||
const token = beginAnnotationMutation(taskId);
|
||||
const token = await beginAnnotationMutation(taskId);
|
||||
if (!token) return false;
|
||||
version = token.version;
|
||||
const before = snapshot(previousSlice);
|
||||
try {
|
||||
const response = await annotationOperationsApi.setSliceDisposition(taskId, {
|
||||
version,
|
||||
const payload = {
|
||||
version: token.version,
|
||||
sliceId,
|
||||
disposition,
|
||||
restorePreviousName,
|
||||
@ -3451,14 +3453,40 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
segments,
|
||||
operations: sliceOperations,
|
||||
statuses: sliceStatuses,
|
||||
};
|
||||
const result = await settleAuthoritativeMutation({
|
||||
scope: annotationMutationScopeRef.current,
|
||||
token,
|
||||
currentContext: currentAnnotationMutationContext,
|
||||
write: () => annotationOperationsApi.setSliceDisposition(taskId, payload),
|
||||
read: () => annotationOperationsApi.getTask(taskId),
|
||||
isApplied: (authoritative: AnnotationTaskDetail) => {
|
||||
const history = authoritative.humanItem?.subject?.payload?.sliceDispositionHistory as
|
||||
Array<{ sliceId?: string; actorUserId?: string; itemVersion?: number; after?: SliceSegment }> | undefined;
|
||||
const entry = history?.at(-1);
|
||||
return (
|
||||
authoritative.humanItem?.version === token.version + 1 &&
|
||||
entry?.sliceId === sliceId &&
|
||||
entry.actorUserId === currentUser?.id &&
|
||||
entry.itemVersion === token.version + 1 &&
|
||||
(entry.after?.deliveryDisposition || "keep") === disposition
|
||||
);
|
||||
},
|
||||
});
|
||||
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return false;
|
||||
if (result.status === "stale") return false;
|
||||
if (result.status !== "confirmed") throw result.error;
|
||||
const response = result.reconciled
|
||||
? {
|
||||
item: result.authoritative.humanItem,
|
||||
workspace: annotationDraftFromHumanItem(result.authoritative.humanItem),
|
||||
}
|
||||
: result.response;
|
||||
const savedItem = { ...response.item, display: response.item.display || detail.humanItem.display };
|
||||
const workspace = normalizeAnnotationWorkspace(response.workspace);
|
||||
if (!workspace) throw new Error("保存切片用途失败:服务器返回的标注工作区无效");
|
||||
if (detailRef.current) detailRef.current = { ...detailRef.current, humanItem: savedItem };
|
||||
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
|
||||
setHumanPools((current) => ({
|
||||
...current,
|
||||
...current,
|
||||
mine: current.mine.map((i) => (i.id === response.item.id ? savedItem : i)),
|
||||
}));
|
||||
@ -3489,10 +3517,111 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
}
|
||||
};
|
||||
|
||||
const persistSliceEditApplication = async (
|
||||
nextSlices: SliceSegment[],
|
||||
nextSegments: AnnotationSegment[],
|
||||
focusSliceId: string,
|
||||
recordHistory = true,
|
||||
restoredOperations = sliceOperations,
|
||||
) => {
|
||||
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return null;
|
||||
const taskId = detail.task.id;
|
||||
const before = sliceEditSnapshot(focusSliceId);
|
||||
const token = await beginAnnotationMutation(taskId);
|
||||
if (!token) return null;
|
||||
const applicationId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;
|
||||
const payload = {
|
||||
version: token.version,
|
||||
applicationId,
|
||||
sliceSegments: nextSlices,
|
||||
segments: nextSegments,
|
||||
operations: restoredOperations,
|
||||
statuses: deriveSliceStatuses(nextSlices, nextSegments, sliceStatuses) as typeof sliceStatuses,
|
||||
dispositions: sliceEditDispositionCommands(sliceSegments, nextSlices),
|
||||
};
|
||||
try {
|
||||
const result = await settleAuthoritativeMutation({
|
||||
scope: annotationMutationScopeRef.current,
|
||||
token,
|
||||
currentContext: currentAnnotationMutationContext,
|
||||
write: () => annotationOperationsApi.applySliceEdit(taskId, payload),
|
||||
read: () => annotationOperationsApi.getTask(taskId),
|
||||
isApplied: (authoritative: AnnotationTaskDetail) => {
|
||||
const applied = authoritative.humanItem?.subject?.payload?.lastSliceEditApplication as
|
||||
{ id?: string; actorUserId?: string; version?: number } | undefined;
|
||||
return (
|
||||
authoritative.humanItem?.version === token.version + 1 &&
|
||||
applied?.id === applicationId &&
|
||||
applied.actorUserId === currentUser?.id &&
|
||||
applied.version === token.version + 1
|
||||
);
|
||||
},
|
||||
});
|
||||
if (result.status === "stale") return null;
|
||||
if (result.status !== "confirmed") {
|
||||
setError(getActionErrorMessage(result.error, "切片改动保存失败,预览仍保留,请核对后重试"));
|
||||
return null;
|
||||
}
|
||||
const item = result.reconciled ? result.authoritative.humanItem : result.response.item;
|
||||
const workspace = result.reconciled
|
||||
? annotationDraftFromHumanItem(item)
|
||||
: normalizeAnnotationWorkspace(result.response.workspace);
|
||||
if (!item || !workspace) {
|
||||
setError("服务器返回的切片工作区无效,请刷新核对保存结果。");
|
||||
return null;
|
||||
}
|
||||
const savedItem = { ...item, display: item.display || detail.humanItem.display };
|
||||
if (detailRef.current) detailRef.current = { ...detailRef.current, humanItem: savedItem };
|
||||
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
|
||||
setHumanPools((current) => ({ ...current, mine: current.mine.map((i) => (i.id === item.id ? savedItem : i)) }));
|
||||
confirmedAnnotationWorkspaceRef.current = { taskId, workspace: structuredClone(workspace) };
|
||||
setSliceSegments(workspace.sliceSegments);
|
||||
setSegments(workspace.segments);
|
||||
setSliceStatuses(workspace.statuses);
|
||||
setSliceOperations(workspace.operations);
|
||||
annotationBaselineRef.current = annotationWorkspaceFingerprint(
|
||||
workspace.sliceSegments,
|
||||
workspace.operations,
|
||||
workspace.segments,
|
||||
workspace.statuses,
|
||||
);
|
||||
if (recordHistory) {
|
||||
editHistoryRef.current.record({
|
||||
before,
|
||||
after: {
|
||||
slices: workspace.sliceSegments,
|
||||
segments: workspace.segments,
|
||||
operations: workspace.operations,
|
||||
statuses: workspace.statuses,
|
||||
location: before.location,
|
||||
},
|
||||
});
|
||||
editHistoryRef.current.markPersisted();
|
||||
}
|
||||
setError("");
|
||||
return workspace;
|
||||
} catch (cause) {
|
||||
if (annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext()))
|
||||
setError(getActionErrorMessage(cause, "切片改动保存失败,预览仍保留"));
|
||||
return null;
|
||||
} finally {
|
||||
endAnnotationMutation(token);
|
||||
}
|
||||
};
|
||||
|
||||
const restorePersistedSliceEdit = async (snapshot: SliceEditSnapshot) => {
|
||||
// Ticket 07(spec §3.5):结构编辑已在标注相解锁(票 02),持久化切片编辑的
|
||||
// 撤销/重做在标注相也要经服务端快照恢复;物化/质检等阶段仍拒绝。
|
||||
if (!detail?.humanItem || !selectedClaimedByMe || !["slice", "annotate"].includes(combinedEditorPhase)) return null;
|
||||
if (sliceEditDispositionCommands(sliceSegments, snapshot.slices).length) {
|
||||
return persistSliceEditApplication(
|
||||
snapshot.slices,
|
||||
snapshot.segments,
|
||||
snapshot.location.sliceId,
|
||||
false,
|
||||
snapshot.operations,
|
||||
);
|
||||
}
|
||||
const taskId = detail.task.id;
|
||||
const version = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||||
const payload = {
|
||||
@ -3502,8 +3631,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
segments: snapshot.segments,
|
||||
statuses: snapshot.statuses,
|
||||
};
|
||||
const token = beginAnnotationMutation(taskId);
|
||||
const token = await beginAnnotationMutation(taskId);
|
||||
if (!token) return null;
|
||||
payload.version = token.version;
|
||||
try {
|
||||
const result = await settleAuthoritativeMutation({
|
||||
scope: annotationMutationScopeRef.current,
|
||||
@ -3514,7 +3644,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
isApplied: (authoritative: AnnotationTaskDetail) => {
|
||||
const workspace = annotationDraftFromHumanItem(authoritative.humanItem);
|
||||
return Boolean(
|
||||
authoritative.humanItem?.version === version + 1 &&
|
||||
authoritative.humanItem?.version === token.version + 1 &&
|
||||
authoritative.humanItem.assignedUserId === currentUser?.id &&
|
||||
authoritative.humanItem.currentStageId === detail.humanItem?.currentStageId &&
|
||||
workspace &&
|
||||
@ -3722,7 +3852,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
};
|
||||
const retryStageReadback = async () => {
|
||||
if (!stageRecovery || !stageResultUnknown || annotationMutationScopeRef.current.busy()) return;
|
||||
const token = beginAnnotationMutation(stageRecovery.taskId);
|
||||
const token = await beginAnnotationMutation(stageRecovery.taskId);
|
||||
if (!token) return;
|
||||
try {
|
||||
await reconcileStageOperation(stageRecovery.taskId, stageRecovery.kind, token);
|
||||
@ -3760,12 +3890,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
taskLabel: "",
|
||||
annotationStatus: "pending" as const,
|
||||
}));
|
||||
const token = beginAnnotationMutation(detail.task.id);
|
||||
const token = await beginAnnotationMutation(detail.task.id);
|
||||
if (!token) return;
|
||||
clearEditHistory();
|
||||
try {
|
||||
const response = await annotationOperationsApi.confirmSlices(detail.task.id, {
|
||||
version: detail.humanItem.version,
|
||||
version: token.version,
|
||||
sliceSegments: confirmationSlices,
|
||||
sliceOperations,
|
||||
changeReason: detail.sliceRevisions.length ? "重新确认切片" : "首次确认切片",
|
||||
@ -3824,6 +3954,8 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
)
|
||||
return;
|
||||
const taskId = detail.task.id;
|
||||
const token = await beginAnnotationMutation(taskId);
|
||||
if (!token) return;
|
||||
const attempt =
|
||||
pendingReslice?.taskId === taskId
|
||||
? pendingReslice
|
||||
@ -3832,9 +3964,8 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
version: detailRef.current?.humanItem?.version ?? detail.humanItem.version,
|
||||
resetToUnifiedRange,
|
||||
};
|
||||
const submittedVersion = attempt.version;
|
||||
const token = beginAnnotationMutation(taskId);
|
||||
if (!token) return;
|
||||
const submittedVersion = pendingReslice?.taskId === taskId ? attempt.version : token.version;
|
||||
attempt.version = submittedVersion;
|
||||
setResliceError("");
|
||||
try {
|
||||
const result = await settleAuthoritativeMutation({
|
||||
@ -3979,7 +4110,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
for (const candidate of candidates) {
|
||||
if (
|
||||
window.confirm(
|
||||
`“${candidate.name}”中 ${candidate.invalidStart.toFixed(3)}–${candidate.invalidEnd.toFixed(3)} 秒的无效动作单独占了一个切片。\n\n是否与前后同名切片合并为 ${candidate.start.toFixed(3)}–${candidate.end.toFixed(3)} 秒的完整切片?全部动作描述、无效标记及时间保持不变。\n确定:合并外层;取消:保留原划分。`,
|
||||
`“${candidate.name}”中 ${formatAnnotationTime(candidate.invalidStart)}–${formatAnnotationTime(candidate.invalidEnd)}的无效动作单独占了一个切片。\n\n是否与前后同名切片合并为 ${formatAnnotationTime(candidate.start)}–${formatAnnotationTime(candidate.end)}的完整切片?全部动作描述、无效标记及时间保持不变。\n确定:合并外层;取消:保留原划分。`,
|
||||
)
|
||||
)
|
||||
consolidateInvalidSliceIds.push(candidate.id);
|
||||
@ -3994,7 +4125,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
)
|
||||
return;
|
||||
const currentTaskId = detail.task.id;
|
||||
const token = beginAnnotationMutation(currentTaskId);
|
||||
const token = await beginAnnotationMutation(currentTaskId);
|
||||
if (!token) return;
|
||||
clearEditHistory();
|
||||
try {
|
||||
@ -4359,10 +4490,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
? "确认释放此任务并退回待领取池吗?其他审核员将可以领取此任务。"
|
||||
: "放弃并释放任务将清空该任务在数据库中的历史切片与标注记录,并退回待领取池。确认继续吗?";
|
||||
if (!window.confirm(confirmMessage)) return;
|
||||
const token = beginAnnotationMutation(detail.task.id);
|
||||
const token = await beginAnnotationMutation(detail.task.id);
|
||||
if (!token) return;
|
||||
try {
|
||||
await humanLoopApi.release(detail.humanItem.id, detail.humanItem.version);
|
||||
await humanLoopApi.release(detail.humanItem.id, token.version);
|
||||
setTaskPoolView("available");
|
||||
selectTask("");
|
||||
await loadProject();
|
||||
@ -6262,7 +6393,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
片段名:{captureLabel}
|
||||
</div>
|
||||
<div className="mt-1 truncate text-[10px] text-slate-500 dark:text-gray-500">
|
||||
{task.clipStart.toFixed(1)}–{task.clipEnd.toFixed(1)}s
|
||||
{formatAnnotationTime(task.clipStart)}–{formatAnnotationTime(task.clipEnd)}
|
||||
</div>
|
||||
</div>
|
||||
{(() => {
|
||||
@ -6800,6 +6931,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
</div>
|
||||
)}
|
||||
<CaptureAnnotationWorkbench
|
||||
operationError={error}
|
||||
key={`${detail.task.id}:${combinedEditorPhase}:${detail.humanItem?.currentStageId || ""}:${currentUser?.id || ""}`}
|
||||
seekRequest={reworkSeekRequest}
|
||||
reworkEmphasis={
|
||||
@ -6965,16 +7097,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
onSliceEditQuickConflictApply={handleSliceEditQuickConflictApply}
|
||||
onSliceEditQuickConflictCancel={handleSliceEditQuickConflictCancel}
|
||||
onSliceEditSessionChange={setSliceEditSessionOpen}
|
||||
onApplySliceEdit={(nextSlices, nextSegments, focusSliceId) => {
|
||||
// 票 04(spec §2 R1-Q1/R1-Q4):切片重设面板 Enter 应用——整套
|
||||
// 预览结构 + 冲突解析产物作为一次原子落库(一条可撤销历史),
|
||||
// 状态按新结构重推导;保存/提交仍走既有草稿与合并送检路径。
|
||||
return applySliceChange(
|
||||
[...nextSlices],
|
||||
{ type: "adjust", segmentIds: nextSlices.map((slice) => slice.id) },
|
||||
nextSegments,
|
||||
);
|
||||
}}
|
||||
onApplySliceEdit={async (nextSlices, nextSegments, focusSliceId) =>
|
||||
Boolean(await persistSliceEditApplication(nextSlices, nextSegments, focusSliceId))
|
||||
}
|
||||
onAnnotationEdit={recordAnnotationEdit}
|
||||
onHistoryCommand={restoreEdit}
|
||||
historyReveal={historyReveal}
|
||||
|
||||
@ -231,6 +231,30 @@ export const annotationOperationsApi = {
|
||||
{ method: "POST", headers: { Prefer: "respond-async" } },
|
||||
payload,
|
||||
),
|
||||
applySliceEdit: (
|
||||
taskId: string,
|
||||
payload: {
|
||||
version: number;
|
||||
applicationId: string;
|
||||
sliceSegments: SliceSegment[];
|
||||
operations: SliceOperation[];
|
||||
segments: AnnotationSegment[];
|
||||
statuses: Record<string, NonNullable<SliceSegment["annotationStatus"]>>;
|
||||
dispositions: {
|
||||
sliceId: string;
|
||||
disposition: string;
|
||||
reason?: string;
|
||||
reasonLabelId?: string;
|
||||
reasonVersion?: number;
|
||||
reasonNote?: string;
|
||||
}[];
|
||||
},
|
||||
) =>
|
||||
apiRequest<{ item: HumanItem; workspace: Omit<typeof payload, "version" | "applicationId" | "dispositions"> }>(
|
||||
`/api/plugins/annotation-qa/tasks/${taskId}/slice-edit-applications`,
|
||||
{ method: "POST" },
|
||||
payload,
|
||||
),
|
||||
restoreSliceEdit: (
|
||||
taskId: string,
|
||||
payload: {
|
||||
|
||||
@ -508,8 +508,10 @@ test("slice-edit panel dispatches its own table: apply/cancel, boundary nudges,
|
||||
assert.equal(sliceEditPanelShortcut(key("e", { isComposing: true })), null);
|
||||
assert.equal(sliceEditPanelShortcut(key("e", { keyCode: 229 })), null);
|
||||
assert.equal(sliceEditPanelShortcut(key("g", { defaultPrevented: true })), null);
|
||||
assert.equal(sliceEditPanelShortcut(key("f")), "dictionary");
|
||||
assert.equal(sliceEditPanelShortcut(key("d")), "dictionary");
|
||||
// 表外键一律 null(面板开着时由分发器整体吞掉,不漏进全局表——结构操作 N/X 等锁死)。
|
||||
for (const outside of ["n", "f", "d", "x", "3", "Backspace", "Tab", "z"])
|
||||
for (const outside of ["n", "x", "3", "Backspace", "Tab", "z"])
|
||||
assert.equal(sliceEditPanelShortcut(key(outside)), null);
|
||||
});
|
||||
|
||||
|
||||
@ -46,6 +46,6 @@ test("production roles can open their existing personal dashboard, not other sta
|
||||
assert.match(app, /effectiveRole === "quality_reviewer" && !personalDashboard && !qualityPath/);
|
||||
assert.match(
|
||||
sidebar,
|
||||
/label: "仪表盘",\s*path: "\/",\s*roles: \["admin", "supplier_manager", "member", "annotator", "quality_reviewer", "acceptance_reviewer"\]/,
|
||||
/label: "仪表盘",\s*path: "\/\?view=dashboard",\s*roles: \["admin", "supplier_manager", "member", "annotator", "quality_reviewer", "acceptance_reviewer"\]/,
|
||||
);
|
||||
});
|
||||
|
||||
@ -137,7 +137,10 @@ test("single-slice E opens the panel directly; the constant slot keeps only the
|
||||
test("slice reconfig panel: E opens the preview panel with Enter/Esc, locks bypasses, and renders pending structure", () => {
|
||||
// 票 04(spec §2 R1-Q1/R1-Q3/R1-Q4/R2-Q5):E 改派切片重设面板——预览不落库、
|
||||
// Enter 应用(冲突走清单)、Esc 整体回退;旁路锁定 + 轨道实时渲染预览结构。
|
||||
assert.match(workbench, /action === "toggle-slice-edit" && phase === "annotate"\) openSliceEditPanel\(\)/);
|
||||
assert.match(
|
||||
workbench,
|
||||
/action === "toggle-slice-edit" && phase === "annotate" && !readOnly && !isQualityReview && !mediaOnly\)\s*openSliceEditPanel\(\)/,
|
||||
);
|
||||
const open = workbench.slice(
|
||||
workbench.indexOf("const openSliceEditPanel ="),
|
||||
workbench.indexOf("const openSliceEditPanelForJump ="),
|
||||
@ -163,7 +166,7 @@ test("slice reconfig panel: E opens the preview panel with Enter/Esc, locks bypa
|
||||
/setSliceEditConflictList\(\{\s*entries: scan\.entries,\s*autoFollows: scan\.autoFollows,\s*decisions: \{\},\s*focus: 0,\s*source: "panel",?\s*\}\);/,
|
||||
);
|
||||
const commit = workbench.slice(
|
||||
workbench.indexOf("const commitSliceEditPanel ="),
|
||||
workbench.indexOf("const commitSliceEditPanel = async"),
|
||||
workbench.indexOf("const applySliceEditPanel ="),
|
||||
);
|
||||
assert.match(commit, /resolveSliceEditConflicts\(/);
|
||||
@ -209,7 +212,7 @@ test("slice reconfig panel: E opens the preview panel with Enter/Esc, locks bypa
|
||||
assert.match(workbench, /面板期间已锁定该操作/);
|
||||
// 页面侧:Enter 应用经 applySliceChange 原子落库(一条可撤销历史)。
|
||||
assert.match(annotationOperations, /onApplySliceEdit=\{/);
|
||||
assert.match(annotationOperations, /return applySliceChange\(/);
|
||||
assert.match(annotationOperations, /await persistSliceEditApplication\(/);
|
||||
});
|
||||
|
||||
test("drag quick path: releases route through the 03 engine into the 04 conflict list (ticket 05)", () => {
|
||||
@ -406,7 +409,7 @@ test("acceptance fix C: E opens despite parked drafts; autosave pauses for the p
|
||||
);
|
||||
assert.match(cancel, /onSliceEditSessionChange\?\.\(false\)/);
|
||||
const commit = workbench.slice(
|
||||
workbench.indexOf("const commitSliceEditPanel ="),
|
||||
workbench.indexOf("const commitSliceEditPanel = async"),
|
||||
workbench.indexOf("const applySliceEditPanel ="),
|
||||
);
|
||||
assert.match(commit, /onSliceEditSessionChange\?\.\(false\)/, "Enter 应用后释放会话");
|
||||
@ -449,10 +452,10 @@ test("production shell keeps real users, collapsible navigation, and a persisted
|
||||
assert.match(annotationOperations, /annotationTaskAction/);
|
||||
assert.doesNotMatch(annotationOperations, /领取标注任务|领取剪切任务/);
|
||||
assert.match(css, /capture-media-controls/);
|
||||
assert.match(annotationOperations, /requireSliceCompletion: true/);
|
||||
assert.match(annotationOperations, /requireSliceCompletion: !detail\.task\.continuousActions/);
|
||||
assert.doesNotMatch(annotationOperations, /sliceProgress\.pending > 0/);
|
||||
assert.match(workbench, /已完整标注/);
|
||||
assert.match(workbench, /允许部分或全部留空/);
|
||||
assert.match(workbench, /语义留空合法/);
|
||||
assert.doesNotMatch(workbench, /个切片已完成标注/);
|
||||
});
|
||||
|
||||
|
||||
114
tests/frontend/oct15-feedback-flows.test.mjs
Normal file
114
tests/frontend/oct15-feedback-flows.test.mjs
Normal file
@ -0,0 +1,114 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { sliceEditDispositionCommands, previewSliceEditDispositions } from "../../src/lib/slice-edit-dispositions.js";
|
||||
import { annotationLandingPath, initialAnnotationPool } from "../../src/lib/annotation-landing.js";
|
||||
import { formatAnnotationTime } from "../../src/lib/annotation-time.js";
|
||||
|
||||
test("whole-slice discard previews archive all states and restore retains adjacent actions", () => {
|
||||
const before = [
|
||||
{ id: "a", name: "slice", start: 0, end: 5 },
|
||||
{ id: "b", start: 5, end: 10 },
|
||||
];
|
||||
const actions = [
|
||||
{ id: "pending", start: 0, end: 2, status: "pending" },
|
||||
{ id: "described", start: 2, end: 4, status: "described", description: "synthetic" },
|
||||
{ id: "invalid", start: 4, end: 5, status: "invalid", isInvalid: true },
|
||||
{ id: "neighbor", start: 5, end: 10, status: "pending" },
|
||||
];
|
||||
const original = structuredClone({ before, actions });
|
||||
const after = [
|
||||
{ ...before[0], deliveryDisposition: "discard", discardReasonLabelId: "reason", discardReasonVersion: 2 },
|
||||
before[1],
|
||||
];
|
||||
const commands = sliceEditDispositionCommands(before, after);
|
||||
assert.equal(commands.length, 1);
|
||||
assert.equal(commands[0].disposition, "discard");
|
||||
assert.equal(commands[0].reasonVersion, 2);
|
||||
const preview = previewSliceEditDispositions(before, after, actions);
|
||||
assert.deepEqual(preview.actions, [actions[3]]);
|
||||
assert.deepEqual(preview.slices[0].discardedAnnotations, actions.slice(0, 3));
|
||||
const restored = previewSliceEditDispositions(preview.slices, before, preview.actions);
|
||||
assert.deepEqual(
|
||||
restored.actions.toSorted((a, b) => a.start - b.start),
|
||||
actions,
|
||||
);
|
||||
assert.deepEqual({ before, actions }, original);
|
||||
assert.deepEqual(
|
||||
sliceEditDispositionCommands(preview.slices, before).map((c) => [c.sliceId, c.disposition]),
|
||||
[["a", "keep"]],
|
||||
);
|
||||
});
|
||||
|
||||
test("undo of a split restores the discarded child before it disappears; reason edits remain explicit", () => {
|
||||
const children = [
|
||||
{
|
||||
id: "left",
|
||||
sourceIds: ["parent"],
|
||||
start: 0,
|
||||
end: 5,
|
||||
deliveryDisposition: "discard",
|
||||
discardReasonLabelId: "r",
|
||||
discardReasonVersion: 1,
|
||||
},
|
||||
{ id: "right", sourceIds: ["parent"], start: 5, end: 10 },
|
||||
];
|
||||
assert.deepEqual(
|
||||
sliceEditDispositionCommands(children, [{ id: "parent", start: 0, end: 10 }]).map((c) => [
|
||||
c.sliceId,
|
||||
c.disposition,
|
||||
]),
|
||||
[["left", "keep"]],
|
||||
);
|
||||
const changed = structuredClone(children);
|
||||
changed[0].discardReasonVersion = 2;
|
||||
assert.equal(sliceEditDispositionCommands(children, changed)[0].reasonVersion, 2);
|
||||
assert.deepEqual(sliceEditDispositionCommands(children, structuredClone(children)), []);
|
||||
});
|
||||
|
||||
test("production landing uses my tasks while explicit review links retain pool preview", () => {
|
||||
for (const [role, mode] of [
|
||||
["annotator", "annotate"],
|
||||
["quality_reviewer", "quality"],
|
||||
["acceptance_reviewer", "acceptance"],
|
||||
]) {
|
||||
assert.equal(annotationLandingPath(role), `/plugins/annotation-qa/workflows/all/${mode}?pool=mine`);
|
||||
assert.equal(initialAnnotationPool({ role, workspaceMode: mode }), "mine");
|
||||
}
|
||||
assert.equal(annotationLandingPath("admin"), null);
|
||||
assert.equal(
|
||||
initialAnnotationPool({ role: "quality_reviewer", workspaceMode: "quality", hasSelection: true }),
|
||||
"available",
|
||||
);
|
||||
assert.equal(
|
||||
initialAnnotationPool({ role: "quality_reviewer", workspaceMode: "quality", pool: "reviewed" }),
|
||||
"reviewed",
|
||||
);
|
||||
});
|
||||
|
||||
test("one time display preserves millisecond boundaries and minute rollover", () => {
|
||||
assert.equal(formatAnnotationTime(0), "00:00.000");
|
||||
assert.equal(formatAnnotationTime(59.999), "00:59.999");
|
||||
assert.equal(formatAnnotationTime(60.001), "01:00.001");
|
||||
assert.equal(formatAnnotationTime(3601.123), "60:01.123");
|
||||
assert.equal(formatAnnotationTime(-1), "00:00.000");
|
||||
});
|
||||
|
||||
test("business validation errors identify the actual blocker near the operation", async () => {
|
||||
const { userErrorMessage } = await import("../../src/lib/user-error-message.js");
|
||||
assert.equal(
|
||||
userErrorMessage({
|
||||
status: 400,
|
||||
message: "Validation failed",
|
||||
issues: [{ field: "sliceSegments.0", message: "舍弃原因版本已变化,请重新选择" }],
|
||||
}),
|
||||
"舍弃原因版本已变化。",
|
||||
);
|
||||
assert.equal(
|
||||
userErrorMessage({
|
||||
status: 409,
|
||||
code: "slice_materialization_required",
|
||||
message: "all Capture slices must be materialized",
|
||||
}),
|
||||
"切片尚未完成生成,请先确认切片;已有标注会保留",
|
||||
);
|
||||
});
|
||||
@ -1,3 +1,4 @@
|
||||
import { initialAnnotationPool } from "../../src/lib/annotation-landing.js";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
@ -41,31 +42,12 @@ test("review pool preview keeps the claimable list selected instead of jumping t
|
||||
);
|
||||
});
|
||||
|
||||
test("review workspaces start on the claimable pool even with a URL task id", async () => {
|
||||
const source = await readFile(operationsURL, "utf8");
|
||||
|
||||
const initializer = source.slice(
|
||||
source.indexOf("const [taskPoolView, setTaskPoolView] = useState<TaskPoolView>(() => {"),
|
||||
source.indexOf('workPage || requestedTaskId || requestedAcceptanceId ? "mine" : "available"'),
|
||||
);
|
||||
assert.ok(initializer.length > 0, "task pool view initializer with review-workspace branch is present");
|
||||
assert.match(initializer, /isOrganizationAdminRole\(role\)/);
|
||||
assert.match(
|
||||
initializer,
|
||||
/workspaceMode === "quality" \|\| workspaceMode === "clip-quality" \|\| workspaceMode === "acceptance"/,
|
||||
);
|
||||
assert.match(initializer, /return "available";/);
|
||||
|
||||
// Account switches use the same ownership semantics instead of eagerly
|
||||
// promoting a review deep link to My Tasks.
|
||||
assert.match(
|
||||
source,
|
||||
/workPage \|\| \(blindAnnotator && \(requestedTaskId \|\| requestedAcceptanceId\)\) \? "mine" : "available"/,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/workPage \|\| \(\(blindAnnotator \|\| reviewOnly\) && \(requestedTaskId \|\| requestedAcceptanceId\)\) \? "mine" : "available"/,
|
||||
);
|
||||
test("review deep links retain available previews while ordinary role entry defaults to My Tasks", () => {
|
||||
for (const workspaceMode of ["quality", "clip-quality", "acceptance"]) {
|
||||
const role = workspaceMode === "acceptance" ? "acceptance_reviewer" : "quality_reviewer";
|
||||
assert.equal(initialAnnotationPool({ role, workspaceMode, hasSelection: true }), "available");
|
||||
assert.equal(initialAnnotationPool({ role, workspaceMode, hasSelection: false }), "mine");
|
||||
}
|
||||
});
|
||||
|
||||
test("claiming from the pool still preserves the current list view", async () => {
|
||||
|
||||
54
tests/frontend/slice-edit-panel-feedback.test.mjs
Normal file
54
tests/frontend/slice-edit-panel-feedback.test.mjs
Normal file
@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import test from "node:test";
|
||||
import { dictionaryKeyDown } from "../../src/lib/annotation-shortcuts.js";
|
||||
|
||||
const panel = fs.readFileSync(new URL("../../src/components/SliceEditPanel.tsx", import.meta.url), "utf8");
|
||||
const discard = fs.readFileSync(new URL("../../src/components/DiscardReasonFields.tsx", import.meta.url), "utf8");
|
||||
const dictionary = fs.readFileSync(
|
||||
new URL("../../src/components/WorkspaceDictionaryPanel.tsx", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
test("slice edit panel exposes an in-panel dictionary trigger for the workbench shortcut dispatcher", () => {
|
||||
assert.match(panel, /data-slice-edit-dictionary-trigger/);
|
||||
assert.match(panel, /formatAnnotationTime\(target\[field\]\)/);
|
||||
assert.match(
|
||||
panel,
|
||||
/aria-label=\{`\$\{field === "start" \? "首帧" : "尾帧"\}\$\{exactFrames \? "帧号" : "时间(秒)"\}`\}/,
|
||||
);
|
||||
assert.match(panel, /role="alert"[\s\S]*?data-testid="slice-edit-panel-error"/);
|
||||
});
|
||||
|
||||
test("first Enter in dictionary search selects the first matching option", () => {
|
||||
let selected = 0;
|
||||
let prevented = false;
|
||||
const option = { click: () => selected++ };
|
||||
const event = {
|
||||
key: "Enter",
|
||||
repeat: false,
|
||||
target: { matches: (selector) => selector === "input" },
|
||||
currentTarget: { querySelectorAll: () => [option] },
|
||||
preventDefault: () => (prevented = true),
|
||||
stopPropagation: () => {},
|
||||
};
|
||||
|
||||
dictionaryKeyDown(event, () => {});
|
||||
|
||||
assert.equal(prevented, true);
|
||||
assert.equal(selected, 1);
|
||||
assert.match(dictionary, /if \(firstOption\) onKeyboardSelect\?\.\(\)/);
|
||||
assert.match(discard, /onKeyboardSelect=\{\(\) => panelRef\.current\?\.focus\(\)\}/);
|
||||
});
|
||||
|
||||
test("discard preview Enter confirms only outside text controls and ignores IME composition", () => {
|
||||
assert.match(panel, /if \(event\.nativeEvent\.isComposing \|\| event\.keyCode === 229\) return/);
|
||||
assert.match(panel, /event\.key === "Enter"[\s\S]*?event\.target\.matches\("input, textarea, select, button"\)/);
|
||||
assert.match(panel, /if \(!event\.repeat && reasonReady\) discard\.onConfirm\(\)/);
|
||||
assert.match(panel, /disabled=\{!reasonReady \|\| saving\}/);
|
||||
assert.match(panel, /discard\.loading \|\| Boolean\(discard\.error\)/);
|
||||
assert.match(panel, /discard\.allowManual && !discard\.reasons\.length[\s\S]*?reason\?\.trim\(\)/);
|
||||
assert.match(panel, /item\.version === discard\.draft\?\.reasonVersion/);
|
||||
assert.match(panel, /requiresNote \|\| item\.name === "其他"[\s\S]*?reasonNote\?\.trim\(\)/);
|
||||
assert.match(discard, /<textarea[\s\S]*?value=\{\(manual \? value\.reason : value\.reasonNote\) \|\| ""\}/);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user