forked from longtao.wu/droboticflow
3966 lines
170 KiB
TypeScript
3966 lines
170 KiB
TypeScript
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||
import { memberCanClaim, memberPoolEmptyReason } from "../lib/member-scope.js";
|
||
import { newAnnotationClaimRequestID } from "../lib/annotation-random-claim.js";
|
||
import { useProjectSliceDictionary } from "../hooks/useProjectSliceDictionary";
|
||
import { alignSliceTimeline, initializeFrameAlignedSlices, sliceTimelineIssue } from "../lib/annotation-timeline.js";
|
||
import { annotationTaskAction } from "../lib/annotation-task-action.js";
|
||
import { FinalAcceptanceWorkspace } from "../components/FinalAcceptanceWorkspace";
|
||
import { AcceptanceTaskCard } from "../components/AcceptanceTaskCard";
|
||
import { Link, useBlocker, useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||
import {
|
||
AlertCircle,
|
||
CheckCircle2,
|
||
ChevronLeft,
|
||
ChevronRight,
|
||
ClipboardCheck,
|
||
Loader2,
|
||
Plus,
|
||
RefreshCw,
|
||
RotateCcw,
|
||
Send,
|
||
Scissors,
|
||
Merge,
|
||
Trash2,
|
||
Undo2,
|
||
XCircle,
|
||
Video,
|
||
Eye,
|
||
ShieldCheck,
|
||
ChevronDown,
|
||
ChevronUp,
|
||
Download,
|
||
FileJson,
|
||
Search,
|
||
} from "lucide-react";
|
||
import type {
|
||
AnnotationSegment,
|
||
AnnotationFrameTimeline,
|
||
AnnotationTaskDetail,
|
||
AnnotationTaskRecord,
|
||
AnnotationTemplate,
|
||
AnnotationWorkloadSummary,
|
||
HumanReject,
|
||
HumanItem,
|
||
DeliveryPackage,
|
||
DeliveryPackageContents,
|
||
DeliveryPackageManifestItem,
|
||
ExecutionData,
|
||
ExecutionRun,
|
||
Project,
|
||
ProjectMember,
|
||
ProjectMemberRole,
|
||
SliceOperation,
|
||
SliceSegment,
|
||
Workflow,
|
||
} from "../types";
|
||
import { useUser } from "../context/UserContext";
|
||
import { useTimeZone } from "../context/TimeZoneContext";
|
||
import { annotationOperationsApi } from "../services/api/annotation-operations";
|
||
import { humanLoopApi } from "../services/api/human-loop";
|
||
import { deliveryPackagesApi } from "../services/api/delivery-packages";
|
||
import { projectsApi } from "../services/api/projects";
|
||
import { runsApi } from "../services/api/runs";
|
||
import {
|
||
analyzeSliceCoverage,
|
||
annotationTaskEditableRange,
|
||
initialCaptureSlices,
|
||
annotationSliceEditorReadOnly,
|
||
annotationStageNavigationPath,
|
||
humanEditableAnnotationSegments,
|
||
normalizeAnnotationSegments,
|
||
scopedHumanQueueEmptyMessage,
|
||
summarizeAnnotationWorkload,
|
||
} from "../lib/annotation-operations.js";
|
||
import {
|
||
annotationDraftFromHumanItem,
|
||
annotationOrphanSegments,
|
||
applySliceStatuses,
|
||
deriveSliceStatuses,
|
||
filterAnnotationTasks,
|
||
nearestFrameBoundaryIndex,
|
||
normalizeFrameBoundaries,
|
||
parseSegmentCommentsFromText,
|
||
stepFrameBoundary,
|
||
summarizeSliceProgress,
|
||
sliceDictionaryNameIssue,
|
||
splitSliceAtBoundary,
|
||
validateAnnotationWorkspace,
|
||
frameBoundaryAligned,
|
||
} from "../lib/annotation-workbench.js";
|
||
import { getActionErrorMessage, recoverableGatewayStatus } from "../lib/action-errors.js";
|
||
import { combinedSubmissionState, combinedSubmissionFinished } from "../lib/annotation-submission-state.js";
|
||
import {
|
||
annotationWorkspaceMatches,
|
||
createAuthoritativeMutationContext,
|
||
createAuthoritativeMutationScope,
|
||
settleAuthoritativeMutation,
|
||
sliceResetWasApplied,
|
||
} from "../lib/annotation-authoritative-mutation.js";
|
||
import { artifactContentPath } from "../lib/artifact-download.js";
|
||
import { CaptureAnnotationWorkbench, type AnnotationDraft } from "../components/CaptureAnnotationWorkbench";
|
||
import RerunArtifactPreview from "../components/RerunArtifactPreview";
|
||
import { LazyVideoPreview } from "../components/LazyVideoPreview";
|
||
import { PageSubnav } from "../components/PageSubnav";
|
||
import { ManifestMemberBrowser } from "../components/ManifestMemberBrowser";
|
||
import { MaterializedSliceWorkbench } from "../components/MaterializedSliceWorkbench";
|
||
import { usePlugins } from "../context/PluginContext";
|
||
import { buildBrowserPlayableVideoURL } from "../lib/video-preview.js";
|
||
import { cn } from "../lib/utils";
|
||
import {
|
||
annotationStageModeFromPath,
|
||
annotationStageModesForRoles,
|
||
getPluginNavigationContributions,
|
||
} from "../lib/plugin-navigation.js";
|
||
import { isOrganizationAdminRole } from "../lib/user-roles";
|
||
import { captureDirectoriesFromHumanTask, uniqueCaptureDirectories } from "../lib/business-display.js";
|
||
import { BusinessExecutionPath } from "../components/BusinessExecutionPath";
|
||
|
||
type Tab = "queue" | "rejects" | "templates" | "workload";
|
||
type WorkspaceMode = "clip" | "clip-quality" | "annotate" | "quality" | "acceptance";
|
||
type TaskPoolView = "available" | "mine" | "all";
|
||
type HumanPools = Record<TaskPoolView, HumanItem[]>;
|
||
type CombinedEditorPhase = "slice" | "materializing" | "annotate";
|
||
|
||
const emptyHumanPools: HumanPools = { available: [], mine: [], all: [] };
|
||
const projectLoadRecoveryAttempts = 3;
|
||
const projectLoadRecoveryDelayMs = 2_000;
|
||
|
||
const statusLabels: Record<string, string> = {
|
||
pending_annotation: "待标注/剪切",
|
||
pending_quality: "待质检",
|
||
pending_acceptance: "待验收",
|
||
rework: "返工中",
|
||
accepted: "已通过",
|
||
rejected: "已拒绝",
|
||
cancelled: "已取消",
|
||
};
|
||
|
||
export type DetailedTaskStatus =
|
||
| "rework"
|
||
| "pending_quality"
|
||
| "pending_acceptance"
|
||
| "accepted"
|
||
| "slicing"
|
||
| "pending_annotation"
|
||
| "pending_slice"
|
||
| "available";
|
||
|
||
export const deriveDetailedTaskStatus = (
|
||
task: AnnotationTaskRecord,
|
||
humanItem?: HumanItem,
|
||
livePhase?: CombinedEditorPhase,
|
||
): DetailedTaskStatus => {
|
||
if (humanItem?.status === "accepted" || task.status === "accepted") return "accepted";
|
||
if (
|
||
task.status === "pending_quality" ||
|
||
humanItem?.currentStageId === "quality_review" ||
|
||
humanItem?.status === "submitted" ||
|
||
Boolean(humanItem?.pendingCombinedSubmissionId)
|
||
) {
|
||
return "pending_quality";
|
||
}
|
||
if (
|
||
task.status === "pending_acceptance" ||
|
||
humanItem?.currentStageId === "acceptance" ||
|
||
humanItem?.currentStageId === "prepackage_acceptance"
|
||
) {
|
||
return "pending_acceptance";
|
||
}
|
||
const sliceWorkflow = humanItem?.subject?.payload?.sliceWorkflow as
|
||
| { status?: string; phase?: string; error?: string }
|
||
| undefined;
|
||
|
||
if (
|
||
task.status === "rework" ||
|
||
humanItem?.status === "rework" ||
|
||
(Number(humanItem?.reviewRound || 0) > 0 && humanItem?.currentStageId === "annotation_combined")
|
||
)
|
||
return "rework";
|
||
|
||
if (livePhase === "materializing" || sliceWorkflow?.status === "processing") {
|
||
return "slicing";
|
||
}
|
||
if (livePhase === "annotate" || sliceWorkflow?.status === "completed" || sliceWorkflow?.phase === "annotate") {
|
||
return "pending_annotation";
|
||
}
|
||
if (
|
||
livePhase === "slice" ||
|
||
sliceWorkflow?.status === "editing" ||
|
||
sliceWorkflow?.phase === "slice" ||
|
||
humanItem?.assignedUserId
|
||
) {
|
||
return "pending_slice";
|
||
}
|
||
return "available";
|
||
};
|
||
|
||
const emptyTemplate = {
|
||
name: "泛宇语义模板",
|
||
version: 1,
|
||
labels: "静止观察,平稳活动,快速移动",
|
||
phrases: "手部,前景目标",
|
||
};
|
||
|
||
const emptyPrepackageAcceptanceStatistics = {
|
||
videoQuality: "",
|
||
annotationAccuracy: "",
|
||
annotationCompleteness: "",
|
||
overallGrade: "",
|
||
headpose: "include" as "include" | "exclude",
|
||
handpose: "include" as "include" | "exclude",
|
||
exclusionReason: "",
|
||
};
|
||
|
||
type PrepackageAcceptanceStatistics = typeof emptyPrepackageAcceptanceStatistics;
|
||
type AnnotationMutationToken = { id: number; taskId: string; userId: string };
|
||
|
||
function annotationWorkspaceFingerprint(
|
||
slices: SliceSegment[],
|
||
operations: SliceOperation[],
|
||
annotations: AnnotationSegment[],
|
||
statuses: Record<string, NonNullable<SliceSegment["annotationStatus"]>>,
|
||
) {
|
||
return JSON.stringify({
|
||
slices: slices.map((slice) => ({ ...slice, annotationStatus: statuses[slice.id] || "pending" })),
|
||
operations,
|
||
annotations,
|
||
});
|
||
}
|
||
|
||
function prepackageAcceptanceStatisticsAreValid(statistics: PrepackageAcceptanceStatistics) {
|
||
const accuracy = Number(statistics.annotationAccuracy);
|
||
const completeness = Number(statistics.annotationCompleteness);
|
||
return (
|
||
statistics.videoQuality.trim() !== "" &&
|
||
statistics.overallGrade.trim() !== "" &&
|
||
statistics.annotationAccuracy.trim() !== "" &&
|
||
statistics.annotationCompleteness.trim() !== "" &&
|
||
Number.isFinite(accuracy) &&
|
||
accuracy >= 0 &&
|
||
accuracy <= 100 &&
|
||
Number.isFinite(completeness) &&
|
||
completeness >= 0 &&
|
||
completeness <= 100
|
||
);
|
||
}
|
||
|
||
function strictAcceptanceDraftIsValid(statistics: PrepackageAcceptanceStatistics) {
|
||
return (
|
||
["include", "exclude"].includes(statistics.headpose) &&
|
||
["include", "exclude"].includes(statistics.handpose) &&
|
||
(statistics.headpose === "include" && statistics.handpose === "include"
|
||
? true
|
||
: statistics.exclusionReason.trim() !== "")
|
||
);
|
||
}
|
||
|
||
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) {
|
||
if (Array.isArray(item.annotation?.descriptions)) return item.annotation.descriptions;
|
||
return Array.isArray(item.annotation?.actions) ? item.annotation.actions : [];
|
||
}
|
||
|
||
function poseEvidenceRefs(summary: Record<string, any>, key: string, fallbackKey?: string) {
|
||
const direct = Array.isArray(summary[key]) ? summary[key] : [];
|
||
if (direct.length > 0 || !fallbackKey) return direct as Array<Record<string, any>>;
|
||
return (Array.isArray(summary[fallbackKey]) ? summary[fallbackKey] : []) as Array<Record<string, any>>;
|
||
}
|
||
|
||
function PoseEvidencePreview({
|
||
itemId,
|
||
artifact,
|
||
title,
|
||
frameCount,
|
||
}: {
|
||
itemId: string;
|
||
artifact?: Record<string, any>;
|
||
title: string;
|
||
frameCount: number;
|
||
}) {
|
||
const artifactId = String(artifact?.artifactId || "").trim();
|
||
if (!artifactId) {
|
||
return (
|
||
<div className="rounded-xl border border-dashed border-[#2a2b2f] bg-[#101114] p-4 text-xs text-gray-500">
|
||
{title}:没有可视化预标证据
|
||
</div>
|
||
);
|
||
}
|
||
const evidenceURL = humanLoopApi.evidenceContentURL(itemId, artifactId);
|
||
return (
|
||
<div className="space-y-3 rounded-xl border border-[#2a2b2f] bg-[#101114] p-4">
|
||
<div className="flex items-center justify-between gap-3">
|
||
<div>
|
||
<div className="text-sm font-medium text-white">{title}</div>
|
||
<div className="mt-1 text-xs text-gray-500">
|
||
{frameCount} 帧 · {String(artifact?.name || artifactId)}
|
||
</div>
|
||
</div>
|
||
<span className="rounded-full border border-blue-500/30 px-2 py-1 text-[10px] text-blue-200">人工质检证据</span>
|
||
</div>
|
||
<LazyVideoPreview
|
||
src={buildBrowserPlayableVideoURL(evidenceURL)}
|
||
originalSrc={evidenceURL}
|
||
title={title}
|
||
errorTitle={`${title}渲染失败`}
|
||
errorDescription="系统未能播放预标叠加视频,可打开原始证据检查;该预标不能在未质检时直接交付。"
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const panelClass = "rounded-2xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)]";
|
||
const inputClass =
|
||
"w-full rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-3 py-2 text-sm text-slate-800 outline-none focus:border-blue-500 dark:text-white";
|
||
|
||
function taskVisibleInMode(task: AnnotationTaskRecord, mode: WorkspaceMode, poolView?: TaskPoolView) {
|
||
if (task.humanStageId) {
|
||
if (mode === "clip") return task.humanStageId === "split_annotation" || task.humanStageId === "cut_adjustment";
|
||
if (mode === "clip-quality")
|
||
return task.humanStageId === "split_quality_review" || task.humanStageId === "cut_review";
|
||
if (mode === "annotate") {
|
||
if (poolView === "available") {
|
||
return task.humanStageId === "semantic_annotation" || task.humanStageId === "annotation_combined";
|
||
}
|
||
return (
|
||
task.humanStageId === "semantic_annotation" ||
|
||
task.humanStageId === "annotation_combined" ||
|
||
task.humanStageId === "quality_review" ||
|
||
task.humanStageId === "semantic_review" ||
|
||
task.humanStageId === "acceptance" ||
|
||
task.humanStageId === "completed"
|
||
);
|
||
}
|
||
if (mode === "quality") {
|
||
if (poolView === "available") {
|
||
return task.humanStageId === "quality_review" || task.humanStageId === "semantic_review";
|
||
}
|
||
return (
|
||
task.humanStageId === "quality_review" ||
|
||
task.humanStageId === "semantic_review" ||
|
||
task.humanStageId === "acceptance" ||
|
||
task.humanStageId === "completed"
|
||
);
|
||
}
|
||
if (mode === "acceptance") {
|
||
if (poolView === "available") {
|
||
return task.humanStageId === "acceptance" || task.humanStageId === "prepackage_acceptance";
|
||
}
|
||
return (
|
||
task.humanStageId === "acceptance" ||
|
||
task.humanStageId === "prepackage_acceptance" ||
|
||
task.humanStageId === "completed"
|
||
);
|
||
}
|
||
}
|
||
if (mode === "clip") {
|
||
return (
|
||
(task.status === "pending_annotation" && task.currentRevision === 0) ||
|
||
(task.status === "rework" && task.currentRevision === 0)
|
||
);
|
||
}
|
||
if (mode === "clip-quality") {
|
||
return task.status === "pending_quality" && task.currentRevision === 0;
|
||
}
|
||
if (mode === "annotate") {
|
||
if (poolView === "available") {
|
||
return (
|
||
(task.status === "pending_annotation" && task.currentRevision > 0) ||
|
||
(task.status === "rework" && task.currentRevision > 0) ||
|
||
(task.templateVersion >= 5 && (task.status === "pending_annotation" || task.status === "rework")) ||
|
||
(task.status === "pending_annotation" && task.currentRevision === 0 && !task.sourceVideo)
|
||
);
|
||
}
|
||
return task.status === "pending_annotation" || task.status === "rework" || task.status === "pending_quality";
|
||
}
|
||
if (mode === "quality") {
|
||
if (poolView === "available") {
|
||
return task.status === "pending_quality" && (task.templateVersion >= 5 || task.currentRevision > 0);
|
||
}
|
||
return task.status === "pending_quality" || task.status === "rework";
|
||
}
|
||
if (mode === "acceptance") {
|
||
return task.status === "pending_acceptance" || task.status === "accepted";
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function humanItemVisibleInMode(item: HumanItem, mode: WorkspaceMode, poolView?: TaskPoolView) {
|
||
if (mode === "clip") return item.currentStageId === "split_annotation" || item.currentStageId === "cut_adjustment";
|
||
if (mode === "clip-quality")
|
||
return item.currentStageId === "split_quality_review" || item.currentStageId === "cut_review";
|
||
if (mode === "annotate") {
|
||
if (poolView === "available") {
|
||
return item.currentStageId === "semantic_annotation" || item.currentStageId === "annotation_combined";
|
||
}
|
||
return (
|
||
item.currentStageId === "semantic_annotation" ||
|
||
item.currentStageId === "annotation_combined" ||
|
||
item.currentStageId === "quality_review" ||
|
||
(item.currentStageId === "split_annotation" && item.status === "rework")
|
||
);
|
||
}
|
||
if (mode === "quality") {
|
||
if (poolView === "available") {
|
||
return item.currentStageId === "quality_review" || item.currentStageId === "semantic_review";
|
||
}
|
||
return item.currentStageId === "quality_review" || item.currentStageId === "semantic_review";
|
||
}
|
||
return item.currentStageId === "acceptance" || item.currentStageId === "prepackage_acceptance";
|
||
}
|
||
|
||
type HumanAssignmentRole = ProjectMemberRole;
|
||
|
||
function assignmentRoleForStage(stageId: string): HumanAssignmentRole {
|
||
if (
|
||
stageId === "split_annotation" ||
|
||
stageId === "cut_adjustment" ||
|
||
stageId === "split_quality_review" ||
|
||
stageId === "cut_review" ||
|
||
stageId === "semantic_annotation" ||
|
||
stageId === "annotation_combined"
|
||
) {
|
||
return "annotator";
|
||
}
|
||
if (stageId === "acceptance" || stageId === "prepackage_acceptance") return "acceptance_reviewer";
|
||
return "quality_reviewer";
|
||
}
|
||
|
||
function assignmentRoleMatches(actual: HumanAssignmentRole, required: HumanAssignmentRole) {
|
||
return actual === required;
|
||
}
|
||
|
||
function assignmentRoleLabel(role: HumanAssignmentRole) {
|
||
if (role === "annotator") return "标注员";
|
||
if (role === "quality_reviewer") return "审核员";
|
||
if (role === "acceptance_reviewer") return "最终验收员";
|
||
return "成员";
|
||
}
|
||
|
||
export default function AnnotationOperations() {
|
||
const { users, role, currentUser } = useUser();
|
||
const { statuses: pluginStatuses } = usePlugins();
|
||
const { timeZone } = useTimeZone();
|
||
const [searchParams, setSearchParams] = useSearchParams();
|
||
const location = useLocation();
|
||
const navigate = useNavigate();
|
||
const { workflowId: pathWorkflowId, itemId: pathItemId } = useParams();
|
||
const workspaceMode: WorkspaceMode = location.pathname.endsWith("/clip")
|
||
? "clip"
|
||
: location.pathname.endsWith("/clip-quality")
|
||
? "clip-quality"
|
||
: location.pathname.endsWith("/quality")
|
||
? "quality"
|
||
: location.pathname.endsWith("/acceptance")
|
||
? "acceptance"
|
||
: "annotate";
|
||
const requestedProjectId = searchParams.get("projectId")?.trim() || "";
|
||
const requestedWorkflowId =
|
||
(pathWorkflowId && pathWorkflowId !== "all" ? pathWorkflowId.trim() : "") ||
|
||
searchParams.get("workflowId")?.trim() ||
|
||
"";
|
||
const requestedRunId = searchParams.get("runId")?.trim() || "";
|
||
const requestedNodeId = searchParams.get("nodeId")?.trim() || "";
|
||
const requestedArtifactId = searchParams.get("artifactId")?.trim() || "";
|
||
const requestedTaskId = searchParams.get("taskId")?.trim() || "";
|
||
const requestedCaptureDirectory = searchParams.get("capture")?.trim() || "";
|
||
const requestedSliceId = searchParams.get("sliceId")?.trim() || "";
|
||
const requestedEventId = searchParams.get("eventId")?.trim() || "";
|
||
const [tab, setTab] = useState<Tab>("queue");
|
||
const [projects, setProjects] = useState<Project[]>([]);
|
||
const [workflows, setWorkflows] = useState<Workflow[]>([]);
|
||
const [projectId, setProjectId] = useState("");
|
||
const [projectMembers, setProjectMembers] = useState<ProjectMember[]>([]);
|
||
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
|
||
const [tasks, setTasks] = useState<AnnotationTaskRecord[]>([]);
|
||
const [humanPools, setHumanPools] = useState<HumanPools>(emptyHumanPools);
|
||
const [taskPoolView, setTaskPoolView] = useState<TaskPoolView>("available");
|
||
const [workload, setWorkload] = useState<AnnotationWorkloadSummary>({ items: [], eventCount: 0 });
|
||
const [rejects, setRejects] = useState<HumanReject[]>([]);
|
||
const [deliveryPackages, setDeliveryPackages] = useState<DeliveryPackage[]>([]);
|
||
const [expandedDeliveryPackageId, setExpandedDeliveryPackageId] = useState("");
|
||
const [prepackageComments, setPrepackageComments] = useState<Record<string, string>>({});
|
||
const [deliveryPackageContents, setDeliveryPackageContents] = useState<Record<string, DeliveryPackageContents>>({});
|
||
const [deliveryPackageContentsLoading, setDeliveryPackageContentsLoading] = useState("");
|
||
const [deliveryPackageContentsErrors, setDeliveryPackageContentsErrors] = useState<Record<string, string>>({});
|
||
const [scopedRun, setScopedRun] = useState<ExecutionRun | null>(null);
|
||
const [selectedAcceptanceEvidence, setSelectedAcceptanceEvidence] = useState<{ itemId: string; index: number }>({
|
||
itemId: "",
|
||
index: 0,
|
||
});
|
||
const [selectedTaskId, setSelectedTaskId] = useState("");
|
||
const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);
|
||
const [workbenchDrafts, setWorkbenchDrafts] = useState<AnnotationDraft[]>([]);
|
||
const workbenchHostRef = useRef<HTMLDivElement>(null);
|
||
const [taskSearch, setTaskSearch] = useState("");
|
||
const [taskStatusFilter, setTaskStatusFilter] = useState("all");
|
||
const [detail, setDetailState] = useState<AnnotationTaskDetail | null>(null);
|
||
const sliceDictionary = useProjectSliceDictionary(detail?.task.projectId, detail?.task.id);
|
||
const detailRef = useRef<AnnotationTaskDetail | null>(null);
|
||
const annotationMutationScopeRef = useRef(createAuthoritativeMutationScope());
|
||
const annotationMutationContextRef = useRef(
|
||
createAuthoritativeMutationContext(annotationMutationScopeRef.current, {
|
||
taskId: selectedTaskId,
|
||
userId: currentUser?.id || "",
|
||
}),
|
||
);
|
||
const renderedMutationContext = annotationMutationContextRef.current.current();
|
||
if (renderedMutationContext.userId !== (currentUser?.id || "")) {
|
||
annotationMutationContextRef.current.switchTo({
|
||
taskId: renderedMutationContext.taskId,
|
||
userId: currentUser?.id || "",
|
||
});
|
||
}
|
||
const setDetail = useCallback((update: React.SetStateAction<AnnotationTaskDetail | null>) => {
|
||
const current = detailRef.current;
|
||
const next = typeof update === "function" ? update(current) : update;
|
||
if (next && selectedTaskDetailIDRef.current && next.task.id !== selectedTaskDetailIDRef.current) return;
|
||
// Late GET responses must not roll back the version returned by a write.
|
||
if (
|
||
current?.task.id === next?.task.id &&
|
||
current?.humanItem &&
|
||
next?.humanItem &&
|
||
next.humanItem.version < current.humanItem.version
|
||
)
|
||
return;
|
||
detailRef.current = next;
|
||
setDetailState(next);
|
||
}, []);
|
||
const [segments, setSegments] = useState<AnnotationSegment[]>([]);
|
||
const [sliceSegments, setSliceSegments] = useState<SliceSegment[]>([]);
|
||
const [sliceStatuses, setSliceStatuses] = useState<Record<string, NonNullable<SliceSegment["annotationStatus"]>>>({});
|
||
const annotationBaselineRef = useRef("");
|
||
const [showBatchSliceEditor, setShowBatchSliceEditor] = useState(false);
|
||
const [sliceOperations, setSliceOperations] = useState<SliceOperation[]>([]);
|
||
const [sliceHistory, setSliceHistory] = useState<SliceSegment[][]>([]);
|
||
const [sliceBoundaryDrafts, setSliceBoundaryDrafts] = useState<Record<string, string>>({});
|
||
// Playback ticks are only consumed by explicit split actions. Keep them out
|
||
// of page state so scrubbing does not re-render the entire task pool.
|
||
const annotationPlayheadRef = useRef(0);
|
||
const setAnnotationPlayhead = useCallback((time: number) => {
|
||
annotationPlayheadRef.current = time;
|
||
}, []);
|
||
const [frameTimeline, setFrameTimeline] = useState<AnnotationFrameTimeline | null>(null);
|
||
const [frameTimelineNotice, setFrameTimelineNotice] = useState("");
|
||
const [timelineState, setTimelineState] = useState<{ taskId: string; status: "loading" | "ready" | "error" }>({
|
||
taskId: "",
|
||
status: "loading",
|
||
});
|
||
const timelineRequestRef = useRef(0);
|
||
const timelineAbortRef = useRef<AbortController | null>(null);
|
||
const [combinedEditorPhase, setCombinedEditorPhase] = useState<CombinedEditorPhase>("slice");
|
||
const [taskDetailRefreshVersion, setTaskDetailRefreshVersion] = useState(0);
|
||
const [showResliceWarning, setShowResliceWarning] = useState(false);
|
||
const projectLoadRequestRef = useRef(0);
|
||
const projectLoadRecoveryAttemptRef = useRef(0);
|
||
const projectLoadRecoveryTimerRef = useRef<number | null>(null);
|
||
const taskDetailRequestRef = useRef(0);
|
||
const selectedTaskDetailIDRef = useRef("");
|
||
const [segmentDraft, setSegmentDraft] = useState({ labelId: "", label: "", start: "0", end: "1" });
|
||
const [reviewComment, setReviewComment] = useState("");
|
||
const [problemSliceIds, setProblemSliceIds] = useState<string[]>([]);
|
||
const [qualityDraft, setQualityDraft] = useState({
|
||
videoQuality: "qualified",
|
||
annotationAccuracy: "100",
|
||
annotationCompleteness: "100",
|
||
overallGrade: "A",
|
||
});
|
||
const [prepackageAcceptanceDrafts, setPrepackageAcceptanceDrafts] = useState<
|
||
Record<string, PrepackageAcceptanceStatistics>
|
||
>({});
|
||
const [templateDraft, setTemplateDraft] = useState(emptyTemplate);
|
||
const [loading, setLoading] = useState(true);
|
||
const [saving, setSaving] = useState(false);
|
||
const [error, setError] = useState("");
|
||
const [projectLoadError, setProjectLoadError] = useState("");
|
||
const [projectLoadRecoveryNotice, setProjectLoadRecoveryNotice] = useState("");
|
||
const [combinedSubmissionNotice, setCombinedSubmissionNotice] = useState("");
|
||
const [processingNotice, setProcessingNotice] = useState("");
|
||
const [projectLoadRetryVersion, setProjectLoadRetryVersion] = useState(0);
|
||
const submittedItemIdsRef = useRef<Set<string>>(new Set());
|
||
const setSelectedAnnotationTaskId = useCallback((nextTaskId: string) => {
|
||
const currentContext = annotationMutationContextRef.current.current();
|
||
if (
|
||
annotationMutationContextRef.current.switchTo({
|
||
taskId: nextTaskId,
|
||
userId: currentContext.userId,
|
||
})
|
||
) {
|
||
++taskDetailRequestRef.current;
|
||
setSaving(false);
|
||
}
|
||
setSelectedTaskId(nextTaskId);
|
||
}, []);
|
||
|
||
const [previewTab, setPreviewTab] = useState<"video" | "rerun">("video");
|
||
|
||
const isManager = isOrganizationAdminRole(role);
|
||
const blindAnnotator = role === "annotator" && (workspaceMode === "annotate" || workspaceMode === "clip");
|
||
const releaseLocked = role === "annotator" || role === "quality_reviewer" || role === "acceptance_reviewer";
|
||
const [claimableCount, setClaimableCount] = useState<{ projectId: string; count: number | null }>({
|
||
projectId: "",
|
||
count: null,
|
||
});
|
||
useEffect(() => {
|
||
// A bookmarked/reloaded owned task belongs to My Tasks. The blind pool
|
||
// deliberately contains no cards and must not clear this selection.
|
||
if (blindAnnotator && requestedTaskId) setTaskPoolView("mine");
|
||
}, [blindAnnotator, requestedTaskId]);
|
||
const [randomClaimBusy, setRandomClaimBusy] = useState(false);
|
||
const randomClaimFlight = useRef(false);
|
||
const randomClaimKeys = useRef<Record<string, string>>({});
|
||
const [randomClaimNotice, setRandomClaimNotice] = useState("");
|
||
const claimContextRef = useRef({ userId: currentUser?.id, projectId });
|
||
claimContextRef.current = { userId: currentUser?.id, projectId };
|
||
const currentProjectMembership = projectMembers.find((member) => member.userId === currentUser?.id);
|
||
const allowedStageModes = useMemo(
|
||
() => annotationStageModesForRoles(role, currentProjectMembership?.roles || []),
|
||
[currentProjectMembership?.roles, role],
|
||
);
|
||
const canAccessWorkspace = isManager || allowedStageModes.includes(workspaceMode);
|
||
const defaultStageMode = allowedStageModes[0] || "";
|
||
|
||
useEffect(() => {
|
||
setTaskPoolView((current) => (!isManager && current === "all" ? "available" : current));
|
||
}, [isManager]);
|
||
const annotationStageTabs = useMemo(
|
||
() =>
|
||
role
|
||
? getPluginNavigationContributions(pluginStatuses, role)
|
||
.filter((item) => {
|
||
if (isManager) return true;
|
||
const mode = annotationStageModeFromPath(item.path);
|
||
return Boolean(mode && allowedStageModes.includes(mode));
|
||
})
|
||
.map((item) => {
|
||
const path = item.path.replace("/workflows/all/", `/workflows/${requestedWorkflowId || "all"}/`);
|
||
return {
|
||
label: item.label,
|
||
to: annotationStageNavigationPath(path, {
|
||
projectId,
|
||
workflowId: requestedWorkflowId,
|
||
runId: requestedRunId,
|
||
captureDirectory: requestedCaptureDirectory,
|
||
}),
|
||
match: [path],
|
||
};
|
||
})
|
||
: [],
|
||
[
|
||
allowedStageModes,
|
||
isManager,
|
||
pluginStatuses,
|
||
projectId,
|
||
requestedCaptureDirectory,
|
||
requestedRunId,
|
||
requestedWorkflowId,
|
||
role,
|
||
],
|
||
);
|
||
|
||
const loadBase = useCallback(async () => {
|
||
setLoading(true);
|
||
setError("");
|
||
try {
|
||
const nextProjects = blindAnnotator ? await annotationOperationsApi.claimProjects() : await projectsApi.list();
|
||
setProjects(nextProjects);
|
||
setProjectId(
|
||
(current) =>
|
||
current || nextProjects.find((item) => item.id === requestedProjectId)?.id || requestedProjectId || "",
|
||
);
|
||
} catch (loadError) {
|
||
setError(getActionErrorMessage(loadError, "加载标注运营基础数据失败"));
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}, [requestedProjectId, blindAnnotator]);
|
||
|
||
const loadProject = useCallback(async () => {
|
||
const requestID = ++projectLoadRequestRef.current;
|
||
setLoading(true);
|
||
setProjectLoadError("");
|
||
try {
|
||
if (blindAnnotator) {
|
||
// Only load the actor's work, not every available Capture and unrelated
|
||
// reports/packages. Claiming itself never waits for this list.
|
||
const [members, mine, nextTemplates, nextWorkflows, count] = await Promise.all([
|
||
projectId ? projectsApi.listMembers(projectId) : Promise.resolve([]),
|
||
humanLoopApi.listItems({ pluginId: "annotation-qa", projectId: projectId || undefined, pool: "mine" }),
|
||
annotationOperationsApi.listTemplates(projectId || undefined),
|
||
projectId ? projectsApi.listWorkflows(projectId) : Promise.resolve([]),
|
||
projectId ? annotationOperationsApi.claimCount(projectId).catch(() => null) : Promise.resolve(null),
|
||
]);
|
||
const owned = mine.filter((i) => i.legacyTaskId);
|
||
const details = await Promise.all(owned.map((i) => annotationOperationsApi.getTaskSummary(i.legacyTaskId)));
|
||
if (requestID !== projectLoadRequestRef.current) return;
|
||
setProjectMembers(members);
|
||
setTemplates(nextTemplates);
|
||
setWorkflows(nextWorkflows);
|
||
setTasks(details.map((d) => d.task));
|
||
setHumanPools({ available: [], mine, all: [] });
|
||
setClaimableCount({ projectId, count: count?.count ?? null });
|
||
projectLoadRecoveryAttemptRef.current = 0;
|
||
if (projectLoadRecoveryTimerRef.current !== null) {
|
||
window.clearTimeout(projectLoadRecoveryTimerRef.current);
|
||
projectLoadRecoveryTimerRef.current = null;
|
||
}
|
||
setProjectLoadRecoveryNotice("");
|
||
return;
|
||
}
|
||
const knownProjects = projects.length > 0 ? projects : await projectsApi.list();
|
||
const [
|
||
nextProjectMembers,
|
||
nextWorkflows,
|
||
nextTemplates,
|
||
nextTasks,
|
||
availableHumanItems,
|
||
myHumanItems,
|
||
allHumanItems,
|
||
nextWorkload,
|
||
nextRejects,
|
||
nextPackages,
|
||
nextScopedRun,
|
||
] = await Promise.all([
|
||
projectId
|
||
? projectsApi.listMembers(projectId)
|
||
: Promise.allSettled(knownProjects.map((p) => projectsApi.listMembers(p.id))).then((results) =>
|
||
results.flatMap((r) => (r.status === "fulfilled" ? r.value : [])),
|
||
),
|
||
projectId
|
||
? projectsApi.listWorkflows(projectId)
|
||
: Promise.allSettled(knownProjects.map((p) => projectsApi.listWorkflows(p.id))).then((results) =>
|
||
results.flatMap((r) => (r.status === "fulfilled" ? r.value : [])),
|
||
),
|
||
annotationOperationsApi.listTemplates(projectId || undefined),
|
||
annotationOperationsApi.listTasks({
|
||
projectId: projectId || undefined,
|
||
workflowId: requestedWorkflowId || undefined,
|
||
runId: requestedRunId || undefined,
|
||
nodeId: requestedNodeId || undefined,
|
||
artifactId: requestedArtifactId || undefined,
|
||
}),
|
||
humanLoopApi.listItems({
|
||
pluginId: "annotation-qa",
|
||
projectId: projectId || undefined,
|
||
workflowId: requestedWorkflowId || undefined,
|
||
runId: requestedRunId || undefined,
|
||
pool: "available",
|
||
}),
|
||
humanLoopApi.listItems({
|
||
pluginId: "annotation-qa",
|
||
projectId: projectId || undefined,
|
||
workflowId: requestedWorkflowId || undefined,
|
||
runId: requestedRunId || undefined,
|
||
pool: "mine",
|
||
}),
|
||
isManager
|
||
? humanLoopApi.listItems({
|
||
pluginId: "annotation-qa",
|
||
projectId: projectId || undefined,
|
||
workflowId: requestedWorkflowId || undefined,
|
||
runId: requestedRunId || undefined,
|
||
pool: "all",
|
||
})
|
||
: Promise.resolve([] as HumanItem[]),
|
||
annotationOperationsApi.workloadSummary(projectId || undefined),
|
||
humanLoopApi.listRejects({
|
||
projectId: projectId || undefined,
|
||
workflowId: requestedWorkflowId || undefined,
|
||
runId: requestedRunId || undefined,
|
||
}),
|
||
deliveryPackagesApi.list({
|
||
projectId: projectId || undefined,
|
||
workflowId: requestedWorkflowId || undefined,
|
||
runId: requestedRunId || undefined,
|
||
status: taskPoolView === "all" ? undefined : "pending_acceptance",
|
||
}),
|
||
isManager && requestedRunId ? runsApi.get(requestedRunId) : Promise.resolve(null),
|
||
]);
|
||
if (requestID !== projectLoadRequestRef.current) return;
|
||
setProjectMembers(nextProjectMembers);
|
||
setWorkflows(nextWorkflows);
|
||
setTemplates(nextTemplates);
|
||
setTasks(
|
||
nextTasks.map((t) =>
|
||
submittedItemIdsRef.current.has(t.id)
|
||
? { ...t, status: "pending_quality", humanStageId: "quality_review" }
|
||
: t,
|
||
),
|
||
);
|
||
setHumanPools({
|
||
available: availableHumanItems.filter((i) => !submittedItemIdsRef.current.has(i.id)),
|
||
mine: myHumanItems.map((i) =>
|
||
submittedItemIdsRef.current.has(i.id) ? { ...i, status: "ready", currentStageId: "quality_review" } : i,
|
||
),
|
||
all: allHumanItems,
|
||
});
|
||
setWorkload(nextWorkload);
|
||
setRejects(nextRejects);
|
||
setDeliveryPackages(nextPackages);
|
||
setScopedRun(nextScopedRun);
|
||
projectLoadRecoveryAttemptRef.current = 0;
|
||
if (projectLoadRecoveryTimerRef.current !== null) {
|
||
window.clearTimeout(projectLoadRecoveryTimerRef.current);
|
||
projectLoadRecoveryTimerRef.current = null;
|
||
}
|
||
setProjectLoadRecoveryNotice("");
|
||
setProjectLoadError("");
|
||
} catch (loadError) {
|
||
if (requestID !== projectLoadRequestRef.current) return;
|
||
const gatewayStatus = recoverableGatewayStatus(loadError);
|
||
if (gatewayStatus && projectLoadRecoveryAttemptRef.current < projectLoadRecoveryAttempts) {
|
||
const attempt = projectLoadRecoveryAttemptRef.current + 1;
|
||
projectLoadRecoveryAttemptRef.current = attempt;
|
||
setProjectLoadError("");
|
||
setProjectLoadRecoveryNotice(`连接短暂中断,正在自动恢复(${attempt}/${projectLoadRecoveryAttempts})`);
|
||
if (projectLoadRecoveryTimerRef.current !== null) {
|
||
window.clearTimeout(projectLoadRecoveryTimerRef.current);
|
||
}
|
||
projectLoadRecoveryTimerRef.current = window.setTimeout(() => {
|
||
projectLoadRecoveryTimerRef.current = null;
|
||
setProjectLoadRetryVersion((current) => current + 1);
|
||
}, projectLoadRecoveryDelayMs * attempt);
|
||
return;
|
||
}
|
||
projectLoadRecoveryAttemptRef.current = 0;
|
||
setProjectLoadRecoveryNotice("");
|
||
setProjectLoadError(
|
||
gatewayStatus
|
||
? `服务连接持续失败(HTTP ${gatewayStatus}),请点击刷新重试。`
|
||
: getActionErrorMessage(loadError, "加载项目标注运营数据失败"),
|
||
);
|
||
} finally {
|
||
if (requestID === projectLoadRequestRef.current) setLoading(false);
|
||
}
|
||
}, [
|
||
currentUser?.id,
|
||
blindAnnotator,
|
||
projectId,
|
||
isManager,
|
||
requestedArtifactId,
|
||
requestedNodeId,
|
||
requestedRunId,
|
||
requestedWorkflowId,
|
||
taskPoolView,
|
||
]);
|
||
|
||
useEffect(() => {
|
||
++projectLoadRequestRef.current;
|
||
++taskDetailRequestRef.current;
|
||
annotationMutationScopeRef.current.invalidate();
|
||
setSaving(false);
|
||
submittedItemIdsRef.current.clear();
|
||
setTasks([]);
|
||
setHumanPools(emptyHumanPools);
|
||
setDetail(null);
|
||
setSelectedAnnotationTaskId("");
|
||
setReviewComment("");
|
||
setProblemSliceIds([]);
|
||
setTaskPoolView(blindAnnotator && requestedTaskId ? "mine" : "available");
|
||
setDeliveryPackages([]);
|
||
setDeliveryPackageContents({});
|
||
}, [currentUser?.id]);
|
||
|
||
useEffect(() => {
|
||
projectLoadRecoveryAttemptRef.current = 0;
|
||
setProjectLoadRecoveryNotice("");
|
||
if (projectLoadRecoveryTimerRef.current !== null) {
|
||
window.clearTimeout(projectLoadRecoveryTimerRef.current);
|
||
projectLoadRecoveryTimerRef.current = null;
|
||
}
|
||
}, [projectId, requestedArtifactId, requestedNodeId, requestedRunId, requestedWorkflowId, taskPoolView]);
|
||
|
||
useEffect(
|
||
() => () => {
|
||
if (projectLoadRecoveryTimerRef.current !== null) {
|
||
window.clearTimeout(projectLoadRecoveryTimerRef.current);
|
||
}
|
||
},
|
||
[],
|
||
);
|
||
|
||
useEffect(() => {
|
||
void loadBase();
|
||
}, [loadBase]);
|
||
|
||
useEffect(() => {
|
||
void loadProject();
|
||
}, [loadProject, projectLoadRetryVersion]);
|
||
|
||
useEffect(() => {
|
||
if (isManager || loading || !projectId || !defaultStageMode || canAccessWorkspace) return;
|
||
const path = `/plugins/annotation-qa/workflows/${requestedWorkflowId || "all"}/${defaultStageMode}`;
|
||
navigate(
|
||
annotationStageNavigationPath(path, {
|
||
projectId,
|
||
workflowId: requestedWorkflowId,
|
||
runId: requestedRunId,
|
||
captureDirectory: requestedCaptureDirectory,
|
||
}),
|
||
{ replace: true },
|
||
);
|
||
}, [
|
||
canAccessWorkspace,
|
||
defaultStageMode,
|
||
isManager,
|
||
loading,
|
||
navigate,
|
||
projectId,
|
||
requestedCaptureDirectory,
|
||
requestedRunId,
|
||
requestedWorkflowId,
|
||
]);
|
||
|
||
useEffect(() => {
|
||
if (!pathItemId) return;
|
||
humanLoopApi
|
||
.getItem(pathItemId)
|
||
.then(({ item }) => {
|
||
if (item.legacyTaskId) {
|
||
setProjectId(item.projectId);
|
||
setSelectedAnnotationTaskId(item.legacyTaskId);
|
||
const next = new URLSearchParams(searchParams);
|
||
next.set("projectId", item.projectId);
|
||
next.set("taskId", item.legacyTaskId);
|
||
if (item.workflowId) next.set("workflowId", item.workflowId);
|
||
if (item.runId) next.set("runId", item.runId);
|
||
setSearchParams(next, { replace: true });
|
||
}
|
||
})
|
||
.catch((loadError) => setError(getActionErrorMessage(loadError, "加载人类在环任务失败")));
|
||
}, [pathItemId]);
|
||
|
||
const loadFrameTimeline = useCallback(
|
||
async (
|
||
task: AnnotationTaskRecord,
|
||
initial: SliceSegment[] = [],
|
||
allowDefault = false,
|
||
parentSignal?: AbortSignal,
|
||
) => {
|
||
const requestId = ++timelineRequestRef.current;
|
||
timelineAbortRef.current?.abort();
|
||
const controller = new AbortController();
|
||
timelineAbortRef.current = controller;
|
||
const abort = () => controller.abort();
|
||
parentSignal?.addEventListener("abort", abort, { once: true });
|
||
if (parentSignal?.aborted) abort();
|
||
setTimelineState({ taskId: task.id, status: "loading" });
|
||
setFrameTimelineNotice("");
|
||
try {
|
||
const timeline = await annotationOperationsApi.getFrameTimeline(task.id, "left", controller.signal);
|
||
if (
|
||
controller.signal.aborted ||
|
||
requestId !== timelineRequestRef.current ||
|
||
selectedTaskDetailIDRef.current !== task.id
|
||
)
|
||
return;
|
||
const fallback = annotationTaskEditableRange(task);
|
||
const start = timeline.rangeStartSecond ?? fallback.start;
|
||
const end = timeline.rangeEndSecond ?? fallback.end;
|
||
if (
|
||
!Number.isFinite(start) ||
|
||
!Number.isFinite(end) ||
|
||
end <= start ||
|
||
normalizeFrameBoundaries(timeline.boundariesSeconds, start, end).length < 2
|
||
)
|
||
throw new Error("统一帧范围无效");
|
||
setFrameTimeline(timeline);
|
||
setSliceSegments((current) => initializeFrameAlignedSlices(current, initial, timeline, allowDefault));
|
||
setTimelineState({ taskId: task.id, status: "ready" });
|
||
} catch (cause) {
|
||
if (
|
||
controller.signal.aborted ||
|
||
requestId !== timelineRequestRef.current ||
|
||
selectedTaskDetailIDRef.current !== task.id
|
||
)
|
||
return;
|
||
setFrameTimeline(null);
|
||
setTimelineState({ taskId: task.id, status: "error" });
|
||
setFrameTimelineNotice("统一帧范围加载失败,切片内容已保留;请重试,未就绪前不能修改或确认切片。");
|
||
} finally {
|
||
parentSignal?.removeEventListener("abort", abort);
|
||
}
|
||
},
|
||
[],
|
||
);
|
||
useEffect(() => () => timelineAbortRef.current?.abort(), []);
|
||
|
||
useEffect(() => {
|
||
const requestID = ++taskDetailRequestRef.current;
|
||
if (selectedTaskDetailIDRef.current !== selectedTaskId) {
|
||
timelineAbortRef.current?.abort();
|
||
setTimelineState({ taskId: selectedTaskId, status: "loading" });
|
||
}
|
||
if (!selectedTaskId) {
|
||
selectedTaskDetailIDRef.current = "";
|
||
setDetail(null);
|
||
setSegments([]);
|
||
setSliceSegments([]);
|
||
setSliceStatuses({});
|
||
setAnnotationPlayhead(0);
|
||
setFrameTimeline(null);
|
||
setFrameTimelineNotice("");
|
||
setCombinedEditorPhase("slice");
|
||
annotationBaselineRef.current = "";
|
||
return;
|
||
}
|
||
const controller = new AbortController();
|
||
const switchingTask = selectedTaskDetailIDRef.current !== selectedTaskId;
|
||
selectedTaskDetailIDRef.current = selectedTaskId;
|
||
if (switchingTask) {
|
||
setDetail(null);
|
||
setSegments([]);
|
||
setSliceSegments([]);
|
||
setSliceStatuses({});
|
||
setAnnotationPlayhead(0);
|
||
setFrameTimeline(null);
|
||
setFrameTimelineNotice("");
|
||
setCombinedEditorPhase("slice");
|
||
}
|
||
annotationOperationsApi
|
||
.getTask(selectedTaskId, controller.signal)
|
||
.then((next) => {
|
||
if (requestID !== taskDetailRequestRef.current || annotationMutationScopeRef.current.busy()) return;
|
||
if (
|
||
detailRef.current?.task.id === next.task.id &&
|
||
detailRef.current.humanItem &&
|
||
next.humanItem &&
|
||
next.humanItem.version < detailRef.current.humanItem.version
|
||
)
|
||
return;
|
||
const storedDraft = annotationDraftFromHumanItem(next.humanItem);
|
||
const discardedWorkspace = Boolean(
|
||
(next.humanItem?.subject?.payload?.sliceWorkflow as { discardedWorkspace?: boolean } | undefined)
|
||
?.discardedWorkspace,
|
||
);
|
||
const restoreDraft = Boolean(
|
||
storedDraft &&
|
||
storedDraft.userId === currentUser?.id &&
|
||
next.humanItem?.assignedUserId === currentUser?.id &&
|
||
["claimed", "in_progress"].includes(next.humanItem.status),
|
||
);
|
||
const nextAnnotations = restoreDraft
|
||
? storedDraft.segments
|
||
: discardedWorkspace
|
||
? []
|
||
: humanEditableAnnotationSegments(next.revisions);
|
||
const nextSlices = initialCaptureSlices(
|
||
next.task,
|
||
discardedWorkspace ? [] : next.sliceRevisions,
|
||
restoreDraft ? storedDraft.sliceSegments : undefined,
|
||
).map((slice, index) => ({
|
||
...slice,
|
||
name: slice.name?.trim() || `切片 ${String(index + 1).padStart(3, "0")}`,
|
||
...(next.task.templateVersion >= 6 ? { taskLabelId: undefined, taskLabel: undefined } : {}),
|
||
}));
|
||
const nextOperations = restoreDraft ? storedDraft.operations : [];
|
||
const nextStatuses = deriveSliceStatuses(
|
||
nextSlices,
|
||
nextAnnotations,
|
||
restoreDraft ? storedDraft.statuses : {},
|
||
) as Record<string, NonNullable<SliceSegment["annotationStatus"]>>;
|
||
const sliceWorkflow = next.humanItem?.subject?.payload?.sliceWorkflow as
|
||
| { status?: string; phase?: string; error?: string }
|
||
| undefined;
|
||
const nextPhase: CombinedEditorPhase =
|
||
sliceWorkflow?.status === "processing"
|
||
? "materializing"
|
||
: sliceWorkflow?.status === "completed" || sliceWorkflow?.phase === "annotate"
|
||
? "annotate"
|
||
: sliceWorkflow?.status === "editing" || sliceWorkflow?.phase === "slice"
|
||
? "slice"
|
||
: requestedSliceId ||
|
||
nextAnnotations.some(
|
||
(segment) => segment.source !== "qwen" && segment.source !== "workflow-prelabel",
|
||
) ||
|
||
Object.values(nextStatuses).some((status) => status !== "pending")
|
||
? "annotate"
|
||
: "slice";
|
||
setDetail(next);
|
||
setSegments(nextAnnotations);
|
||
setSliceSegments(nextSlices);
|
||
setSliceOperations(nextOperations);
|
||
setSliceStatuses(nextStatuses);
|
||
setAnnotationPlayhead(nextSlices[0]?.start ?? next.task.clipStart ?? 0);
|
||
setCombinedEditorPhase(nextPhase);
|
||
if (next.humanItem) {
|
||
setHumanPools((current) => ({
|
||
available: current.available.map((item) => (item.id === next.humanItem?.id ? next.humanItem! : item)),
|
||
mine: current.mine.map((item) => (item.id === next.humanItem?.id ? next.humanItem! : item)),
|
||
all: current.all.map((item) => (item.id === next.humanItem?.id ? next.humanItem! : item)),
|
||
}));
|
||
}
|
||
annotationBaselineRef.current = annotationWorkspaceFingerprint(
|
||
nextSlices,
|
||
nextOperations,
|
||
nextAnnotations,
|
||
nextStatuses,
|
||
);
|
||
setSliceHistory([]);
|
||
setProblemSliceIds([]);
|
||
setSliceBoundaryDrafts({});
|
||
setShowBatchSliceEditor(nextPhase === "slice");
|
||
if (sliceWorkflow?.status === "failed" && sliceWorkflow.error) {
|
||
setError(`切片生成失败:${sliceWorkflow.error}`);
|
||
}
|
||
if (switchingTask || timelineState.status !== "ready" || timelineState.taskId !== next.task.id)
|
||
void loadFrameTimeline(
|
||
next.task,
|
||
nextSlices,
|
||
!restoreDraft &&
|
||
!next.sliceRevisions.some(
|
||
(revision) =>
|
||
revision.segments?.length && !(revision.revision === 0 && revision.authorUserId === "system"),
|
||
),
|
||
);
|
||
})
|
||
.catch((loadError) => {
|
||
if (requestID === taskDetailRequestRef.current && (loadError as Error)?.name !== "AbortError") {
|
||
const msg = getActionErrorMessage(loadError, "加载标注任务详情失败");
|
||
if (msg.includes("current human stage role is required")) {
|
||
closeTaskAndReturnToPool();
|
||
} else {
|
||
setError(msg);
|
||
}
|
||
}
|
||
});
|
||
return () => controller.abort();
|
||
}, [currentUser?.id, selectedTaskId, taskDetailRefreshVersion, loadFrameTimeline]);
|
||
|
||
useEffect(() => {
|
||
if (combinedEditorPhase !== "materializing" || !selectedTaskId) return;
|
||
const controller = new AbortController();
|
||
let timer: ReturnType<typeof setTimeout>;
|
||
const poll = async () => {
|
||
try {
|
||
const status = await annotationOperationsApi.getTaskStatus(selectedTaskId, controller.signal);
|
||
if (controller.signal.aborted) return;
|
||
const labels: Record<string, string> = {
|
||
queued: "等待处理资源",
|
||
validating: "校验源数据",
|
||
slicing: "生成或复用切片",
|
||
publishing: "写入审核数据",
|
||
};
|
||
setProcessingNotice(
|
||
status.progress
|
||
? `${labels[status.progress.stage] || "正在处理"} · ${status.progress.completedSlices}/${status.progress.totalSlices} 个切片`
|
||
: "正在处理,等待后台结果",
|
||
);
|
||
if (status.sliceStatus !== "processing" || status.needsRefresh) {
|
||
setTaskDetailRefreshVersion((current) => current + 1);
|
||
return;
|
||
}
|
||
} catch {
|
||
if (controller.signal.aborted) return;
|
||
setError("切片进度暂时无法读取,正在重试;不会重复提交切片。");
|
||
}
|
||
timer = setTimeout(poll, 2_000);
|
||
};
|
||
timer = setTimeout(poll, 2_000);
|
||
return () => {
|
||
controller.abort();
|
||
clearTimeout(timer);
|
||
};
|
||
}, [combinedEditorPhase, selectedTaskId, taskDetailRefreshVersion]);
|
||
|
||
const selectedTemplate = useMemo(
|
||
() =>
|
||
templates.find((item) => item.id === detail?.task.templateId) ||
|
||
templates.find((item) => item.status === "published") ||
|
||
null,
|
||
[detail?.task.templateId, templates],
|
||
);
|
||
const selectedLabels = detail?.task.labelSnapshot || [];
|
||
const modelPrelabels = useMemo(
|
||
() =>
|
||
detail?.revisions
|
||
.find((revision) => revision.revision === 0 || revision.segments.some((segment) => segment.source === "qwen"))
|
||
?.segments.filter((segment) => segment.source === "qwen" || segment.source === "workflow-prelabel") || [],
|
||
[detail?.revisions],
|
||
);
|
||
const fallbackRange = annotationTaskEditableRange(detail?.task);
|
||
const editableTimelineStart = frameTimeline?.rangeStartSecond ?? fallbackRange.start;
|
||
const editableTimelineEnd = frameTimeline?.rangeEndSecond ?? fallbackRange.end;
|
||
const frameBoundaries = useMemo(
|
||
() => normalizeFrameBoundaries(frameTimeline?.boundariesSeconds || [], editableTimelineStart, editableTimelineEnd),
|
||
[editableTimelineEnd, editableTimelineStart, frameTimeline?.boundariesSeconds],
|
||
);
|
||
const frameTimelineStatus =
|
||
timelineState.taskId === detail?.task.id && detail?.task.id === selectedTaskId ? timelineState.status : "loading";
|
||
const exactFrameEditing = frameTimelineStatus === "ready" && frameBoundaries.length >= 2;
|
||
const frameBoundaryIndex = useCallback(
|
||
(time: number) => (exactFrameEditing ? nearestFrameBoundaryIndex(frameBoundaries, time) : -1),
|
||
[exactFrameEditing, frameBoundaries],
|
||
);
|
||
const sliceCoverage = useMemo(
|
||
() => analyzeSliceCoverage(sliceSegments, editableTimelineStart, editableTimelineEnd),
|
||
[editableTimelineEnd, editableTimelineStart, sliceSegments],
|
||
);
|
||
const sliceAlignmentIssue = exactFrameEditing
|
||
? sliceTimelineIssue(sliceSegments, editableTimelineStart, editableTimelineEnd, frameBoundaries)
|
||
: "";
|
||
const sliceProgress = useMemo(
|
||
() => summarizeSliceProgress(sliceSegments, segments, sliceStatuses),
|
||
[segments, sliceSegments, sliceStatuses],
|
||
);
|
||
const annotationWorkspaceIssues = useMemo(
|
||
() => validateAnnotationWorkspace(sliceSegments, segments),
|
||
[segments, sliceSegments],
|
||
);
|
||
const annotationFingerprint = useMemo(
|
||
() => annotationWorkspaceFingerprint(sliceSegments, sliceOperations, segments, sliceProgress.statuses),
|
||
[segments, sliceOperations, sliceProgress.statuses, sliceSegments],
|
||
);
|
||
const annotationDirty = Boolean(
|
||
workbenchDrafts.length ||
|
||
(detail && annotationBaselineRef.current && annotationFingerprint !== annotationBaselineRef.current),
|
||
);
|
||
const leaveDirtyRef = useRef(annotationDirty);
|
||
leaveDirtyRef.current = annotationDirty;
|
||
const leaveBlocker = useBlocker(
|
||
({ currentLocation, nextLocation }) =>
|
||
leaveDirtyRef.current &&
|
||
(currentLocation.pathname !== nextLocation.pathname || currentLocation.search !== nextLocation.search),
|
||
);
|
||
useEffect(() => {
|
||
setWorkbenchDrafts([]);
|
||
}, [selectedTaskId, combinedEditorPhase, currentUser?.id, detail?.humanItem?.currentStageId]);
|
||
const workloadTotals = useMemo(() => summarizeAnnotationWorkload(workload.items), [workload.items]);
|
||
const annotationStage =
|
||
detail?.humanItem?.currentStageId ||
|
||
(workspaceMode === "clip"
|
||
? "split_annotation"
|
||
: workspaceMode === "clip-quality"
|
||
? "split_quality_review"
|
||
: workspaceMode === "quality"
|
||
? "quality_review"
|
||
: workspaceMode === "acceptance"
|
||
? "acceptance"
|
||
: detail?.task?.currentRevision && detail.task.currentRevision > 0
|
||
? "semantic_annotation"
|
||
: "split_annotation");
|
||
const poolItems = humanPools[isManager ? taskPoolView : taskPoolView === "all" ? "available" : taskPoolView];
|
||
const captureDirectories = useMemo(
|
||
() =>
|
||
uniqueCaptureDirectories(
|
||
poolItems.flatMap((item) =>
|
||
captureDirectoriesFromHumanTask(
|
||
item,
|
||
tasks.find((task) => task.id === item.legacyTaskId),
|
||
),
|
||
),
|
||
),
|
||
[poolItems, tasks],
|
||
);
|
||
const matchesPoolFilters = useCallback(
|
||
(item: HumanItem, pool: TaskPoolView) => {
|
||
if (!humanItemVisibleInMode(item, workspaceMode, pool)) return false;
|
||
const task = tasks.find((t) => t.id === item.legacyTaskId);
|
||
const directories = captureDirectoriesFromHumanTask(item, task);
|
||
if (requestedCaptureDirectory && !directories.includes(requestedCaptureDirectory)) return false;
|
||
if (
|
||
taskSearch &&
|
||
!`${directories.join(" ")} ${item.display?.projectName || ""}`.toLowerCase().includes(taskSearch.toLowerCase())
|
||
)
|
||
return false;
|
||
const status = task
|
||
? deriveDetailedTaskStatus(task, item)
|
||
: item.status === "accepted"
|
||
? "accepted"
|
||
: "pending_acceptance";
|
||
return taskStatusFilter === "all" || status === taskStatusFilter;
|
||
},
|
||
[workspaceMode, tasks, requestedCaptureDirectory, taskSearch, taskStatusFilter],
|
||
);
|
||
const visiblePoolItems = useMemo(
|
||
() => poolItems.filter((item) => matchesPoolFilters(item, taskPoolView)),
|
||
[poolItems, taskPoolView, matchesPoolFilters],
|
||
);
|
||
const prepackageAcceptanceItems = useMemo(
|
||
() => visiblePoolItems.filter((item) => item.currentStageId === "prepackage_acceptance"),
|
||
[visiblePoolItems],
|
||
);
|
||
const visibleDeliveryPackages = useMemo(
|
||
() =>
|
||
deliveryPackages.filter((item) => {
|
||
if (taskPoolView === "all") return true;
|
||
if (taskPoolView === "mine") return item.assignedUserId === currentUser?.id;
|
||
return !item.assignedUserId;
|
||
}),
|
||
[currentUser?.id, deliveryPackages, taskPoolView],
|
||
);
|
||
const visibleTasks = useMemo(() => {
|
||
const taskIds = new Set(visiblePoolItems.map((item) => item.legacyTaskId).filter(Boolean));
|
||
return tasks.filter(
|
||
(task) =>
|
||
taskIds.has(task.id) ||
|
||
(isManager &&
|
||
taskPoolView === "all" &&
|
||
!task.humanStageId &&
|
||
taskVisibleInMode(task, workspaceMode, taskPoolView)),
|
||
);
|
||
}, [isManager, taskPoolView, tasks, visiblePoolItems, workspaceMode]);
|
||
const taskContextById = useMemo(
|
||
() =>
|
||
new Map(
|
||
visibleTasks.map((task) => {
|
||
const poolItem = visiblePoolItems.find((item) => item.legacyTaskId === task.id);
|
||
const humanItem = task.id === selectedTaskId && detail?.humanItem ? detail.humanItem : poolItem;
|
||
const livePhase = task.id === selectedTaskId ? combinedEditorPhase : undefined;
|
||
return [
|
||
task.id,
|
||
{
|
||
projectName: humanItem?.display?.projectName || projects.find((item) => item.id === task.projectId)?.name,
|
||
workflowName:
|
||
humanItem?.display?.workflowName || workflows.find((item) => item.id === task.workflowId)?.name,
|
||
captureDirectories: captureDirectoriesFromHumanTask(humanItem, task),
|
||
detailedStatus: deriveDetailedTaskStatus(task, humanItem, livePhase),
|
||
},
|
||
];
|
||
}),
|
||
),
|
||
[combinedEditorPhase, detail?.humanItem, projects, selectedTaskId, visiblePoolItems, visibleTasks, workflows],
|
||
);
|
||
const filteredVisibleTasks = useMemo(
|
||
() => filterAnnotationTasks(visibleTasks, taskContextById, taskSearch, taskStatusFilter),
|
||
[taskContextById, taskSearch, taskStatusFilter, visibleTasks],
|
||
);
|
||
const visibleHumanItemByTaskId = useMemo(
|
||
() =>
|
||
new Map(visiblePoolItems.filter((item) => item.legacyTaskId).map((item) => [item.legacyTaskId as string, item])),
|
||
[visiblePoolItems],
|
||
);
|
||
const poolCounts = useMemo(
|
||
() =>
|
||
Object.fromEntries(
|
||
(["available", "mine", "all"] as const).map((pool) => [
|
||
pool,
|
||
humanPools[pool].filter((item) => matchesPoolFilters(item, pool)).length,
|
||
]),
|
||
) as Record<TaskPoolView, number>,
|
||
[humanPools, matchesPoolFilters],
|
||
);
|
||
const stageEmptyLabel =
|
||
workspaceMode === "quality"
|
||
? "切分与标注审核"
|
||
: workspaceMode === "acceptance"
|
||
? "最终验收"
|
||
: workspaceMode === "annotate"
|
||
? "切分与语义标注"
|
||
: "人工";
|
||
const scopedEmptyMessage = scopedHumanQueueEmptyMessage({
|
||
runId: requestedRunId,
|
||
runStatus: scopedRun?.status,
|
||
currentNodeId: scopedRun?.currentNodeId,
|
||
stageLabel: stageEmptyLabel,
|
||
});
|
||
|
||
useEffect(() => {
|
||
if (loading || saving) return;
|
||
let nextTaskId = "";
|
||
if (requestedTaskId && visibleTasks.some((item) => item.id === requestedTaskId)) nextTaskId = requestedTaskId;
|
||
else if (selectedTaskId && visibleTasks.some((item) => item.id === selectedTaskId)) nextTaskId = selectedTaskId;
|
||
if (nextTaskId !== selectedTaskId) setSelectedAnnotationTaskId(nextTaskId);
|
||
}, [requestedTaskId, visibleTasks, loading, saving, selectedTaskId]);
|
||
useEffect(() => {
|
||
if (!annotationDirty) return;
|
||
const warn = (event: BeforeUnloadEvent) => {
|
||
event.preventDefault();
|
||
event.returnValue = "";
|
||
};
|
||
window.addEventListener("beforeunload", warn);
|
||
return () => window.removeEventListener("beforeunload", warn);
|
||
}, [annotationDirty]);
|
||
const selectedHumanItem = detail?.humanItem;
|
||
const selectedVideoSource = useMemo(() => {
|
||
if (!detail) return "";
|
||
if (selectedHumanItem?.id) {
|
||
return humanLoopApi.subjectContentURL(selectedHumanItem.id);
|
||
}
|
||
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;
|
||
const materializedDirectoryArtifact = useMemo<ExecutionData | null>(() => {
|
||
if (!selectedMaterialization?.runId || !selectedMaterialization.artifactId) return null;
|
||
return {
|
||
id: selectedMaterialization.artifactId,
|
||
runId: selectedMaterialization.runId,
|
||
nodeId: detail?.task.nodeId || "",
|
||
portId: "materializedSliceDirectory",
|
||
portName: "materializedSliceDirectory",
|
||
name: "当前切片数据",
|
||
type: "file",
|
||
size: "",
|
||
data: { schemaVersion: "droboticflow.directory-index/v1", presentation: "collection" },
|
||
};
|
||
}, [detail?.task.nodeId, selectedMaterialization]);
|
||
const selectedRequiredRole = assignmentRoleForStage(selectedHumanItem?.currentStageId || annotationStage);
|
||
const eligibleAssigneesForScope = useCallback(
|
||
(supplierId: string | undefined, requiredRole: HumanAssignmentRole, currentAssigneeId = "") => {
|
||
if (!isManager) return [];
|
||
const eligibleIds = new Set(
|
||
projectMembers
|
||
.filter(
|
||
(member) =>
|
||
member.roles.includes(requiredRole as ProjectMember["roles"][number]) &&
|
||
(supplierId ? member.supplierId === supplierId : true),
|
||
)
|
||
.map((member) => member.userId),
|
||
);
|
||
if (currentAssigneeId) eligibleIds.add(currentAssigneeId);
|
||
return users.filter((user) => eligibleIds.has(user.id) && user.status !== "disabled");
|
||
},
|
||
[isManager, projectMembers, users],
|
||
);
|
||
const eligibleAssignees = useMemo(
|
||
() =>
|
||
selectedHumanItem
|
||
? eligibleAssigneesForScope(
|
||
selectedHumanItem.supplierId,
|
||
selectedRequiredRole,
|
||
selectedHumanItem.assignedUserId,
|
||
)
|
||
: [],
|
||
[eligibleAssigneesForScope, selectedHumanItem, selectedRequiredRole],
|
||
);
|
||
// Old combined v5 batches remain readable while all newly created v5 work
|
||
// uses the four independent stage IDs above.
|
||
const isV5Combined = Boolean(
|
||
detail &&
|
||
detail.task.templateVersion >= 5 &&
|
||
(workspaceMode === "annotate" || selectedHumanItem?.currentStageId === "annotation_combined"),
|
||
);
|
||
const isV5CombinedQuality = Boolean(
|
||
detail &&
|
||
detail.task.templateVersion >= 5 &&
|
||
(workspaceMode === "quality" || workspaceMode === "acceptance") &&
|
||
(selectedHumanItem?.currentStageId === "quality_review" ||
|
||
selectedHumanItem?.currentStageId === "acceptance" ||
|
||
selectedHumanItem?.currentStageId === "prepackage_acceptance"),
|
||
);
|
||
const submissionState = combinedSubmissionState(detail?.humanItem);
|
||
const combinedSubmissionProcessing = submissionState === "processing";
|
||
const combinedSubmissionConflicted =
|
||
submissionState === "conflicted" &&
|
||
combinedEditorPhase === "annotate" &&
|
||
selectedMaterialization?.status !== "running";
|
||
const combinedSubmissionLocked = combinedSubmissionProcessing;
|
||
|
||
const latestRejectReview = useMemo(() => {
|
||
if (!detail) return null;
|
||
const matchedRejects = (detail.reviews || [])
|
||
.filter((r) => r.decision === "rejected")
|
||
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||
if (matchedRejects.length > 0) return matchedRejects[0];
|
||
const matchedRejectRecord = (rejects || []).find(
|
||
(r) => r.itemId === detail.humanItem?.id || r.runId === detail.task.runId,
|
||
);
|
||
if (matchedRejectRecord) {
|
||
return {
|
||
id: matchedRejectRecord.id,
|
||
taskId: detail.task.id,
|
||
revision: matchedRejectRecord.reviewedRevision || 0,
|
||
stage: matchedRejectRecord.stageId === "acceptance" ? "acceptance" : "quality",
|
||
decision: "rejected" as const,
|
||
reviewerUserId: matchedRejectRecord.rejectedByUserId,
|
||
comment: matchedRejectRecord.comment,
|
||
reasonCodes: matchedRejectRecord.reasonCodes,
|
||
problemSliceIds: matchedRejectRecord.problemSliceIds,
|
||
createdAt: "",
|
||
};
|
||
}
|
||
return null;
|
||
}, [detail, rejects]);
|
||
|
||
const isReworkTask = Boolean(
|
||
detail &&
|
||
(detail.task.status === "rework" ||
|
||
detail.humanItem?.status === "rework" ||
|
||
(Number(detail.humanItem?.reviewRound) > 0 && detail.humanItem?.currentStageId === "annotation_combined")),
|
||
);
|
||
|
||
const reworkNotice = useMemo(() => {
|
||
if (!isReworkTask) return undefined;
|
||
return {
|
||
stageName: latestRejectReview?.stage === "acceptance" ? "最终验收打回" : "切片与标注审核打回",
|
||
reasonCodes: latestRejectReview?.reasonCodes || [],
|
||
comment:
|
||
latestRejectReview?.comment ||
|
||
(detail?.humanItem?.cancellationReason
|
||
? `打回原因:${detail.humanItem.cancellationReason}`
|
||
: "该任务已被打回返工,请根据审核意见修改切片与描述。"),
|
||
problemSliceIds: latestRejectReview?.problemSliceIds || [],
|
||
};
|
||
}, [detail?.humanItem?.cancellationReason, isReworkTask, latestRejectReview]);
|
||
|
||
const currentAnnotationMutationContext = annotationMutationContextRef.current.current;
|
||
const beginAnnotationMutation = (taskId: string) => {
|
||
const currentContext = currentAnnotationMutationContext();
|
||
const token = annotationMutationScopeRef.current.begin({
|
||
taskId,
|
||
userId: currentContext.userId,
|
||
}) as AnnotationMutationToken | null;
|
||
if (!token) return null;
|
||
++taskDetailRequestRef.current;
|
||
setSaving(true);
|
||
setError("");
|
||
return token;
|
||
};
|
||
const endAnnotationMutation = (token: AnnotationMutationToken) => {
|
||
if (annotationMutationScopeRef.current.end(token)) setSaving(false);
|
||
};
|
||
const handleAnnotationMutationError = async (
|
||
failure: unknown,
|
||
fallback: string,
|
||
taskId: string,
|
||
token: AnnotationMutationToken,
|
||
) => {
|
||
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return;
|
||
const message = getActionErrorMessage(failure, fallback);
|
||
try {
|
||
await annotationOperationsApi.getTask(taskId);
|
||
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return;
|
||
setError(`${message} 已核对服务器状态;当前编辑已保留,请刷新载入权威内容后再重试。`);
|
||
} catch {
|
||
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return;
|
||
setError(`${message} 暂时无法核对服务器结果;当前编辑已保留,请勿重复提交并稍后刷新。`);
|
||
}
|
||
};
|
||
const selectedClaimedByMe = Boolean(
|
||
selectedHumanItem &&
|
||
selectedHumanItem.assignedUserId === currentUser?.id &&
|
||
["claimed", "in_progress"].includes(selectedHumanItem.status),
|
||
);
|
||
const submissionCheck = useMemo(() => {
|
||
if (!selectedClaimedByMe) {
|
||
return { canSubmit: false, reason: "当前任务尚未领取或已被释放" };
|
||
}
|
||
if (combinedSubmissionProcessing) {
|
||
return { canSubmit: false, reason: "正在提交中..." };
|
||
}
|
||
if (!sliceCoverage.complete) {
|
||
return { canSubmit: false, reason: "视频片段尚未完全由切片覆盖" };
|
||
}
|
||
if (
|
||
!exactFrameEditing ||
|
||
[...sliceSegments, ...segments].some(
|
||
(s) => !frameBoundaryAligned(frameBoundaries, s.start) || !frameBoundaryAligned(frameBoundaries, s.end),
|
||
)
|
||
) {
|
||
return { canSubmit: false, reason: "存在未对齐统一帧边界的数据,请先调整确认;不会自动移动旧标注" };
|
||
}
|
||
if (annotationWorkspaceIssues.length > 0) {
|
||
return { canSubmit: false, reason: "请修正已有描述的重复 ID、重叠或跨切片问题;未标注区间允许留空" };
|
||
}
|
||
if (segments.some((segment) => !segment.description?.trim())) {
|
||
return { canSubmit: false, reason: "请填写已添加的描述,或删除未填写的描述区间" };
|
||
}
|
||
return { canSubmit: true, reason: "" };
|
||
}, [
|
||
selectedClaimedByMe,
|
||
combinedSubmissionProcessing,
|
||
sliceCoverage.complete,
|
||
annotationWorkspaceIssues,
|
||
sliceSegments,
|
||
segments,
|
||
exactFrameEditing,
|
||
frameBoundaries,
|
||
]);
|
||
const canCurrentUserClaimItem = useCallback(
|
||
(item: HumanItem | undefined) => {
|
||
if (!item) return false;
|
||
if (isManager) return true;
|
||
const requiredRole = assignmentRoleForStage(item.currentStageId || "");
|
||
const member = projectMembers.find((m) => m.userId === currentUser?.id && m.projectId === item.projectId);
|
||
return memberCanClaim(item, member, requiredRole);
|
||
},
|
||
[currentUser?.id, isManager, projectMembers],
|
||
);
|
||
const sliceEditorReadOnly = annotationSliceEditorReadOnly({
|
||
workspaceMode,
|
||
isCombinedQuality: isV5CombinedQuality,
|
||
claimedByMe: selectedClaimedByMe,
|
||
});
|
||
const workspaceTitle =
|
||
workspaceMode === "clip"
|
||
? "人工调切"
|
||
: workspaceMode === "clip-quality"
|
||
? "剪切审核"
|
||
: workspaceMode === "quality"
|
||
? "切分与标注审核"
|
||
: workspaceMode === "acceptance"
|
||
? "最终验收"
|
||
: "真实切分与语义标注";
|
||
const queueTabLabel =
|
||
workspaceMode === "clip"
|
||
? "调切队列"
|
||
: workspaceMode === "clip-quality"
|
||
? "剪切审核队列"
|
||
: workspaceMode === "quality"
|
||
? "切分与标注审核队列"
|
||
: workspaceMode === "acceptance"
|
||
? "验收队列"
|
||
: "切分与标注队列";
|
||
|
||
const addSegment = () => {
|
||
if (!detail) return;
|
||
const label = selectedLabels.find((item) => item.id === segmentDraft.labelId);
|
||
const next = normalizeAnnotationSegments(
|
||
[
|
||
...segments,
|
||
{
|
||
id: `segment-${Date.now()}`,
|
||
labelId: label?.id || segmentDraft.labelId,
|
||
label: label?.name || segmentDraft.label,
|
||
start: Number(segmentDraft.start),
|
||
end: Number(segmentDraft.end),
|
||
confidence: 1,
|
||
source: "manual",
|
||
},
|
||
],
|
||
editableTimelineStart,
|
||
editableTimelineEnd,
|
||
);
|
||
setSegments(next);
|
||
setSliceStatuses(
|
||
deriveSliceStatuses(sliceSegments, next, sliceStatuses) as Record<
|
||
string,
|
||
NonNullable<SliceSegment["annotationStatus"]>
|
||
>,
|
||
);
|
||
};
|
||
|
||
const updateSegments = useCallback(
|
||
(next: AnnotationSegment[]) => {
|
||
setSegments(next);
|
||
setSliceStatuses(
|
||
deriveSliceStatuses(sliceSegments, next, sliceStatuses) as Record<
|
||
string,
|
||
NonNullable<SliceSegment["annotationStatus"]>
|
||
>,
|
||
);
|
||
},
|
||
[sliceSegments, sliceStatuses],
|
||
);
|
||
|
||
const confirmAnnotationDescription = async (nextSegments: AnnotationSegment[], sliceId: string) => {
|
||
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked) return false;
|
||
const taskId = detail.task.id;
|
||
const submittedVersion = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||
const nextStatuses = deriveSliceStatuses(sliceSegments, nextSegments, sliceStatuses) as Record<
|
||
string,
|
||
NonNullable<SliceSegment["annotationStatus"]>
|
||
>;
|
||
const payload = {
|
||
version: submittedVersion,
|
||
sliceSegments: applySliceStatuses(
|
||
sliceSegments.map((slice) => ({ ...slice, taskLabelId: "", taskLabel: "" })),
|
||
nextStatuses,
|
||
),
|
||
operations: sliceOperations,
|
||
segments: nextSegments.map((segment) => ({ ...segment, label: "", handedness: "" })),
|
||
statuses: nextStatuses,
|
||
};
|
||
const token = beginAnnotationMutation(taskId);
|
||
if (!token) return false;
|
||
try {
|
||
const result = await settleAuthoritativeMutation({
|
||
scope: annotationMutationScopeRef.current,
|
||
token,
|
||
currentContext: currentAnnotationMutationContext,
|
||
write: () => annotationOperationsApi.confirmAnnotations(taskId, payload),
|
||
read: () => annotationOperationsApi.getTask(taskId),
|
||
isApplied: (authoritative: AnnotationTaskDetail) => {
|
||
const workspace = annotationDraftFromHumanItem(authoritative.humanItem);
|
||
return Boolean(
|
||
authoritative.humanItem &&
|
||
authoritative.humanItem.version > submittedVersion &&
|
||
workspace &&
|
||
annotationWorkspaceMatches(workspace, payload),
|
||
);
|
||
},
|
||
});
|
||
if (result.status === "stale") return false;
|
||
if (result.status !== "confirmed") {
|
||
const base = getActionErrorMessage(result.error, "确认描述失败");
|
||
const message =
|
||
result.status === "unknown"
|
||
? `${base} 暂时无法核对服务器结果;描述仍保留在编辑器中,请勿重复提交并稍后刷新。`
|
||
: `${base} 已核对服务器状态,本次描述未保存;描述仍保留在编辑器中,请刷新载入权威内容后再恢复编辑。`;
|
||
setError(message);
|
||
throw new Error(message);
|
||
}
|
||
const confirmedItem = result.reconciled ? result.authoritative.humanItem : result.response.item;
|
||
if (!confirmedItem) return false;
|
||
setDetail((current) => (current ? { ...current, humanItem: confirmedItem } : current));
|
||
setSegments(nextSegments);
|
||
setSliceStatuses(nextStatuses);
|
||
annotationBaselineRef.current = annotationWorkspaceFingerprint(
|
||
sliceSegments,
|
||
sliceOperations,
|
||
nextSegments,
|
||
nextStatuses,
|
||
);
|
||
return true;
|
||
} finally {
|
||
endAnnotationMutation(token);
|
||
}
|
||
};
|
||
|
||
const applySliceChange = (
|
||
next: SliceSegment[],
|
||
operation: Omit<SliceOperation, "before" | "after">,
|
||
candidateSegments = segments,
|
||
) => {
|
||
if (!exactFrameEditing) {
|
||
setError("统一帧范围尚未就绪,暂不能修改切片。");
|
||
return false;
|
||
}
|
||
const sorted = [...next].sort((left, right) => left.start - right.start);
|
||
if (
|
||
sliceSegments.some(
|
||
(s) =>
|
||
s.deliveryDisposition === "discard" &&
|
||
!sorted.some((n) => n.id === s.id && n.start === s.start && n.end === s.end),
|
||
)
|
||
) {
|
||
setError("请先恢复舍弃片段,再调整、删除或合并它的边界。");
|
||
return false;
|
||
}
|
||
// Preserve old descriptions; invalid boundaries are reported, never pruned.
|
||
const validSegments = candidateSegments;
|
||
setError("");
|
||
setSliceHistory((history) => [...history, sliceSegments]);
|
||
setSliceOperations((operations) => [...operations, { ...operation, before: sliceSegments, after: sorted }]);
|
||
setSliceSegments(sorted);
|
||
setSliceStatuses(
|
||
deriveSliceStatuses(sorted, validSegments, sliceStatuses) as Record<
|
||
string,
|
||
NonNullable<SliceSegment["annotationStatus"]>
|
||
>,
|
||
);
|
||
return true;
|
||
};
|
||
|
||
const adjustSlice = (id: string, field: "start" | "end", value: number) => {
|
||
const index = sliceSegments.findIndex((item) => item.id === id);
|
||
if (index < 0) return;
|
||
const current = sliceSegments[index];
|
||
const previous = sliceSegments[index - 1];
|
||
const following = sliceSegments[index + 1];
|
||
if (
|
||
current.deliveryDisposition === "discard" ||
|
||
(field === "start" ? previous : following)?.deliveryDisposition === "discard"
|
||
) {
|
||
setError("请先恢复舍弃片段,再调整边界。");
|
||
return;
|
||
}
|
||
if (
|
||
!Number.isFinite(value) ||
|
||
(field === "start" && (value >= current.end || (previous ? value <= previous.start : value !== current.start))) ||
|
||
(field === "end" && (value <= current.start || (following ? value >= following.end : value !== current.end)))
|
||
) {
|
||
setError("首尾边界固定;内部边界必须保持相邻切片均至少包含一帧。");
|
||
return;
|
||
}
|
||
const oldBoundary = field === "end" ? current.end : current.start;
|
||
const next = sliceSegments.map((item) => ({ ...item }));
|
||
const affected = [id];
|
||
next[index] = { ...next[index], [field]: value };
|
||
if (field === "end" && next[index + 1]) {
|
||
next[index + 1].start = value;
|
||
affected.push(next[index + 1].id);
|
||
}
|
||
if (field === "start" && next[index - 1]) {
|
||
next[index - 1].end = value;
|
||
affected.push(next[index - 1].id);
|
||
}
|
||
|
||
// Synchronously adjust action segments touching this boundary so no gaps or deletions occur
|
||
const updatedSegments = segments.map((seg) => {
|
||
if (Math.abs(seg.end - oldBoundary) <= 0.000001 && value > seg.start + 0.01) {
|
||
return { ...seg, end: value };
|
||
}
|
||
if (Math.abs(seg.start - oldBoundary) <= 0.000001 && value < seg.end - 0.01) {
|
||
return { ...seg, start: value };
|
||
}
|
||
return seg;
|
||
});
|
||
setSegments(updatedSegments);
|
||
|
||
applySliceChange(next, { type: "adjust", segmentIds: affected }, updatedSegments);
|
||
};
|
||
|
||
const commitSliceBoundaryDraft = (id: string, field: "start" | "end") => {
|
||
const key = `${id}:${field}`;
|
||
const raw = sliceBoundaryDrafts[key];
|
||
if (raw == null) return;
|
||
const requestedValue = Number(raw);
|
||
const frameIndex = exactFrameEditing ? nearestFrameBoundaryIndex(frameBoundaries, requestedValue) : -1;
|
||
const value = frameIndex >= 0 ? frameBoundaries[frameIndex] : requestedValue;
|
||
const slice = sliceSegments.find((item) => item.id === id);
|
||
if (!slice || !Number.isFinite(value) || (field === "start" ? value >= slice.end : value <= slice.start)) {
|
||
setError("切片边界必须是有效数字,且开始时间必须小于结束时间。");
|
||
setSliceBoundaryDrafts((current) => {
|
||
const next = { ...current };
|
||
delete next[key];
|
||
return next;
|
||
});
|
||
return;
|
||
}
|
||
adjustSlice(id, field, value);
|
||
setSliceBoundaryDrafts((current) => {
|
||
const next = { ...current };
|
||
delete next[key];
|
||
return next;
|
||
});
|
||
};
|
||
|
||
const stepSliceBoundaryByFrame = (id: string, field: "start" | "end", direction: -1 | 1) => {
|
||
const slice = sliceSegments.find((item) => item.id === id);
|
||
if (!slice || !exactFrameEditing) return;
|
||
const currentValue = field === "start" ? slice.start : slice.end;
|
||
const value = stepFrameBoundary(frameBoundaries, currentValue, direction);
|
||
if (Math.abs(value - currentValue) <= 0.0000005) return;
|
||
adjustSlice(id, field, value);
|
||
};
|
||
|
||
const splitSlice = (index: number, requestedAt = annotationPlayheadRef.current) => {
|
||
const current = sliceSegments[index];
|
||
if (!current) return;
|
||
if (requestedAt <= current.start + 0.001 || requestedAt >= current.end - 0.001) {
|
||
setError(`请先把播放头移动到切片 ${index + 1} 内需要拆分的位置。`);
|
||
return;
|
||
}
|
||
const frameIndex = exactFrameEditing ? nearestFrameBoundaryIndex(frameBoundaries, requestedAt) : -1;
|
||
const at = frameIndex >= 0 ? frameBoundaries[frameIndex] : Number(requestedAt.toFixed(3));
|
||
if (at <= current.start + 0.000001 || at >= current.end - 0.000001) {
|
||
setError(`当前帧位于切片 ${index + 1} 边界,请移动到片段内部帧后再拆分。`);
|
||
return;
|
||
}
|
||
const revision = Date.now();
|
||
const split = splitSliceAtBoundary(
|
||
sliceSegments,
|
||
index,
|
||
at,
|
||
`${current.id}-a-${revision}`,
|
||
`${current.id}-b-${revision}`,
|
||
);
|
||
if (!split || !applySliceChange(split.slices, { type: "split", segmentIds: [current.id], at })) return;
|
||
return split.selectedSliceId;
|
||
};
|
||
|
||
const mergeSlice = (index: number) => {
|
||
const current = sliceSegments[index];
|
||
const nextItem = sliceSegments[index + 1];
|
||
if (!current || !nextItem) return;
|
||
const next = [...sliceSegments];
|
||
next.splice(index, 2, {
|
||
id: `merged-${Date.now()}`,
|
||
name: current.name || nextItem.name || `切片 ${String(index + 1).padStart(3, "0")}`,
|
||
start: current.start,
|
||
end: nextItem.end,
|
||
sourceIds: [current.id, nextItem.id],
|
||
});
|
||
applySliceChange(next, { type: "merge", segmentIds: [current.id, nextItem.id] });
|
||
};
|
||
|
||
const deleteSlice = (index: number) => {
|
||
if (sliceSegments.length <= 1) return;
|
||
const current = sliceSegments[index];
|
||
const next = sliceSegments.map((slice) => ({ ...slice }));
|
||
if (index < next.length - 1) {
|
||
next[index + 1].start = current.start;
|
||
} else {
|
||
next[index - 1].end = current.end;
|
||
}
|
||
next.splice(index, 1);
|
||
applySliceChange(next, { type: "delete", segmentIds: current ? [current.id] : [] });
|
||
};
|
||
|
||
const updateSliceName = (id: string, name: string) => {
|
||
if (!exactFrameEditing) return;
|
||
setSliceSegments((current) => current.map((slice) => (slice.id === id ? { ...slice, name } : slice)));
|
||
};
|
||
|
||
const setSliceDisposition = async (sliceId: string, disposition: "keep" | "discard", reason: string) => {
|
||
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return false;
|
||
const taskId = detail.task.id;
|
||
const token = beginAnnotationMutation(taskId);
|
||
if (!token) return false;
|
||
try {
|
||
const response = await annotationOperationsApi.setSliceDisposition(taskId, {
|
||
version: detailRef.current?.humanItem?.version ?? detail.humanItem.version,
|
||
sliceId,
|
||
disposition,
|
||
reason,
|
||
sliceSegments,
|
||
segments,
|
||
operations: sliceOperations,
|
||
statuses: sliceStatuses,
|
||
});
|
||
if (selectedTaskDetailIDRef.current !== taskId) return false;
|
||
const savedItem = { ...response.item, display: response.item.display || detail.humanItem.display };
|
||
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
|
||
setHumanPools((current) => ({
|
||
...current,
|
||
mine: current.mine.map((i) => (i.id === response.item.id ? savedItem : i)),
|
||
}));
|
||
setSliceSegments(response.workspace.sliceSegments);
|
||
setSegments(response.workspace.segments);
|
||
setSliceStatuses(response.workspace.statuses);
|
||
setSliceOperations(response.workspace.operations || []);
|
||
setSliceHistory([]);
|
||
annotationBaselineRef.current = annotationWorkspaceFingerprint(
|
||
response.workspace.sliceSegments,
|
||
response.workspace.operations || [],
|
||
response.workspace.segments,
|
||
response.workspace.statuses,
|
||
);
|
||
return true;
|
||
} catch (error) {
|
||
await handleAnnotationMutationError(error, "保存切片用途失败", taskId, token);
|
||
throw error;
|
||
} finally {
|
||
endAnnotationMutation(token);
|
||
}
|
||
};
|
||
|
||
const undoSlice = () => {
|
||
if (!exactFrameEditing) return;
|
||
const previous = sliceHistory[sliceHistory.length - 1];
|
||
if (!previous) return;
|
||
setSliceSegments(previous);
|
||
setSliceStatuses(
|
||
deriveSliceStatuses(previous, segments, sliceStatuses) as Record<
|
||
string,
|
||
NonNullable<SliceSegment["annotationStatus"]>
|
||
>,
|
||
);
|
||
setSliceHistory((history) => history.slice(0, -1));
|
||
setSliceOperations((operations) => operations.slice(0, -1));
|
||
};
|
||
|
||
const alignCurrentSliceBoundaries = () => {
|
||
if (
|
||
!detail ||
|
||
!exactFrameEditing ||
|
||
saving ||
|
||
combinedSubmissionLocked ||
|
||
annotationMutationScopeRef.current.busy() ||
|
||
(!selectedClaimedByMe && !isManager)
|
||
)
|
||
return;
|
||
const aligned = alignSliceTimeline(sliceSegments, frameBoundaries, segments);
|
||
if (aligned.error) {
|
||
setError(aligned.error);
|
||
return;
|
||
}
|
||
if (!aligned.changed) return;
|
||
if (
|
||
!window.confirm(
|
||
`将保留 ${sliceSegments.length} 个切片的名称、数量和顺序,把首尾对齐有效范围、内部分界对齐最近的真实帧;不会提交任务。确认对齐?`,
|
||
)
|
||
)
|
||
return;
|
||
applySliceChange(aligned.segments, { type: "adjust", segmentIds: sliceSegments.map((slice) => slice.id) });
|
||
};
|
||
|
||
const confirmSlicesAndMaterialize = async () => {
|
||
if (combinedSubmissionLocked || annotationMutationScopeRef.current.busy()) return;
|
||
const nameIssue = sliceDictionaryNameIssue(
|
||
sliceSegments,
|
||
sliceDictionary.items,
|
||
sliceDictionary.loading,
|
||
sliceDictionary.error,
|
||
);
|
||
if (nameIssue) {
|
||
setError(nameIssue);
|
||
return;
|
||
}
|
||
if (!detail?.humanItem || !selectedClaimedByMe || !exactFrameEditing || sliceAlignmentIssue) {
|
||
setError(!exactFrameEditing ? "统一帧范围尚未就绪,请等待或重试加载。" : sliceAlignmentIssue || "请先领取任务。");
|
||
return;
|
||
}
|
||
const confirmationSlices = sliceSegments.map((slice, index) => ({
|
||
...slice,
|
||
name: slice.name?.trim() || `切片 ${String(index + 1).padStart(3, "0")}`,
|
||
taskLabelId: "",
|
||
taskLabel: "",
|
||
annotationStatus: "pending" as const,
|
||
}));
|
||
const token = beginAnnotationMutation(detail.task.id);
|
||
if (!token) return;
|
||
try {
|
||
const response = await annotationOperationsApi.confirmSlices(detail.task.id, {
|
||
version: detail.humanItem.version,
|
||
sliceSegments: confirmationSlices,
|
||
sliceOperations,
|
||
changeReason: detail.sliceRevisions.length ? "重新确认切片" : "首次确认切片",
|
||
});
|
||
if (selectedTaskDetailIDRef.current !== detail.task.id) return;
|
||
setDetail((current) => (current ? { ...current, humanItem: response.item } : current));
|
||
if (response.item) {
|
||
setHumanPools((current) => ({
|
||
available: current.available.map((item) => (item.id === response.item.id ? response.item : item)),
|
||
mine: current.mine.map((item) => (item.id === response.item.id ? response.item : item)),
|
||
all: current.all.map((item) => (item.id === response.item.id ? response.item : item)),
|
||
}));
|
||
}
|
||
setSliceSegments(confirmationSlices);
|
||
setSegments([]);
|
||
setSliceStatuses(
|
||
Object.fromEntries(confirmationSlices.map((slice) => [slice.id, "pending"])) as Record<
|
||
string,
|
||
NonNullable<SliceSegment["annotationStatus"]>
|
||
>,
|
||
);
|
||
setCombinedEditorPhase("materializing");
|
||
setShowBatchSliceEditor(false);
|
||
setTaskDetailRefreshVersion((current) => current + 1);
|
||
} catch (confirmationError) {
|
||
await handleAnnotationMutationError(confirmationError, "确认切片失败", detail.task.id, token);
|
||
setCombinedEditorPhase("slice");
|
||
} finally {
|
||
endAnnotationMutation(token);
|
||
}
|
||
};
|
||
|
||
const resetToSliceEditing = async () => {
|
||
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked) return;
|
||
const taskId = detail.task.id;
|
||
const submittedVersion = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
|
||
const token = beginAnnotationMutation(taskId);
|
||
if (!token) return;
|
||
try {
|
||
const result = await settleAuthoritativeMutation({
|
||
scope: annotationMutationScopeRef.current,
|
||
token,
|
||
currentContext: currentAnnotationMutationContext,
|
||
write: () => annotationOperationsApi.resetSlices(taskId, submittedVersion),
|
||
read: () => annotationOperationsApi.getTask(taskId),
|
||
isApplied: (authoritative: AnnotationTaskDetail) => sliceResetWasApplied(authoritative, submittedVersion),
|
||
});
|
||
if (result.status === "stale") return;
|
||
if (result.status !== "confirmed") {
|
||
const base = getActionErrorMessage(result.error, "重新进入切片流程失败");
|
||
setError(
|
||
result.status === "unknown"
|
||
? `${base} 暂时无法核对服务器结果;现有切片和描述仍保留,请勿重复提交并稍后刷新。`
|
||
: `${base} 已核对服务器状态,本次重新切片未确认;现有切片和描述仍保留,请刷新载入权威内容后重试。`,
|
||
);
|
||
return;
|
||
}
|
||
const confirmedItem = result.reconciled ? result.authoritative.humanItem : result.response.item;
|
||
const workspace = result.reconciled
|
||
? annotationDraftFromHumanItem(result.authoritative.humanItem)
|
||
: result.response.workspace;
|
||
if (!confirmedItem || !workspace) return;
|
||
const nextSlices = workspace.sliceSegments;
|
||
setDetail((current) => (current ? { ...current, humanItem: confirmedItem } : current));
|
||
if (confirmedItem) {
|
||
setHumanPools((current) => ({
|
||
available: current.available.map((item) => (item.id === confirmedItem.id ? confirmedItem : item)),
|
||
mine: current.mine.map((item) => (item.id === confirmedItem.id ? confirmedItem : item)),
|
||
all: current.all.map((item) => (item.id === confirmedItem.id ? confirmedItem : item)),
|
||
}));
|
||
}
|
||
setSliceSegments(nextSlices);
|
||
setSliceOperations(workspace.operations || []);
|
||
setSegments([]);
|
||
setSliceStatuses(workspace.statuses || {});
|
||
setCombinedEditorPhase("slice");
|
||
setShowBatchSliceEditor(true);
|
||
setShowResliceWarning(false);
|
||
annotationBaselineRef.current = annotationWorkspaceFingerprint(
|
||
nextSlices,
|
||
workspace.operations || [],
|
||
[],
|
||
workspace.statuses || {},
|
||
);
|
||
} finally {
|
||
endAnnotationMutation(token);
|
||
}
|
||
};
|
||
|
||
const submitSliceRevision = async () => {
|
||
if (!detail || sliceSegments.length === 0) return;
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await annotationOperationsApi.submitSliceRevision(detail.task.id, {
|
||
segments: sliceSegments,
|
||
operations: sliceOperations,
|
||
changeReason: detail.sliceRevisions.length ? "切片返工修订" : "首轮切片校正",
|
||
});
|
||
const next = await annotationOperationsApi.getTask(detail.task.id);
|
||
setDetail(next);
|
||
setSliceOperations([]);
|
||
setSliceHistory([]);
|
||
await loadProject();
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "提交切片校正失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const submitRevision = async () => {
|
||
if (!detail || segments.length === 0) return;
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await annotationOperationsApi.submitRevision(detail.task.id, {
|
||
segments,
|
||
changeReason: detail.task.currentRevision > 0 ? "人工返工修订" : "首轮人工标注",
|
||
});
|
||
await loadProject();
|
||
setDetail(await annotationOperationsApi.getTask(detail.task.id));
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "提交标注失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const submitCombined = async () => {
|
||
// Descriptions are optional; kept media still covers every slice.
|
||
if (!detail?.humanItem || !selectedClaimedByMe || sliceSegments.length === 0 || combinedSubmissionProcessing)
|
||
return;
|
||
if (annotationWorkspaceIssues.length > 0) {
|
||
setError("切片或 JSON 描述存在重复 ID、跨切片或无归属问题,请修正后再完成任务。");
|
||
return;
|
||
}
|
||
const progress = summarizeSliceProgress(sliceSegments, segments, sliceStatuses);
|
||
const orphaned = annotationOrphanSegments(sliceSegments, segments);
|
||
if (orphaned.length > 0) {
|
||
setError(`有 ${orphaned.length} 条 JSON 描述不完整属于任何切片,请先修正描述时间范围。`);
|
||
return;
|
||
}
|
||
if (segments.some((segment) => !segment.description?.trim())) {
|
||
setError("请填写已添加的描述,或删除未填写的描述区间");
|
||
return;
|
||
}
|
||
const currentItemId = detail.humanItem.id;
|
||
const currentTaskId = detail.task.id;
|
||
const token = beginAnnotationMutation(currentTaskId);
|
||
if (!token) return;
|
||
try {
|
||
const submission = await annotationOperationsApi.submitCombined(detail.task.id, {
|
||
version: detailRef.current?.humanItem?.version ?? detail.humanItem.version,
|
||
sliceSegments: applySliceStatuses(
|
||
sliceSegments.map((slice) => ({ ...slice, taskLabelId: "", taskLabel: "" })),
|
||
progress.statuses,
|
||
),
|
||
sliceOperations,
|
||
segments: segments.map((segment) => ({ ...segment, label: "", handedness: "" })),
|
||
requireSliceCompletion: true,
|
||
changeReason: detail.task.currentRevision > 0 ? "逐片 JSON 描述返工" : "逐片 JSON 描述完成",
|
||
});
|
||
if (submission.item) setDetail((current) => (current ? { ...current, humanItem: submission.item } : current));
|
||
if (submission.status === "processing") {
|
||
setCombinedSubmissionNotice("已接收提交,正在生成审核数据;完成后才会流转质检,请勿重复提交。");
|
||
return;
|
||
}
|
||
} catch (saveError) {
|
||
await handleAnnotationMutationError(saveError, "提交切片与语义标注失败", detail.task.id, token);
|
||
return;
|
||
} finally {
|
||
endAnnotationMutation(token);
|
||
}
|
||
submittedItemIdsRef.current.add(currentItemId);
|
||
submittedItemIdsRef.current.add(currentTaskId);
|
||
setSliceOperations([]);
|
||
setSliceHistory([]);
|
||
setHumanPools((current) => ({
|
||
...current,
|
||
available: current.available.filter((item) => item.id !== currentItemId),
|
||
mine: current.mine.map((item) =>
|
||
item.id === currentItemId ? { ...item, status: "ready", currentStageId: "quality_review" } : item,
|
||
),
|
||
}));
|
||
setTasks((current) =>
|
||
current.map((task) =>
|
||
task.id === currentTaskId ? { ...task, status: "pending_quality", humanStageId: "quality_review" } : task,
|
||
),
|
||
);
|
||
closeTaskAndReturnToPool("任务已提交质检,已流转至同供应商质检审核池。");
|
||
};
|
||
|
||
useEffect(() => {
|
||
if (!detail?.task.id || !combinedSubmissionProcessing) return;
|
||
const taskId = detail.task.id;
|
||
let disposed = false;
|
||
let timer: ReturnType<typeof setTimeout>;
|
||
const poll = async () => {
|
||
try {
|
||
const status = await annotationOperationsApi.getTaskStatus(taskId);
|
||
if (disposed || selectedTaskDetailIDRef.current !== taskId) return;
|
||
if (status.progress)
|
||
setCombinedSubmissionNotice(
|
||
`提交处理中 · 已处理 ${status.progress.completedSlices}/${status.progress.totalSlices} 个切片;审核数据写入完成后流转质检。`,
|
||
);
|
||
if (status.pendingSubmissionId && !status.needsRefresh) {
|
||
timer = setTimeout(poll, 3000);
|
||
return;
|
||
}
|
||
const next = await annotationOperationsApi.getTask(taskId);
|
||
if (disposed || selectedTaskDetailIDRef.current !== taskId) return;
|
||
setDetail(next);
|
||
if (combinedSubmissionFinished(next)) {
|
||
closeTaskAndReturnToPool("审核数据已生成,任务已提交质检。");
|
||
void loadProject();
|
||
return;
|
||
}
|
||
if (combinedSubmissionState(next.humanItem) !== "processing") {
|
||
setCombinedSubmissionNotice("");
|
||
setError("上次提交未完成,已保留描述。请确认任务状态后重新提交。");
|
||
void loadProject();
|
||
return;
|
||
}
|
||
} catch (failure) {
|
||
if (disposed) return;
|
||
setCombinedSubmissionNotice("");
|
||
setError(getActionErrorMessage(failure, "暂时无法确认提交结果,请刷新任务池查看。"));
|
||
void loadProject();
|
||
// A role change may make the old stage unreadable. Neither that nor a
|
||
// network failure proves success, and neither should discard edits.
|
||
return;
|
||
}
|
||
timer = setTimeout(poll, 3000);
|
||
};
|
||
timer = setTimeout(poll, 3000);
|
||
return () => {
|
||
disposed = true;
|
||
clearTimeout(timer);
|
||
};
|
||
}, [combinedSubmissionProcessing, detail?.task.id, loadProject, setDetail]);
|
||
|
||
const toggleSliceUsability = (sliceId: string, usable: boolean) => {
|
||
const target = sliceSegments.find((slice) => slice.id === sliceId);
|
||
if (!target) return;
|
||
if (!usable) {
|
||
// 标记为不可用 (empty_confirmed)
|
||
const remainingSegments = segments.filter((s) => s.start < target.start - 0.001 || s.end > target.end + 0.001);
|
||
setSegments(remainingSegments);
|
||
setSliceSegments((current) =>
|
||
current.map((slice) =>
|
||
slice.id === sliceId
|
||
? { ...slice, taskLabelId: undefined, taskLabel: undefined, annotationStatus: "empty_confirmed" }
|
||
: slice,
|
||
),
|
||
);
|
||
setSliceStatuses((current) => ({ ...current, [sliceId]: "empty_confirmed" }));
|
||
} else {
|
||
// 标记为可用切片
|
||
setSliceSegments((current) =>
|
||
current.map((slice) => (slice.id === sliceId ? { ...slice, annotationStatus: "pending" } : slice)),
|
||
);
|
||
setSliceStatuses((current) => ({ ...current, [sliceId]: "pending" }));
|
||
const hasEvents = segments.some((s) => s.start >= target.start - 0.001 && s.end <= target.end + 0.001);
|
||
if (!hasEvents) {
|
||
const initialSegment: AnnotationSegment = {
|
||
id: `description-${sliceId}-${Date.now()}`,
|
||
labelId: "",
|
||
label: "",
|
||
description: "",
|
||
start: target.start,
|
||
end: target.end,
|
||
confidence: 1,
|
||
source: "manual",
|
||
};
|
||
setSegments([...segments, initialSegment]);
|
||
}
|
||
}
|
||
};
|
||
|
||
const confirmSliceEmpty = (sliceId: string) => {
|
||
const target = sliceSegments.find((slice) => slice.id === sliceId);
|
||
if (!target) return;
|
||
const hasEvents = segments.some((segment) => segment.start >= target.start && segment.end <= target.end);
|
||
if (hasEvents) {
|
||
setError("当前切片已有 JSON 描述;请先删除描述后再确认无动作。");
|
||
return;
|
||
}
|
||
setSliceSegments((current) =>
|
||
current.map((slice) =>
|
||
slice.id === sliceId
|
||
? { ...slice, taskLabelId: undefined, taskLabel: undefined, annotationStatus: "empty_confirmed" }
|
||
: slice,
|
||
),
|
||
);
|
||
setSliceStatuses((current) => ({ ...current, [sliceId]: "empty_confirmed" }));
|
||
};
|
||
|
||
const resetSliceCompletion = (sliceId: string) => {
|
||
setSliceStatuses((current) => ({ ...current, [sliceId]: "pending" }));
|
||
};
|
||
|
||
const rejectAnnotationInput = async () => {
|
||
if (!detail || !reviewComment.trim()) {
|
||
setError("拒绝输入必须填写原因。");
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await annotationOperationsApi.rejectTask(detail.task.id, {
|
||
reasonCodes: ["annotation_input_rejected"],
|
||
comment: reviewComment.trim(),
|
||
});
|
||
setReviewComment("");
|
||
closeTaskAndReturnToPool("已拒绝该标注输入。");
|
||
await loadProject();
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "拒绝标注输入失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const review = async (
|
||
stage: "split_quality" | "quality" | "acceptance",
|
||
decision: "approved" | "rejected",
|
||
rejectTarget?: "cut_adjustment" | "semantic_annotation",
|
||
) => {
|
||
if (!detail) return;
|
||
if (decision === "rejected" && !reviewComment.trim()) {
|
||
setError("打回必须填写原因,便于操作员按轮次返工。");
|
||
return;
|
||
}
|
||
|
||
let effectiveProblemSliceIds = [...problemSliceIds];
|
||
if (decision === "rejected" && effectiveProblemSliceIds.length === 0) {
|
||
const parsed = parseSegmentCommentsFromText(reviewComment);
|
||
const matchedFromComment = sliceSegments
|
||
.filter((s, idx) => parsed.segmentComments.some((c) => c.sliceName === (s.name || `切片 ${idx + 1}`)))
|
||
.map((s) => s.id);
|
||
if (matchedFromComment.length > 0) {
|
||
effectiveProblemSliceIds = matchedFromComment;
|
||
}
|
||
}
|
||
|
||
if (decision === "rejected" && isV5CombinedQuality && effectiveProblemSliceIds.length === 0) {
|
||
if (sliceSegments.length > 0) {
|
||
effectiveProblemSliceIds = sliceSegments.map((s) => s.id);
|
||
}
|
||
}
|
||
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await annotationOperationsApi.review(detail.task.id, {
|
||
stage,
|
||
decision,
|
||
comment: reviewComment,
|
||
rejectTargets:
|
||
decision === "rejected"
|
||
? selectedHumanItem?.currentStageId === "cut_review"
|
||
? ["cut_adjustment"]
|
||
: selectedHumanItem?.currentStageId === "semantic_review"
|
||
? [rejectTarget || "semantic_annotation"]
|
||
: stage === "split_quality"
|
||
? ["split_annotation"]
|
||
: stage === "quality"
|
||
? ["semantic_annotation"]
|
||
: ["quality_review"]
|
||
: undefined,
|
||
reasonCodes: decision === "rejected" ? ["manual_review_reject"] : undefined,
|
||
problemSliceIds:
|
||
decision === "rejected" && (isV5CombinedQuality || effectiveProblemSliceIds.length > 0)
|
||
? effectiveProblemSliceIds
|
||
: undefined,
|
||
videoQuality: isV5CombinedQuality ? undefined : qualityDraft.videoQuality,
|
||
annotationAccuracy: isV5CombinedQuality ? undefined : Number(qualityDraft.annotationAccuracy),
|
||
annotationCompleteness: isV5CombinedQuality ? undefined : Number(qualityDraft.annotationCompleteness),
|
||
overallGrade: isV5CombinedQuality ? undefined : qualityDraft.overallGrade,
|
||
});
|
||
setReviewComment("");
|
||
setProblemSliceIds([]);
|
||
closeTaskAndReturnToPool(
|
||
decision === "rejected" ? "任务已打回给标注员进行返工修改。" : "任务已审核通过,流转至下一阶段。",
|
||
);
|
||
void loadProject();
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "提交审核决定失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const createTemplate = async () => {
|
||
if (!projectId || !templateDraft.name.trim()) return;
|
||
setSaving(true);
|
||
try {
|
||
await annotationOperationsApi.createTemplate({
|
||
projectId,
|
||
name: templateDraft.name,
|
||
version: Number(templateDraft.version),
|
||
labels: [],
|
||
phrases: templateDraft.phrases
|
||
.split(",")
|
||
.map((item) => item.trim())
|
||
.filter(Boolean),
|
||
prelabel: { enabled: true, minimumConfidence: 0.7, enableWilor: true, enableHead: false },
|
||
});
|
||
setTemplateDraft(emptyTemplate);
|
||
await loadProject();
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "创建语义模板失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const claimTask = async (task: AnnotationTaskRecord, item: HumanItem) => {
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.claim(item.id, item.version);
|
||
setSelectedAnnotationTaskId(task.id);
|
||
setTaskPoolView("mine");
|
||
await loadProject();
|
||
setTaskDetailRefreshVersion((current) => current + 1);
|
||
} catch (claimError) {
|
||
setError(getActionErrorMessage(claimError, "领取任务失败,任务可能已被其他成员领取"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const releaseSelectedTask = async () => {
|
||
if (releaseLocked) return;
|
||
if (!detail?.humanItem || combinedSubmissionLocked || annotationMutationScopeRef.current.busy()) return;
|
||
const isQuality =
|
||
workspaceMode === "quality" || workspaceMode === "clip-quality" || detail.task.status === "pending_quality";
|
||
const confirmMessage = isQuality
|
||
? "确认释放此任务并退回待领取池吗?其他审核员将可以领取此任务。"
|
||
: "放弃并释放任务将清空该任务在数据库中的历史切片与标注记录,并退回待领取池。确认继续吗?";
|
||
if (!window.confirm(confirmMessage)) return;
|
||
const token = beginAnnotationMutation(detail.task.id);
|
||
if (!token) return;
|
||
try {
|
||
await humanLoopApi.release(detail.humanItem.id, detail.humanItem.version);
|
||
setTaskPoolView("available");
|
||
selectTask("");
|
||
await loadProject();
|
||
} catch (releaseError) {
|
||
await handleAnnotationMutationError(releaseError, "释放任务失败", detail.task.id, token);
|
||
} finally {
|
||
endAnnotationMutation(token);
|
||
}
|
||
};
|
||
|
||
const assignHumanItem = async (item: HumanItem, assignedUserId: string, taskId = "") => {
|
||
if (!isManager) return;
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.assign(item.id, item.version, assignedUserId);
|
||
if (taskId) setDetail(await annotationOperationsApi.getTask(taskId));
|
||
await loadProject();
|
||
} catch (assignmentError) {
|
||
setError(getActionErrorMessage(assignmentError, "管理员改派任务失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const assignSelectedTask = async (assignedUserId: string) => {
|
||
if (!detail?.humanItem) return;
|
||
await assignHumanItem(detail.humanItem, assignedUserId, detail.task.id);
|
||
};
|
||
|
||
const reopenReject = async (reject: HumanReject, targetStageId: string) => {
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
let itemVersion: number;
|
||
try {
|
||
const { item } = await humanLoopApi.getItem(reject.itemId);
|
||
itemVersion = item.version;
|
||
} catch {
|
||
itemVersion = (await deliveryPackagesApi.get(reject.itemId)).version;
|
||
}
|
||
await humanLoopApi.reopen(reject.id, {
|
||
itemVersion,
|
||
rejectVersion: reject.version,
|
||
targetStageId,
|
||
comment: "管理员从拒绝区定向重开",
|
||
});
|
||
await loadProject();
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "从拒绝区重开任务失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const decideDeliveryPackage = async (item: DeliveryPackage, decision: "approved" | "rejected") => {
|
||
if (decision === "rejected" && !reviewComment.trim()) {
|
||
setError("验收拒绝必须填写原因。");
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await deliveryPackagesApi.decide(item.id, {
|
||
version: item.version,
|
||
decision,
|
||
comment: reviewComment.trim(),
|
||
videoQuality: qualityDraft.videoQuality,
|
||
annotationAccuracy: Number(qualityDraft.annotationAccuracy),
|
||
annotationCompleteness: Number(qualityDraft.annotationCompleteness),
|
||
overallGrade: qualityDraft.overallGrade,
|
||
reasonCodes: decision === "rejected" ? ["acceptance_rejected"] : undefined,
|
||
});
|
||
setReviewComment("");
|
||
await loadProject();
|
||
} catch (saveError) {
|
||
setError(getActionErrorMessage(saveError, "提交成品包验收失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const claimDeliveryPackage = async (item: DeliveryPackage) => {
|
||
if (!item.acceptanceHumanItemId || !item.acceptanceHumanItemVersion) {
|
||
setError("验收任务池记录尚未就绪,请稍后刷新。");
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.claim(item.acceptanceHumanItemId, item.acceptanceHumanItemVersion);
|
||
await loadProject();
|
||
} catch (claimError) {
|
||
setError(getActionErrorMessage(claimError, "领取验收任务失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const releaseDeliveryPackage = async (item: DeliveryPackage) => {
|
||
if (releaseLocked) return;
|
||
if (!item.acceptanceHumanItemId || !item.acceptanceHumanItemVersion) {
|
||
setError("验收任务池记录尚未就绪,请稍后刷新。");
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.release(item.acceptanceHumanItemId, item.acceptanceHumanItemVersion);
|
||
await loadProject();
|
||
} catch (releaseError) {
|
||
setError(getActionErrorMessage(releaseError, "释放验收任务失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const assignDeliveryPackage = async (item: DeliveryPackage, assignedUserId: string) => {
|
||
if (!isManager || !item.acceptanceHumanItemId || !item.acceptanceHumanItemVersion) return;
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.assign(item.acceptanceHumanItemId, item.acceptanceHumanItemVersion, assignedUserId);
|
||
await loadProject();
|
||
} catch (assignmentError) {
|
||
setError(getActionErrorMessage(assignmentError, "管理员改派成品包验收任务失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
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) => {
|
||
if (releaseLocked) return;
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.release(item.id, item.version);
|
||
await loadProject();
|
||
} catch (releaseError) {
|
||
setError(getActionErrorMessage(releaseError, "释放包前最终验收失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const claimPrepackageAcceptance = async (item: HumanItem) => {
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.claim(item.id, item.version);
|
||
setTaskPoolView("mine");
|
||
setSelectedAnnotationTaskId("");
|
||
setExpandedDeliveryPackageId(item.id);
|
||
await loadProject();
|
||
} catch (claimError) {
|
||
setError(getActionErrorMessage(claimError, "领取包前最终验收失败"));
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const decidePrepackageAcceptance = async (
|
||
item: HumanItem,
|
||
statistics: PrepackageAcceptanceStatistics,
|
||
decision: "approved" | "rejected",
|
||
strictThreeRole: boolean,
|
||
acceptanceComment = reviewComment,
|
||
) => {
|
||
const rawHuman = item.processingProfile === "raw_human";
|
||
if (decision === "approved" && strictThreeRole && !rawHuman && !strictAcceptanceDraftIsValid(statistics)) {
|
||
setError("排除 HeadPose 或 HandPose 时必须填写原因。");
|
||
return;
|
||
}
|
||
if (decision === "approved" && !strictThreeRole && !prepackageAcceptanceStatisticsAreValid(statistics)) {
|
||
setError("请填写视频质量、总体等级,以及 0–100 的标注准确性和完整性后再确认。");
|
||
return;
|
||
}
|
||
if (decision === "rejected" && !acceptanceComment.trim()) {
|
||
setError("整包验收不通过必须填写问题说明。");
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
setError("");
|
||
try {
|
||
await humanLoopApi.decide(item.id, {
|
||
version: item.version,
|
||
decision,
|
||
reviewedRevision: item.currentRevision,
|
||
comment:
|
||
acceptanceComment.trim() ||
|
||
(!rawHuman && (statistics.headpose === "exclude" || statistics.handpose === "exclude")
|
||
? statistics.exclusionReason.trim()
|
||
: ""),
|
||
reasonCodes:
|
||
decision === "rejected"
|
||
? ["batch_acceptance_rejected"]
|
||
: !rawHuman && (statistics.headpose === "exclude" || statistics.handpose === "exclude")
|
||
? ["pose_excluded"]
|
||
: undefined,
|
||
videoQuality: strictThreeRole ? undefined : statistics.videoQuality,
|
||
annotationAccuracy: strictThreeRole ? undefined : Number(statistics.annotationAccuracy),
|
||
annotationCompleteness: strictThreeRole ? undefined : Number(statistics.annotationCompleteness),
|
||
overallGrade: strictThreeRole ? undefined : statistics.overallGrade,
|
||
poseDelivery:
|
||
strictThreeRole && !rawHuman
|
||
? {
|
||
headpose: statistics.headpose,
|
||
handpose: statistics.handpose,
|
||
reasonCodes:
|
||
statistics.headpose === "exclude" || statistics.handpose === "exclude"
|
||
? ["pose_excluded"]
|
||
: undefined,
|
||
}
|
||
: undefined,
|
||
});
|
||
setPrepackageComments((current) => ({ ...current, [item.id]: "" }));
|
||
closeTaskAndReturnToPool(
|
||
decision === "rejected" ? "验收结果已保存,已打回。" : "验收结果已保存,交付数据仍需等待后台打包完成。",
|
||
);
|
||
void loadProject();
|
||
} catch (confirmError) {
|
||
setError(
|
||
getActionErrorMessage(
|
||
confirmError,
|
||
decision === "rejected" ? "整包打回失败" : "确认最终验收失败;下游打包未释放",
|
||
),
|
||
);
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const selectProject = (nextProjectId: string) => {
|
||
if (annotationDirty) {
|
||
setError("当前任务有未确认修改;请先放弃修改后再切换项目。");
|
||
return;
|
||
}
|
||
setProjectId(nextProjectId);
|
||
const next = new URLSearchParams(searchParams);
|
||
if (nextProjectId) next.set("projectId", nextProjectId);
|
||
else next.delete("projectId");
|
||
next.delete("taskId");
|
||
next.delete("workflowId");
|
||
next.delete("capture");
|
||
next.delete("runId");
|
||
setSearchParams(next, { replace: true });
|
||
};
|
||
|
||
const selectWorkflow = (nextWorkflowId: string) => {
|
||
if (annotationDirty) {
|
||
setError("当前任务有未确认修改;请先放弃修改后再切换工作流。");
|
||
return;
|
||
}
|
||
const next = new URLSearchParams(searchParams);
|
||
if (nextWorkflowId) next.set("workflowId", nextWorkflowId);
|
||
else next.delete("workflowId");
|
||
next.delete("capture");
|
||
next.delete("taskId");
|
||
next.delete("runId");
|
||
setSearchParams(next, { replace: true });
|
||
};
|
||
|
||
const selectCaptureDirectory = (captureDirectory: string) => {
|
||
if (annotationDirty) {
|
||
setError("当前任务有未确认修改;请先放弃修改后再切换 Capture。");
|
||
return;
|
||
}
|
||
const next = new URLSearchParams(searchParams);
|
||
if (captureDirectory) next.set("capture", captureDirectory);
|
||
else next.delete("capture");
|
||
next.delete("taskId");
|
||
setSearchParams(next, { replace: true });
|
||
};
|
||
|
||
const closeTaskAndReturnToPool = (notice = "") => {
|
||
leaveDirtyRef.current = false;
|
||
setWorkbenchDrafts([]);
|
||
annotationBaselineRef.current = "";
|
||
setPendingTaskId(null);
|
||
setSelectedAnnotationTaskId("");
|
||
setDetail(null);
|
||
if (notice) {
|
||
setCombinedSubmissionNotice(notice);
|
||
setError("");
|
||
}
|
||
const next = new URLSearchParams(searchParams);
|
||
next.delete("taskId");
|
||
next.delete("sliceId");
|
||
next.delete("eventId");
|
||
setSearchParams(next, { replace: true });
|
||
};
|
||
|
||
const selectTask = (taskId: string) => {
|
||
if (taskId !== selectedTaskId && annotationDirty) {
|
||
setPendingTaskId(taskId);
|
||
return;
|
||
}
|
||
if (!taskId) {
|
||
closeTaskAndReturnToPool();
|
||
return;
|
||
}
|
||
setSelectedAnnotationTaskId(taskId);
|
||
const next = new URLSearchParams(searchParams);
|
||
if (taskId) next.set("taskId", taskId);
|
||
else next.delete("taskId");
|
||
next.delete("sliceId");
|
||
next.delete("eventId");
|
||
setSearchParams(next, { replace: true });
|
||
};
|
||
|
||
const randomClaimTask = async () => {
|
||
if (!blindAnnotator || !projectId || !currentUser || randomClaimFlight.current || annotationDirty) return;
|
||
const actorID = currentUser.id;
|
||
const selectedProject = projectId;
|
||
const key = `droboticflow.random-claim:${actorID}:${selectedProject}`;
|
||
randomClaimFlight.current = true;
|
||
setRandomClaimBusy(true);
|
||
setRandomClaimNotice("");
|
||
let requestId = randomClaimKeys.current[key];
|
||
try {
|
||
if (!requestId) {
|
||
try {
|
||
requestId = sessionStorage.getItem(key) || "";
|
||
} catch {}
|
||
}
|
||
if (!requestId) requestId = newAnnotationClaimRequestID();
|
||
randomClaimKeys.current[key] = requestId;
|
||
try {
|
||
sessionStorage.setItem(key, requestId);
|
||
} catch {}
|
||
const response = await annotationOperationsApi.randomClaim(selectedProject, requestId);
|
||
delete randomClaimKeys.current[key];
|
||
try {
|
||
sessionStorage.removeItem(key);
|
||
} catch {}
|
||
if (claimContextRef.current.userId !== actorID || claimContextRef.current.projectId !== selectedProject) return;
|
||
if (!response.item || !response.task) {
|
||
setRandomClaimNotice(response.message || "本项目暂无您可领取的标注任务");
|
||
return;
|
||
}
|
||
++projectLoadRequestRef.current;
|
||
setLoading(false);
|
||
setProjectLoadError("");
|
||
const item = response.item,
|
||
task = response.task;
|
||
setHumanPools((current) => ({ ...current, mine: [item, ...current.mine.filter((i) => i.id !== item.id)] }));
|
||
setTasks((current) => [task, ...current.filter((t) => t.id !== task.id)]);
|
||
setTaskPoolView("mine");
|
||
selectTask(task.id);
|
||
setRandomClaimNotice("任务已领取并归您处理;视频加载失败也可从我的任务继续。");
|
||
} catch (cause) {
|
||
const status = (cause as { status?: number }).status;
|
||
if (
|
||
[400, 401, 403, 404].includes(status) ||
|
||
["claim_result_unavailable", "claim_candidate_taken"].includes((cause as { code?: string }).code)
|
||
) {
|
||
delete randomClaimKeys.current[key];
|
||
try {
|
||
sessionStorage.removeItem(key);
|
||
} catch {}
|
||
}
|
||
if (claimContextRef.current.userId === actorID && claimContextRef.current.projectId === selectedProject) {
|
||
setRandomClaimNotice(getActionErrorMessage(cause, "领取结果暂未确认,请重试;同一次请求不会重复分配任务。"));
|
||
}
|
||
} finally {
|
||
randomClaimFlight.current = false;
|
||
setRandomClaimBusy(false);
|
||
}
|
||
};
|
||
|
||
const cancelLeave = () => {
|
||
setPendingTaskId(null);
|
||
if (leaveBlocker.state === "blocked") leaveBlocker.reset();
|
||
workbenchHostRef.current?.querySelector<HTMLElement>(".capture-workbench")?.focus({ preventScroll: true });
|
||
};
|
||
|
||
const discardChangesAndSelectTask = () => {
|
||
const taskId = pendingTaskId;
|
||
setPendingTaskId(null);
|
||
annotationBaselineRef.current = "";
|
||
setWorkbenchDrafts([]);
|
||
leaveDirtyRef.current = false;
|
||
if (leaveBlocker.state === "blocked") {
|
||
// A stage/header link may reuse this page and select the same task again.
|
||
// Unmount its session editor and reload saved data even in that case.
|
||
setDetail(null);
|
||
setTaskDetailRefreshVersion((current) => current + 1);
|
||
leaveBlocker.proceed();
|
||
return;
|
||
}
|
||
if (!taskId) {
|
||
closeTaskAndReturnToPool();
|
||
return;
|
||
}
|
||
setSelectedAnnotationTaskId(taskId);
|
||
const next = new URLSearchParams(searchParams);
|
||
if (taskId) next.set("taskId", taskId);
|
||
else next.delete("taskId");
|
||
next.delete("sliceId");
|
||
next.delete("eventId");
|
||
setSearchParams(next, { replace: true });
|
||
};
|
||
|
||
if (!isManager && projectId && !loading && !projectLoadError && allowedStageModes.length === 0) {
|
||
return (
|
||
<div className="rounded-xl border border-red-500/30 bg-red-500/10 px-5 py-4 text-sm text-red-100">
|
||
当前账号未配置此项目的标注、审核或最终验收角色。
|
||
</div>
|
||
);
|
||
}
|
||
|
||
if (!isManager && projectId && !loading && defaultStageMode && !canAccessWorkspace) {
|
||
return (
|
||
<div className="flex min-h-[320px] items-center justify-center gap-2 text-sm text-gray-400">
|
||
<Loader2 className="h-4 w-4 animate-spin" /> 正在进入授权工作台…
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const adaptiveSliceLayout = workspaceMode === "annotate" && tab === "queue" && combinedEditorPhase === "slice";
|
||
|
||
return (
|
||
<div className="annotation-operations-page space-y-4" data-adaptive-slice={adaptiveSliceLayout || undefined}>
|
||
{pendingTaskId !== null || leaveBlocker.state === "blocked" ? (
|
||
<div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/70 p-4">
|
||
<div
|
||
role="dialog"
|
||
aria-modal="true"
|
||
aria-label="离开未保存修改确认"
|
||
onKeyDown={(event) => {
|
||
event.stopPropagation();
|
||
if (event.key === "Escape") {
|
||
event.preventDefault();
|
||
cancelLeave();
|
||
}
|
||
}}
|
||
className="w-full max-w-md rounded-2xl border border-[#303137] bg-[#151619] p-5 shadow-2xl"
|
||
>
|
||
<div className="text-base font-semibold text-white">当前任务有未确认修改</div>
|
||
<div className="mt-2 text-sm leading-6 text-gray-400">
|
||
离开将清空本次未确认的切片调整和各片未保存的描述草稿。
|
||
</div>
|
||
<div className="mt-5 flex justify-end gap-2">
|
||
<button
|
||
type="button"
|
||
onClick={cancelLeave}
|
||
autoFocus
|
||
className="rounded-lg border border-[#34363b] px-4 py-2 text-sm text-gray-200"
|
||
>
|
||
继续编辑
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={discardChangesAndSelectTask}
|
||
className="rounded-lg border border-red-500/40 bg-red-500/10 px-4 py-2 text-sm text-red-200"
|
||
>
|
||
清空并切换
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
<div className="annotation-workspace-heading space-y-3">
|
||
<h1 className="sr-only">{workspaceTitle}</h1>
|
||
<PageSubnav compact items={annotationStageTabs} label="标注中心阶段导航" />
|
||
<div className="annotation-workspace-filters grid items-end gap-2 md:grid-cols-2 xl:grid-cols-[minmax(170px,0.7fr)_auto_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.25fr)_auto]">
|
||
{isManager ? (
|
||
<select
|
||
className={inputClass}
|
||
value={tab}
|
||
onChange={(event) => setTab(event.target.value as Tab)}
|
||
aria-label="当前工作台视图"
|
||
>
|
||
<option value="queue">{queueTabLabel}</option>
|
||
<option value="rejects">拒绝区</option>
|
||
<option value="templates">模板版本</option>
|
||
<option value="workload">工时统计</option>
|
||
</select>
|
||
) : null}
|
||
{isManager ? (
|
||
<Link
|
||
to={`/sampling${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`}
|
||
className="rounded-lg border border-[#2a2b2f] px-3 py-2 text-sm text-gray-300 hover:border-blue-500/50 hover:text-white"
|
||
>
|
||
主动抽检
|
||
</Link>
|
||
) : null}
|
||
<label className="min-w-0 space-y-1 text-[10px] text-gray-500">
|
||
<span>1. 项目</span>
|
||
<select
|
||
className={inputClass}
|
||
aria-label="1. 项目"
|
||
value={projectId}
|
||
onChange={(event) => selectProject(event.target.value)}
|
||
disabled={randomClaimBusy || (!blindAnnotator && Boolean(requestedRunId))}
|
||
title={requestedRunId ? "当前页面已锁定到指定执行记录的项目" : "切换项目"}
|
||
>
|
||
<option value="">{blindAnnotator ? "请选择项目" : "全部项目"}</option>
|
||
{projects.map((project) => (
|
||
<option key={project.id} value={project.id}>
|
||
{project.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
{!blindAnnotator && (
|
||
<label className="min-w-0 space-y-1 text-[10px] text-gray-500">
|
||
<span>2. 工作流</span>
|
||
<select
|
||
className={inputClass}
|
||
aria-label="2. 工作流"
|
||
value={requestedWorkflowId}
|
||
onChange={(event) => selectWorkflow(event.target.value)}
|
||
disabled={Boolean(requestedRunId || (pathWorkflowId && pathWorkflowId !== "all"))}
|
||
title="切换工作流"
|
||
>
|
||
<option value="">全部工作流</option>
|
||
{workflows.map((workflow) => (
|
||
<option key={workflow.id} value={workflow.id}>
|
||
{workflow.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
)}
|
||
{!blindAnnotator && (
|
||
<label className="min-w-0 space-y-1 text-[10px] text-gray-500">
|
||
<span>3. Capture 子目录</span>
|
||
<select
|
||
className={inputClass}
|
||
aria-label="3. Capture 子目录"
|
||
value={requestedCaptureDirectory}
|
||
onChange={(event) => selectCaptureDirectory(event.target.value)}
|
||
title="按每条采集记录筛选"
|
||
>
|
||
<option value="">全部 Capture 子目录</option>
|
||
{captureDirectories.map((directory) => (
|
||
<option key={directory} value={directory}>
|
||
{directory}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
)}
|
||
<button
|
||
type="button"
|
||
onClick={() => void loadProject()}
|
||
className="rounded-lg border border-[#2a2b2f] p-2 text-gray-300 hover:border-blue-500/50 hover:text-white"
|
||
title="刷新"
|
||
>
|
||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
{combinedSubmissionNotice ? (
|
||
<div
|
||
role="status"
|
||
data-testid="combined-submission-status"
|
||
className="flex items-center gap-2 rounded-xl border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-800 dark:text-emerald-200"
|
||
>
|
||
{combinedSubmissionProcessing ? (
|
||
<Loader2 className="h-4 w-4 animate-spin text-emerald-600 dark:text-emerald-400" />
|
||
) : (
|
||
<CheckCircle2 className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
|
||
)}
|
||
{combinedSubmissionNotice}
|
||
</div>
|
||
) : error || projectLoadError ? (
|
||
<div role="alert" className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">
|
||
{(error || projectLoadError)?.includes("project annotation membership is required")
|
||
? "您当前没有该任务所属项目的标注成员权限(或该任务所属项目已归档/移除)"
|
||
: error || projectLoadError}
|
||
</div>
|
||
) : combinedSubmissionConflicted ? (
|
||
<div
|
||
role="alert"
|
||
className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-700 dark:text-amber-200"
|
||
>
|
||
上次提交后描述发生了变化,质检交接未完成。已保留当前描述,请重新点击“完成任务并提交质检”。
|
||
</div>
|
||
) : projectLoadRecoveryNotice ? (
|
||
<div
|
||
role="status"
|
||
data-testid="annotation-load-recovery"
|
||
className="flex items-center gap-2 rounded-xl border border-blue-500/30 bg-blue-500/10 px-4 py-3 text-sm text-blue-100"
|
||
>
|
||
<Loader2 className="h-4 w-4 animate-spin" />
|
||
{projectLoadRecoveryNotice}
|
||
</div>
|
||
) : null}
|
||
|
||
{requestedRunId ? (
|
||
<div
|
||
data-testid="annotation-run-scope"
|
||
className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-blue-500/25 bg-blue-500/[0.06] px-3 py-2"
|
||
>
|
||
<div>
|
||
<BusinessExecutionPath
|
||
projectName={scopedRun?.projectName || projects.find((item) => item.id === projectId)?.name}
|
||
workflowName={scopedRun?.workflowName || workflows.find((item) => item.id === requestedWorkflowId)?.name}
|
||
captureDirectories={scopedRun?.captureDirectories}
|
||
runId={requestedRunId}
|
||
compact
|
||
/>
|
||
</div>
|
||
<div className="text-right text-xs text-gray-400">
|
||
<div>状态:{scopedRun?.status || "加载中"}</div>
|
||
{scopedRun?.currentNodeId ? <div className="mt-1">当前节点:{scopedRun.currentNodeId}</div> : null}
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{tab === "rejects" ? (
|
||
<div className={`${panelClass} p-5`}>
|
||
<div className="flex items-center justify-between">
|
||
<div>
|
||
<div className="text-lg font-semibold text-white">拒绝区</div>
|
||
<div className="mt-1 text-sm text-gray-500">
|
||
拒绝事实永久保留;重开会创建新 Attempt,不修改原审核结论。
|
||
</div>
|
||
</div>
|
||
<span className="rounded-full border border-red-500/30 px-3 py-1 text-xs text-red-200">
|
||
{rejects.filter((item) => item.status === "open").length} 待处置
|
||
</span>
|
||
</div>
|
||
<div className="mt-4 space-y-3">
|
||
{rejects.map((reject) => (
|
||
<div key={reject.id} className="rounded-xl border border-[#2a2b2f] bg-[#101114] p-4">
|
||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||
<div>
|
||
<BusinessExecutionPath
|
||
projectName={
|
||
reject.display?.projectName || projects.find((item) => item.id === reject.projectId)?.name
|
||
}
|
||
workflowName={
|
||
reject.display?.workflowName || workflows.find((item) => item.id === reject.workflowId)?.name
|
||
}
|
||
captureDirectories={reject.display?.captureDirectories}
|
||
runId={reject.runId}
|
||
compact
|
||
/>
|
||
<div className="mt-1 text-sm text-white">
|
||
{reject.stageId} · {reject.comment}
|
||
</div>
|
||
<div className="mt-1 text-xs text-gray-500">
|
||
原因:{reject.reasonCodes.join("、") || "未填写"} · round {reject.attemptRound}
|
||
</div>
|
||
</div>
|
||
<span className="text-xs text-gray-400">{reject.status}</span>
|
||
</div>
|
||
{isManager && reject.status === "open" ? (
|
||
<div className="mt-3 flex flex-wrap gap-2">
|
||
{reject.allowedReopenStages.map((stage) => (
|
||
<button
|
||
key={stage}
|
||
type="button"
|
||
disabled={saving}
|
||
onClick={() => void reopenReject(reject, stage)}
|
||
className="rounded-lg border border-blue-500/30 px-3 py-2 text-xs text-blue-200 hover:bg-blue-500/10 disabled:opacity-50"
|
||
>
|
||
重开至 {stage}
|
||
</button>
|
||
))}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
))}
|
||
{rejects.length === 0 ? (
|
||
<div className="py-12 text-center text-sm text-gray-500">当前项目没有拒绝记录</div>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{tab === "queue" ? (
|
||
<div className="annotation-task-workspace grid grid-cols-[minmax(0,1fr)] gap-4 xl:grid-cols-[220px_minmax(0,1fr)]">
|
||
<div className="annotation-task-pool min-w-0 space-y-4 xl:sticky xl:top-3 xl:self-start">
|
||
<div className={`annotation-task-pool-panel ${panelClass} p-3`}>
|
||
<div className="annotation-task-pool-title text-sm font-semibold text-[color:var(--app-text)]">
|
||
任务池
|
||
</div>
|
||
<div className="annotation-task-pool-tabs mt-3 flex flex-wrap gap-2">
|
||
{(
|
||
[
|
||
["available", blindAnnotator ? "随机领取" : "可领取", poolCounts.available],
|
||
["mine", "我的任务", poolCounts.mine],
|
||
...(isManager ? ([["all", "全部任务", poolCounts.all]] as const) : []),
|
||
] as Array<[TaskPoolView, string, number]>
|
||
).map(([value, label, count]) => (
|
||
<button
|
||
key={value}
|
||
type="button"
|
||
onClick={() => setTaskPoolView(value)}
|
||
data-testid={`human-task-pool-${value}`}
|
||
aria-pressed={taskPoolView === value}
|
||
className={`rounded-lg border px-3 py-2 text-xs transition-colors ${taskPoolView === value ? "border-blue-500 bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-200 font-medium" : "border-[color:var(--app-border)] text-slate-600 hover:text-slate-900 dark:text-gray-400 dark:hover:text-white"}`}
|
||
>
|
||
{label}{" "}
|
||
{blindAnnotator && value === "available"
|
||
? claimableCount.projectId === projectId
|
||
? (claimableCount.count ?? "—")
|
||
: "—"
|
||
: count}
|
||
</button>
|
||
))}
|
||
</div>
|
||
{blindAnnotator && (
|
||
<div className="mt-3 space-y-2" data-testid="project-random-claim">
|
||
<p className="text-xs text-slate-500">先选项目,再随机领取一条任务;领取后不能主动释放。</p>
|
||
<button
|
||
type="button"
|
||
onClick={() => void randomClaimTask()}
|
||
disabled={!projectId || randomClaimBusy || annotationDirty}
|
||
className="w-full rounded-lg bg-orange-500 px-3 py-2 font-semibold text-white disabled:opacity-50"
|
||
>
|
||
{randomClaimBusy ? "正在领取…" : "随机领取任务"}
|
||
</button>
|
||
{annotationDirty && <p className="text-xs text-amber-700">请先确认当前编辑,再领取新任务。</p>}
|
||
{randomClaimNotice && (
|
||
<p role="status" className="break-words text-xs text-slate-600">
|
||
{randomClaimNotice}
|
||
</p>
|
||
)}
|
||
</div>
|
||
)}
|
||
{(!blindAnnotator || taskPoolView === "mine") && (
|
||
<>
|
||
<div className="annotation-task-pool-filters mt-3 grid gap-2">
|
||
<label className="relative">
|
||
<Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
|
||
<input
|
||
className={`${inputClass} pl-9`}
|
||
value={taskSearch}
|
||
onChange={(event) => setTaskSearch(event.target.value)}
|
||
placeholder="搜索 Capture"
|
||
aria-label="搜索标注任务"
|
||
/>
|
||
</label>
|
||
<select
|
||
className={inputClass}
|
||
value={taskStatusFilter}
|
||
onChange={(event) => setTaskStatusFilter(event.target.value)}
|
||
aria-label="按任务状态筛选"
|
||
>
|
||
<option value="all">全部状态</option>
|
||
<option value="pending_slice">待切片</option>
|
||
<option value="slicing">正在切片</option>
|
||
<option value="pending_annotation">待标注</option>
|
||
<option value="rework">打回</option>
|
||
<option value="pending_quality">已送检</option>
|
||
<option value="pending_acceptance">待验收</option>
|
||
<option value="accepted">已通过</option>
|
||
</select>
|
||
</div>
|
||
<div className="annotation-task-list-label mt-4 text-xs font-medium text-slate-500 dark:text-gray-400">
|
||
逐段任务
|
||
</div>
|
||
<div className="annotation-task-list mt-3 max-h-[calc(100vh-330px)] space-y-1.5 overflow-auto pr-1">
|
||
{loading && (
|
||
<div role="status" className="p-3 text-sm">
|
||
正在加载任务…
|
||
</div>
|
||
)}
|
||
{projectLoadError && (
|
||
<div role="alert" className="p-3 text-sm text-red-600">
|
||
任务加载失败,请点击刷新重试。
|
||
</div>
|
||
)}
|
||
{prepackageAcceptanceItems.map((item) => (
|
||
<AcceptanceTaskCard
|
||
key={item.id}
|
||
item={item}
|
||
name={
|
||
captureDirectoriesFromHumanTask(item)[0] || item.display?.projectName || "Capture 验收任务"
|
||
}
|
||
selected={expandedDeliveryPackageId === item.id}
|
||
mine={item.assignedUserId === currentUser?.id}
|
||
assignee={
|
||
users.find((user) => user.id === item.assignedUserId)?.name ||
|
||
(item.assignedUserId === currentUser?.id ? currentUser?.name || "" : "已领取")
|
||
}
|
||
claimable={
|
||
!isManager &&
|
||
!item.assignedUserId &&
|
||
["ready", "rework", "submitted"].includes(item.status) &&
|
||
canCurrentUserClaimItem(item)
|
||
}
|
||
saving={saving}
|
||
onPreview={() => {
|
||
setSelectedAnnotationTaskId("");
|
||
setExpandedDeliveryPackageId(item.id);
|
||
}}
|
||
onClaim={() => void claimPrepackageAcceptance(item)}
|
||
/>
|
||
))}
|
||
{filteredVisibleTasks.map((task) => {
|
||
const poolItem = visibleHumanItemByTaskId.get(task.id);
|
||
const humanItem = task.id === selectedTaskId && detail?.humanItem ? detail.humanItem : poolItem;
|
||
const livePhase = task.id === selectedTaskId ? combinedEditorPhase : undefined;
|
||
const detailedStatus = deriveDetailedTaskStatus(task, humanItem, livePhase);
|
||
const assignee = users.find((user) => user.id === humanItem?.assignedUserId);
|
||
const taskCaptureDirectories = captureDirectoriesFromHumanTask(humanItem, task);
|
||
const captureLabel = taskCaptureDirectories[0] || "未识别 Capture";
|
||
const claimable = Boolean(
|
||
humanItem &&
|
||
!humanItem.assignedUserId &&
|
||
["ready", "rework", "submitted"].includes(humanItem.status) &&
|
||
canCurrentUserClaimItem(humanItem),
|
||
);
|
||
const claimedByMe = Boolean(
|
||
humanItem?.assignedUserId === currentUser?.id &&
|
||
["claimed", "in_progress"].includes(humanItem?.status || ""),
|
||
);
|
||
const isTaskRework = detailedStatus === "rework";
|
||
const isTaskPendingQuality = detailedStatus === "pending_quality";
|
||
const isTaskPendingAcceptance = detailedStatus === "pending_acceptance";
|
||
const isTaskAccepted = detailedStatus === "accepted";
|
||
const awaitingDownstream =
|
||
workspaceMode === "annotate" &&
|
||
(isTaskPendingQuality || isTaskPendingAcceptance || isTaskAccepted);
|
||
const taskAction = annotationTaskAction({
|
||
awaitingDownstream,
|
||
status: detailedStatus,
|
||
claimable,
|
||
claimedByMe,
|
||
saving,
|
||
});
|
||
return (
|
||
<article
|
||
key={task.id}
|
||
data-task-id={task.id}
|
||
data-capture-directory={captureLabel}
|
||
className={`w-full rounded-lg border ${selectedTaskId === task.id ? "border-orange-400 bg-orange-50/50 dark:bg-orange-500/10" : "border-[color:var(--app-border)] bg-[color:var(--app-panel)] hover:border-orange-400/50"}`}
|
||
>
|
||
<button
|
||
type="button"
|
||
onClick={() => selectTask(task.id)}
|
||
data-testid="annotation-task-card"
|
||
className="w-full px-3 py-2.5 text-left"
|
||
>
|
||
<div className="flex items-start justify-between gap-2">
|
||
<div className="min-w-0">
|
||
<div
|
||
className="truncate text-xs font-semibold text-[color:var(--app-text)]"
|
||
title={captureLabel}
|
||
>
|
||
{captureLabel}
|
||
</div>
|
||
<div className="mt-1 truncate text-[10px] text-slate-500 dark:text-gray-500">
|
||
{task.clipStart.toFixed(1)}–{task.clipEnd.toFixed(1)}s
|
||
</div>
|
||
</div>
|
||
{(() => {
|
||
switch (detailedStatus) {
|
||
case "rework":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-rose-500/50 bg-rose-50 px-2 py-0.5 text-[9px] font-semibold text-rose-700 dark:border-rose-500/40 dark:bg-rose-500/20 dark:text-rose-300">
|
||
<AlertCircle className="h-2.5 w-2.5" />
|
||
打回
|
||
</span>
|
||
);
|
||
case "slicing":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-amber-500/50 bg-amber-50 px-2 py-0.5 text-[9px] font-semibold text-amber-700 dark:border-amber-500/40 dark:bg-amber-500/20 dark:text-amber-300">
|
||
<Loader2 className="h-2.5 w-2.5 animate-spin text-amber-600" />
|
||
正在切片
|
||
</span>
|
||
);
|
||
case "pending_annotation":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-orange-500/50 bg-orange-50 px-2 py-0.5 text-[9px] font-semibold text-orange-700 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-300">
|
||
<span className="h-1.5 w-1.5 rounded-full bg-orange-500 animate-pulse" />
|
||
待标注
|
||
</span>
|
||
);
|
||
case "pending_slice":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-sky-500/40 bg-sky-50 px-2 py-0.5 text-[9px] font-semibold text-sky-700 dark:border-sky-500/40 dark:bg-sky-500/20 dark:text-sky-300">
|
||
<span className="h-1.5 w-1.5 rounded-full bg-sky-500" />
|
||
待切片
|
||
</span>
|
||
);
|
||
case "pending_quality":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-blue-500/40 bg-blue-50 px-2 py-0.5 text-[9px] font-medium text-blue-700 dark:bg-blue-500/20 dark:text-blue-300">
|
||
已送检
|
||
</span>
|
||
);
|
||
case "pending_acceptance":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-cyan-500/40 bg-cyan-50 px-2 py-0.5 text-[9px] font-medium text-cyan-700 dark:bg-cyan-500/20 dark:text-cyan-300">
|
||
待验收
|
||
</span>
|
||
);
|
||
case "accepted":
|
||
return (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-emerald-500/40 bg-emerald-50 px-2 py-0.5 text-[9px] font-medium text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300">
|
||
已通过
|
||
</span>
|
||
);
|
||
default:
|
||
return humanItem?.assignedUserId ? (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-purple-500/40 bg-purple-50 px-2 py-0.5 text-[9px] font-semibold text-purple-700 dark:border-purple-500/40 dark:bg-purple-500/20 dark:text-purple-300">
|
||
处理中({assignee?.name || "他人"})
|
||
</span>
|
||
) : (
|
||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-slate-300 bg-slate-50 px-2 py-0.5 text-[9px] font-semibold text-slate-600 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300">
|
||
待领取
|
||
</span>
|
||
);
|
||
}
|
||
})()}
|
||
</div>
|
||
<div className="mt-1.5 text-[10px] text-gray-500">
|
||
{humanItem?.assignedUserId
|
||
? `领取人:${assignee?.name || humanItem.assignedUserId}`
|
||
: detailedStatus === "pending_quality"
|
||
? "待审核员领取质检"
|
||
: detailedStatus === "accepted"
|
||
? "处理已完成"
|
||
: "尚未领取"}
|
||
</div>
|
||
</button>
|
||
<div className="flex justify-end border-t border-[color:var(--app-border)] px-3 py-2">
|
||
<button
|
||
type="button"
|
||
data-testid="annotation-task-action"
|
||
disabled={taskAction.disabled}
|
||
onClick={() => {
|
||
if (taskAction.disabled) return;
|
||
if (taskAction.kind === "claim" && humanItem) void claimTask(task, humanItem);
|
||
else selectTask(task.id);
|
||
}}
|
||
className={cn(
|
||
"rounded px-3 py-1.5 text-xs font-semibold transition disabled:cursor-not-allowed",
|
||
taskAction.className,
|
||
)}
|
||
>
|
||
{taskAction.label}
|
||
</button>
|
||
</div>
|
||
</article>
|
||
);
|
||
})}
|
||
{!loading &&
|
||
!projectLoadError &&
|
||
filteredVisibleTasks.length === 0 &&
|
||
prepackageAcceptanceItems.length === 0 ? (
|
||
<div className="py-8 text-center text-sm text-gray-500">
|
||
{visiblePoolItems.length
|
||
? "任务关联数据缺失,请联系管理员核查。"
|
||
: taskSearch || taskStatusFilter !== "all"
|
||
? "没有符合筛选条件的任务"
|
||
: !isManager && !requestedRunId && taskPoolView === "available"
|
||
? memberPoolEmptyReason(
|
||
projectMembers,
|
||
currentUser?.id,
|
||
projectId,
|
||
workspaceMode === "acceptance"
|
||
? "acceptance_reviewer"
|
||
: workspaceMode === "quality" || workspaceMode === "clip-quality"
|
||
? "quality_reviewer"
|
||
: "annotator",
|
||
)
|
||
: scopedEmptyMessage}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</>
|
||
)}
|
||
</div>
|
||
</div>
|
||
|
||
<div className={`annotation-task-detail-panel ${panelClass} min-w-0 min-h-[640px] p-3`}>
|
||
{prepackageAcceptanceItems
|
||
.filter((i) => i.id === expandedDeliveryPackageId)
|
||
.map((item) => {
|
||
const stats = prepackageAcceptanceDrafts[item.id] || {
|
||
...emptyPrepackageAcceptanceStatistics,
|
||
headpose: "include",
|
||
handpose: "include",
|
||
};
|
||
const mine = item.assignedUserId === currentUser?.id;
|
||
return (
|
||
<FinalAcceptanceWorkspace
|
||
key={item.id}
|
||
item={item}
|
||
mine={mine}
|
||
saving={saving}
|
||
error={error}
|
||
timeZone={timeZone}
|
||
draft={stats}
|
||
comment={prepackageComments[item.id] || ""}
|
||
onDraftChange={(patch) =>
|
||
setPrepackageAcceptanceDrafts((current) => ({
|
||
...current,
|
||
[item.id]: { ...(current[item.id] || stats), ...patch },
|
||
}))
|
||
}
|
||
onCommentChange={(value) => setPrepackageComments((current) => ({ ...current, [item.id]: value }))}
|
||
onApprove={() =>
|
||
void decidePrepackageAcceptance(item, stats, "approved", true, prepackageComments[item.id] || "")
|
||
}
|
||
onReject={() =>
|
||
void decidePrepackageAcceptance(item, stats, "rejected", true, prepackageComments[item.id] || "")
|
||
}
|
||
onRelease={releaseLocked ? undefined : () => void releasePrepackageAcceptance(item)}
|
||
/>
|
||
);
|
||
})}
|
||
{detail ? (
|
||
<div className="annotation-task-detail min-w-0 space-y-3 break-words pb-20">
|
||
{detail.task.processingProfile === "raw_human" && (
|
||
<p className="rounded border border-amber-200 bg-amber-50 p-3 text-xs text-amber-800">
|
||
原始数据人工版 · 未自动去畸变或脱敏;请按原始画面切片与标注。
|
||
</p>
|
||
)}
|
||
<div className="annotation-task-heading flex flex-wrap items-center justify-between gap-3">
|
||
<div className="min-w-0">
|
||
<div className="truncate text-sm font-semibold text-white">
|
||
{captureDirectoriesFromHumanTask(selectedHumanItem, detail.task)[0] || "未识别 Capture"}
|
||
</div>
|
||
<div className="mt-1 flex flex-wrap items-center gap-2 text-[10px] text-gray-500">
|
||
<span>{statusLabels[detail.task.status]}</span>
|
||
{detail.task.runId && isOrganizationAdminRole(role) ? (
|
||
<Link
|
||
className="font-mono text-blue-300 hover:text-blue-200"
|
||
to={`/monitoring?runId=${encodeURIComponent(detail.task.runId)}`}
|
||
>
|
||
Run {detail.task.runId}
|
||
</Link>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
|
||
<div className="flex min-w-0 w-full max-w-full flex-wrap items-center gap-2 sm:w-auto">
|
||
{!isV5Combined && detail.task.sourceVideo.toLowerCase().endsWith(".rrd") ? (
|
||
<div className="flex items-center gap-1 rounded border border-[#2a2b2f] bg-[#0a0a0a] p-1">
|
||
<button
|
||
type="button"
|
||
onClick={() => setPreviewTab("video")}
|
||
className={
|
||
previewTab === "video"
|
||
? "rounded bg-blue-600 px-2 py-1 text-[10px] text-white"
|
||
: "px-2 py-1 text-[10px] text-gray-400"
|
||
}
|
||
>
|
||
视频
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => setPreviewTab("rerun")}
|
||
className={
|
||
previewTab === "rerun"
|
||
? "rounded bg-blue-600 px-2 py-1 text-[10px] text-white"
|
||
: "px-2 py-1 text-[10px] text-gray-400"
|
||
}
|
||
>
|
||
Rerun
|
||
</button>
|
||
</div>
|
||
) : null}
|
||
<div className="rounded border border-blue-500/30 bg-blue-500/10 px-2 py-1 text-[10px] text-blue-200">
|
||
{annotationStage === "split_annotation" || annotationStage === "cut_adjustment"
|
||
? "人工剪切调整"
|
||
: annotationStage === "split_quality_review" || annotationStage === "cut_review"
|
||
? "剪切审核"
|
||
: annotationStage === "semantic_annotation"
|
||
? "语义标注"
|
||
: annotationStage === "annotation_combined"
|
||
? "切分与标注"
|
||
: annotationStage === "semantic_review"
|
||
? "标注审核"
|
||
: annotationStage === "acceptance" ||
|
||
annotationStage === "prepackage_acceptance" ||
|
||
workspaceMode === "acceptance"
|
||
? "最终验收"
|
||
: "标注质检"}
|
||
</div>
|
||
{(() => {
|
||
const detailedStatus = detail
|
||
? deriveDetailedTaskStatus(detail.task, detail.humanItem, combinedEditorPhase)
|
||
: "available";
|
||
|
||
switch (detailedStatus) {
|
||
case "rework":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-rose-500/40 bg-rose-500/15 px-2.5 py-1 text-xs font-semibold text-rose-300">
|
||
<AlertCircle className="h-3.5 w-3.5" />
|
||
<span>打回(需返工)</span>
|
||
</div>
|
||
);
|
||
case "slicing":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/15 px-2.5 py-1 text-xs font-semibold text-amber-300">
|
||
<Loader2 className="h-3.5 w-3.5 animate-spin text-amber-400" />
|
||
<span>正在切片数据包…</span>
|
||
</div>
|
||
);
|
||
case "pending_annotation":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-orange-500/40 bg-orange-500/15 px-2.5 py-1 text-xs font-semibold text-orange-300">
|
||
<span className="h-2 w-2 rounded-full bg-orange-400 animate-pulse" />
|
||
<span>待标注</span>
|
||
</div>
|
||
);
|
||
case "pending_slice":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-sky-500/40 bg-sky-500/15 px-2.5 py-1 text-xs font-semibold text-sky-300">
|
||
<span className="h-2 w-2 rounded-full bg-sky-400" />
|
||
<span>待切片</span>
|
||
</div>
|
||
);
|
||
case "pending_quality":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-blue-500/40 bg-blue-500/15 px-2.5 py-1 text-xs font-semibold text-blue-300">
|
||
<span>已送检(待质检)</span>
|
||
</div>
|
||
);
|
||
case "pending_acceptance":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-cyan-500/40 bg-cyan-500/15 px-2.5 py-1 text-xs font-semibold text-cyan-300">
|
||
<span>待验收</span>
|
||
</div>
|
||
);
|
||
case "accepted":
|
||
return (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-emerald-500/40 bg-emerald-500/15 px-2.5 py-1 text-xs font-semibold text-emerald-300">
|
||
<span>已通过</span>
|
||
</div>
|
||
);
|
||
default:
|
||
return selectedHumanItem?.assignedUserId ? (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-purple-500/40 bg-purple-500/15 px-2.5 py-1 text-xs font-semibold text-purple-300">
|
||
<span>处理中(领取人:{selectedHumanItem.assignedUserId})</span>
|
||
</div>
|
||
) : (
|
||
<div className="inline-flex items-center gap-1.5 rounded-full border border-blue-500/40 bg-blue-500/15 px-2.5 py-1 text-xs font-semibold text-blue-300">
|
||
<span>待领取</span>
|
||
</div>
|
||
);
|
||
}
|
||
})()}
|
||
{isManager && selectedHumanItem ? (
|
||
<label className="flex min-w-0 max-w-full items-center gap-2 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-inset)] px-2 py-1 text-xs text-[color:var(--app-text)]">
|
||
<span className="shrink-0 whitespace-nowrap">管理员改派</span>
|
||
<select
|
||
aria-label="管理员任务改派"
|
||
className="min-w-0 flex-1 bg-transparent text-xs text-[color:var(--app-text)] outline-none"
|
||
value={selectedHumanItem.assignedUserId || ""}
|
||
disabled={
|
||
saving ||
|
||
combinedSubmissionLocked ||
|
||
["accepted", "rejected", "escalated", "cancelled"].includes(selectedHumanItem.status)
|
||
}
|
||
onChange={(event) => void assignSelectedTask(event.target.value)}
|
||
>
|
||
<option value="">退回待领取池</option>
|
||
{eligibleAssignees.map((user) => (
|
||
<option key={user.id} value={user.id}>
|
||
{user.name} ·{" "}
|
||
{user.id === currentUser?.id ? "管理员" : assignmentRoleLabel(selectedRequiredRole)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
|
||
{combinedEditorPhase === "materializing" ? (
|
||
<div
|
||
className="space-y-4 rounded-xl border border-blue-500/30 bg-blue-500/[0.07] px-6 py-12 text-center"
|
||
data-testid="slice-materialization-progress"
|
||
>
|
||
<Loader2 className="mx-auto h-10 w-10 animate-spin text-blue-500 dark:text-blue-300" />
|
||
<div className="text-lg font-semibold text-gray-900 dark:text-white">正在生成切片…</div>
|
||
<div role="status" className="text-sm text-gray-600 dark:text-gray-300">
|
||
{processingNotice || "已接收切片请求,等待处理"}
|
||
</div>
|
||
<div className="mx-auto max-w-lg text-xs leading-relaxed text-gray-600 dark:text-gray-300">
|
||
正在处理您确认的{" "}
|
||
<span className="font-semibold text-blue-600 dark:text-blue-300">
|
||
{sliceSegments.length} 个切片
|
||
</span>
|
||
,完成后自动进入描述编辑。
|
||
</div>
|
||
<div className="pt-2">
|
||
<button
|
||
type="button"
|
||
onClick={() => void resetToSliceEditing()}
|
||
className="inline-flex items-center gap-1.5 rounded-lg border border-gray-300 bg-[color:var(--app-panel)] px-4 py-2 text-xs font-medium text-gray-700 shadow-sm transition-colors hover:bg-gray-50 hover:text-gray-900 dark:border-[#34363b] dark:text-gray-200 dark:hover:border-gray-500 dark:hover:text-white"
|
||
>
|
||
<Undo2 className="h-3.5 w-3.5" />
|
||
返回调整切片
|
||
</button>
|
||
</div>
|
||
</div>
|
||
) : (
|
||
<div ref={workbenchHostRef} key={detail.task.id} className="capture-workbench-host min-w-0">
|
||
<CaptureAnnotationWorkbench
|
||
key={`${detail.task.id}:${combinedEditorPhase}:${detail.humanItem?.currentStageId || ""}:${currentUser?.id || ""}`}
|
||
onDraftsChange={setWorkbenchDrafts}
|
||
adaptiveLayout={adaptiveSliceLayout}
|
||
taskId={detail.task.id}
|
||
frameTimelineStatus={frameTimelineStatus}
|
||
onRetryFrameTimeline={() =>
|
||
void loadFrameTimeline(
|
||
detail.task,
|
||
initialCaptureSlices(detail.task),
|
||
!annotationDraftFromHumanItem(detail.humanItem) &&
|
||
!detail.sliceRevisions.some(
|
||
(revision) =>
|
||
revision.segments?.length &&
|
||
!(revision.revision === 0 && revision.authorUserId === "system"),
|
||
),
|
||
)
|
||
}
|
||
onAlignSliceBoundaries={alignCurrentSliceBoundaries}
|
||
videoSource={selectedVideoSource}
|
||
rightVideoSource={selectedRightVideoSource}
|
||
clipStart={editableTimelineStart}
|
||
clipEnd={editableTimelineEnd}
|
||
sourceIsFullVideo={detail.task.sourceIsFullVideo}
|
||
slices={sliceSegments}
|
||
segments={segments}
|
||
labels={selectedLabels}
|
||
sliceDictionary={sliceDictionary.items}
|
||
sliceDictionaryLoading={sliceDictionary.loading}
|
||
sliceDictionaryError={sliceDictionary.error}
|
||
onRefreshSliceDictionary={sliceDictionary.refresh}
|
||
statuses={sliceProgress.statuses}
|
||
phase={combinedEditorPhase === "slice" ? "slice" : "annotate"}
|
||
frameBoundaries={frameBoundaries}
|
||
rightMediaBoundaries={frameTimeline?.rightBoundariesSeconds}
|
||
unifiedBoundaries={frameTimeline?.boundaryContract === "hardware-frame-v1"}
|
||
readOnlyStatusLabel={statusLabels[detail.task.status] || "只读查看"}
|
||
readOnly={
|
||
(workspaceMode === "annotate" &&
|
||
(detail.task.status === "pending_quality" ||
|
||
detail.task.status === "pending_acceptance" ||
|
||
detail.task.status === "accepted")) ||
|
||
((workspaceMode === "quality" ||
|
||
workspaceMode === "acceptance" ||
|
||
workspaceMode === "clip-quality") &&
|
||
(detail.task.status === "accepted" || (!selectedClaimedByMe && !isManager))) ||
|
||
(!selectedClaimedByMe && !isManager) ||
|
||
combinedSubmissionProcessing
|
||
}
|
||
isQualityReview={
|
||
(workspaceMode === "quality" ||
|
||
workspaceMode === "acceptance" ||
|
||
workspaceMode === "clip-quality") &&
|
||
(selectedClaimedByMe || isManager) &&
|
||
detail.task.status !== "accepted"
|
||
}
|
||
reviewMode={workspaceMode === "acceptance" ? "acceptance" : "quality"}
|
||
reviewComment={
|
||
workspaceMode === "quality" ||
|
||
workspaceMode === "acceptance" ||
|
||
workspaceMode === "clip-quality"
|
||
? reviewComment
|
||
: ""
|
||
}
|
||
onReviewCommentChange={setReviewComment}
|
||
onApprove={
|
||
workspaceMode === "quality" ||
|
||
workspaceMode === "acceptance" ||
|
||
workspaceMode === "clip-quality"
|
||
? () => void review(workspaceMode === "acceptance" ? "acceptance" : "quality", "approved")
|
||
: undefined
|
||
}
|
||
onReject={
|
||
workspaceMode === "quality" ||
|
||
workspaceMode === "acceptance" ||
|
||
workspaceMode === "clip-quality"
|
||
? () => void review(workspaceMode === "acceptance" ? "acceptance" : "quality", "rejected")
|
||
: undefined
|
||
}
|
||
reworkNotice={reworkNotice}
|
||
onChange={updateSegments}
|
||
onPlayheadChange={setAnnotationPlayhead}
|
||
onSliceNameChange={updateSliceName}
|
||
onSliceDispositionChange={setSliceDisposition}
|
||
onSliceBoundaryChange={adjustSlice}
|
||
onSplitSlice={(sliceIndex, at) => {
|
||
setAnnotationPlayhead(at);
|
||
return splitSlice(sliceIndex, at);
|
||
}}
|
||
onDeleteSlice={deleteSlice}
|
||
onConfirmSlices={() => void confirmSlicesAndMaterialize()}
|
||
canConfirmSlices={
|
||
!sliceAlignmentIssue &&
|
||
sliceCoverage.complete &&
|
||
exactFrameEditing &&
|
||
sliceSegments.every(
|
||
(s) =>
|
||
frameBoundaryAligned(frameBoundaries, s.start) &&
|
||
frameBoundaryAligned(frameBoundaries, s.end),
|
||
) &&
|
||
!saving &&
|
||
selectedClaimedByMe
|
||
}
|
||
onConfirmAnnotations={confirmAnnotationDescription}
|
||
problemSliceIds={problemSliceIds}
|
||
onProblemSliceIdsChange={setProblemSliceIds}
|
||
onRequestReslice={() => setShowResliceWarning(true)}
|
||
claimLocked={releaseLocked && selectedClaimedByMe}
|
||
onReleaseTask={
|
||
releaseLocked || !selectedClaimedByMe || detail.task.status === "pending_quality"
|
||
? undefined
|
||
: () => void releaseSelectedTask()
|
||
}
|
||
onSubmitTask={() => void submitCombined()}
|
||
canSubmitTask={submissionCheck.canSubmit}
|
||
submissionBlockerReason={submissionCheck.reason}
|
||
saving={saving || combinedSubmissionProcessing}
|
||
initialSliceId={requestedSliceId}
|
||
onReturnToPool={() => selectTask("")}
|
||
/>
|
||
</div>
|
||
)}
|
||
</div>
|
||
) : prepackageAcceptanceItems.some((item) => item.id === expandedDeliveryPackageId) ? null : (
|
||
<div className="annotation-task-empty flex min-h-[560px] items-center justify-center text-sm text-gray-500">
|
||
{blindAnnotator && taskPoolView === "available"
|
||
? "选择项目并随机领取任务,领取成功后进入标注。"
|
||
: "选择一个任务进入时间轴编辑"}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{tab === "templates" ? (
|
||
<div className="grid gap-6 lg:grid-cols-[360px_1fr]">
|
||
{isManager ? (
|
||
<div className={`${panelClass} space-y-3 p-5`}>
|
||
<div className="text-base font-semibold text-white">创建模板版本</div>
|
||
<input
|
||
className={inputClass}
|
||
value={templateDraft.name}
|
||
onChange={(event) => setTemplateDraft((current) => ({ ...current, name: event.target.value }))}
|
||
/>
|
||
<input
|
||
className={inputClass}
|
||
type="number"
|
||
value={templateDraft.version}
|
||
onChange={(event) =>
|
||
setTemplateDraft((current) => ({ ...current, version: Number(event.target.value) }))
|
||
}
|
||
/>
|
||
<div className="rounded-lg border border-violet-500/20 bg-violet-500/5 px-3 py-2 text-xs leading-5 text-violet-100/80">
|
||
模板标签来自项目“语义标签”页启用的组织字典,不能在这里创建同名但含义不同的标签。
|
||
</div>
|
||
<textarea
|
||
className={inputClass}
|
||
value={templateDraft.phrases}
|
||
onChange={(event) => setTemplateDraft((current) => ({ ...current, phrases: event.target.value }))}
|
||
/>
|
||
<button
|
||
type="button"
|
||
onClick={() => void createTemplate()}
|
||
className="w-full rounded-lg bg-blue-600 px-3 py-2 text-sm text-white"
|
||
>
|
||
创建草稿
|
||
</button>
|
||
</div>
|
||
) : null}
|
||
<div className={`${panelClass} p-5`}>
|
||
<div className="grid gap-3 md:grid-cols-2">
|
||
{templates.map((item) => (
|
||
<div key={item.id} className="rounded-xl border border-[#2a2b2f] bg-[#101114] p-4">
|
||
<div className="flex justify-between">
|
||
<div className="font-medium text-white">
|
||
{item.name} v{item.version}
|
||
</div>
|
||
<span className="text-xs text-gray-500">{item.status}</span>
|
||
</div>
|
||
<div className="mt-3 flex flex-wrap gap-2">
|
||
{item.labels.map((label) => (
|
||
<span key={label.id} className="rounded-full bg-blue-500/10 px-2 py-1 text-xs text-blue-200">
|
||
{label.name}
|
||
</span>
|
||
))}
|
||
</div>
|
||
{isManager && item.status === "draft" ? (
|
||
<button
|
||
type="button"
|
||
onClick={() => annotationOperationsApi.publishTemplate(item.id).then(loadProject)}
|
||
className="mt-4 rounded-lg border border-emerald-500/30 px-3 py-1.5 text-xs text-emerald-200"
|
||
>
|
||
发布版本
|
||
</button>
|
||
) : null}
|
||
</div>
|
||
))}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{tab === "workload" ? (
|
||
<div className="space-y-5">
|
||
<div className="grid gap-3 md:grid-cols-5">
|
||
{[
|
||
["正式产出", workloadTotals.outputCount],
|
||
["返工", workloadTotals.reworkCount],
|
||
["通过", workloadTotals.approvedCount],
|
||
["拒绝", workloadTotals.rejectedCount],
|
||
["总工时", `${Math.round(workloadTotals.durationSeconds / 60)} min`],
|
||
].map(([label, value]) => (
|
||
<div key={String(label)} className={`${panelClass} p-4`}>
|
||
<div className="text-xs text-gray-500">{label}</div>
|
||
<div className="mt-2 text-2xl font-semibold text-white">{value}</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
<div className={`${panelClass} overflow-hidden`}>
|
||
<div className="grid grid-cols-[1.2fr_1fr_repeat(4,0.7fr)] gap-3 border-b border-[#2a2b2f] px-4 py-3 text-xs text-gray-500">
|
||
<span>用户</span>
|
||
<span>供应商</span>
|
||
<span>模板</span>
|
||
<span>产出</span>
|
||
<span>返工</span>
|
||
<span>工时</span>
|
||
</div>
|
||
{workload.items.map((item, index) => (
|
||
<div
|
||
key={`${item.userId}-${item.templateVersion}-${index}`}
|
||
className="grid grid-cols-[1.2fr_1fr_repeat(4,0.7fr)] gap-3 border-b border-[#202227] px-4 py-3 text-sm text-gray-300"
|
||
>
|
||
<span>{users.find((user) => user.id === item.userId)?.name || item.userId || "系统"}</span>
|
||
<span>{item.vendorId}</span>
|
||
<span>v{item.templateVersion}</span>
|
||
<span>{item.outputCount}</span>
|
||
<span>{item.reworkCount}</span>
|
||
<span>{Math.round(item.durationSeconds / 60)}m</span>
|
||
</div>
|
||
))}
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
|
||
{showResliceWarning ? (
|
||
<div
|
||
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/75 p-4"
|
||
role="dialog"
|
||
aria-modal="true"
|
||
aria-label="重新切片警告"
|
||
>
|
||
<div className="w-full max-w-lg rounded-2xl border border-red-500/35 bg-[#151619] p-6 shadow-2xl">
|
||
<div className="flex items-center gap-3 text-red-200">
|
||
<XCircle className="h-6 w-6" />
|
||
<h2 className="text-lg font-semibold">重新切片会丢失全部标注</h2>
|
||
</div>
|
||
<p className="mt-4 text-sm leading-6 text-gray-300">
|
||
当前 Capture 的所有 JSON 描述、无动作确认和标注进度都会被清空,并返回切片编辑。
|
||
</p>
|
||
<div className="mt-6 flex justify-end gap-3">
|
||
<button
|
||
type="button"
|
||
onClick={() => setShowResliceWarning(false)}
|
||
className="rounded-lg border border-[#34363b] px-4 py-2 text-sm text-gray-300"
|
||
>
|
||
取消
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => void resetToSliceEditing()}
|
||
disabled={saving}
|
||
className="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white disabled:opacity-40"
|
||
>
|
||
{saving ? "正在重置…" : "清空标注并重新切片"}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
);
|
||
}
|