From 7c04c2bebdcda16ee1e360cc37bd7a7995d2ea6d Mon Sep 17 00:00:00 2001 From: eust-w Date: Sat, 22 Aug 2026 00:01:30 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Show=20delivery=20contents=20in=20a?= =?UTF-8?q?cceptance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/delivery_package_contents_test.go | 75 ++++++ internal/api/delivery_packages.go | 92 ++++++++ internal/api/server.go | 3 + src/pages/AnnotationOperations.tsx | 215 ++++++++++++++++-- src/services/api/delivery-packages.ts | 4 +- src/types.ts | 21 ++ tests/frontend/fanyu-v5-four-stage.test.mjs | 5 + 7 files changed, 398 insertions(+), 17 deletions(-) create mode 100644 internal/api/delivery_package_contents_test.go diff --git a/internal/api/delivery_package_contents_test.go b/internal/api/delivery_package_contents_test.go new file mode 100644 index 00000000..9d1b2b32 --- /dev/null +++ b/internal/api/delivery_package_contents_test.go @@ -0,0 +1,75 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "droboticflow/internal/domain" + "droboticflow/internal/store" +) + +func TestDeliveryPackageContentsExposeOnlyFinalArtifactsToReviewer(t *testing.T) { + ctx := context.Background() + dataStore := store.NewMemoryStore() + videoPath := filepath.Join(t.TempDir(), "final-001.mp4") + if err := os.WriteFile(videoPath, []byte("final-video"), 0o600); err != nil { + t.Fatal(err) + } + manifestID, videoID := "artifact-manifest", "artifact-video" + run := domain.RunRecord{ + ID: "run-final", OrganizationID: domain.DefaultOrganizationID, WorkflowID: "workflow-final", ProjectID: "project-final", Status: domain.RunStatusCompleted, + Artifacts: []domain.ExecutionArtifact{ + {ID: manifestID, RunID: "run-final", NodeID: "package", Name: "packages-manifest.json", Type: domain.PortTypeJSON, Data: map[string]any{"packageCount": 1, "trainingEnabled": false, "items": []any{map[string]any{"packageName": "slice-package", "clipId": "slice", "clipName": "final-001.mp4", "startSecond": 0.0, "endSecond": 10.2, "duration": 10.2}}}}, + {ID: videoID, RunID: "run-final", NodeID: "package", Name: "final-001.mp4", Type: domain.PortTypeVideo, Path: videoPath, Size: "11 B", Metadata: &domain.ArtifactMetadata{MimeType: "video/mp4"}}, + {ID: "artifact-upstream", RunID: "run-parent", NodeID: "human", Name: "annotations.json", Type: domain.PortTypeJSON}, + }, + } + if err := dataStore.UpsertRun(ctx, run); err != nil { + t.Fatal(err) + } + item := domain.DeliveryPackageRecord{ + ID: "delivery-final", OrganizationID: domain.DefaultOrganizationID, ProjectID: run.ProjectID, WorkflowID: run.WorkflowID, + ChildRunID: run.ID, Status: domain.DeliveryPackageAccepted, FinalExportArtifactIDs: []string{manifestID, videoID}, Version: 1, + } + if err := dataStore.UpsertDeliveryPackage(ctx, item); err != nil { + t.Fatal(err) + } + principal := &authenticatedPrincipal{User: domain.UserRecord{ID: "admin", OrganizationID: domain.DefaultOrganizationID, Role: domain.UserRoleAdmin}, Organization: domain.OrganizationRecord{ID: domain.DefaultOrganizationID}} + handler := NewHandler(dataStore, nil) + + request := httptest.NewRequest(http.MethodGet, "/api/delivery-packages/"+item.ID+"/contents", nil) + request = request.WithContext(context.WithValue(request.Context(), authContextKey{}, principal)) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusOK { + t.Fatalf("contents status=%d body=%s", recorder.Code, recorder.Body.String()) + } + var payload struct { + Artifacts []domain.ExecutionArtifact `json:"artifacts"` + Manifest map[string]any `json:"manifest"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if len(payload.Artifacts) != 2 || payload.Manifest["packageCount"] != float64(1) { + t.Fatalf("unexpected delivery contents: %#v", payload) + } + for _, artifact := range payload.Artifacts { + if artifact.ID == "artifact-upstream" || artifact.Data["contentURL"] == "" { + t.Fatalf("contents leaked an upstream artifact or omitted content URL: %#v", artifact) + } + } + + contentRequest := httptest.NewRequest(http.MethodGet, "/api/delivery-packages/"+item.ID+"/artifacts/"+videoID+"/content", nil) + contentRequest = contentRequest.WithContext(context.WithValue(contentRequest.Context(), authContextKey{}, principal)) + contentRecorder := httptest.NewRecorder() + handler.ServeHTTP(contentRecorder, contentRequest) + if contentRecorder.Code != http.StatusOK || contentRecorder.Body.String() != "final-video" { + t.Fatalf("video content status=%d body=%q", contentRecorder.Code, contentRecorder.Body.String()) + } +} diff --git a/internal/api/delivery_packages.go b/internal/api/delivery_packages.go index d3281e96..7d1241f7 100644 --- a/internal/api/delivery_packages.go +++ b/internal/api/delivery_packages.go @@ -56,6 +56,98 @@ func (server *server) handleDeliveryPackagesList(writer http.ResponseWriter, req renderJSON(writer, http.StatusOK, map[string]any{"items": items}) } +func (server *server) deliveryPackageForReviewer(writer http.ResponseWriter, request *http.Request) (*domain.DeliveryPackageRecord, bool) { + item, err := server.store.GetDeliveryPackage(request.Context(), chi.URLParam(request, "id")) + if err != nil { + renderError(writer, http.StatusInternalServerError, err) + return nil, false + } + if item == nil { + renderJSON(writer, http.StatusNotFound, map[string]string{"error": "Delivery package not found"}) + return nil, false + } + if !server.ensureTenantAccess(writer, request, item.OrganizationID, "Delivery package") { + return nil, false + } + if !server.deliveryPackageReviewer(request, *item) { + renderJSON(writer, http.StatusForbidden, map[string]string{"error": "acceptance reviewer membership is required"}) + return nil, false + } + return item, true +} + +func deliveryPackageArtifactAllowed(item *domain.DeliveryPackageRecord, artifactID string) bool { + if item == nil || strings.TrimSpace(artifactID) == "" { + return false + } + for _, allowedID := range item.FinalExportArtifactIDs { + if allowedID == artifactID { + return true + } + } + return false +} + +func (server *server) handleDeliveryPackageContents(writer http.ResponseWriter, request *http.Request) { + item, ok := server.deliveryPackageForReviewer(writer, request) + if !ok { + return + } + run, err := server.store.GetRun(request.Context(), item.ChildRunID) + if err != nil { + renderError(writer, http.StatusInternalServerError, err) + return + } + if run == nil { + renderJSON(writer, http.StatusNotFound, map[string]string{"error": "Delivery package Run not found"}) + return + } + allowed := make(map[string]struct{}, len(item.FinalExportArtifactIDs)) + for _, artifactID := range item.FinalExportArtifactIDs { + allowed[artifactID] = struct{}{} + } + artifacts := make([]domain.ExecutionArtifact, 0, len(allowed)) + var manifest map[string]any + for _, artifact := range run.Artifacts { + if _, exists := allowed[artifact.ID]; !exists || artifact.RunID != run.ID { + continue + } + copy := artifact + if copy.Data == nil { + copy.Data = make(map[string]any) + } + contentURL := "/api/delivery-packages/" + item.ID + "/artifacts/" + artifact.ID + "/content" + copy.Data["contentURL"] = contentURL + if copy.Type == domain.PortTypeVideo || (copy.Metadata != nil && strings.HasPrefix(strings.TrimSpace(copy.Metadata.MimeType), "video/")) { + preview := mapValue(copy.Data["preview"]) + if preview == nil { + preview = make(map[string]any) + } + preview["kind"] = "video" + preview["url"] = contentURL + copy.Data["preview"] = preview + } + if copy.Name == "packages-manifest.json" { + manifest = artifactStructuredData(&artifact) + } + artifacts = append(artifacts, copy) + } + renderJSON(writer, http.StatusOK, map[string]any{"deliveryPackage": item, "artifacts": artifacts, "manifest": manifest}) +} + +func (server *server) handleDeliveryPackageArtifactContent(writer http.ResponseWriter, request *http.Request) { + item, ok := server.deliveryPackageForReviewer(writer, request) + if !ok { + return + } + artifactID := strings.TrimSpace(chi.URLParam(request, "artifactId")) + if !deliveryPackageArtifactAllowed(item, artifactID) { + renderJSON(writer, http.StatusForbidden, map[string]string{"error": "artifact is not a final delivery output"}) + return + } + server.serveRunArtifactContent(writer, request, item.ChildRunID, artifactID) +} + func (server *server) enrichDeliveryPackageAcceptance(request *http.Request, item *domain.DeliveryPackageRecord) error { if item == nil || strings.TrimSpace(item.AcceptanceHumanItemID) == "" { return nil diff --git a/internal/api/server.go b/internal/api/server.go index 042227ad..462bc1ee 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -1460,6 +1460,9 @@ func NewHandlerWithConfig(dataStore store.Store, aiService ai.Service, appConfig router.Get("/api/packages/{runId}/{packageName}/content", instance.handlePackageContent) router.Get("/api/delivery-packages", instance.handleDeliveryPackagesList) router.Get("/api/delivery-packages/{id}", instance.handleDeliveryPackageGet) + router.Get("/api/delivery-packages/{id}/contents", instance.handleDeliveryPackageContents) + router.Get("/api/delivery-packages/{id}/artifacts/{artifactId}/content", instance.handleDeliveryPackageArtifactContent) + router.Head("/api/delivery-packages/{id}/artifacts/{artifactId}/content", instance.handleDeliveryPackageArtifactContent) router.Group(func(router chi.Router) { router.Use(instance.requireBusinessRole(domain.UserRoleAdmin, domain.UserRoleAcceptanceReviewer)) router.Post("/api/delivery-packages/{id}/claim", instance.handleDeliveryPackageClaim) diff --git a/src/pages/AnnotationOperations.tsx b/src/pages/AnnotationOperations.tsx index 26da400a..20389de6 100644 --- a/src/pages/AnnotationOperations.tsx +++ b/src/pages/AnnotationOperations.tsx @@ -20,6 +20,10 @@ import { Video, Eye, ShieldCheck, + ChevronDown, + ChevronUp, + Download, + FileJson, } from "lucide-react"; import type { AnnotationSegment, @@ -31,6 +35,9 @@ import type { HumanReject, HumanItem, DeliveryPackage, + DeliveryPackageContents, + DeliveryPackageManifestItem, + ExecutionData, Project, ProjectAnnotationMembership, SliceOperation, @@ -45,6 +52,7 @@ import { projectsApi } from "../services/api/projects"; import { normalizeAnnotationSegments, summarizeAnnotationWorkload } from "../lib/annotation-operations.js"; import { formatCompactDateTime } from "../lib/datetime"; import { getActionErrorMessage } from "../lib/action-errors.js"; +import { artifactContentPath } from "../lib/artifact-download.js"; import AnnotationTimelineEditor from "../components/AnnotationTimelineEditor"; import RerunArtifactPreview from "../components/RerunArtifactPreview"; import { buildBrowserPlayableVideoURL } from "../lib/video-preview.js"; @@ -102,6 +110,20 @@ function prepackageAcceptanceStatisticsAreValid(statistics: PrepackageAcceptance ); } +function deliveryArtifactPreviewURL(item: ExecutionData | undefined) { + const preview = item?.data?.preview; + if (preview && typeof preview === "object" && typeof preview.url === "string") return preview.url; + return ""; +} + +function deliveryArtifactDownloadURL(item: ExecutionData) { + return artifactContentPath(item, { download: true }); +} + +function deliveryActions(item: DeliveryPackageManifestItem) { + return Array.isArray(item.annotation?.actions) ? item.annotation.actions : []; +} + const panelClass = "rounded-2xl border border-[#2a2b2f] bg-[#151619]"; const inputClass = "w-full rounded-lg border border-[#2a2b2f] bg-[#0a0a0a] px-3 py-2 text-sm text-white outline-none focus:border-blue-500"; @@ -175,6 +197,10 @@ export default function AnnotationOperations() { const [workload, setWorkload] = useState({ items: [], eventCount: 0 }); const [rejects, setRejects] = useState([]); const [deliveryPackages, setDeliveryPackages] = useState([]); + const [expandedDeliveryPackageId, setExpandedDeliveryPackageId] = useState(""); + const [deliveryPackageContents, setDeliveryPackageContents] = useState>({}); + const [deliveryPackageContentsLoading, setDeliveryPackageContentsLoading] = useState(""); + const [deliveryPackageContentsErrors, setDeliveryPackageContentsErrors] = useState>({}); const [prepackageAcceptanceItems, setPrepackageAcceptanceItems] = useState([]); const [selectedAcceptanceEvidence, setSelectedAcceptanceEvidence] = useState<{ itemId: string; index: number }>({ itemId: "", @@ -826,6 +852,28 @@ export default function AnnotationOperations() { } }; + const toggleDeliveryPackageContents = async (item: DeliveryPackage) => { + if (expandedDeliveryPackageId === item.id) { + setExpandedDeliveryPackageId(""); + return; + } + setExpandedDeliveryPackageId(item.id); + if (deliveryPackageContents[item.id]) return; + setDeliveryPackageContentsLoading(item.id); + setDeliveryPackageContentsErrors((current) => ({ ...current, [item.id]: "" })); + try { + const contents = await deliveryPackagesApi.contents(item.id); + setDeliveryPackageContents((current) => ({ ...current, [item.id]: contents })); + } catch (loadError) { + setDeliveryPackageContentsErrors((current) => ({ + ...current, + [item.id]: getActionErrorMessage(loadError, "加载验收内容失败"), + })); + } finally { + setDeliveryPackageContentsLoading(""); + } + }; + const releasePrepackageAcceptance = async (item: HumanItem) => { setSaving(true); setError(""); @@ -1227,6 +1275,14 @@ export default function AnnotationOperations() { const overallGrade = prePackageAcceptance?.statistics?.overallGrade || item.acceptanceReviews?.at(-1)?.overallGrade || "-"; const assignedToMe = item.assignedUserId === currentUser?.id; + const isExpanded = expandedDeliveryPackageId === item.id; + const contents = deliveryPackageContents[item.id]; + const manifestItems = contents?.manifest?.items || []; + const acceptanceStatistics = ( + contents?.deliveryPackage.qualitySummary?.prePackageAcceptance as + | { statistics?: Record } + | undefined + )?.statistics; return (
@@ -1237,28 +1293,155 @@ export default function AnnotationOperations() { 个最终产物 · 状态 {item.status} · 质检等级 {overallGrade}
- {item.status === "pending_acceptance" && item.acceptanceHumanItemId && !item.assignedUserId ? ( +
- ) : null} - {assignedToMe ? ( - - ) : null} + {item.status === "pending_acceptance" && item.acceptanceHumanItemId && !item.assignedUserId ? ( + + ) : null} + {assignedToMe ? ( + + ) : null} +
+ {isExpanded ? ( +
+ {deliveryPackageContentsLoading === item.id ? ( +
+ 正在加载验收内容... +
+ ) : deliveryPackageContentsErrors[item.id] ? ( +
+ {deliveryPackageContentsErrors[item.id]} +
+ ) : contents ? ( + <> +
+ {[ + ["视频质量", acceptanceStatistics?.videoQuality === "qualified" ? "合格" : "-"], + ["标注准确性", acceptanceStatistics?.annotationAccuracy ?? "-"], + ["标注完整性", acceptanceStatistics?.annotationCompleteness ?? "-"], + ["总体等级", acceptanceStatistics?.overallGrade ?? overallGrade], + ["HeadPose", acceptanceStatistics?.headposeEnabled === false ? "未启用" : "-"], + ["HandPose", acceptanceStatistics?.handposeEnabled === false ? "未启用" : "-"], + ].map(([label, value]) => ( +
+
{label}
+
{String(value)}
+
+ ))} +
+ +
+ {manifestItems.map((packageItem) => { + const videoArtifact = contents.artifacts.find( + (artifact) => artifact.name === packageItem.clipName, + ); + const videoURL = deliveryArtifactPreviewURL(videoArtifact); + const actions = deliveryActions(packageItem); + return ( +
+
+
{packageItem.clipName}
+
+ 最终边界 {packageItem.startSecond.toFixed(2)}–{packageItem.endSecond.toFixed(2)}s · + 时长 {packageItem.duration.toFixed(2)}s +
+
+ {videoURL ? ( +
+ ); + })} +
+ +
+
+ 最终交付文件({contents.artifacts.length}) +
+
+ {contents.artifacts.map((artifact) => ( +
+
+ {artifact.type === "video" ? ( +
+ + 下载 + +
+ ))} +
+
+ + ) : null} +
+ ) : null} + {assignedToMe ? (
diff --git a/src/services/api/delivery-packages.ts b/src/services/api/delivery-packages.ts index 9bda3a84..63735655 100644 --- a/src/services/api/delivery-packages.ts +++ b/src/services/api/delivery-packages.ts @@ -1,4 +1,4 @@ -import type { DeliveryPackage } from "../../types"; +import type { DeliveryPackage, DeliveryPackageContents } from "../../types"; import { apiRequest } from "./client"; const packageQuery = (values: Record) => { @@ -14,6 +14,8 @@ export const deliveryPackagesApi = { list: async (filters: { projectId?: string; workflowId?: string; status?: DeliveryPackage["status"] } = {}) => (await apiRequest<{ items: DeliveryPackage[] }>(`/api/delivery-packages${packageQuery(filters)}`)).items, get: (id: string) => apiRequest(`/api/delivery-packages/${encodeURIComponent(id)}`), + contents: (id: string) => + apiRequest(`/api/delivery-packages/${encodeURIComponent(id)}/contents`), claim: (id: string, version: number) => apiRequest( `/api/delivery-packages/${encodeURIComponent(id)}/claim`, diff --git a/src/types.ts b/src/types.ts index 039ff332..f4ce475a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1820,3 +1820,24 @@ export interface DeliveryPackage { createdAt: string; updatedAt: string; } + +export interface DeliveryPackageManifestItem { + packageName: string; + clipId: string; + clipName: string; + startSecond: number; + endSecond: number; + duration: number; + annotation?: Record; + segmentManifest?: Record; +} + +export interface DeliveryPackageContents { + deliveryPackage: DeliveryPackage; + artifacts: ExecutionData[]; + manifest?: { + packageCount?: number; + trainingEnabled?: boolean; + items?: DeliveryPackageManifestItem[]; + }; +} diff --git a/tests/frontend/fanyu-v5-four-stage.test.mjs b/tests/frontend/fanyu-v5-four-stage.test.mjs index f88356f0..fd49fef5 100644 --- a/tests/frontend/fanyu-v5-four-stage.test.mjs +++ b/tests/frontend/fanyu-v5-four-stage.test.mjs @@ -34,4 +34,9 @@ test("aggregate confirmation skips pose stages and releases only packaging", asy assert.match(source, /item\.finalExportArtifactIds\?\.length/); assert.match(source, /qualitySummary\?\.prePackageAcceptance/); assert.doesNotMatch(source, /item\.packageName|item\.itemCount|acceptanceHumanItemAssigneeId/); + assert.match(source, /查看验收内容/); + assert.match(source, /deliveryPackagesApi\.contents/); + assert.match(source, /最终边界/); + assert.match(source, /最终交付文件/); + assert.match(source, /buildBrowserPlayableVideoURL\(videoURL\)/); });