package api import ( "net/http" "droboticflow/internal/domain" "github.com/go-chi/chi/v5" ) type sliceEditApplicationInput struct { combinedAnnotationDraftInput RestoreClassifications bool `json:"restoreClassifications,omitempty"` 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 } if rejectInvalidSavedAnnotationWorkspaces(w, stored) { return } workflow := mapValue(stored.Subject.Payload["sliceWorkflow"]) if stringValue(workflow["status"]) == "failed" && !failedSliceEditingAvailable(stored) { renderJSON(w, 409, map[string]string{"error": "任务处理尚未就绪,请完成或恢复后再应用改动"}) return } switch stringValue(workflow["status"]) { case "processing", "running", "materializing", "queued": 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" && !failedSliceEditingAvailable(stored))) { 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 } original := stored stored, err = sliceEditBaseline(original) if err != nil { renderJSON(w, 409, map[string]string{"error": err.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 { command.RestoreClassifications = body.RestoreClassifications 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 { command.RestoreClassifications = body.RestoreClassifications 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...) previousByID := make(map[string]domain.SliceSegment, len(previous)) for _, saved := range previous { previousByID[saved.ID] = saved } for i, candidate := range baseline { if _, changed := commands[candidate.ID]; changed { // Stable identity wins over ancestry. A restored child may retain the // identity of a still-discarded sibling as an older ancestor. old := previousByID[candidate.ID] if old.ID == "" { // Cuts list the immediate parent before flattened older ancestors. for _, id := range candidate.SourceIDs { if saved, ok := previousByID[id]; ok { old = saved break } } } baseline[i] = sliceEditPolicyBaseline(candidate, old) if command := commands[candidate.ID]; command.Disposition == "discard" && !old.IsDiscarded() { baseline[i].Name = old.Name baseline[i].Dictionary = old.Dictionary } } } slices, issues := s.canonicalSliceDispositionState(r.Context(), &item, baseline, body.normalizedOperations()) issues = append(issues, s.validateProjectSliceNames(r.Context(), stored, slices, applicationDictionaryMode(body))...) 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 } } if issues := s.canonicalActionDictionaries(r.Context(), stored, segmentsForApplication, applicationDictionaryMode(body)); len(issues) > 0 { renderValidationError(w, issues...) return } copyClassificationRecoveryState(&item, stored) 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 { command.RestoreClassifications = body.RestoreClassifications 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"]) // Boundary archiving must not hide an unsupported action state from the // normal continuous-action guard that runs on the remaining active track. if s.continuousActionsForItem(r.Context(), &item) { if stateIssues := validateContinuousActionStates(segments, false); len(stateIssues) > 0 { renderValidationError(w, stateIssues...) return } } template, e := s.store.GetAnnotationTemplate(r.Context(), task.TemplateID) if e != nil { renderError(w, 500, e) return } // Check dictionary IDs and containment before archiving removes pieces from // the active track. Discard ownership is checked against the real slices below. validationSlices := append([]domain.SliceSegment(nil), slices...) for i := range validationSlices { validationSlices[i].DeliveryDisposition = "keep" validationSlices[i].AnnotationStatus = "" } if inputIssues := validateDraftFanyuV5CombinedSemanticSegments(segments, validationSlices, annotationTemplateWithTaskSnapshot(template, task)); len(inputIssues) > 0 { renderValidationError(w, inputIssues...) return } segments = archiveSliceEditBoundaryActions(&item, previous, slices, 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 slices[i].Dictionary = candidate.Dictionary } } } issues = s.validateProjectSliceNames(r.Context(), stored, slices, applicationDictionaryMode(body)) issues = append(issues, s.canonicalActionDictionaries(r.Context(), stored, segments, applicationDictionaryMode(body))...) copyClassificationRecoveryState(&item, stored) issues = append(issues, s.validateSliceEditFrameBounds(r, task, &item, slices, segments)...) issues = append(issues, validateDraftCombinedAnnotationEvents(segments, *task)...) 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 storeSliceEditWorkspace(&item, original, workspace) // Recheck dictionary versions immediately before the single commit. for _, command := range body.Dispositions { command.RestoreClassifications = body.RestoreClassifications 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.DiscardReasonDictionary = old.DiscardReasonDictionary 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 } func applicationDictionaryMode(body sliceEditApplicationInput) string { if body.RestoreClassifications { return "restore" } return "draft" }