✨ Complete Fanyu Capture operations gaps
This commit is contained in:
parent
95fb898407
commit
b085e371b2
@ -401,6 +401,53 @@ def _read_imu(path: pathlib.Path) -> list[dict[str, Any]]:
|
||||
return result
|
||||
|
||||
|
||||
def _read_materialized_pts(path: pathlib.Path) -> list[int]:
|
||||
header, rows = _read_rows(path)
|
||||
normalized = {name.lower(): index for index, name in enumerate(header)}
|
||||
timestamp_column = normalized.get("timestamp_ms")
|
||||
if timestamp_column is None:
|
||||
raise RuntimeError(f"materialized PTS CSV must contain timestamp_ms: {path.name}")
|
||||
values: list[int] = []
|
||||
for row in rows:
|
||||
try:
|
||||
value = int(round(float(row[timestamp_column]) * 1000))
|
||||
except (IndexError, ValueError) as exc:
|
||||
raise RuntimeError(f"materialized PTS CSV contains an invalid timestamp_ms: {path.name}") from exc
|
||||
if values and value <= values[-1]:
|
||||
raise RuntimeError(f"materialized PTS CSV timestamp_ms must be strictly increasing: {path.name}")
|
||||
values.append(value)
|
||||
if not values:
|
||||
raise RuntimeError(f"materialized PTS CSV has no frame timestamps: {path.name}")
|
||||
return values
|
||||
|
||||
|
||||
def _validate_materialized_imu(path: pathlib.Path, start_us: int, end_us: int) -> int:
|
||||
header, rows = _read_rows(path)
|
||||
indexes = {name.lower(): index for index, name in enumerate(header)}
|
||||
required = {"timestamp_ms", "clip_time_ms", "x", "y", "z", "type"}
|
||||
if not required.issubset(indexes):
|
||||
raise RuntimeError(f"materialized IMU CSV is missing required columns: {path.name}")
|
||||
previous = -1
|
||||
seen_types: dict[int, set[str]] = {}
|
||||
for row in rows:
|
||||
try:
|
||||
timestamp_us = int(round(float(row[indexes["timestamp_ms"]]) * 1000))
|
||||
kind = row[indexes["type"]].lower()
|
||||
for key in ("x", "y", "z"):
|
||||
float(row[indexes[key]])
|
||||
except (IndexError, ValueError) as exc:
|
||||
raise RuntimeError(f"materialized IMU CSV contains an invalid row: {path.name}") from exc
|
||||
if timestamp_us < previous or kind not in {"accel", "gyro"}:
|
||||
raise RuntimeError(f"materialized IMU ordering/type is invalid: {path.name}")
|
||||
if timestamp_us < start_us or timestamp_us >= end_us:
|
||||
raise RuntimeError(f"materialized IMU row is outside the synchronized slice window: {path.name}")
|
||||
previous = timestamp_us
|
||||
seen_types.setdefault(timestamp_us, set()).add(kind)
|
||||
if not rows or any(types != {"accel", "gyro"} for types in seen_types.values()):
|
||||
raise RuntimeError(f"materialized IMU must contain paired accel/gyro samples: {path.name}")
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _ffprobe_frame_count(path: pathlib.Path) -> int:
|
||||
completed = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "default=nokey=1:noprint_wrappers=1", str(path)], capture_output=True, text=True, check=False)
|
||||
try:
|
||||
@ -1051,6 +1098,27 @@ def _run_accepted_slice_directory(
|
||||
shutil.copytree(source_slice, target_slice, dirs_exist_ok=True)
|
||||
start = float(raw.get("startSecond") or 0.0)
|
||||
end = float(raw.get("endSecond") or 0.0)
|
||||
start_us = int(raw.get("startTimestampUs") or 0)
|
||||
end_us = int(raw.get("endTimestampUs") or 0)
|
||||
required_files = ["left.mp4", "right.mp4", "left_pts.csv", "right_pts.csv", "imu.csv", "annotation.json", "synchronized-slice.json"]
|
||||
missing_files = [name for name in required_files if not (target_slice / name).is_file()]
|
||||
if missing_files:
|
||||
raise RuntimeError(f"accepted slice {slice_id} is missing required files: {', '.join(missing_files)}")
|
||||
left_pts = _read_materialized_pts(target_slice / "left_pts.csv")
|
||||
right_pts = _read_materialized_pts(target_slice / "right_pts.csv")
|
||||
if _ffprobe_frame_count(target_slice / "left.mp4") != len(left_pts):
|
||||
raise RuntimeError(f"accepted slice {slice_id} left video/PTS frame count mismatch")
|
||||
if _ffprobe_frame_count(target_slice / "right.mp4") != len(right_pts):
|
||||
raise RuntimeError(f"accepted slice {slice_id} right video/PTS frame count mismatch")
|
||||
_validate_materialized_imu(target_slice / "imu.csv", start_us, end_us)
|
||||
declared_files = raw.get("files") if isinstance(raw.get("files"), dict) else {}
|
||||
for declared in declared_files.values():
|
||||
if not isinstance(declared, dict):
|
||||
continue
|
||||
name = str(declared.get("name") or "").strip()
|
||||
expected_sha = str(declared.get("sha256") or "").strip()
|
||||
if name and expected_sha and (target_slice / name).is_file() and _sha256_file(target_slice / name) != expected_sha:
|
||||
raise RuntimeError(f"accepted slice {slice_id} checksum mismatch: {name}")
|
||||
if pose_policy.get("headpose") == "include":
|
||||
cropped = _crop_pose(headpose, start, end, "headpose") if headpose else None
|
||||
if cropped is None or cropped.get("frameCount", 0) <= 0:
|
||||
@ -1089,7 +1157,21 @@ def _run_accepted_slice_directory(
|
||||
"randomValue": final_acceptance.get("samplingRandomValue"),
|
||||
"decidedAt": final_acceptance.get("samplingDecidedAt"),
|
||||
}
|
||||
manifest = {"schemaVersion": "droboticflow.delivery.manifest/v5", "datasetType": "fanyu-accepted-slice-directories", "revision": revision_manifest.get("revision"), "sliceCount": len(package_items), "coverage": coverage, "acceptanceSampling": sampling, "poseDelivery": pose_policy, "calibration": calibration, "lineage": {"acceptedSliceDirectoryArtifactId": directory_artifact.get("id"), "humanItemId": revision_manifest.get("humanItemId"), "taskId": revision_manifest.get("taskId"), "sourceRunId": revision_manifest.get("runId")}, "items": package_items}
|
||||
capture_record = summary_payload.get("capture") if isinstance(summary_payload.get("capture"), dict) else revision_manifest.get("capture") if isinstance(revision_manifest.get("capture"), dict) else {}
|
||||
quality_reviews = summary_payload.get("qualityReviews") if isinstance(summary_payload.get("qualityReviews"), list) else []
|
||||
capture_manifest = {"schemaVersion": "droboticflow.capture-delivery/v1", "capture": capture_record, "revision": revision_manifest.get("revision"), "coverage": coverage, "sliceCount": len(package_items), "lineage": {"acceptedSliceDirectoryArtifactId": directory_artifact.get("id"), "humanItemId": revision_manifest.get("humanItemId"), "taskId": revision_manifest.get("taskId"), "sourceRunId": revision_manifest.get("runId")}}
|
||||
evidence_payloads = {
|
||||
"capture-manifest.json": capture_manifest,
|
||||
"quality-review.json": {"schemaVersion": "droboticflow.capture-quality-review/v1", "reviews": quality_reviews},
|
||||
"acceptance-record.json": {"schemaVersion": "droboticflow.capture-acceptance/v1", "finalAcceptance": final_acceptance},
|
||||
"sampling-evidence.json": {"schemaVersion": "droboticflow.capture-sampling/v1", **sampling},
|
||||
}
|
||||
root_evidence = []
|
||||
for name, payload in evidence_payloads.items():
|
||||
path = delivery_root / name
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
root_evidence.append({"name": name, "sha256": _sha256_file(path), "bytes": path.stat().st_size})
|
||||
manifest = {"schemaVersion": "droboticflow.delivery.manifest/v5", "datasetType": "fanyu-accepted-slice-directories", "capture": capture_record, "revision": revision_manifest.get("revision"), "sliceCount": len(package_items), "coverage": coverage, "acceptanceSampling": sampling, "poseDelivery": pose_policy, "calibration": calibration, "rootEvidence": root_evidence, "lineage": {"acceptedSliceDirectoryArtifactId": directory_artifact.get("id"), "humanItemId": revision_manifest.get("humanItemId"), "taskId": revision_manifest.get("taskId"), "sourceRunId": revision_manifest.get("runId")}, "items": package_items}
|
||||
manifest_binding = _output(node_data, helpers, "deliveryManifest")
|
||||
directory_binding = _output(node_data, helpers, "deliveryDirectory")
|
||||
result = [helpers["write_json_artifact"](run_id, node_id, delivery_root, "packages-manifest.json", manifest, output=manifest_binding)]
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
|
||||
`项目 → Capture 目录 → 切片`
|
||||
|
||||
工作流只是 Capture 的处理配置,不是数据层级。泛宇不使用“15 分钟数据包”或 Episode 概念;平台中 LeRobot、RLDS、DROID 等通用算子的行业术语不受影响。
|
||||
工作流只是 Capture 的处理配置,不是数据层级。泛宇全部页面、接口、目录和交付文件统一使用“项目、Capture、切片”三个业务概念;通用数据集算子的行业数据结构不受影响。
|
||||
|
||||
## 生产流程
|
||||
|
||||
|
||||
@ -22,6 +22,15 @@ type annotationLabelInput struct {
|
||||
Status domain.AnnotationLabelStatus `json:"status"`
|
||||
}
|
||||
|
||||
func annotationLabelRevision(item domain.AnnotationLabelRecord) domain.AnnotationLabelRevision {
|
||||
return domain.AnnotationLabelRevision{
|
||||
Version: item.Version, Code: item.Code, Name: item.Name, Category: item.Category,
|
||||
Description: item.Description, Example: item.Example, Color: item.Color,
|
||||
Aliases: append([]string(nil), item.Aliases...), Status: item.Status,
|
||||
UpdatedByUserID: item.UpdatedByUserID, UpdatedAt: item.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeAnnotationLabelInput(input annotationLabelInput) annotationLabelInput {
|
||||
input.Code = strings.TrimSpace(input.Code)
|
||||
input.Name = strings.TrimSpace(input.Name)
|
||||
@ -69,6 +78,11 @@ func (server *server) handleAnnotationLabelsList(writer http.ResponseWriter, req
|
||||
renderError(writer, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
for index := range items {
|
||||
if len(items[index].History) == 0 {
|
||||
items[index].History = []domain.AnnotationLabelRevision{annotationLabelRevision(items[index])}
|
||||
}
|
||||
}
|
||||
renderJSON(writer, http.StatusOK, map[string]any{"items": items})
|
||||
}
|
||||
|
||||
@ -108,6 +122,7 @@ func (server *server) handleAnnotationLabelCreate(writer http.ResponseWriter, re
|
||||
Aliases: payload.Aliases, Status: payload.Status, Version: 1,
|
||||
CreatedByUserID: actorID, UpdatedByUserID: actorID, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
item.History = []domain.AnnotationLabelRevision{annotationLabelRevision(item)}
|
||||
if err := server.store.UpsertAnnotationLabel(request.Context(), item); err != nil {
|
||||
renderError(writer, http.StatusInternalServerError, err)
|
||||
return
|
||||
@ -152,6 +167,10 @@ func (server *server) handleAnnotationLabelPatch(writer http.ResponseWriter, req
|
||||
item.Aliases, item.Status = payload.Aliases, payload.Status
|
||||
item.Version++
|
||||
item.UpdatedByUserID, item.UpdatedAt = principal.User.ID, nowISO()
|
||||
item.History = append(item.History, annotationLabelRevision(*item))
|
||||
if len(item.History) > 100 {
|
||||
item.History = append([]domain.AnnotationLabelRevision(nil), item.History[len(item.History)-100:]...)
|
||||
}
|
||||
if err := server.store.UpsertAnnotationLabel(request.Context(), *item); err != nil {
|
||||
renderError(writer, http.StatusInternalServerError, err)
|
||||
return
|
||||
|
||||
@ -127,6 +127,12 @@ func (server *server) captureAutomationPayload(ctx context.Context, ctxWorkflow
|
||||
record.NextRetryAt = run.AvailableAt
|
||||
}
|
||||
record.ParentRunID = run.ParentRunID
|
||||
if run.Failure != nil {
|
||||
record.FailedNodeID = strings.TrimSpace(run.Failure.NodeID)
|
||||
if strings.TrimSpace(record.Error) == "" {
|
||||
record.Error = strings.TrimSpace(run.Failure.Message)
|
||||
}
|
||||
}
|
||||
record.BusinessStage = server.captureBusinessStage(ctx, *record, run)
|
||||
}
|
||||
return captureAutomationResponse{Config: config, Counts: captureAutomationCounts(records), Records: records}
|
||||
|
||||
@ -95,6 +95,47 @@ func TestCaptureAutomationCountsSeparateFailuresAndCancellations(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureAutomationReleasedWorkflowRejectsManualProductionRootRun(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
dataStore := store.NewMemoryStore()
|
||||
project, err := dataStore.CreateProject(ctx, domain.CreateProjectInput{OrganizationID: domain.DefaultOrganizationID, Name: "Fanyu"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workflow, err := dataStore.CreateWorkflow(ctx, domain.CreateWorkflowInput{
|
||||
OrganizationID: domain.DefaultOrganizationID,
|
||||
ProjectID: project.ID,
|
||||
Name: "Capture listener",
|
||||
Type: domain.WorkflowTypeBatch,
|
||||
WorkflowInputs: []domain.WorkflowInputDefinition{{
|
||||
ID: "sourceDirectory", Name: "sourceDirectory", Type: domain.PortTypeFile,
|
||||
Container: domain.PortContainerDirectory, PayloadMode: domain.ArtifactTransferModeRef, Required: true,
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workflow.DefinitionState = domain.WorkflowDefinitionStateReleased
|
||||
workflow.CaptureAutomation = &domain.CaptureAutomationConfig{Enabled: true, WorkflowInputID: "sourceDirectory"}
|
||||
if err := dataStore.UpsertWorkflow(ctx, *workflow); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
handler := NewHandler(dataStore, nil)
|
||||
body := bytes.NewBufferString(`{"trigger":"manual","mode":"production","inputs":{"sourceDirectory":{"mode":"ref","type":"file","ref":{"provider":"bos","bucket":"drobodata-fanyu","prefix":"test","kind":"directory"}}}}`)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/workflows/"+workflow.ID+"/run", body)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), `"code":"capture_automation_manual_run_forbidden"`) {
|
||||
t.Fatalf("manual Capture root run status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
runs, err := dataStore.ListRuns(ctx, "")
|
||||
if err != nil || len(runs) != 0 {
|
||||
t.Fatalf("manual root request created runs: %#v err=%v", runs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureRecordCancelStopsRunCancelsHumanWorkAndKeepsRetryMetadata(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
dataStore := store.NewMemoryStore()
|
||||
|
||||
@ -308,11 +308,15 @@ func (server *server) handleHumanItemSubjectContent(writer http.ResponseWriter,
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(item.RunID) == "" || strings.TrimSpace(item.Subject.ArtifactID) == "" {
|
||||
artifactID := strings.TrimSpace(item.Subject.ArtifactID)
|
||||
if strings.EqualFold(strings.TrimSpace(request.URL.Query().Get("side")), "right") && item.Subject.Payload != nil {
|
||||
artifactID = strings.TrimSpace(fmt.Sprint(item.Subject.Payload["rightArtifactId"]))
|
||||
}
|
||||
if strings.TrimSpace(item.RunID) == "" || artifactID == "" {
|
||||
renderJSON(writer, http.StatusNotFound, map[string]string{"error": "Human item subject artifact not found"})
|
||||
return
|
||||
}
|
||||
server.serveRunArtifactContent(writer, request, item.RunID, item.Subject.ArtifactID)
|
||||
server.serveRunArtifactContent(writer, request, item.RunID, artifactID)
|
||||
}
|
||||
|
||||
func humanEvidenceArtifactRunIDs(value any, inheritedRunID string, destination map[string]string) {
|
||||
|
||||
@ -714,7 +714,16 @@ func (server *server) materializeCombinedSliceSubmission(ctx context.Context, ta
|
||||
return nil, fmt.Errorf("slice reconstruction coverage mismatch: left=%d/%d right=%d/%d imu=%d/%d", deliveredLeftFrames, expectedLeftFrames, deliveredRightFrames, expectedRightFrames, deliveredIMURows, imuCommonCount)
|
||||
}
|
||||
coverage := map[string]any{"mode": "full_common_range", "contiguous": true, "gapMicroseconds": 0, "overlapMicroseconds": 0, "startSecond": commonMediaStart, "endSecond": commonMediaEnd, "durationSeconds": commonMediaEnd - commonMediaStart, "startTimestampUs": commonStart, "endTimestampUs": commonEnd, "ptsToMediaScale": ptsToMediaScale, "sliceCount": len(manifestItems), "reconstruction": map[string]any{"leftFrameCount": deliveredLeftFrames, "rightFrameCount": deliveredRightFrames, "imuRowCount": deliveredIMURows}}
|
||||
revisionManifest := map[string]any{"schemaVersion": "droboticflow.slice-materialization/v2", "revision": revision, "humanItemId": item.ID, "taskId": task.ID, "runId": task.RunID, "collectionId": collectionID, "status": "materialized", "sliceCount": len(manifestItems), "coverage": coverage, "items": manifestItems}
|
||||
captureEvidence := map[string]any{}
|
||||
if capture, captureErr := server.store.GetCaptureRecordByRunID(ctx, task.RunID); captureErr != nil {
|
||||
return nil, captureErr
|
||||
} else if capture != nil {
|
||||
captureEvidence = map[string]any{
|
||||
"captureRecordId": capture.ID, "captureId": capture.CaptureID, "prefix": capture.Prefix,
|
||||
"fingerprint": capture.Fingerprint, "contractRevision": capture.ContractRevision,
|
||||
}
|
||||
}
|
||||
revisionManifest := map[string]any{"schemaVersion": "droboticflow.slice-materialization/v2", "revision": revision, "humanItemId": item.ID, "taskId": task.ID, "runId": task.RunID, "collectionId": collectionID, "capture": captureEvidence, "status": "materialized", "sliceCount": len(manifestItems), "coverage": coverage, "items": manifestItems}
|
||||
manifestPath := filepath.Join(root, "revision-manifest.json")
|
||||
manifestSHA, manifestBytes, err := writeJSONFile(manifestPath, revisionManifest)
|
||||
if err != nil {
|
||||
|
||||
@ -37,6 +37,21 @@ func isOrganizationAdmin(principal *authenticatedPrincipal) bool {
|
||||
return principal != nil && (principal.User.IsSuperAdmin || principal.User.Role == domain.UserRoleAdmin || principal.User.Role == domain.UserRoleOrganizationAdmin)
|
||||
}
|
||||
|
||||
func isSupplierManager(principal *authenticatedPrincipal) bool {
|
||||
return principal != nil && principal.User.Role == domain.UserRoleSupplierManager && strings.TrimSpace(principal.User.SupplierID) != ""
|
||||
}
|
||||
|
||||
func projectMemberManager(principal *authenticatedPrincipal) bool {
|
||||
return isOrganizationAdmin(principal) || isSupplierManager(principal)
|
||||
}
|
||||
|
||||
func projectMemberSupplierAllowed(principal *authenticatedPrincipal, supplierID string) bool {
|
||||
if isOrganizationAdmin(principal) {
|
||||
return true
|
||||
}
|
||||
return isSupplierManager(principal) && strings.TrimSpace(principal.User.SupplierID) == strings.TrimSpace(supplierID)
|
||||
}
|
||||
|
||||
func normalizedMemberRoles(values []domain.AnnotationAssignmentRole) ([]domain.AnnotationAssignmentRole, bool) {
|
||||
roles := domain.NormalizeProjectMemberRoles(values)
|
||||
return roles, len(roles) > 0
|
||||
@ -124,7 +139,7 @@ func (server *server) handleProjectMembersList(writer http.ResponseWriter, reque
|
||||
renderJSON(writer, http.StatusOK, map[string]any{"items": filtered})
|
||||
}
|
||||
|
||||
func (server *server) saveProjectMember(writer http.ResponseWriter, request *http.Request, project *domain.ProjectRecord, member *domain.ProjectMemberRecord, payload projectMemberInput, created bool) {
|
||||
func (server *server) saveProjectMember(writer http.ResponseWriter, request *http.Request, principal *authenticatedPrincipal, project *domain.ProjectRecord, member *domain.ProjectMemberRecord, payload projectMemberInput, created bool) {
|
||||
payload.UserID = strings.TrimSpace(payload.UserID)
|
||||
payload.SupplierID = strings.TrimSpace(payload.SupplierID)
|
||||
roles, valid := normalizedMemberRoles(payload.Roles)
|
||||
@ -144,6 +159,10 @@ func (server *server) saveProjectMember(writer http.ResponseWriter, request *htt
|
||||
if payload.SupplierID == "" {
|
||||
payload.SupplierID = strings.TrimSpace(user.SupplierID)
|
||||
}
|
||||
if !projectMemberSupplierAllowed(principal, payload.SupplierID) || (isSupplierManager(principal) && strings.TrimSpace(user.SupplierID) != strings.TrimSpace(principal.User.SupplierID)) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "supplier manager may only maintain users and project members in their own supplier", "code": "supplier_scope_forbidden"})
|
||||
return
|
||||
}
|
||||
if payload.SupplierID != "" {
|
||||
supplier, supplierErr := server.store.GetSupplier(request.Context(), payload.SupplierID)
|
||||
if supplierErr != nil {
|
||||
@ -173,8 +192,8 @@ func (server *server) saveProjectMember(writer http.ResponseWriter, request *htt
|
||||
|
||||
func (server *server) handleProjectMemberCreate(writer http.ResponseWriter, request *http.Request) {
|
||||
principal, _ := currentPrincipal(request)
|
||||
if !isOrganizationAdmin(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin is required"})
|
||||
if !projectMemberManager(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin or supplier manager is required"})
|
||||
return
|
||||
}
|
||||
projectID := strings.TrimSpace(chi.URLParam(request, "id"))
|
||||
@ -200,13 +219,13 @@ func (server *server) handleProjectMemberCreate(writer http.ResponseWriter, requ
|
||||
renderJSON(writer, http.StatusConflict, map[string]any{"error": "project member already exists", "member": existing})
|
||||
return
|
||||
}
|
||||
server.saveProjectMember(writer, request, project, nil, payload, true)
|
||||
server.saveProjectMember(writer, request, principal, project, nil, payload, true)
|
||||
}
|
||||
|
||||
func (server *server) handleProjectMemberUpdate(writer http.ResponseWriter, request *http.Request) {
|
||||
principal, _ := currentPrincipal(request)
|
||||
if !isOrganizationAdmin(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin is required"})
|
||||
if !projectMemberManager(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin or supplier manager is required"})
|
||||
return
|
||||
}
|
||||
member, err := server.store.GetProjectMember(request.Context(), strings.TrimSpace(chi.URLParam(request, "memberId")))
|
||||
@ -218,6 +237,10 @@ func (server *server) handleProjectMemberUpdate(writer http.ResponseWriter, requ
|
||||
renderJSON(writer, http.StatusNotFound, map[string]string{"error": "project member not found"})
|
||||
return
|
||||
}
|
||||
if !projectMemberSupplierAllowed(principal, member.SupplierID) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "supplier manager may only maintain project members in their own supplier", "code": "supplier_scope_forbidden"})
|
||||
return
|
||||
}
|
||||
project, err := server.store.GetProject(request.Context(), member.ProjectID)
|
||||
if err != nil || project == nil {
|
||||
if err != nil {
|
||||
@ -232,7 +255,7 @@ func (server *server) handleProjectMemberUpdate(writer http.ResponseWriter, requ
|
||||
return
|
||||
}
|
||||
payload.UserID = member.UserID
|
||||
server.saveProjectMember(writer, request, project, member, payload, false)
|
||||
server.saveProjectMember(writer, request, principal, project, member, payload, false)
|
||||
}
|
||||
|
||||
func (server *server) releaseProjectMemberTasks(ctx context.Context, organizationID string, member domain.ProjectMemberRecord, actorID string) (int, error) {
|
||||
@ -267,8 +290,8 @@ func (server *server) releaseProjectMemberTasks(ctx context.Context, organizatio
|
||||
|
||||
func (server *server) handleProjectMemberDelete(writer http.ResponseWriter, request *http.Request) {
|
||||
principal, _ := currentPrincipal(request)
|
||||
if !isOrganizationAdmin(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin is required"})
|
||||
if !projectMemberManager(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin or supplier manager is required"})
|
||||
return
|
||||
}
|
||||
member, err := server.store.GetProjectMember(request.Context(), strings.TrimSpace(chi.URLParam(request, "memberId")))
|
||||
@ -280,6 +303,10 @@ func (server *server) handleProjectMemberDelete(writer http.ResponseWriter, requ
|
||||
renderJSON(writer, http.StatusNotFound, map[string]string{"error": "project member not found"})
|
||||
return
|
||||
}
|
||||
if !projectMemberSupplierAllowed(principal, member.SupplierID) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "supplier manager may only maintain project members in their own supplier", "code": "supplier_scope_forbidden"})
|
||||
return
|
||||
}
|
||||
releaseTasks := strings.EqualFold(strings.TrimSpace(request.URL.Query().Get("releaseTasks")), "true")
|
||||
if releaseTasks {
|
||||
if _, err := server.releaseProjectMemberTasks(request.Context(), member.OrganizationID, *member, principal.User.ID); err != nil {
|
||||
@ -301,8 +328,8 @@ func (server *server) handleProjectMemberDelete(writer http.ResponseWriter, requ
|
||||
|
||||
func (server *server) handleProjectMembersBulk(writer http.ResponseWriter, request *http.Request) {
|
||||
principal, _ := currentPrincipal(request)
|
||||
if !isOrganizationAdmin(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin is required"})
|
||||
if !projectMemberManager(principal) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization admin or supplier manager is required"})
|
||||
return
|
||||
}
|
||||
projectID := strings.TrimSpace(chi.URLParam(request, "id"))
|
||||
@ -321,7 +348,7 @@ func (server *server) handleProjectMembersBulk(writer http.ResponseWriter, reque
|
||||
}
|
||||
payload.Action = strings.ToLower(strings.TrimSpace(payload.Action))
|
||||
if payload.Action == "add" {
|
||||
server.handleProjectMembersBulkAdd(writer, request, project, payload.Entries)
|
||||
server.handleProjectMembersBulkAdd(writer, request, principal, project, payload.Entries)
|
||||
return
|
||||
}
|
||||
roles, valid := normalizedMemberRoles(payload.Roles)
|
||||
@ -335,6 +362,10 @@ func (server *server) handleProjectMembersBulk(writer http.ResponseWriter, reque
|
||||
if err != nil || member == nil || member.ProjectID != projectID || !server.filterByTenant(request, member.OrganizationID) {
|
||||
continue
|
||||
}
|
||||
if !projectMemberSupplierAllowed(principal, member.SupplierID) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "supplier manager may only maintain project members in their own supplier", "code": "supplier_scope_forbidden"})
|
||||
return
|
||||
}
|
||||
if payload.Action == "remove" {
|
||||
if _, err = server.releaseProjectMemberTasks(request.Context(), member.OrganizationID, *member, principal.User.ID); err == nil {
|
||||
_, err = server.store.DeleteProjectMember(request.Context(), member.ID)
|
||||
@ -352,7 +383,7 @@ func (server *server) handleProjectMembersBulk(writer http.ResponseWriter, reque
|
||||
renderJSON(writer, http.StatusOK, projectMemberBulkResult{Updated: updated})
|
||||
}
|
||||
|
||||
func (server *server) handleProjectMembersBulkAdd(writer http.ResponseWriter, request *http.Request, project *domain.ProjectRecord, entries []projectMemberInput) {
|
||||
func (server *server) handleProjectMembersBulkAdd(writer http.ResponseWriter, request *http.Request, principal *authenticatedPrincipal, project *domain.ProjectRecord, entries []projectMemberInput) {
|
||||
if len(entries) == 0 {
|
||||
renderValidationError(writer, validationIssue{Field: "entries", Message: "at least one project member entry is required"})
|
||||
return
|
||||
@ -411,6 +442,10 @@ func (server *server) handleProjectMembersBulkAdd(writer http.ResponseWriter, re
|
||||
if entry.SupplierID == "" {
|
||||
entry.SupplierID = strings.TrimSpace(user.SupplierID)
|
||||
}
|
||||
if !projectMemberSupplierAllowed(principal, entry.SupplierID) || (isSupplierManager(principal) && strings.TrimSpace(user.SupplierID) != strings.TrimSpace(principal.User.SupplierID)) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "supplier manager may only maintain users and project members in their own supplier", "code": "supplier_scope_forbidden"})
|
||||
return
|
||||
}
|
||||
if entry.SupplierID != "" {
|
||||
supplier, cached := supplierCache[entry.SupplierID]
|
||||
if !cached {
|
||||
|
||||
@ -186,6 +186,80 @@ func TestBulkProjectMemberAddValidatesWholeRequestBeforeWriting(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupplierManagerMaintainsOnlyOwnSupplierProjectMembers(t *testing.T) {
|
||||
t.Setenv("DROBOTICFLOW_REQUIRE_SESSION_AUTH", "true")
|
||||
ctx := context.Background()
|
||||
dataStore := store.NewMemoryStore()
|
||||
handler := NewHandler(dataStore, nil)
|
||||
rootCookie := bootstrapSuperAdminSession(t, handler)
|
||||
organization := adminCreateOrganization(t, handler, rootCookie, "Supplier member scope", "supplier-member-scope")
|
||||
supplierA := domain.SupplierRecord{ID: "supplier-a", OrganizationID: organization.ID, Name: "Supplier A", Status: "active"}
|
||||
supplierB := domain.SupplierRecord{ID: "supplier-b", OrganizationID: organization.ID, Name: "Supplier B", Status: "active"}
|
||||
if err := dataStore.UpsertSupplier(ctx, supplierA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dataStore.UpsertSupplier(ctx, supplierB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager := adminCreateUser(t, handler, rootCookie, organization.ID, "Supplier Manager", "supplier-manager@example.com", domain.UserRoleSupplierManager, "manager-password")
|
||||
storedManager, err := dataStore.GetUser(ctx, manager.ID)
|
||||
if err != nil || storedManager == nil {
|
||||
t.Fatalf("load manager: %#v err=%v", storedManager, err)
|
||||
}
|
||||
storedManager.SupplierID = supplierA.ID
|
||||
if err := dataStore.UpsertUser(ctx, *storedManager); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workerA := adminCreateUser(t, handler, rootCookie, organization.ID, "Worker A", "supplier-worker-a@example.com", domain.UserRoleMember, "worker-password")
|
||||
storedWorkerA, err := dataStore.GetUser(ctx, workerA.ID)
|
||||
if err != nil || storedWorkerA == nil {
|
||||
t.Fatalf("load worker A: %#v err=%v", storedWorkerA, err)
|
||||
}
|
||||
storedWorkerA.SupplierID = supplierA.ID
|
||||
if err := dataStore.UpsertUser(ctx, *storedWorkerA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workerB := adminCreateUser(t, handler, rootCookie, organization.ID, "Worker B", "supplier-worker-b@example.com", domain.UserRoleMember, "worker-password")
|
||||
storedWorkerB, err := dataStore.GetUser(ctx, workerB.ID)
|
||||
if err != nil || storedWorkerB == nil {
|
||||
t.Fatalf("load worker B: %#v err=%v", storedWorkerB, err)
|
||||
}
|
||||
storedWorkerB.SupplierID = supplierB.ID
|
||||
if err := dataStore.UpsertUser(ctx, *storedWorkerB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
managerCookie := loginSession(t, handler, manager.Email, "manager-password")
|
||||
project, err := dataStore.CreateProject(ctx, domain.CreateProjectInput{OrganizationID: organization.ID, Name: "Supplier project"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ownBody, _ := json.Marshal(map[string]any{"userId": workerA.ID, "supplierId": supplierA.ID, "roles": []string{"annotator"}})
|
||||
created := serveJSONWithCookie(handler, http.MethodPost, "/api/projects/"+project.ID+"/members", ownBody, managerCookie)
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("supplier manager create own member=%d body=%s", created.Code, created.Body.String())
|
||||
}
|
||||
var ownMember domain.ProjectMemberRecord
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &ownMember); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updateBody, _ := json.Marshal(map[string]any{"supplierId": supplierA.ID, "roles": []string{"annotator", "quality_reviewer"}})
|
||||
updated := serveJSONWithCookie(handler, http.MethodPatch, "/api/projects/"+project.ID+"/members/"+ownMember.ID, updateBody, managerCookie)
|
||||
if updated.Code != http.StatusOK || !jsonContains(updated.Body.String(), "quality_reviewer") {
|
||||
t.Fatalf("supplier manager update own member=%d body=%s", updated.Code, updated.Body.String())
|
||||
}
|
||||
|
||||
otherBody, _ := json.Marshal(map[string]any{"userId": workerB.ID, "supplierId": supplierB.ID, "roles": []string{"annotator"}})
|
||||
forbidden := serveJSONWithCookie(handler, http.MethodPost, "/api/projects/"+project.ID+"/members", otherBody, managerCookie)
|
||||
if forbidden.Code != http.StatusForbidden || !jsonContains(forbidden.Body.String(), `"code":"supplier_scope_forbidden"`) {
|
||||
t.Fatalf("supplier manager crossed supplier scope=%d body=%s", forbidden.Code, forbidden.Body.String())
|
||||
}
|
||||
otherMember, _ := dataStore.GetProjectMemberByProjectUser(ctx, organization.ID, project.ID, workerB.ID)
|
||||
if otherMember != nil {
|
||||
t.Fatalf("cross-supplier member was created: %#v", otherMember)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonContains(value string, expected string) bool {
|
||||
return len(expected) == 0 || (len(value) >= len(expected) && containsText(value, expected))
|
||||
}
|
||||
|
||||
@ -1459,7 +1459,7 @@ func NewHandlerWithConfig(dataStore store.Store, aiService ai.Service, appConfig
|
||||
router.Post("/api/scan-configs/{id}/run", instance.handleScanConfigsRun)
|
||||
})
|
||||
router.Group(func(router chi.Router) {
|
||||
router.Use(instance.requireBusinessRole(domain.UserRoleAdmin, domain.UserRoleOrganizationAdmin))
|
||||
router.Use(instance.requireBusinessRole(domain.UserRoleAdmin, domain.UserRoleOrganizationAdmin, domain.UserRoleSupplierManager))
|
||||
router.Post("/api/suppliers", instance.handleSupplierCreate)
|
||||
router.Post("/api/projects/{id}/members", instance.handleProjectMemberCreate)
|
||||
router.Patch("/api/projects/{id}/members/{memberId}", instance.handleProjectMemberUpdate)
|
||||
@ -1567,8 +1567,11 @@ func NewHandlerWithConfig(dataStore store.Store, aiService ai.Service, appConfig
|
||||
router.Put("/api/users/{id}/storage-path-favorites", instance.handleUserStoragePathFavoritesUpdate)
|
||||
router.Put("/api/users/me", instance.handleCurrentUserProfileUpdate)
|
||||
router.Group(func(router chi.Router) {
|
||||
router.Use(instance.requireBusinessRole(domain.UserRoleAdmin))
|
||||
router.Use(instance.requireBusinessRole(domain.UserRoleAdmin, domain.UserRoleSupplierManager))
|
||||
router.Get("/api/users", instance.handleUsersList)
|
||||
})
|
||||
router.Group(func(router chi.Router) {
|
||||
router.Use(instance.requireBusinessRole(domain.UserRoleAdmin))
|
||||
router.Post("/api/users", instance.handleUsersCreate)
|
||||
router.Put("/api/users/{id}", instance.handleUsersUpdate)
|
||||
router.Delete("/api/users/{id}", instance.handleUsersDelete)
|
||||
@ -4869,6 +4872,13 @@ func (server *server) handleWorkflowRun(writer http.ResponseWriter, request *htt
|
||||
})
|
||||
return
|
||||
}
|
||||
if mode == domain.RunModeProduction && payload.Trigger == domain.RunTriggerManual && workflow.CaptureAutomation != nil && workflow.CaptureAutomation.Enabled {
|
||||
renderJSON(writer, http.StatusConflict, map[string]string{
|
||||
"error": "持续 Capture 工作流由目录监听器逐条创建 Run,不能手工运行整个监听根目录;请等待 Capture 自动进入流程,或在 Capture 列表中使用重新处理",
|
||||
"code": "capture_automation_manual_run_forbidden",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate node overrides and debug target against workflow nodes
|
||||
nodeMap := make(map[string]domain.WorkflowNode, len(workflow.Nodes))
|
||||
|
||||
@ -247,6 +247,20 @@ func (server *server) projectVisibleToRequest(request *http.Request, organizatio
|
||||
switch principal.User.Role {
|
||||
case domain.UserRoleAdmin, domain.UserRolePipelineEngineer, domain.UserRoleOperator:
|
||||
return true
|
||||
case domain.UserRoleSupplierManager:
|
||||
if strings.TrimSpace(principal.User.SupplierID) == "" {
|
||||
return false
|
||||
}
|
||||
members, err := server.store.ListProjectMembers(request.Context(), organizationID, projectID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, member := range members {
|
||||
if strings.TrimSpace(member.SupplierID) == strings.TrimSpace(principal.User.SupplierID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
case domain.UserRoleCutter, domain.UserRoleAnnotator, domain.UserRoleQualityReviewer, domain.UserRoleAcceptanceReviewer:
|
||||
// Standard RoboData roles are project scoped below.
|
||||
default:
|
||||
@ -341,7 +355,14 @@ func (server *server) filterSamplingTasksForRequest(request *http.Request, items
|
||||
|
||||
func (server *server) filterUsersForRequest(request *http.Request, items []domain.UserRecord) []domain.UserRecord {
|
||||
return filterTenantRecords(items, func(item domain.UserRecord) bool {
|
||||
return server.filterByTenant(request, item.OrganizationID)
|
||||
if !server.filterByTenant(request, item.OrganizationID) {
|
||||
return false
|
||||
}
|
||||
principal, ok := currentPrincipal(request)
|
||||
if !ok || principal == nil || principal.User.Role != domain.UserRoleSupplierManager {
|
||||
return true
|
||||
}
|
||||
return strings.TrimSpace(principal.User.SupplierID) != "" && strings.TrimSpace(item.SupplierID) == strings.TrimSpace(principal.User.SupplierID)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@ -155,6 +155,19 @@ func TestOrganizationLabelDictionaryAndProjectSelection(t *testing.T) {
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &label); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if label.Version != 1 || len(label.History) != 1 {
|
||||
t.Fatalf("created label has no first immutable revision: %#v", label)
|
||||
}
|
||||
patched := serveJSONWithCookie(handler, http.MethodPatch, "/api/annotation-labels/"+label.ID, []byte(`{"code":"pick","name":"拿取物品","category":"动作","description":"拿起目标物","example":"右手拿起水瓶","status":"active"}`), adminCookie)
|
||||
if patched.Code != http.StatusOK {
|
||||
t.Fatalf("patch label=%d body=%s", patched.Code, patched.Body.String())
|
||||
}
|
||||
if err := json.Unmarshal(patched.Body.Bytes(), &label); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if label.Version != 2 || len(label.History) != 2 || label.History[1].Example != "右手拿起水瓶" {
|
||||
t.Fatalf("label revision history=%#v", label)
|
||||
}
|
||||
selectedBody, _ := json.Marshal(map[string]any{"labelIds": []string{label.ID}})
|
||||
selected := serveJSONWithCookie(handler, http.MethodPut, "/api/projects/"+project.ID+"/annotation-labels", selectedBody, adminCookie)
|
||||
if selected.Code != http.StatusOK || !jsonContains(selected.Body.String(), label.ID) {
|
||||
|
||||
@ -8,8 +8,26 @@ const (
|
||||
)
|
||||
|
||||
type AnnotationLabelRecord struct {
|
||||
ID string `json:"id" bson:"id"`
|
||||
OrganizationID string `json:"organizationId" bson:"organizationId"`
|
||||
ID string `json:"id" bson:"id"`
|
||||
OrganizationID string `json:"organizationId" bson:"organizationId"`
|
||||
Code string `json:"code" bson:"code"`
|
||||
Name string `json:"name" bson:"name"`
|
||||
Category string `json:"category,omitempty" bson:"category,omitempty"`
|
||||
Description string `json:"description,omitempty" bson:"description,omitempty"`
|
||||
Example string `json:"example,omitempty" bson:"example,omitempty"`
|
||||
Color string `json:"color,omitempty" bson:"color,omitempty"`
|
||||
Aliases []string `json:"aliases,omitempty" bson:"aliases,omitempty"`
|
||||
Status AnnotationLabelStatus `json:"status" bson:"status"`
|
||||
Version int `json:"version" bson:"version"`
|
||||
CreatedByUserID string `json:"createdByUserId" bson:"createdByUserId"`
|
||||
UpdatedByUserID string `json:"updatedByUserId" bson:"updatedByUserId"`
|
||||
CreatedAt string `json:"createdAt" bson:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt" bson:"updatedAt"`
|
||||
History []AnnotationLabelRevision `json:"history,omitempty" bson:"history,omitempty"`
|
||||
}
|
||||
|
||||
type AnnotationLabelRevision struct {
|
||||
Version int `json:"version" bson:"version"`
|
||||
Code string `json:"code" bson:"code"`
|
||||
Name string `json:"name" bson:"name"`
|
||||
Category string `json:"category,omitempty" bson:"category,omitempty"`
|
||||
@ -18,10 +36,7 @@ type AnnotationLabelRecord struct {
|
||||
Color string `json:"color,omitempty" bson:"color,omitempty"`
|
||||
Aliases []string `json:"aliases,omitempty" bson:"aliases,omitempty"`
|
||||
Status AnnotationLabelStatus `json:"status" bson:"status"`
|
||||
Version int `json:"version" bson:"version"`
|
||||
CreatedByUserID string `json:"createdByUserId" bson:"createdByUserId"`
|
||||
UpdatedByUserID string `json:"updatedByUserId" bson:"updatedByUserId"`
|
||||
CreatedAt string `json:"createdAt" bson:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt" bson:"updatedAt"`
|
||||
}
|
||||
|
||||
|
||||
@ -160,6 +160,8 @@ type AnnotationTaskRecord struct {
|
||||
NodeID string `json:"nodeId,omitempty" bson:"nodeId,omitempty"`
|
||||
ArtifactID string `json:"artifactId,omitempty" bson:"artifactId,omitempty"`
|
||||
SourceVideo string `json:"sourceVideo" bson:"sourceVideo"`
|
||||
RightArtifactID string `json:"rightArtifactId,omitempty" bson:"rightArtifactId,omitempty"`
|
||||
RightSourceVideo string `json:"rightSourceVideo,omitempty" bson:"rightSourceVideo,omitempty"`
|
||||
ClipStart float64 `json:"clipStart" bson:"clipStart"`
|
||||
ClipEnd float64 `json:"clipEnd" bson:"clipEnd"`
|
||||
SourceIsFullVideo bool `json:"sourceIsFullVideo,omitempty" bson:"sourceIsFullVideo,omitempty"`
|
||||
|
||||
@ -77,6 +77,7 @@ type CaptureRecord struct {
|
||||
MaxAttempts int `json:"maxAttempts,omitempty" bson:"-"`
|
||||
NextRetryAt string `json:"nextRetryAt,omitempty" bson:"-"`
|
||||
ParentRunID string `json:"parentRunId,omitempty" bson:"-"`
|
||||
FailedNodeID string `json:"failedNodeId,omitempty" bson:"-"`
|
||||
BusinessStage CaptureBusinessStage `json:"businessStage,omitempty" bson:"businessStage,omitempty"`
|
||||
ContractRevision string `json:"contractRevision,omitempty" bson:"contractRevision,omitempty"`
|
||||
RuntimePolicyRevision int `json:"runtimePolicyRevision,omitempty" bson:"runtimePolicyRevision,omitempty"`
|
||||
|
||||
@ -530,6 +530,22 @@ func bindingArtifacts(bindings []domain.NodeInputBinding, targetPortID string) [
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchingCollectionArtifact(source domain.ExecutionArtifact, candidates []domain.ExecutionArtifact) *domain.ExecutionArtifact {
|
||||
collectionID := strings.TrimSpace(fmt.Sprint(source.Data["collectionId"]))
|
||||
for index := range candidates {
|
||||
candidateID := strings.TrimSpace(fmt.Sprint(candidates[index].Data["collectionId"]))
|
||||
if collectionID != "" && candidateID == collectionID {
|
||||
copy := candidates[index]
|
||||
return ©
|
||||
}
|
||||
}
|
||||
if len(candidates) == 1 {
|
||||
copy := candidates[0]
|
||||
return ©
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func annotationSourceDuration(artifact domain.ExecutionArtifact, windows []map[string]any) float64 {
|
||||
for _, key := range []string{"sourceDurationSeconds", "duration"} {
|
||||
if value, ok := annotationNumber(artifact.Data[key]); ok && value > 0 {
|
||||
@ -747,6 +763,7 @@ func (runtime *Runtime) createAnnotationGateTasks(
|
||||
}
|
||||
if nodeHasInputPort(node, "roughCutWindows") {
|
||||
leftVideos := bindingArtifacts(inputBindings, "fullLeftVideos")
|
||||
rightVideos := bindingArtifacts(inputBindings, "fullRightVideos")
|
||||
if len(leftVideos) == 0 {
|
||||
return nil, fmt.Errorf("timestamp-window human gate requires fullLeftVideos")
|
||||
}
|
||||
@ -755,6 +772,7 @@ func (runtime *Runtime) createAnnotationGateTasks(
|
||||
poseSummary := annotationPoseSummary(poseInputs)
|
||||
tasks := make([]domain.AnnotationTaskRecord, 0, len(leftVideos))
|
||||
for _, artifact := range leftVideos {
|
||||
rightArtifact := matchingCollectionArtifact(artifact, rightVideos)
|
||||
collectionID := strings.TrimSpace(fmt.Sprint(artifact.Data["collectionId"]))
|
||||
matchedWindows := make([]map[string]any, 0)
|
||||
for _, window := range windows {
|
||||
@ -768,6 +786,10 @@ func (runtime *Runtime) createAnnotationGateTasks(
|
||||
return nil, fmt.Errorf("human gate cannot resolve full source duration for %s", artifact.Name)
|
||||
}
|
||||
task := domain.AnnotationTaskRecord{ID: domain.NewID("annotation-task"), OrganizationID: run.OrganizationID, ProjectID: run.ProjectID, DataTaskID: run.TaskID, WorkflowID: run.WorkflowID, RunID: run.ID, NodeID: node.ID, ArtifactID: artifact.ID, SourceVideo: fmt.Sprintf("/api/runs/%s/artifacts/%s/content", url.PathEscape(run.ID), url.PathEscape(artifact.ID)), ClipStart: 0, ClipEnd: duration, SourceIsFullVideo: true, SourceDurationSeconds: duration, CoverageStartSecond: 0, CoverageEndSecond: duration, CoverageMode: "full_source_pending_common_range", TemplateID: template.ID, TemplateVersion: template.Version, LabelSnapshot: append([]domain.SemanticLabelDefinition(nil), labelSnapshot...), SupplierID: config.SupplierID, Status: domain.AnnotationTaskStatusPendingAnnotation, PoseSummary: poseSummary, CreatedAt: nowISO(), UpdatedAt: nowISO()}
|
||||
if rightArtifact != nil {
|
||||
task.RightArtifactID = rightArtifact.ID
|
||||
task.RightSourceVideo = fmt.Sprintf("/api/runs/%s/artifacts/%s/content", url.PathEscape(run.ID), url.PathEscape(rightArtifact.ID))
|
||||
}
|
||||
if err := runtime.store.UpsertAnnotationTask(ctx, task); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -998,6 +1020,8 @@ func (runtime *Runtime) ensureAnnotationHumanBatch(
|
||||
"clipEnd": task.ClipEnd,
|
||||
"sourceIsFullVideo": task.SourceIsFullVideo,
|
||||
"sourceDurationSeconds": task.SourceDurationSeconds,
|
||||
"rightArtifactId": task.RightArtifactID,
|
||||
"rightSourceVideo": task.RightSourceVideo,
|
||||
"templateId": task.TemplateID,
|
||||
"poseSummary": task.PoseSummary,
|
||||
},
|
||||
@ -1213,7 +1237,34 @@ func (runtime *Runtime) releasePartitionArtifacts(
|
||||
materialized.PortName = directoryPortName
|
||||
artifacts = append(artifacts, *materialized)
|
||||
}
|
||||
summary := map[string]any{"schemaVersion": "droboticflow.acceptance-summary/v1", "decision": "approved", "partitionId": partition.ID, "itemCount": len(selected), "finalAcceptance": acceptanceEvidence}
|
||||
qualityReviews := make([]map[string]any, 0, len(selected))
|
||||
for _, itemID := range partition.ItemIDs {
|
||||
item := selected[itemID]
|
||||
if strings.TrimSpace(item.LegacyTaskID) == "" {
|
||||
continue
|
||||
}
|
||||
reviews, reviewErr := runtime.store.ListAnnotationReviews(ctx, batch.OrganizationID, item.LegacyTaskID)
|
||||
if reviewErr != nil {
|
||||
return nil, reviewErr
|
||||
}
|
||||
for _, review := range reviews {
|
||||
qualityReviews = append(qualityReviews, map[string]any{
|
||||
"taskId": review.TaskID, "revision": review.Revision, "decision": review.Decision,
|
||||
"reasonCodes": review.ReasonCodes, "problemSliceIds": review.ProblemSliceIDs,
|
||||
"comment": review.Comment, "reviewerUserId": review.ReviewerUserID, "createdAt": review.CreatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
captureEvidence := map[string]any{}
|
||||
if capture, captureErr := runtime.store.GetCaptureRecordByRunID(ctx, run.ID); captureErr != nil {
|
||||
return nil, captureErr
|
||||
} else if capture != nil {
|
||||
captureEvidence = map[string]any{
|
||||
"captureRecordId": capture.ID, "captureId": capture.CaptureID, "prefix": capture.Prefix,
|
||||
"fingerprint": capture.Fingerprint, "contractRevision": capture.ContractRevision,
|
||||
}
|
||||
}
|
||||
summary := map[string]any{"schemaVersion": "droboticflow.acceptance-summary/v2", "decision": "approved", "partitionId": partition.ID, "itemCount": len(selected), "capture": captureEvidence, "qualityReviews": qualityReviews, "finalAcceptance": acceptanceEvidence}
|
||||
encoded, _ := json.Marshal(summary)
|
||||
artifacts = append(artifacts, domain.ExecutionArtifact{ID: fmt.Sprintf("%s-%s-acceptance-summary", run.ID, node.ID), RunID: run.ID, NodeID: node.ID, PortID: summaryPortID, PortName: summaryPortName, Name: "acceptance-summary.json", Type: domain.PortTypeJSON, Size: annotationArtifactSize(int64(len(encoded))), SizeBytes: int64(len(encoded)), Data: summary, Payload: &domain.ArtifactPayload{Mode: domain.ArtifactTransferModeInline, Type: domain.PortTypeJSON, Inline: summary}})
|
||||
return artifacts, nil
|
||||
|
||||
@ -68,3 +68,18 @@ func TestAnnotationGateSupplierResolutionIsFailClosed(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMatchingCollectionArtifactKeepsStereoCaptureTogether(t *testing.T) {
|
||||
left := domain.ExecutionArtifact{ID: "left-a", Data: map[string]any{"collectionId": "capture-a"}}
|
||||
rights := []domain.ExecutionArtifact{
|
||||
{ID: "right-b", Data: map[string]any{"collectionId": "capture-b"}},
|
||||
{ID: "right-a", Data: map[string]any{"collectionId": "capture-a"}},
|
||||
}
|
||||
matched := matchingCollectionArtifact(left, rights)
|
||||
if matched == nil || matched.ID != "right-a" {
|
||||
t.Fatalf("matched right artifact=%#v", matched)
|
||||
}
|
||||
if ambiguous := matchingCollectionArtifact(domain.ExecutionArtifact{ID: "left-unknown"}, rights); ambiguous != nil {
|
||||
t.Fatalf("unscoped left artifact must not guess among multiple right videos: %#v", ambiguous)
|
||||
}
|
||||
}
|
||||
|
||||
@ -401,6 +401,53 @@ def _read_imu(path: pathlib.Path) -> list[dict[str, Any]]:
|
||||
return result
|
||||
|
||||
|
||||
def _read_materialized_pts(path: pathlib.Path) -> list[int]:
|
||||
header, rows = _read_rows(path)
|
||||
normalized = {name.lower(): index for index, name in enumerate(header)}
|
||||
timestamp_column = normalized.get("timestamp_ms")
|
||||
if timestamp_column is None:
|
||||
raise RuntimeError(f"materialized PTS CSV must contain timestamp_ms: {path.name}")
|
||||
values: list[int] = []
|
||||
for row in rows:
|
||||
try:
|
||||
value = int(round(float(row[timestamp_column]) * 1000))
|
||||
except (IndexError, ValueError) as exc:
|
||||
raise RuntimeError(f"materialized PTS CSV contains an invalid timestamp_ms: {path.name}") from exc
|
||||
if values and value <= values[-1]:
|
||||
raise RuntimeError(f"materialized PTS CSV timestamp_ms must be strictly increasing: {path.name}")
|
||||
values.append(value)
|
||||
if not values:
|
||||
raise RuntimeError(f"materialized PTS CSV has no frame timestamps: {path.name}")
|
||||
return values
|
||||
|
||||
|
||||
def _validate_materialized_imu(path: pathlib.Path, start_us: int, end_us: int) -> int:
|
||||
header, rows = _read_rows(path)
|
||||
indexes = {name.lower(): index for index, name in enumerate(header)}
|
||||
required = {"timestamp_ms", "clip_time_ms", "x", "y", "z", "type"}
|
||||
if not required.issubset(indexes):
|
||||
raise RuntimeError(f"materialized IMU CSV is missing required columns: {path.name}")
|
||||
previous = -1
|
||||
seen_types: dict[int, set[str]] = {}
|
||||
for row in rows:
|
||||
try:
|
||||
timestamp_us = int(round(float(row[indexes["timestamp_ms"]]) * 1000))
|
||||
kind = row[indexes["type"]].lower()
|
||||
for key in ("x", "y", "z"):
|
||||
float(row[indexes[key]])
|
||||
except (IndexError, ValueError) as exc:
|
||||
raise RuntimeError(f"materialized IMU CSV contains an invalid row: {path.name}") from exc
|
||||
if timestamp_us < previous or kind not in {"accel", "gyro"}:
|
||||
raise RuntimeError(f"materialized IMU ordering/type is invalid: {path.name}")
|
||||
if timestamp_us < start_us or timestamp_us >= end_us:
|
||||
raise RuntimeError(f"materialized IMU row is outside the synchronized slice window: {path.name}")
|
||||
previous = timestamp_us
|
||||
seen_types.setdefault(timestamp_us, set()).add(kind)
|
||||
if not rows or any(types != {"accel", "gyro"} for types in seen_types.values()):
|
||||
raise RuntimeError(f"materialized IMU must contain paired accel/gyro samples: {path.name}")
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _ffprobe_frame_count(path: pathlib.Path) -> int:
|
||||
completed = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "default=nokey=1:noprint_wrappers=1", str(path)], capture_output=True, text=True, check=False)
|
||||
try:
|
||||
@ -1051,6 +1098,27 @@ def _run_accepted_slice_directory(
|
||||
shutil.copytree(source_slice, target_slice, dirs_exist_ok=True)
|
||||
start = float(raw.get("startSecond") or 0.0)
|
||||
end = float(raw.get("endSecond") or 0.0)
|
||||
start_us = int(raw.get("startTimestampUs") or 0)
|
||||
end_us = int(raw.get("endTimestampUs") or 0)
|
||||
required_files = ["left.mp4", "right.mp4", "left_pts.csv", "right_pts.csv", "imu.csv", "annotation.json", "synchronized-slice.json"]
|
||||
missing_files = [name for name in required_files if not (target_slice / name).is_file()]
|
||||
if missing_files:
|
||||
raise RuntimeError(f"accepted slice {slice_id} is missing required files: {', '.join(missing_files)}")
|
||||
left_pts = _read_materialized_pts(target_slice / "left_pts.csv")
|
||||
right_pts = _read_materialized_pts(target_slice / "right_pts.csv")
|
||||
if _ffprobe_frame_count(target_slice / "left.mp4") != len(left_pts):
|
||||
raise RuntimeError(f"accepted slice {slice_id} left video/PTS frame count mismatch")
|
||||
if _ffprobe_frame_count(target_slice / "right.mp4") != len(right_pts):
|
||||
raise RuntimeError(f"accepted slice {slice_id} right video/PTS frame count mismatch")
|
||||
_validate_materialized_imu(target_slice / "imu.csv", start_us, end_us)
|
||||
declared_files = raw.get("files") if isinstance(raw.get("files"), dict) else {}
|
||||
for declared in declared_files.values():
|
||||
if not isinstance(declared, dict):
|
||||
continue
|
||||
name = str(declared.get("name") or "").strip()
|
||||
expected_sha = str(declared.get("sha256") or "").strip()
|
||||
if name and expected_sha and (target_slice / name).is_file() and _sha256_file(target_slice / name) != expected_sha:
|
||||
raise RuntimeError(f"accepted slice {slice_id} checksum mismatch: {name}")
|
||||
if pose_policy.get("headpose") == "include":
|
||||
cropped = _crop_pose(headpose, start, end, "headpose") if headpose else None
|
||||
if cropped is None or cropped.get("frameCount", 0) <= 0:
|
||||
@ -1089,7 +1157,21 @@ def _run_accepted_slice_directory(
|
||||
"randomValue": final_acceptance.get("samplingRandomValue"),
|
||||
"decidedAt": final_acceptance.get("samplingDecidedAt"),
|
||||
}
|
||||
manifest = {"schemaVersion": "droboticflow.delivery.manifest/v5", "datasetType": "fanyu-accepted-slice-directories", "revision": revision_manifest.get("revision"), "sliceCount": len(package_items), "coverage": coverage, "acceptanceSampling": sampling, "poseDelivery": pose_policy, "calibration": calibration, "lineage": {"acceptedSliceDirectoryArtifactId": directory_artifact.get("id"), "humanItemId": revision_manifest.get("humanItemId"), "taskId": revision_manifest.get("taskId"), "sourceRunId": revision_manifest.get("runId")}, "items": package_items}
|
||||
capture_record = summary_payload.get("capture") if isinstance(summary_payload.get("capture"), dict) else revision_manifest.get("capture") if isinstance(revision_manifest.get("capture"), dict) else {}
|
||||
quality_reviews = summary_payload.get("qualityReviews") if isinstance(summary_payload.get("qualityReviews"), list) else []
|
||||
capture_manifest = {"schemaVersion": "droboticflow.capture-delivery/v1", "capture": capture_record, "revision": revision_manifest.get("revision"), "coverage": coverage, "sliceCount": len(package_items), "lineage": {"acceptedSliceDirectoryArtifactId": directory_artifact.get("id"), "humanItemId": revision_manifest.get("humanItemId"), "taskId": revision_manifest.get("taskId"), "sourceRunId": revision_manifest.get("runId")}}
|
||||
evidence_payloads = {
|
||||
"capture-manifest.json": capture_manifest,
|
||||
"quality-review.json": {"schemaVersion": "droboticflow.capture-quality-review/v1", "reviews": quality_reviews},
|
||||
"acceptance-record.json": {"schemaVersion": "droboticflow.capture-acceptance/v1", "finalAcceptance": final_acceptance},
|
||||
"sampling-evidence.json": {"schemaVersion": "droboticflow.capture-sampling/v1", **sampling},
|
||||
}
|
||||
root_evidence = []
|
||||
for name, payload in evidence_payloads.items():
|
||||
path = delivery_root / name
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
root_evidence.append({"name": name, "sha256": _sha256_file(path), "bytes": path.stat().st_size})
|
||||
manifest = {"schemaVersion": "droboticflow.delivery.manifest/v5", "datasetType": "fanyu-accepted-slice-directories", "capture": capture_record, "revision": revision_manifest.get("revision"), "sliceCount": len(package_items), "coverage": coverage, "acceptanceSampling": sampling, "poseDelivery": pose_policy, "calibration": calibration, "rootEvidence": root_evidence, "lineage": {"acceptedSliceDirectoryArtifactId": directory_artifact.get("id"), "humanItemId": revision_manifest.get("humanItemId"), "taskId": revision_manifest.get("taskId"), "sourceRunId": revision_manifest.get("runId")}, "items": package_items}
|
||||
manifest_binding = _output(node_data, helpers, "deliveryManifest")
|
||||
directory_binding = _output(node_data, helpers, "deliveryDirectory")
|
||||
result = [helpers["write_json_artifact"](run_id, node_id, delivery_root, "packages-manifest.json", manifest, output=manifest_binding)]
|
||||
|
||||
@ -119,7 +119,12 @@ function RoleRouteGuard({ children }: { children: React.ReactNode }) {
|
||||
: currentUser?.role === "pipeline_engineer" || currentUser?.role === "operator"
|
||||
? "admin"
|
||||
: currentUser?.role;
|
||||
if (effectiveRole === "supplier_manager" && path !== "/") {
|
||||
if (
|
||||
effectiveRole === "supplier_manager" &&
|
||||
path !== "/" &&
|
||||
path !== "/projects" &&
|
||||
!path.startsWith("/project/")
|
||||
) {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
if (
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import { Loader2, Plus, Save, Tags } from "lucide-react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Edit3, Loader2, Plus, Save, Tags, X } from "lucide-react";
|
||||
import { apiRequest } from "../services/api/client";
|
||||
import { getActionErrorMessage } from "../lib/action-errors.js";
|
||||
import type { AnnotationLabelRecord, ProjectAnnotationLabelsRecord } from "../types";
|
||||
@ -10,7 +10,15 @@ export function AnnotationLabelsPanel({ projectId, canManage }: { projectId: str
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [draft, setDraft] = useState({ code: "", name: "", category: "", description: "" });
|
||||
const [editingLabelId, setEditingLabelId] = useState("");
|
||||
const [draft, setDraft] = useState({
|
||||
code: "",
|
||||
name: "",
|
||||
category: "",
|
||||
description: "",
|
||||
example: "",
|
||||
status: "active" as "active" | "inactive",
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
@ -33,25 +41,43 @@ export function AnnotationLabelsPanel({ projectId, canManage }: { projectId: str
|
||||
void load();
|
||||
}, [projectId]);
|
||||
|
||||
const activeLabels = useMemo(() => labels.filter((item) => item.status === "active"), [labels]);
|
||||
const resetDraft = () => {
|
||||
setEditingLabelId("");
|
||||
setDraft({ code: "", name: "", category: "", description: "", example: "", status: "active" });
|
||||
};
|
||||
|
||||
const createLabel = async () => {
|
||||
const editLabel = (label: AnnotationLabelRecord) => {
|
||||
setEditingLabelId(label.id);
|
||||
setDraft({
|
||||
code: label.code,
|
||||
name: label.name,
|
||||
category: label.category || "",
|
||||
description: label.description || "",
|
||||
example: label.example || "",
|
||||
status: label.status,
|
||||
});
|
||||
};
|
||||
|
||||
const saveLabel = async () => {
|
||||
if (!draft.code.trim() || !draft.name.trim()) return;
|
||||
setSaving(true);
|
||||
setError("");
|
||||
try {
|
||||
const created = await apiRequest<AnnotationLabelRecord>(
|
||||
"/api/annotation-labels",
|
||||
{ method: "POST" },
|
||||
{
|
||||
...draft,
|
||||
status: "active",
|
||||
},
|
||||
const saved = await apiRequest<AnnotationLabelRecord>(
|
||||
editingLabelId ? `/api/annotation-labels/${editingLabelId}` : "/api/annotation-labels",
|
||||
{ method: editingLabelId ? "PATCH" : "POST" },
|
||||
draft,
|
||||
);
|
||||
setLabels((items) => [...items, created].sort((a, b) => a.code.localeCompare(b.code)));
|
||||
setDraft({ code: "", name: "", category: "", description: "" });
|
||||
setLabels((items) => {
|
||||
const next = editingLabelId ? items.map((item) => (item.id === saved.id ? saved : item)) : [...items, saved];
|
||||
return next.sort((a, b) => a.code.localeCompare(b.code));
|
||||
});
|
||||
if (saved.status === "inactive") {
|
||||
setEnabled((items) => items.filter((id) => id !== saved.id));
|
||||
}
|
||||
resetDraft();
|
||||
} catch (saveError) {
|
||||
setError(getActionErrorMessage(saveError, "创建全局标签失败"));
|
||||
setError(getActionErrorMessage(saveError, editingLabelId ? "更新全局标签失败" : "创建全局标签失败"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@ -119,21 +145,46 @@ export function AnnotationLabelsPanel({ projectId, canManage }: { projectId: str
|
||||
placeholder="分类"
|
||||
className="rounded-md border border-[#2a2b2f] bg-black px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
<button
|
||||
onClick={() => void createLabel()}
|
||||
disabled={saving || !draft.code.trim() || !draft.name.trim()}
|
||||
className="inline-flex items-center justify-center gap-2 rounded-md border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm text-violet-200 disabled:opacity-40"
|
||||
<select
|
||||
value={draft.status}
|
||||
onChange={(event) => setDraft((item) => ({ ...item, status: event.target.value as "active" | "inactive" }))}
|
||||
className="rounded-md border border-[#2a2b2f] bg-black px-3 py-2 text-sm text-white"
|
||||
aria-label="标签启停状态"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
新增全局标签
|
||||
</button>
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">停用</option>
|
||||
</select>
|
||||
<textarea
|
||||
value={draft.description}
|
||||
onChange={(event) => setDraft((item) => ({ ...item, description: event.target.value }))}
|
||||
placeholder="说明或示例"
|
||||
placeholder="标签说明"
|
||||
rows={2}
|
||||
className="md:col-span-4 rounded-md border border-[#2a2b2f] bg-black px-3 py-2 text-sm text-white"
|
||||
className="md:col-span-2 rounded-md border border-[#2a2b2f] bg-black px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
<textarea
|
||||
value={draft.example}
|
||||
onChange={(event) => setDraft((item) => ({ ...item, example: event.target.value }))}
|
||||
placeholder="正例或使用示例"
|
||||
rows={2}
|
||||
className="md:col-span-2 rounded-md border border-[#2a2b2f] bg-black px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
<button
|
||||
onClick={() => void saveLabel()}
|
||||
disabled={saving || !draft.code.trim() || !draft.name.trim()}
|
||||
className="inline-flex items-center justify-center gap-2 rounded-md border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm text-violet-200 disabled:opacity-40"
|
||||
>
|
||||
{editingLabelId ? <Save className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
|
||||
{editingLabelId ? "保存标签新版本" : "新增全局标签"}
|
||||
</button>
|
||||
{editingLabelId ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetDraft}
|
||||
className="inline-flex items-center justify-center gap-2 rounded-md border border-[#2a2b2f] px-3 py-2 text-sm text-gray-300"
|
||||
>
|
||||
<X className="h-4 w-4" />取消编辑
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{loading ? (
|
||||
@ -143,17 +194,17 @@ export function AnnotationLabelsPanel({ projectId, canManage }: { projectId: str
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
|
||||
{activeLabels.map((label) => {
|
||||
{labels.map((label) => {
|
||||
const checked = enabled.includes(label.id);
|
||||
return (
|
||||
<label
|
||||
<div
|
||||
key={label.id}
|
||||
className="flex cursor-pointer gap-3 rounded-lg border border-[#2a2b2f] bg-[#0d0e10] p-4"
|
||||
className="flex gap-3 rounded-lg border border-[#2a2b2f] bg-[#0d0e10] p-4"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={!canManage}
|
||||
disabled={!canManage || label.status !== "active"}
|
||||
onChange={(event) =>
|
||||
setEnabled((items) =>
|
||||
event.target.checked ? [...items, label.id] : items.filter((id) => id !== label.id),
|
||||
@ -162,17 +213,44 @@ export function AnnotationLabelsPanel({ projectId, canManage }: { projectId: str
|
||||
className="mt-1 h-4 w-4 accent-violet-500"
|
||||
/>
|
||||
<span>
|
||||
<span className="block font-medium text-white">{label.name}</span>
|
||||
<span className="flex items-center gap-2 font-medium text-white">
|
||||
{label.name}
|
||||
<span className="rounded border border-white/10 px-1.5 py-0.5 text-[10px] text-gray-400">v{label.version}</span>
|
||||
{label.status === "inactive" ? (
|
||||
<span className="rounded border border-amber-500/30 px-1.5 py-0.5 text-[10px] text-amber-300">已停用</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="mt-1 block font-mono text-xs text-violet-300">{label.code}</span>
|
||||
<span className="mt-1 block text-xs text-gray-500">
|
||||
{label.category || "未分类"}
|
||||
{label.description ? ` · ${label.description}` : ""}
|
||||
</span>
|
||||
{label.example ? <span className="mt-1 block text-xs text-gray-600">示例:{label.example}</span> : null}
|
||||
{label.history?.length ? (
|
||||
<details className="mt-2 text-[10px] text-gray-500">
|
||||
<summary className="cursor-pointer">版本记录({label.history.length})</summary>
|
||||
{label.history.map((revision) => (
|
||||
<div key={revision.version} className="mt-1 font-mono">
|
||||
v{revision.version} · {revision.status} · {revision.updatedAt}
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
) : null}
|
||||
</span>
|
||||
</label>
|
||||
{canManage ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => editLabel(label)}
|
||||
className="ml-auto self-start rounded border border-[#2a2b2f] p-1.5 text-gray-300"
|
||||
aria-label={`编辑标签 ${label.name}`}
|
||||
>
|
||||
<Edit3 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{!activeLabels.length ? <div className="py-10 text-sm text-gray-500">当前组织还没有有效标签。</div> : null}
|
||||
{!labels.length ? <div className="py-10 text-sm text-gray-500">当前组织还没有标签。</div> : null}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@ -34,10 +34,12 @@ import { cn } from "../lib/utils";
|
||||
|
||||
type PlaybackMode = "once" | "loop" | "auto-next";
|
||||
type NavigatorTab = "slices" | "events";
|
||||
type CameraMode = "left" | "right" | "dual";
|
||||
|
||||
type AnnotationWorkbenchEditorProps = {
|
||||
taskId: string;
|
||||
videoSource: string;
|
||||
rightVideoSource?: string;
|
||||
clipStart: number;
|
||||
clipEnd: number;
|
||||
sourceIsFullVideo?: boolean;
|
||||
@ -73,6 +75,7 @@ function statusTone(status?: SliceSegment["annotationStatus"]) {
|
||||
export function AnnotationWorkbenchEditor({
|
||||
taskId,
|
||||
videoSource,
|
||||
rightVideoSource = "",
|
||||
clipStart,
|
||||
clipEnd,
|
||||
sourceIsFullVideo = false,
|
||||
@ -90,6 +93,7 @@ export function AnnotationWorkbenchEditor({
|
||||
onNavigationChange,
|
||||
}: AnnotationWorkbenchEditorProps) {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const rightVideoRef = useRef<HTMLVideoElement>(null);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const sliceButtonRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const eventButtonRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
@ -101,6 +105,7 @@ export function AnnotationWorkbenchEditor({
|
||||
const [playbackMode, setPlaybackMode] = useState<PlaybackMode>("auto-next");
|
||||
const [playbackRate, setPlaybackRate] = useState(1);
|
||||
const [muted, setMuted] = useState(false);
|
||||
const [cameraMode, setCameraMode] = useState<CameraMode>(rightVideoSource ? "dual" : "left");
|
||||
const [navigatorTab, setNavigatorTab] = useState<NavigatorTab>("slices");
|
||||
const [navigatorSearch, setNavigatorSearch] = useState("");
|
||||
const [navigatorStatus, setNavigatorStatus] = useState("all");
|
||||
@ -123,6 +128,7 @@ export function AnnotationWorkbenchEditor({
|
||||
const activeEvent = segments.find((segment) => currentTime >= segment.start && currentTime < segment.end) || null;
|
||||
const progress = useMemo(() => summarizeSliceProgress(slices, segments, statuses), [segments, slices, statuses]);
|
||||
const playableSource = buildBrowserPlayableVideoURL(videoSource);
|
||||
const playableRightSource = buildBrowserPlayableVideoURL(rightVideoSource);
|
||||
|
||||
const absoluteToMedia = useCallback(
|
||||
(absolute: number) => (sourceIsFullVideo ? absolute : absolute - clipStart),
|
||||
@ -139,6 +145,10 @@ export function AnnotationWorkbenchEditor({
|
||||
videoRef.current.currentTime = Math.max(0, absoluteToMedia(bounded));
|
||||
if (autoplay) void videoRef.current.play();
|
||||
}
|
||||
if (rightVideoRef.current) {
|
||||
rightVideoRef.current.currentTime = Math.max(0, absoluteToMedia(bounded));
|
||||
if (autoplay) void rightVideoRef.current.play();
|
||||
}
|
||||
setCurrentTime(bounded);
|
||||
},
|
||||
[absoluteToMedia, clipEnd, clipStart],
|
||||
@ -198,8 +208,13 @@ export function AnnotationWorkbenchEditor({
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
if (!videoRef.current) return;
|
||||
if (videoRef.current.paused) void videoRef.current.play();
|
||||
else videoRef.current.pause();
|
||||
if (videoRef.current.paused) {
|
||||
void videoRef.current.play();
|
||||
if (rightVideoRef.current) void rightVideoRef.current.play();
|
||||
} else {
|
||||
videoRef.current.pause();
|
||||
rightVideoRef.current?.pause();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const stepPreviewFrame = useCallback(
|
||||
@ -351,10 +366,28 @@ export function AnnotationWorkbenchEditor({
|
||||
<div className="grid xl:grid-cols-[minmax(0,1fr)_300px] 2xl:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="min-w-0 border-b border-[#292a30] xl:border-b-0 xl:border-r">
|
||||
<div className="relative bg-black">
|
||||
{playableRightSource ? (
|
||||
<div className="absolute right-3 top-3 z-10 flex rounded-lg border border-white/15 bg-black/75 p-1 text-[10px] text-gray-300">
|
||||
{(["left", "right", "dual"] as CameraMode[]).map((mode) => (
|
||||
<button
|
||||
key={mode}
|
||||
type="button"
|
||||
onClick={() => setCameraMode(mode)}
|
||||
className={cn("rounded px-2 py-1", cameraMode === mode && "bg-blue-600 text-white")}
|
||||
>
|
||||
{mode === "left" ? "左目" : mode === "right" ? "右目" : "双目"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className={cn("grid", cameraMode === "dual" && playableRightSource ? "grid-cols-2" : "grid-cols-1")}>
|
||||
<video
|
||||
ref={videoRef}
|
||||
src={playableSource}
|
||||
className="aspect-video max-h-[360px] w-full bg-black object-contain [@media(max-height:820px)]:max-h-[180px] 2xl:max-h-[420px]"
|
||||
className={cn(
|
||||
"aspect-video max-h-[360px] w-full bg-black object-contain [@media(max-height:820px)]:max-h-[180px] 2xl:max-h-[420px]",
|
||||
cameraMode === "right" && playableRightSource && "hidden",
|
||||
)}
|
||||
preload="auto"
|
||||
muted={muted}
|
||||
playsInline
|
||||
@ -365,6 +398,9 @@ export function AnnotationWorkbenchEditor({
|
||||
onTimeUpdate={(event) => {
|
||||
const absolute = mediaToAbsolute(event.currentTarget.currentTime);
|
||||
const bounded = Math.min(clipEnd, absolute);
|
||||
if (rightVideoRef.current && Math.abs(rightVideoRef.current.currentTime - event.currentTarget.currentTime) > 0.05) {
|
||||
rightVideoRef.current.currentTime = event.currentTarget.currentTime;
|
||||
}
|
||||
setCurrentTime(bounded);
|
||||
if (selectedSlice && bounded >= selectedSlice.end - 0.015) {
|
||||
if (playbackMode === "loop") {
|
||||
@ -389,6 +425,21 @@ export function AnnotationWorkbenchEditor({
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{playableRightSource ? (
|
||||
<video
|
||||
ref={rightVideoRef}
|
||||
src={playableRightSource}
|
||||
className={cn(
|
||||
"aspect-video max-h-[360px] w-full bg-black object-contain [@media(max-height:820px)]:max-h-[180px] 2xl:max-h-[420px]",
|
||||
cameraMode === "left" && "hidden",
|
||||
)}
|
||||
preload="auto"
|
||||
muted
|
||||
playsInline
|
||||
onLoadedMetadata={() => seekTo(selectedSlice?.start ?? clipStart)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{activeEvent ? (
|
||||
<div className="pointer-events-none absolute bottom-4 left-1/2 -translate-x-1/2 rounded-md bg-black/80 px-4 py-2 text-sm font-semibold text-white shadow-xl">
|
||||
{activeEvent.label}
|
||||
@ -465,6 +516,7 @@ export function AnnotationWorkbenchEditor({
|
||||
const value = Number(event.target.value);
|
||||
setPlaybackRate(value);
|
||||
if (videoRef.current) videoRef.current.playbackRate = value;
|
||||
if (rightVideoRef.current) rightVideoRef.current.playbackRate = value;
|
||||
}}
|
||||
className="rounded-md border border-[#303137] bg-[#090a0c] px-2 py-2 text-[11px] text-gray-200"
|
||||
aria-label="播放速度"
|
||||
@ -661,9 +713,13 @@ export function AnnotationWorkbenchEditor({
|
||||
</div>
|
||||
<div className="max-h-[430px] space-y-1.5 overflow-auto p-3" data-testid="slice-event-navigator">
|
||||
{navigatorTab === "slices"
|
||||
? filteredSlices.map((slice) => {
|
||||
? filteredSlices.map((slice) => {
|
||||
const index = slices.findIndex((item) => item.id === slice.id);
|
||||
const status = progress.statuses[slice.id] || "pending";
|
||||
const previous = index > 0 ? slices[index - 1] : undefined;
|
||||
const anomaly =
|
||||
slice.end <= slice.start ||
|
||||
(previous ? Math.abs(previous.end - slice.start) > 0.001 : Math.abs(slice.start - clipStart) > 0.001);
|
||||
return (
|
||||
<button
|
||||
key={slice.id}
|
||||
@ -687,9 +743,14 @@ export function AnnotationWorkbenchEditor({
|
||||
<span className={cn("rounded border px-1.5 py-0.5 text-[9px]", statusTone(status))}>
|
||||
{statusLabel(status)}
|
||||
</span>
|
||||
{anomaly ? (
|
||||
<span className="rounded border border-red-500/35 bg-red-500/10 px-1.5 py-0.5 text-[9px] text-red-200">
|
||||
边界异常
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-1 font-mono text-[10px] text-gray-500">
|
||||
{formatSeconds(slice.start)}–{formatSeconds(slice.end)} ·{" "}
|
||||
{formatSeconds(slice.start)}–{formatSeconds(slice.end)} · 时长 {formatSeconds(slice.end - slice.start)} ·{" "}
|
||||
{annotationSegmentsForSlice(slice, segments).length} 事件
|
||||
</div>
|
||||
</button>
|
||||
|
||||
@ -64,7 +64,7 @@ const navItems: readonly NavigationItem[] = [
|
||||
icon: FolderKanban,
|
||||
label: "项目管理",
|
||||
path: "/projects",
|
||||
roles: ["admin"],
|
||||
roles: ["admin", "supplier_manager"],
|
||||
},
|
||||
{
|
||||
icon: FileCode,
|
||||
|
||||
@ -69,7 +69,7 @@ export function UserProvider({ children }: { children: ReactNode }) {
|
||||
try {
|
||||
const session = await authApi.me();
|
||||
setOrganization(session.organization);
|
||||
if (isOrganizationAdminRole(session.user.role) && !session.user.isSuperAdmin) {
|
||||
if ((isOrganizationAdminRole(session.user.role) || session.user.role === "supplier_manager") && !session.user.isSuperAdmin) {
|
||||
const adminVisibleUsers = await usersApi.list();
|
||||
const resolvedCurrentUser = resolveCurrentUser(adminVisibleUsers, session.user.id) || session.user;
|
||||
setUsers(adminVisibleUsers);
|
||||
|
||||
@ -865,6 +865,13 @@ export default function AnnotationOperations() {
|
||||
}
|
||||
return detail.task.sourceVideo;
|
||||
}, [detail, selectedHumanItem?.id]);
|
||||
const selectedRightVideoSource = useMemo(() => {
|
||||
if (!detail?.task.rightArtifactId && !detail?.task.rightSourceVideo) return "";
|
||||
if (selectedHumanItem?.id) {
|
||||
return humanLoopApi.subjectContentURL(selectedHumanItem.id, "right");
|
||||
}
|
||||
return detail.task.rightSourceVideo || "";
|
||||
}, [detail, selectedHumanItem?.id]);
|
||||
const selectedMaterialization = selectedHumanItem?.subject?.payload?.materialization as
|
||||
| { status?: string; runId?: string; artifactId?: string; revision?: number; sliceCount?: number }
|
||||
| undefined;
|
||||
@ -3090,6 +3097,7 @@ export default function AnnotationOperations() {
|
||||
<AnnotationWorkbenchEditor
|
||||
taskId={detail.task.id}
|
||||
videoSource={selectedVideoSource}
|
||||
rightVideoSource={selectedRightVideoSource}
|
||||
clipStart={editableTimelineStart}
|
||||
clipEnd={editableTimelineEnd}
|
||||
sourceIsFullVideo={detail.task.sourceIsFullVideo}
|
||||
|
||||
@ -23,7 +23,6 @@ import { getActionErrorMessage } from "../lib/action-errors.js";
|
||||
import { primaryCaptureDirectory } from "../lib/business-display.js";
|
||||
import { projectsApi } from "../services/api/projects";
|
||||
import { monitoringApi } from "../services/api/monitoring";
|
||||
import { workflowsApi } from "../services/api/workflows";
|
||||
import { useTimeZone } from "../context/TimeZoneContext";
|
||||
import type { ExecutionData, ExecutionLineage, ExecutionRun, ExecutionRunSummary, Project, Workflow } from "../types";
|
||||
|
||||
@ -147,7 +146,7 @@ export default function DataAssets() {
|
||||
}, [selectedProjectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedWorkflowId) {
|
||||
if (!selectedProjectId) {
|
||||
setRuns([]);
|
||||
setRunsLoading(false);
|
||||
return undefined;
|
||||
@ -155,10 +154,10 @@ export default function DataAssets() {
|
||||
let cancelled = false;
|
||||
setRunsLoading(true);
|
||||
setSelectionError("");
|
||||
workflowsApi
|
||||
.listRuns(selectedWorkflowId)
|
||||
.then((items) => {
|
||||
if (!cancelled) setRuns([...items].sort((left, right) => runTimestamp(right) - runTimestamp(left)));
|
||||
monitoringApi
|
||||
.listRuns({ projectId: selectedProjectId, workflowId: selectedWorkflowId || undefined, limit: 500 })
|
||||
.then((page) => {
|
||||
if (!cancelled) setRuns([...page.items].sort((left, right) => runTimestamp(right) - runTimestamp(left)));
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) {
|
||||
@ -172,7 +171,7 @@ export default function DataAssets() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedWorkflowId]);
|
||||
}, [selectedProjectId, selectedWorkflowId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedRunId) {
|
||||
@ -214,26 +213,25 @@ export default function DataAssets() {
|
||||
}, [selectedRunId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!runDetail || (selectedProjectId && selectedWorkflowId)) return;
|
||||
if (!runDetail || selectedProjectId) return;
|
||||
updateSelection({
|
||||
projectId: selectedProjectId || runDetail.projectId,
|
||||
workflowId: selectedWorkflowId || runDetail.workflowId,
|
||||
runId: runDetail.id,
|
||||
});
|
||||
}, [runDetail, selectedProjectId, selectedWorkflowId, updateSelection]);
|
||||
}, [runDetail, selectedProjectId, updateSelection]);
|
||||
|
||||
const runOptions = useMemo(() => {
|
||||
const byId = new Map<string, ExecutionRunSummary>(runs.map((run) => [run.id, run]));
|
||||
if (runDetail && runDetail.workflowId === selectedWorkflowId) byId.set(runDetail.id, runDetail);
|
||||
if (runDetail && runDetail.projectId === selectedProjectId) byId.set(runDetail.id, runDetail);
|
||||
return [...byId.values()].sort((left, right) => runTimestamp(right) - runTimestamp(left));
|
||||
}, [runDetail, runs, selectedWorkflowId]);
|
||||
}, [runDetail, runs, selectedProjectId]);
|
||||
|
||||
const selectedRun = useMemo(
|
||||
() => runOptions.find((run) => run.id === selectedRunId) || runDetail,
|
||||
[runDetail, runOptions, selectedRunId],
|
||||
);
|
||||
const selectedProject = projects.find((project) => project.id === selectedProjectId);
|
||||
const selectedWorkflow = workflows.find((workflow) => workflow.id === selectedWorkflowId);
|
||||
const selectedWorkflow = workflows.find((workflow) => workflow.id === (selectedRun?.workflowId || selectedWorkflowId));
|
||||
const childRuns = useMemo(
|
||||
() => runOptions.filter((run) => run.parentRunId === selectedRunId),
|
||||
[runOptions, selectedRunId],
|
||||
@ -268,7 +266,7 @@ export default function DataAssets() {
|
||||
<div className="mb-4 flex items-start gap-3 rounded-xl border border-blue-500/20 bg-blue-500/5 px-4 py-3">
|
||||
<Boxes className="mt-0.5 h-4 w-4 shrink-0 text-blue-400" />
|
||||
<div className="text-sm leading-6 text-blue-100">
|
||||
依次选择项目、工作流和 Capture 执行记录,查看这条采集记录的全部输入、中间产物和最终结果。
|
||||
依次选择项目和 Capture,查看该 Capture 的输入、中间产物、切片与最终结果;工作流只用于筛选处理来源。
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
@ -290,16 +288,35 @@ export default function DataAssets() {
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-2">
|
||||
<span className="text-xs font-medium text-gray-400">2. 工作流</span>
|
||||
<span className="text-xs font-medium text-gray-400">2. Capture</span>
|
||||
<select
|
||||
aria-label="选择工作流"
|
||||
aria-label="选择 Capture"
|
||||
value={selectedRunId}
|
||||
disabled={!selectedProjectId || runsLoading}
|
||||
onChange={(event) => updateSelection({ runId: event.target.value })}
|
||||
className="w-full rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2.5 text-sm text-white disabled:opacity-50"
|
||||
>
|
||||
<option value="">
|
||||
{!selectedProjectId ? "请先选择项目" : runsLoading ? "正在加载 Capture…" : "请选择 Capture"}
|
||||
</option>
|
||||
{runOptions.map((run) => (
|
||||
<option key={run.id} value={run.id}>
|
||||
{runOptionLabel(run)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-2">
|
||||
<span className="text-xs font-medium text-gray-400">筛选:工作流(可选)</span>
|
||||
<select
|
||||
aria-label="按工作流筛选 Capture"
|
||||
value={selectedWorkflowId}
|
||||
disabled={!selectedProjectId || workflowsLoading}
|
||||
onChange={(event) => updateSelection({ workflowId: event.target.value, runId: "" })}
|
||||
className="w-full rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2.5 text-sm text-white disabled:opacity-50"
|
||||
>
|
||||
<option value="">
|
||||
{!selectedProjectId ? "请先选择项目" : workflowsLoading ? "正在加载工作流…" : "请选择工作流"}
|
||||
{!selectedProjectId ? "请先选择项目" : workflowsLoading ? "正在加载工作流…" : "全部工作流"}
|
||||
</option>
|
||||
{workflows.map((workflow) => (
|
||||
<option key={workflow.id} value={workflow.id}>
|
||||
@ -308,25 +325,6 @@ export default function DataAssets() {
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-2">
|
||||
<span className="text-xs font-medium text-gray-400">3. Capture / 执行记录</span>
|
||||
<select
|
||||
aria-label="选择 Capture 执行记录"
|
||||
value={selectedRunId}
|
||||
disabled={!selectedWorkflowId || runsLoading}
|
||||
onChange={(event) => updateSelection({ runId: event.target.value })}
|
||||
className="w-full rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2.5 font-mono text-xs text-white disabled:opacity-50"
|
||||
>
|
||||
<option value="">
|
||||
{!selectedWorkflowId ? "请先选择工作流" : runsLoading ? "正在加载执行记录…" : "请选择 Capture 执行记录"}
|
||||
</option>
|
||||
{runOptions.map((run) => (
|
||||
<option key={run.id} value={run.id}>
|
||||
{runOptionLabel(run)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{selectionError ? (
|
||||
<div className="mt-4 flex items-center gap-2 rounded-lg border border-red-500/20 bg-red-500/10 px-3 py-2 text-xs text-red-200">
|
||||
|
||||
@ -496,6 +496,7 @@ export default function ProjectDetail() {
|
||||
if (!project) return <div>项目未找到</div>;
|
||||
|
||||
const canManage = canManagePipelineDesign(role);
|
||||
const canManageMembers = canManage || role === "supplier_manager";
|
||||
const projectAssetsPath = buildDataAssetsPath({
|
||||
tab: DATA_ASSET_PACKAGES_TAB,
|
||||
projectId: project.id,
|
||||
@ -1759,7 +1760,7 @@ export default function ProjectDetail() {
|
||||
<ProjectMembersPanel
|
||||
projectId={project.id}
|
||||
users={users}
|
||||
canManage={canManage}
|
||||
canManage={canManageMembers}
|
||||
onCountChange={setProjectMemberCount}
|
||||
/>
|
||||
)}
|
||||
@ -2785,6 +2786,17 @@ export default function ProjectDetail() {
|
||||
{Math.round(record.samplingDecision.probability * 100)}%
|
||||
</div>
|
||||
) : null}
|
||||
{record.parentRunId ? (
|
||||
<div className="mt-1 break-all font-mono text-[10px] text-gray-600">
|
||||
父 Run:{record.parentRunId}
|
||||
</div>
|
||||
) : null}
|
||||
{record.error ? (
|
||||
<div className="mt-1 max-w-[320px] text-[10px] text-red-300" title={record.error}>
|
||||
{record.failedNodeId ? `失败节点 ${record.failedNodeId}:` : "失败原因:"}
|
||||
{record.error}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-gray-400">
|
||||
{record.fileCount} 个 · {formatBytes(record.totalBytes)}
|
||||
|
||||
@ -26,7 +26,8 @@ export const humanLoopApi = {
|
||||
listItems: async (filters: HumanItemFilters = {}) =>
|
||||
(await apiRequest<{ items: HumanItem[] }>(`/api/human-items${queryString(filters)}`)).items,
|
||||
getItem: (id: string) => apiRequest<{ item: HumanItem }>(`/api/human-items/${encodeURIComponent(id)}`),
|
||||
subjectContentURL: (id: string) => `/api/human-items/${encodeURIComponent(id)}/subject-content`,
|
||||
subjectContentURL: (id: string, side: "left" | "right" = "left") =>
|
||||
`/api/human-items/${encodeURIComponent(id)}/subject-content${side === "right" ? "?side=right" : ""}`,
|
||||
evidenceContentURL: (id: string, artifactId: string) =>
|
||||
`/api/human-items/${encodeURIComponent(id)}/evidence/${encodeURIComponent(artifactId)}/content`,
|
||||
listEvidenceMembers: (
|
||||
|
||||
16
src/types.ts
16
src/types.ts
@ -1114,6 +1114,7 @@ export interface CaptureRecord {
|
||||
maxAttempts?: number;
|
||||
nextRetryAt?: string;
|
||||
parentRunId?: string;
|
||||
failedNodeId?: string;
|
||||
businessStage?: CaptureBusinessStage;
|
||||
contractRevision?: string;
|
||||
runtimePolicyRevision?: number;
|
||||
@ -1877,6 +1878,19 @@ export interface AnnotationLabelRecord {
|
||||
status: "active" | "inactive";
|
||||
version: number;
|
||||
updatedAt: string;
|
||||
history?: Array<{
|
||||
version: number;
|
||||
code: string;
|
||||
name: string;
|
||||
category?: string;
|
||||
description?: string;
|
||||
example?: string;
|
||||
color?: string;
|
||||
aliases?: string[];
|
||||
status: "active" | "inactive";
|
||||
updatedByUserId: string;
|
||||
updatedAt: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ProjectAnnotationLabelsRecord {
|
||||
@ -1968,6 +1982,8 @@ export interface AnnotationTaskRecord {
|
||||
nodeId?: string;
|
||||
artifactId?: string;
|
||||
sourceVideo: string;
|
||||
rightArtifactId?: string;
|
||||
rightSourceVideo?: string;
|
||||
clipStart: number;
|
||||
clipEnd: number;
|
||||
sourceIsFullVideo?: boolean;
|
||||
|
||||
@ -434,12 +434,19 @@ def test_package_multiport_binds_directory_media_semantic_segment_and_summary(tm
|
||||
assert len({item["id"] for item in artifacts}) == len(artifacts)
|
||||
|
||||
|
||||
def test_v58_package_organizes_accepted_revision_directory_without_first_cut(tmp_path):
|
||||
def test_v58_package_organizes_accepted_revision_directory_without_first_cut(tmp_path, monkeypatch):
|
||||
accepted_root = tmp_path / "accepted" / "revision-000001"
|
||||
source_slice = accepted_root / "slices" / "slice-000001"
|
||||
source_slice.mkdir(parents=True)
|
||||
for name in ("left.mp4", "right.mp4", "left_pts.csv", "right_pts.csv", "imu.csv", "annotation.json"):
|
||||
for name in ("left.mp4", "right.mp4"):
|
||||
(source_slice / name).write_bytes(b"accepted-materialized-file")
|
||||
for name in ("left_pts.csv", "right_pts.csv"):
|
||||
(source_slice / name).write_text("frame_index,timestamp_ms,clip_time_ms\n0,1000,0\n1,1500,500\n", encoding="utf-8")
|
||||
(source_slice / "imu.csv").write_text(
|
||||
"timestamp_ms,clip_time_ms,x,y,z,type\n1000,0,0,0,9.8,accel\n1000,0,0,0,0,gyro\n1500,500,0,0,9.8,accel\n1500,500,0,0,0,gyro\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(source_slice / "annotation.json").write_text(json.dumps({"actions": []}), encoding="utf-8")
|
||||
(source_slice / "synchronized-slice.json").write_text(json.dumps({"schemaVersion": "droboticflow.synchronized-slice/v1"}), encoding="utf-8")
|
||||
(accepted_root / "revision-manifest.json").write_text(json.dumps({
|
||||
"schemaVersion": "droboticflow.slice-materialization/v2",
|
||||
@ -457,7 +464,7 @@ def test_v58_package_organizes_accepted_revision_directory_without_first_cut(tmp
|
||||
imu_calibration.write_text("imu: real\n", encoding="utf-8")
|
||||
inputs = [
|
||||
{"id": "accepted-directory", "name": "revision.directory.index", "path": str(accepted_root), "type": "file", "portId": "acceptedSliceDirectory", "data": {}},
|
||||
{"id": "acceptance", "name": "acceptance-summary.json", "type": "json", "portId": "acceptanceSummary", "data": {"finalAcceptance": {"sampled": False, "samplingDecision": "not_selected", "samplingProbability": 0.5, "samplingPolicyRevision": 2, "samplingRandomValue": 0.8, "poseDelivery": {"headpose": "include", "handpose": "exclude"}}}},
|
||||
{"id": "acceptance", "name": "acceptance-summary.json", "type": "json", "portId": "acceptanceSummary", "data": {"capture": {"captureId": "capture-a", "prefix": "test/capture-a", "fingerprint": "sha"}, "qualityReviews": [{"decision": "approved", "revision": 1}], "finalAcceptance": {"sampled": False, "samplingDecision": "not_selected", "samplingProbability": 0.5, "samplingPolicyRevision": 2, "samplingRandomValue": 0.8, "poseDelivery": {"headpose": "include", "handpose": "exclude"}}}},
|
||||
{"id": "headpose", "name": "headpose.json", "type": "json", "portId": "headpose", "data": {"schemaVersion": "droboticflow.headpose/v1", "frames": [{"frameIndex": 0, "timestampSeconds": 0.5, "yawDeg": 0, "pitchDeg": 0, "rollDeg": 0}]}},
|
||||
{"id": "handpose", "name": "handpose.json", "type": "json", "portId": "handpose", "data": {"schemaVersion": "droboticflow.wilor.hand_pose_result/v1", "result": {"frames": [{"frameIndex": 0, "timestampSeconds": 0.5}]}}},
|
||||
{"id": "camera-calibration", "name": camera_calibration.name, "path": str(camera_calibration), "type": "file", "portId": "calibrations", "data": {}},
|
||||
@ -484,6 +491,7 @@ def test_v58_package_organizes_accepted_revision_directory_without_first_cut(tmp
|
||||
def virtual(run_id, node_id, name, path, artifact_type, size_bytes, data=None, metadata=None, output=None):
|
||||
return {"id": f"{run_id}-{name}", "name": name, "path": str(path), "type": artifact_type, "data": data or {}, "portId": output["id"], "portName": output["name"]}
|
||||
|
||||
monkeypatch.setattr(package_operator, "_ffprobe_frame_count", lambda path: 2)
|
||||
artifacts = package_operator.run(
|
||||
"package-run", "package", tmp_path / "output", {"outputs": outputs}, inputs,
|
||||
{
|
||||
@ -508,6 +516,9 @@ def test_v58_package_organizes_accepted_revision_directory_without_first_cut(tmp
|
||||
assert manifest["poseDelivery"] == {"headpose": "include", "handpose": "exclude"}
|
||||
assert manifest["acceptanceSampling"] == {"sampled": False, "decision": "not_selected", "probability": 0.5, "policyRevision": 2, "randomValue": 0.8, "decidedAt": None}
|
||||
assert manifest["coverage"]["contiguous"] is True
|
||||
assert manifest["capture"]["captureId"] == "capture-a"
|
||||
assert {item["name"] for item in manifest["rootEvidence"]} == {"capture-manifest.json", "quality-review.json", "acceptance-record.json", "sampling-evidence.json"}
|
||||
assert json.loads((delivery / "quality-review.json").read_text(encoding="utf-8"))["reviews"][0]["decision"] == "approved"
|
||||
assert {item["portId"] for item in artifacts} == {"deliveryDirectory", "deliveryManifest", "deliverySummary"}
|
||||
|
||||
|
||||
|
||||
@ -160,6 +160,10 @@ test("annotation operations uses the draggable video timeline and workflow deep
|
||||
new URL("../../src/components/MaterializedSliceWorkbench.tsx", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const workbench = fs.readFileSync(
|
||||
new URL("../../src/components/AnnotationWorkbenchEditor.tsx", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
assert.match(page, /AnnotationTimelineEditor/);
|
||||
assert.match(page, /requestedRunId/);
|
||||
assert.match(page, /annotationStageNavigationPath/);
|
||||
@ -185,6 +189,10 @@ test("annotation operations uses the draggable video timeline and workflow deep
|
||||
assert.match(page, /humanLoopApi\.subjectContentURL\(selectedHumanItem\.id\)/);
|
||||
assert.match(page, /disabled=\{sliceEditorReadOnly\}/);
|
||||
assert.match(page, /data-testid="slice-coverage-status"/);
|
||||
assert.match(page, /rightVideoSource=\{selectedRightVideoSource\}/);
|
||||
assert.match(page, /subjectContentURL\(selectedHumanItem\.id, "right"\)/);
|
||||
assert.match(workbench, /边界异常/);
|
||||
assert.match(workbench, /cameraMode/);
|
||||
assert.match(page, /data-testid="annotation-load-recovery"/);
|
||||
assert.match(page, /recoverableGatewayStatus\(loadError\)/);
|
||||
assert.match(page, /setProjectLoadRetryVersion/);
|
||||
|
||||
@ -49,17 +49,17 @@ test("artifact group parsing supports final intermediate and input", () => {
|
||||
assert.equal(parseDataAssetsGroup("unexpected"), DATA_ASSET_FINAL_GROUP);
|
||||
});
|
||||
|
||||
test("data assets page selects project workflow and run before loading all artifacts", async () => {
|
||||
test("data assets page uses project and Capture as hierarchy with workflow as an optional filter", async () => {
|
||||
const page = await readFile(new URL("../../src/pages/DataAssets.tsx", import.meta.url), "utf8");
|
||||
const explorer = await readFile(new URL("../../src/components/RunArtifactsExplorer.tsx", import.meta.url), "utf8");
|
||||
|
||||
assert.match(page, /aria-label="选择项目"/);
|
||||
assert.match(page, /aria-label="选择工作流"/);
|
||||
assert.match(page, /aria-label="选择 Capture 执行记录"/);
|
||||
assert.match(page, /aria-label="选择 Capture"/);
|
||||
assert.match(page, /aria-label="按工作流筛选 Capture"/);
|
||||
assert.match(page, /BusinessExecutionPath/);
|
||||
assert.match(page, /primaryCaptureDirectory/);
|
||||
assert.match(page, /\.listWorkflows\(selectedProjectId\)/);
|
||||
assert.match(page, /\.listRuns\(selectedWorkflowId\)/);
|
||||
assert.match(page, /monitoringApi[\s\S]*\.listRuns\(\{ projectId: selectedProjectId, workflowId: selectedWorkflowId \|\| undefined/);
|
||||
assert.match(page, /monitoringApi\.getExecutionData\(selectedRunId\)/);
|
||||
assert.match(page, /monitoringApi\.getLineage\(selectedRunId\)/);
|
||||
assert.match(page, /runInputArtifacts\(runDetail\)/);
|
||||
|
||||
@ -78,8 +78,11 @@ test("v5.8 submits a combined revision and uses strict whole-package acceptance"
|
||||
assert.match(source, /pendingCombinedSubmissionId/);
|
||||
});
|
||||
|
||||
test("supplier managers are redirected away from non-dashboard deep links", async () => {
|
||||
const source = await readFile(appURL, "utf8");
|
||||
test("supplier managers can maintain supplier-scoped project members but remain outside engineering routes", async () => {
|
||||
const [source, sidebar] = await Promise.all([readFile(appURL, "utf8"), readFile(sidebarURL, "utf8")]);
|
||||
assert.match(source, /effectiveRole === "supplier_manager"/);
|
||||
assert.match(source, /path !== "\/projects"/);
|
||||
assert.match(source, /!path\.startsWith\("\/project\/"\)/);
|
||||
assert.match(source, /<Navigate to="\/" replace/);
|
||||
assert.match(sidebar, /path: "\/projects",[\s\S]*roles: \["admin", "supplier_manager"\]/);
|
||||
});
|
||||
|
||||
@ -11,6 +11,7 @@ test("project detail exposes project-scoped human roles and safe workflow deleti
|
||||
const members = fs.readFileSync(path.join(root, "src/components/ProjectMembersPanel.tsx"), "utf8");
|
||||
assert.match(projectDetail, /成员与角色/);
|
||||
assert.match(projectDetail, /ProjectMembersPanel/);
|
||||
assert.match(projectDetail, /role === "supplier_manager"/);
|
||||
assert.match(members, /标注员[\s\S]*真实切分校正与语义标注/);
|
||||
assert.match(members, /审核员[\s\S]*审核切分、双目同步与语义标注/);
|
||||
assert.match(members, /最终验收员[\s\S]*独立完成整包最终验收/);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user