droboticflow/src/pages/AnnotationOperations.tsx
2026-11-19 11:35:20 +08:00

8627 lines
389 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { reviewItemForSelection } from "../lib/review-item-selection.js";
import { isHumanPoolSummary } from "../types";
import { annotationTimelineFailure } from "../lib/annotation-source-validation.js";
import type { AnnotationTimelineFailure } from "../lib/annotation-source-validation";
// Keep the workbench rules ahead of the review framing rules, matching the
// order they had when both were pulled in by the global entry stylesheet.
import "../styles/capture-workspace.css";
import "../styles/review-workspace.css";
import { AcceptanceMisreports } from "../components/AcceptanceMisreports";
import { useReviewTrace, ReviewTracePanel, ReviewListTrace } from "../components/ReviewTrace";
import {
annotationGenerationConfirmationMode,
retryAnnotationGeneration,
prepareSavedAnnotationGeneration,
RECONFIRM_SAVED_GENERATION_LABEL,
} from "../lib/annotation-generation-retry.js";
import { createReviewDecisionCompletion } from "../lib/review-decision-completion.js";
import { createSliceEditSession, freezeSliceEditSession } from "../lib/slice-edit-session.js";
import { createAnnotationPersistence } from "../lib/annotation-persistence.js";
import { dictionarySelection } from "../lib/dictionary-selection";
import type { DictionarySelection } from "../types";
import { AnnotationWorkModeToggle } from "../components/AnnotationWorkModeToggle";
import { loadOwnedAnnotationProject, loadAnnotationPoolPage } from "../lib/annotation-project-loading.js";
import { FailedSliceRecoveryNotice } from "../components/FailedSliceRecoveryNotice";
import { initialAnnotationPool } from "../lib/annotation-landing.js";
import { sliceEditDispositionCommands } from "../lib/slice-edit-dispositions.js";
import { formatAnnotationTime } from "../lib/annotation-time.js";
/*
* AnnotationOperations.tsx — region map (grep anchors, NOT line numbers; keep in sync when regions move).
* This file is ~7k lines; navigate by anchor instead of reading end-to-end:
* - top-level flags & guards ......... `const reviewOnly` · `const projectPoolView` · `const reviewDraftGuardRef` / `leaveDraftGuard`
* - pool rendering & counts .......... `poolCounts` (tab counts; scope vs list filters live in src/lib/annotation-workbench.js)
* - random claim / notices ........... `setRandomClaimNotice`
* - task cards & claim handlers ...... `const claimPrepackageAcceptance` · `const toggleDeliveryPackageContents` · `releasePrepackageAcceptance`
* - decisions & saving token ......... `decidePrepackageAcceptance` · `savingOperationRef` (approve/reject + never-wedged reset)
* - acceptance workspace render ...... `<FinalAcceptanceWorkspace` (stats/draft/comment/onApprove wiring)
* - review session status bars ....... `review-session-status` · `review-decision-status` (pending-decision banner)
*/
import { ReviewHistorySummary } from "../components/ReviewHistorySummary";
import { userErrorMessage } from "../lib/user-error-message.js";
import { useReviewProjectScope } from "../hooks/useReviewProjectScope";
import { invalidSliceConsolidationCandidates } from "../lib/invalid-slice-consolidation.js";
import { ReviewDecisionDialog } from "../components/ReviewDecisionDialog";
import { useReviewContinuation } from "../hooks/useReviewContinuation";
import { useReviewEntryIntent } from "../hooks/useReviewEntryIntent";
import { reviewDecisionApi } from "../services/api/review-decision";
import { useReviewDecision, type ReviewDecisionRequest } from "../hooks/useReviewDecision";
import { ReviewProblemPanel } from "../components/ReviewProblemPanel";
import { useReworkReviewEmphasis } from "../hooks/useReworkReviewEmphasis";
import { useReworkEmphasis } from "../hooks/useReworkEmphasis";
import { reworkApi } from "../services/api/rework";
import { ReworkReceiveBanner } from "../components/ReworkReceiveBanner";
import { ReworkChangesPanel } from "../components/ReworkChangesPanel";
import { ReworkOpinionRail } from "../components/ReworkOpinionRail";
import { qcReworkWalk, reworkActionIndexOf, reworkSliceLabelOf } from "../lib/rework-review-rows.js";
import { stripTaskOpinionLines } from "../lib/task-scope-visibility.js";
import type { ReworkOpinionView } from "../lib/rework-emphasis-types";
import type { ReviewViewingController } from "../components/review-viewing";
import { useReviewDraft } from "../hooks/useReviewDraft";
import type { ReviewProblem } from "../services/api/review-draft";
import { APIError } from "../services/api/client";
import { useReviewSession } from "../hooks/useReviewSession";
import { completeActionPartitions } from "../lib/continuous-actions.js";
import React, { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAnnotationWorkspaceLayout } from "../context/AnnotationWorkspaceLayoutContext";
import { memberCanClaim, memberPoolEmptyReason } from "../lib/member-scope.js";
import { newAnnotationClaimRequestID } from "../lib/annotation-random-claim.js";
import { createAnnotationHistory } from "../lib/annotation-history.js";
import { useProjectDiscardReasons } from "../hooks/useProjectDiscardReasons";
import { useProjectSliceDictionary } from "../hooks/useProjectSliceDictionary";
import {
refillAnnotationWorkBuffer,
hasDirectedAnnotationRework,
reconcileAnnotationBufferSummaries,
} from "../lib/annotation-work-mode.js";
import { loadReviewClaimCandidates } from "../lib/review-claim-candidates.js";
import { useAnnotationWorkSession, type AnnotationWorkSession } from "../hooks/useAnnotationWorkSession";
import { alignSliceTimeline, initializeFrameAlignedSlices, sliceTimelineIssue } from "../lib/annotation-timeline.js";
import { resolveSliceEditConflicts } from "../lib/slice-edit-conflict.js";
import type { SliceEditAutoFollow, SliceEditChoice, SliceEditConflictEntry } from "../lib/slice-edit-conflict-types";
import { checkSliceEditResolution, planSliceEditDragRelease } from "../lib/slice-edit-drag-quick-path.js";
import { annotationTaskAction } from "../lib/annotation-task-action.js";
import { FinalAcceptanceWorkspace } from "../components/FinalAcceptanceWorkspace";
import { AcceptanceTaskCard } from "../components/AcceptanceTaskCard";
import { CaptureName } from "../components/CaptureName";
import { loadMoviPlayer } from "../lib/movi-player";
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,
summarizeWorkBuffer,
type AnnotationBufferSnapshot,
type AnnotationBufferSummary,
} from "../services/api/annotation-operations";
import { annotationEditorPhase } from "../lib/annotation-workspace.js";
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,
} from "../lib/annotation-operations.js";
import {
annotationDraftFromHumanItem,
annotationWorkspaceForAssignee,
annotationOrphanSegments,
applySliceStatuses,
deriveSliceStatuses,
filterAnnotationTasks,
nearestFrameBoundaryIndex,
normalizeAnnotationWorkspace,
normalizeFrameBoundaries,
parseSegmentCommentsFromText,
stepFrameBoundary,
summarizeSliceProgress,
sliceDictionaryNameIssue,
splitSliceAtBoundary,
cancelSlicePartition,
mergeSlicePartitions,
poolTabCounts,
sliceIndexAtPlayhead,
validateAnnotationWorkspace,
frameBoundaryAligned,
} from "../lib/annotation-workbench.js";
import {
autosaveSegmentsWithDrafts,
sliceEditSessionFlushEdge,
workbenchDraftsFingerprint,
reworkActionsWithDrafts,
sliceEditActionsWithDrafts,
} from "../lib/annotation-autosave.js";
import { useAnnotationAutosave } from "../hooks/useAnnotationAutosave";
import { getActionErrorMessage, recoverableGatewayStatus } from "../lib/action-errors.js";
import { combinedSubmissionState, combinedSubmissionFinished } from "../lib/annotation-submission-state.js";
import {
annotationWorkspaceMatches,
createAuthoritativeMutationContext,
createAuthoritativeMutationScope,
sliceResetWasApplied,
} from "../lib/annotation-authoritative-mutation.js";
import { artifactContentPath } from "../lib/artifact-download.js";
import {
CaptureAnnotationWorkbench,
type AnnotationDraft,
type AnnotationEditState,
type SliceEditor,
} from "../components/CaptureAnnotationWorkbench";
import { LazyVideoPreview } from "../components/LazyVideoPreview";
import { PageSubnav } from "../components/PageSubnav";
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,
captureTaskDisplayName,
uniqueCaptureDirectories,
} from "../lib/business-display.js";
import { BusinessExecutionPath } from "../components/BusinessExecutionPath";
// The workload report renders only after the "workload" tab is opened. Loading
// it on demand keeps its table, detail modal and workforce API out of the
// annotation first screen; Dashboard and ProductionQualityDashboard import the
// same module id, so Rollup emits one shared chunk for every call site.
const WorkforceStatisticsPanel = lazy(() =>
import("../components/WorkforceStatisticsPanel").then((module) => ({ default: module.WorkforceStatisticsPanel })),
);
type Tab = "queue" | "rejects" | "templates" | "workload";
type WorkspaceMode = "clip" | "clip-quality" | "annotate" | "quality" | "acceptance";
type TaskPoolView = "available" | "mine" | "all" | "reviewed";
type HumanPools = Record<TaskPoolView, HumanItem[]>;
type CombinedEditorPhase = "slice" | "materializing" | "annotate";
type AnnotationEditSnapshot = {
kind: "annotation";
state: AnnotationEditState;
persisted: {
sliceSegments: SliceSegment[];
operations: SliceOperation[];
segments: AnnotationSegment[];
statuses: Record<string, NonNullable<SliceSegment["annotationStatus"]>>;
};
};
type DispositionEditSnapshot = {
kind: "disposition";
sliceId: string;
disposition: "keep" | "discard";
name: string;
restoreNameFromVersion: number;
reason: { reason?: string; reasonLabelId?: string; reasonVersion?: number; reasonNote?: string };
location: { sliceId: string; time: number };
};
type SliceEditSnapshot = {
slices: SliceSegment[];
operations: SliceOperation[];
segments: AnnotationSegment[];
statuses: Record<string, NonNullable<SliceSegment["annotationStatus"]>>;
location: { sliceId: string; time: number };
};
// 票 05(spec §2 R2-Q3):结构快捷入口(拖动释放/悬停+拆分/垃圾桶合并)撞出冲突时
// 的待决改动集。base* 为扫描基线(拖动前/拆分前的工作区);pendingSlices 为释放点
// 预览结构;dragEdit 非空表示来自拖动——几何已预览到位,Esc 须整段回退到拖动前,
// 落定时整段手势 + 处置合并为一条可撤销历史(与旧处置卡同款承诺)。
// 票 06 起 slice 相提交式挪动(←/→ 与 Shift+←/→)同走此管线(单一处置入口)。
type SliceEditQuickConflict = {
frozen: ReturnType<typeof freezeSliceEditSession>;
taskId: string;
entries: SliceEditConflictEntry[];
autoFollows?: SliceEditAutoFollow[];
baseSlices: SliceSegment[];
baseSegments: AnnotationSegment[];
actions: AnnotationSegment[];
draftsFingerprint: string;
hasUnfinishedDrafts: boolean;
pendingSlices: SliceSegment[];
operation: Omit<SliceOperation, "before" | "after">;
anchorTime: number;
focusSliceId: string;
dragEdit: { before: SliceEditSnapshot; after?: SliceEditSnapshot } | null;
};
const idleAdminPoolFilters: Parameters<typeof annotationOperationsApi.adminPool>[0] = { pool: "available", limit: 200 };
const emptyHumanPools: HumanPools = { available: [], mine: [], all: [], reviewed: [] };
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 =
| "submitting"
| "submission_conflicted"
| "rework"
| "rework_review"
| "pending_quality"
| "pending_acceptance"
| "accepted"
| "slicing"
| "pending_annotation"
| "pending_slice"
| "available";
export const deriveDetailedTaskStatus = (
task: AnnotationTaskRecord,
humanItem?: HumanItem,
livePhase?: CombinedEditorPhase,
): DetailedTaskStatus => {
if (humanItem?.reviewHistoryStatus) return humanItem.reviewHistoryStatus;
if (humanItem?.status === "accepted" || task.status === "accepted") return "accepted";
if (humanItem?.pendingCombinedSubmissionId)
return combinedSubmissionState(humanItem) === "conflicted" ? "submission_conflicted" : "submitting";
// B03 返工复查徽标:退回后再送检的质检任务(spec §5.4-6 队列徽标,不新造队列)。
if (
Number(humanItem?.reviewRound || 0) > 0 &&
(humanItem?.currentStageId === "quality_review" ||
humanItem?.currentStageId === "prepackage_acceptance" ||
humanItem?.currentStageId === "acceptance")
)
return "rework_review";
if (
task.status === "pending_quality" ||
humanItem?.currentStageId === "quality_review" ||
humanItem?.status === "submitted"
) {
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 isOwnedRecoverableAnnotationItem(
item: Pick<HumanItem, "projectId" | "assignedUserId" | "legacyTaskId" | "status" | "currentStageId">,
projectId: string,
userId: string | undefined,
) {
return Boolean(
item.projectId === projectId &&
item.assignedUserId === userId &&
item.legacyTaskId &&
["claimed", "in_progress", "rework"].includes(item.status) &&
["annotation_combined", "semantic_annotation"].includes(item.currentStageId),
);
}
function readyBufferedItems(items: AnnotationBufferSummary[], processing: Record<string, { status: string }> = {}) {
const phase = (item: AnnotationBufferSummary) => ({ status: item.sliceStatus, phase: item.slicePhase });
return items
.filter(
(item) =>
!item.sourceValidationStatus &&
!item.pendingCombinedSubmissionId &&
processing[item.id]?.status !== "failed" &&
!["processing", "failed"].includes(phase(item)?.status || ""),
)
.sort(
(a, b) =>
Number(hasDirectedAnnotationRework([b])) - Number(hasDirectedAnnotationRework([a])) ||
Number(!(phase(a)?.status === "completed" || phase(a)?.phase === "annotate")) -
Number(!(phase(b)?.status === "completed" || phase(b)?.phase === "annotate")) ||
(a.claimedAt || "").localeCompare(b.claimedAt || ""),
);
}
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" })),
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-[11px] text-blue-700 dark: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 (poolView === "reviewed") return true;
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";
}
// Server-side stage pushdown mirrors humanItemVisibleInMode for the pool
// queries: the store skips the whole unassigned backlog before sorting.
function humanItemStageIdsForMode(mode: WorkspaceMode): string[] | undefined {
if (mode === "clip") return ["split_annotation", "cut_adjustment"];
if (mode === "clip-quality") return ["split_quality_review", "cut_review"];
if (mode === "quality") return ["quality_review", "semantic_review"];
if (mode === "acceptance") return ["acceptance", "prepackage_acceptance"];
// annotate keeps the unscoped pool: its pool rules include rework rows the
// simple stage pushdown would drop; annotator slowness is handled by the
// tasks window and the work-buffer, not the pool page.
return undefined;
}
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({ workPage = false }: { workPage?: boolean }) {
const { users, role, currentUser } = useUser();
const { layout: workspaceLayout } = useAnnotationWorkspaceLayout();
const { statuses: pluginStatuses } = usePlugins();
const { timeZone } = useTimeZone();
// Warm the vendored movi-player module as soon as the annotation pages open
// so <movi-player> is already defined when a task workbench mounts (the
// capture transport requires the element to answer HTMLMediaElement calls
// from its first render).
useEffect(() => {
loadMoviPlayer().catch(() => {
// The workbench falls back to the native direct path for this session.
});
}, []);
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 reviewFocused =
["quality", "clip-quality", "acceptance"].includes(workspaceMode) && searchParams.get("reviewFocus") === "1";
const [reviewViewportLatched, setReviewViewportLatched] = useState(false);
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 requestedAcceptanceId = searchParams.get("acceptanceId")?.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 [refreshingProject, setRefreshingProject] = useState(false);
const [reviewAuxiliaryError, setReviewAuxiliaryError] = useState("");
const [reviewAuxiliaryLoading, setReviewAuxiliaryLoading] = useState(false);
const loadedProjectScope = useRef("");
const skipClaimPoolReload = useRef("");
const [projects, setProjects] = useState<Project[]>([]);
const [workflows, setWorkflows] = useState<Workflow[]>([]);
const [projectId, setProjectId] = useState(requestedProjectId);
const workSession = useAnnotationWorkSession(currentUser?.id || "", projectId || requestedProjectId, workPage);
const [viewportSize, setViewportSize] = useState(() => ({ width: window.innerWidth, height: window.innerHeight }));
const viewportTooSmall =
(reviewFocused || (workPage && workspaceLayout === "focused")) &&
(viewportSize.width < 1413 || viewportSize.height < 615);
const viewportPaused =
viewportTooSmall || (reviewFocused && reviewViewportLatched) || (workPage && workSession.viewportSuspended);
// The 1413×615 bottom line is a review-workspace requirement in both
// layouts. Only review continuation consumes this gate; annotation pages
// keep the existing focused/workPage-only viewportPaused semantics.
const reviewWindowUndersized = viewportSize.width < 1413 || viewportSize.height < 615;
useEffect(() => {
if (reviewFocused && viewportTooSmall) setReviewViewportLatched(true);
}, [reviewFocused, viewportTooSmall]);
// Read the actual content area at dispatch boundaries too, before React's
// resize render. Existing request/session fences deliberately ignore this latch.
const viewportBlocksDispatch = () =>
workPage &&
(workSession.isViewportSuspended() ||
(workspaceLayout === "focused" && (window.innerWidth < 1413 || window.innerHeight < 615)));
useEffect(() => {
const measure = () => {
setViewportSize({ width: window.innerWidth, height: window.innerHeight });
if (workPage && workspaceLayout === "focused" && (window.innerWidth < 1413 || window.innerHeight < 615))
workSession.setViewportSuspended(true);
};
measure();
window.addEventListener("resize", measure);
return () => window.removeEventListener("resize", measure);
}, [workPage, workspaceLayout, workSession.active, workSession.setViewportSuspended]);
const [projectMembers, setProjectMembers] = useState<ProjectMember[]>([]);
const [templates, setTemplates] = useState<AnnotationTemplate[]>([]);
const [tasks, setTasks] = useState<AnnotationTaskRecord[]>([]);
const [humanPools, setHumanPools] = useState<HumanPools>(emptyHumanPools);
const [reviewPoolTotals, setReviewPoolTotals] = useState<{
scope: string;
counts: Record<TaskPoolView, number>;
} | null>(null);
const [reviewPoolCountError, setReviewPoolCountError] = useState("");
const [reviewPoolCountRevision, setReviewPoolCountRevision] = useState(0);
const [reviewPoolCountLoading, setReviewPoolCountLoading] = useState(false);
const [acceptancePoolDetail, setAcceptancePoolDetail] = useState<{ scope: string; item: HumanItem } | null>(null);
const [acceptancePoolDetailError, setAcceptancePoolDetailError] = useState("");
const [acceptanceDetailRetry, setAcceptanceDetailRetry] = useState(0);
// A URL task id is a selection, not ownership; deep-link previews retain their pool.
const defaultTaskPoolView = () =>
initialAnnotationPool({
role,
workspaceMode,
workPage,
hasSelection: Boolean(requestedTaskId || requestedAcceptanceId),
pool: searchParams.get("pool"),
}) as TaskPoolView;
const [taskPoolView, setTaskPoolView] = useState<TaskPoolView>(defaultTaskPoolView);
const [workload, setWorkload] = useState<AnnotationWorkloadSummary>({ items: [], eventCount: 0 });
const [rejectCursor, setRejectCursor] = useState("");
const [rejectNextCursor, setRejectNextCursor] = useState("");
const [rejectError, setRejectError] = useState("");
const [rejectLoading, setRejectLoading] = useState(false);
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 [stageRecovery, setStageRecovery] = useState<{
taskId: string;
userId: string;
kind: "slice" | "annotate";
message: string;
} | null>(null);
const [workbenchDrafts, setWorkbenchDrafts] = useState<AnnotationDraft[]>([]);
const workbenchHostRef = useRef<HTMLDivElement>(null);
const [taskSearch, setTaskSearch] = useState("");
const [adminSearch, setAdminSearch] = useState("");
const projectReadAbortRef = useRef<AbortController | null>(null);
const poolPageAbortRef = useRef<AbortController | null>(null);
const taskPoolCursorRef = useRef("");
const reviewPoolCursorsRef = useRef<Partial<Record<TaskPoolView, string>>>({});
const taskPoolFetchOwnerRef = useRef<symbol | null>(null);
const [taskPoolFetchBusy, setTaskPoolFetchBusy] = useState(false);
useEffect(
() => () => {
projectReadAbortRef.current?.abort();
poolPageAbortRef.current?.abort();
},
[],
);
const [adminPoolTotals, setAdminPoolTotals] = useState<{
scope: string;
counts: { available: number; mine: number; all: number };
} | null>(null);
const [annotatorTaskView, setAnnotatorTaskView] = useState<"active" | "submitted">("active");
const minePoolCursorRef = useRef("");
const [submittedHumanItems, setSubmittedHumanItems] = useState<HumanItem[]>([]);
const [taskStatusFilter, setTaskStatusFilter] = useState("all");
const [detail, setDetailState] = useState<AnnotationTaskDetail | null>(null);
const discardReasons = useProjectDiscardReasons(detail?.task.projectId, detail?.task.id);
const sliceDictionary = useProjectSliceDictionary(detail?.task.projectId, detail?.task.id);
const actionDictionary = useProjectSliceDictionary(detail?.task.projectId, detail?.task.id, "action");
const detailRef = useRef<AnnotationTaskDetail | null>(null);
const annotationMutationScopeRef = useRef(createAuthoritativeMutationScope());
useEffect(() => {
const leaveDocument = () => {
annotationMutationScopeRef.current.invalidate();
claimContextRef.current = { ...claimContextRef.current };
// pagehide follows an accepted native leave prompt. A BFCache restore
// must resume saved work just like reload, without reviving local drafts.
leaveDirtyRef.current = false;
annotationBaselineRef.current = "";
clearEditHistory();
setWorkbenchDrafts([]);
setDetail(null);
setSaving(false);
setStageRecovery(null);
setTaskDetailRefreshVersion((version) => version + 1);
};
window.addEventListener("pagehide", leaveDocument);
return () => {
window.removeEventListener("pagehide", leaveDocument);
annotationMutationScopeRef.current.invalidate();
};
}, []);
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("");
// Unlike local editor state, this remains the last authoritative workspace,
// including tasks initially loaded from revisions without a saved workspace.
const confirmedAnnotationWorkspaceRef = useRef<{
taskId: string;
workspace: AnnotationEditSnapshot["persisted"];
} | null>(null);
const [showBatchSliceEditor, setShowBatchSliceEditor] = useState(false);
const [sliceOperations, setSliceOperations] = useState<SliceOperation[]>([]);
const editHistoryRef = useRef(createAnnotationHistory());
const historyRevealRevisionRef = useRef(0);
const sliceDragEditRef = useRef<{ before: SliceEditSnapshot; after?: SliceEditSnapshot } | null>(null);
// 票 05:结构快捷入口的冲突清单待决集(03 引擎条目);非空即冻结其它边界改动。
const [sliceEditQuickConflict, setSliceEditQuickConflict] = useState<SliceEditQuickConflict | null>(null);
const sliceEditQuickApplyingRef = useRef<SliceEditQuickConflict | null>(null);
const [sliceEditAppliedRevision, setSliceEditAppliedRevision] = useState(0);
const [historyReveal, setHistoryReveal] = useState<{
sliceId: string;
time: number;
revision: number;
editor?: SliceEditor | null;
revealAnnotation?: { id: string; start: number };
} | null>(null);
const clearEditHistory = () => {
editHistoryRef.current.clear();
sliceDragEditRef.current = null;
// A phase change remounts the workbench. Clear its replay request in the
// same update so the new stage cannot restore the previous stage's editor.
setHistoryReveal(null);
};
// 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 [frameTimelineFailure, setFrameTimelineFailure] = useState<AnnotationTimelineFailure | null>(null);
const [sourceValidationRetryTask, setSourceValidationRetryTask] = 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");
useEffect(() => {
clearEditHistory();
}, [selectedTaskId, currentUser?.id, combinedEditorPhase, detail?.humanItem?.currentStageId]);
const [taskDetailRefreshVersion, setTaskDetailRefreshVersion] = useState(0);
// 票 06(D1 修订版):首标「重新切片」警告弹窗与核对态(提交结果未知时驻留)。
const [showResliceWarning, setShowResliceWarning] = useState(false);
const [resetToUnifiedRange, setResetToUnifiedRange] = useState(true);
const [resliceError, setResliceError] = useState("");
const [pendingReslice, setPendingReslice] = useState<{
taskId: string;
version: number;
resetToUnifiedRange: boolean;
} | null>(null);
const projectLoadRequestRef = useRef(0);
useEffect(
() => () => {
++projectLoadRequestRef.current;
},
[],
);
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 [sidebarReadyScope, setSidebarReadyScope] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [projectLoadError, setProjectLoadError] = useState("");
const [taskPoolReadError, setTaskPoolReadError] = useState("");
const [projectLoadRecoveryNotice, setProjectLoadRecoveryNotice] = useState("");
const [combinedSubmissionNotice, setCombinedSubmissionNotice] = useState("");
// Acceptance-fixes defect 4/5: a dirty review draft used to make 开始/继续审查,
// 返回任务池 and other-task clicks die SILENTLY (canLeave()=false with the
// message buried in the aside). This page-level notice echoes the block right
// where the user clicked, with the way out.
const [draftGuardNotice, setDraftGuardNotice] = useState("");
const leaveDraftGuard = (action: string) => {
if (reviewDraftGuardRef.current()) {
setDraftGuardNotice("");
return true;
}
setDraftGuardNotice(`还有意见未保存:请先在右侧意见面板保存或取消修改,再${action}。`);
return false;
};
const [processingNotice, setProcessingNotice] = useState("");
const [projectLoadRetryVersion, setProjectLoadRetryVersion] = useState(0);
const submittedItemIdsRef = useRef<Set<string>>(new Set());
const reviewDraftGuardRef = useRef<() => boolean>(() => true);
// Monotonic token for the shared `saving` flag: a finishing operation only
// clears the flag when no newer operation started. Unlike the old
// projectDataScope guard, this cannot leave `saving` wedged on after the
// scope changed mid-request (acceptance-fixes defect 6: every button on the
// page stayed disabled until reload).
const savingOperationRef = useRef(0);
const setSelectedAnnotationTaskId = useCallback((nextTaskId: string) => {
if (!reviewDraftGuardRef.current()) return;
const currentContext = annotationMutationContextRef.current.current();
if (
annotationMutationContextRef.current.switchTo({
taskId: nextTaskId,
userId: currentContext.userId,
})
) {
++taskDetailRequestRef.current;
sliceEditQuickApplyingRef.current = null;
sliceDragEditRef.current = null;
setSliceEditQuickConflict(null);
setSaving(false);
setError("");
setCombinedSubmissionNotice("");
setProcessingNotice("");
setStageRecovery(null);
setRandomClaimNotice("");
}
setSelectedTaskId(nextTaskId);
}, []);
const [previewTab, setPreviewTab] = useState<"video" | "rerun">("video");
const isManager = isOrganizationAdminRole(role);
const reviewOnly =
!isManager && (workspaceMode === "quality" || workspaceMode === "clip-quality" || workspaceMode === "acceptance");
const acceptanceWorkspace = workspaceMode === "acceptance";
const deferReviewReports = reviewOnly || acceptanceWorkspace;
// Review pools retain independent pages; changing tabs reuses their rows.
const projectPoolView = deferReviewReports ? "all" : taskPoolView;
const managerAnnotationPool = isManager && workspaceMode === "annotate";
const pagedReviewPool = reviewOnly || acceptanceWorkspace;
useEffect(() => {
if (!managerAnnotationPool && !pagedReviewPool) return;
const timer = window.setTimeout(() => setAdminSearch(taskSearch.trim()), 350);
return () => window.clearTimeout(timer);
}, [managerAnnotationPool, pagedReviewPool, taskSearch]);
const managerPoolFilters = useMemo(
() =>
managerAnnotationPool
? {
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
nodeId: requestedNodeId || undefined,
artifactId: requestedArtifactId || undefined,
capture: requestedCaptureDirectory || undefined,
pool: (taskPoolView === "mine" || taskPoolView === "all" ? taskPoolView : "available") as
| "available"
| "mine"
| "all",
search: adminSearch || undefined,
category: taskStatusFilter,
limit: 200,
}
: idleAdminPoolFilters,
[
managerAnnotationPool,
projectId,
requestedWorkflowId,
requestedRunId,
requestedNodeId,
requestedArtifactId,
requestedCaptureDirectory,
taskPoolView,
adminSearch,
taskStatusFilter,
],
);
const projectDataScope = JSON.stringify([
currentUser?.id,
role,
projectId,
workspaceMode,
requestedArtifactId,
requestedNodeId,
requestedRunId,
requestedWorkflowId,
annotatorTaskView,
...(managerAnnotationPool ? [managerPoolFilters] : []),
...(pagedReviewPool ? [adminSearch, taskStatusFilter, requestedCaptureDirectory] : []),
]);
useEffect(() => {
if (!pagedReviewPool) {
setReviewPoolCountError("");
setReviewPoolCountLoading(false);
return;
}
const controller = new AbortController();
setReviewPoolCountError("");
setReviewPoolCountLoading(true);
void humanLoopApi
.poolCounts(
{
pluginId: "annotation-qa",
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
search: adminSearch || undefined,
capture: requestedCaptureDirectory || undefined,
category: taskStatusFilter,
stageIds: acceptanceWorkspace
? ["acceptance", "prepackage_acceptance"]
: humanItemStageIdsForMode(workspaceMode),
reviewedStageIds: acceptanceWorkspace ? ["acceptance", "prepackage_acceptance"] : undefined,
},
{ signal: controller.signal },
)
.then((result) => {
if (controller.signal.aborted) return;
if (
!["available", "mine", "reviewed", ...(isManager ? ["all"] : [])].every(
(key) => Number.isInteger(result.counts?.[key]) && result.counts[key] >= 0,
)
)
throw new Error("Incomplete task counts");
setReviewPoolTotals({ scope: projectDataScope, counts: result.counts });
})
.catch(() => {
if (!controller.signal.aborted) {
setReviewPoolTotals(null);
setReviewPoolCountError("任务数量暂时无法读取");
}
})
.finally(() => {
if (!controller.signal.aborted) setReviewPoolCountLoading(false);
});
return () => controller.abort();
}, [pagedReviewPool, projectDataScope, humanPools, reviewPoolCountRevision]);
const reviewPoolViewRef = useRef(taskPoolView);
reviewPoolViewRef.current = taskPoolView;
const reviewActionScopeRef = useRef(projectDataScope);
if (reviewActionScopeRef.current !== projectDataScope) skipClaimPoolReload.current = "";
reviewActionScopeRef.current = projectDataScope;
const reviewActionContextRef = useRef({ scope: projectDataScope });
if (reviewActionContextRef.current.scope !== projectDataScope)
reviewActionContextRef.current = { scope: projectDataScope };
const reviewActionContext = reviewActionContextRef.current;
const reviewSelectionRef = useRef({ task: selectedTaskId, acceptance: expandedDeliveryPackageId });
reviewSelectionRef.current = { task: selectedTaskId, acceptance: expandedDeliveryPackageId };
const blindAnnotator = role === "annotator" && (workspaceMode === "annotate" || workspaceMode === "clip");
const sidebarLoading = blindAnnotator ? sidebarReadyScope !== projectDataScope && !projectLoadError : loading;
const releaseLocked = role === "annotator" || role === "quality_reviewer" || role === "acceptance_reviewer";
const [claimableCount, setClaimableCount] = useState<{ projectId: string; count: number | null }>({
projectId: "",
count: null,
});
const requestedReviewItemOwned = Boolean(
currentUser?.id &&
(requestedTaskId
? humanPools.mine.some((item) => item.legacyTaskId === requestedTaskId) ||
(detail?.task.id === requestedTaskId && detail.humanItem?.assignedUserId === currentUser.id)
: requestedAcceptanceId && humanPools.mine.some((item) => item.id === requestedAcceptanceId)),
);
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 || workPage)) {
setTaskPoolView((current) => (current === "reviewed" ? current : "mine"));
return;
}
if (reviewOnly && (requestedTaskId || requestedAcceptanceId) && requestedReviewItemOwned)
setTaskPoolView((current) => (current === "reviewed" ? current : "mine"));
}, [blindAnnotator, reviewOnly, requestedTaskId, requestedAcceptanceId, workPage, requestedReviewItemOwned]);
const [randomClaimBusy, setRandomClaimBusy] = useState(false);
const humanPoolsSnapshotRef = useRef(humanPools);
humanPoolsSnapshotRef.current = humanPools;
const [workBuffer, setWorkBuffer] = useState<AnnotationBufferSnapshot>({
enabled: false,
capacity: 2,
occupied: 0,
summaries: [],
});
useEffect(() => {
setWorkBuffer({ enabled: false, capacity: 2, occupied: 0, summaries: [] });
}, [projectId, currentUser?.id]);
const bufferReadEpochRef = useRef(0);
const bufferManagedIdsRef = useRef(new Set<string>());
const [externalBufferTaskId, setExternalBufferTaskId] = useState<string | null>(null);
useEffect(() => {
++bufferReadEpochRef.current;
bufferManagedIdsRef.current = new Set();
setExternalBufferTaskId(null);
}, [projectId, currentUser?.id]);
const bufferFlight = useRef(false);
const explicitBufferTask = useRef(requestedTaskId || "");
const [capacityBusy, setCapacityBusy] = useState(false);
const randomClaimFlight = useRef(false);
const reviewRandomClaimFlight = useRef(false);
const workEntryFlight = useRef(false);
const viewportDeferredEntryRef = useRef<{ resumeOnly: boolean; isCurrent: () => boolean } | null>(null);
const [workEntryBusy, setWorkEntryBusy] = useState(false);
const randomClaimKeys = useRef<Record<string, string>>({});
const [nextAfterHandoff, setNextAfterHandoff] = useState("");
const handledHandoffs = useRef(new Set<string>());
// Browser/account/project receipts survive tab closure. sessionStorage is
// retained for older-page compatibility; durable storage is required
// before sending a new request whose server result might become unknown.
const pendingClaimRequest = (key: string) =>
localStorage.getItem(key) || randomClaimKeys.current[key] || sessionStorage.getItem(key) || "";
const forgetClaimRequest = (key: string, requestId: string) => {
if (randomClaimKeys.current[key] === requestId) delete randomClaimKeys.current[key];
if (localStorage.getItem(key) === requestId) localStorage.removeItem(key);
if (sessionStorage.getItem(key) === requestId) sessionStorage.removeItem(key);
};
const [randomClaimNotice, setRandomClaimNotice] = useState("");
const claimPermissionRef = useRef(false);
const claimContextRef = useRef({ userId: currentUser?.id, projectId, locationKey: location.key, role });
if (
claimContextRef.current.userId !== currentUser?.id ||
claimContextRef.current.projectId !== projectId ||
claimContextRef.current.locationKey !== location.key ||
claimContextRef.current.role !== role
) {
claimContextRef.current = { userId: currentUser?.id, projectId, locationKey: location.key, role };
}
useEffect(
() => () => {
// A pending entry cannot navigate from an unmounted page, even if the
// next page has the same account, project and selected task.
claimContextRef.current = { ...claimContextRef.current };
},
[],
);
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);
claimPermissionRef.current = blindAnnotator && canAccessWorkspace;
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 ||
(blindAnnotator ? nextProjects[0]?.id : "") ||
"",
);
} catch (loadError) {
setError(getActionErrorMessage(loadError, "加载标注运营基础数据失败"));
} finally {
setLoading(false);
}
}, [requestedProjectId, blindAnnotator]);
const loadProject = useCallback(async () => {
if (reviewActionScopeRef.current !== projectDataScope) return;
const requestID = ++projectLoadRequestRef.current;
const controller = new AbortController();
const current = () =>
!controller.signal.aborted &&
requestID === projectLoadRequestRef.current &&
reviewActionScopeRef.current === projectDataScope &&
(!pagedReviewPool || reviewPoolViewRef.current === taskPoolView);
// A refresh supersedes pagination even when the project ID stays the same.
taskPoolFetchOwnerRef.current = null;
setTaskPoolFetchBusy(false);
taskPoolCursorRef.current = "";
minePoolCursorRef.current = "";
reviewPoolCursorsRef.current = {};
setTaskPoolReadError("");
projectReadAbortRef.current?.abort();
poolPageAbortRef.current?.abort();
projectReadAbortRef.current = controller;
const foreground = !deferReviewReports || loadedProjectScope.current !== projectDataScope;
setLoading(foreground);
setRefreshingProject(!foreground);
setProjectLoadError("");
if (managerAnnotationPool || pagedReviewPool) {
setHumanPools(emptyHumanPools);
setTasks([]);
}
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,
templates: nextTemplates,
workflows: nextWorkflows,
} = await loadOwnedAnnotationProject({
projectId,
projects: projectsApi,
human: humanLoopApi,
annotation: annotationOperationsApi,
isCurrent: current,
signal: controller.signal,
annotationView: annotatorTaskView,
workflowId: requestedWorkflowId,
runId: requestedRunId,
onTasks: ({ mine, tasks: nextTasks }: { mine: HumanItem[]; tasks: AnnotationTaskRecord[] }) => {
if (!current()) return;
setTasks(nextTasks);
if (annotatorTaskView === "submitted") setSubmittedHumanItems(mine);
else setHumanPools({ available: [], mine, all: [], reviewed: [] });
setSidebarReadyScope(projectDataScope);
},
onPage: (page: { nextCursor?: string }) => {
minePoolCursorRef.current = page.nextCursor || "";
},
onCount: (count: number | null) => setClaimableCount({ projectId, count }),
});
if (!current()) return;
setProjectMembers(members);
setTemplates(nextTemplates);
setWorkflows(nextWorkflows);
projectLoadRecoveryAttemptRef.current = 0;
if (projectLoadRecoveryTimerRef.current !== null) {
window.clearTimeout(projectLoadRecoveryTimerRef.current);
projectLoadRecoveryTimerRef.current = null;
}
setProjectLoadRecoveryNotice("");
loadedProjectScope.current = projectDataScope;
return;
}
// Only the legacy non-manager project view needs cross-project metadata.
// Review eligibility and enriched names come from the server pool entries.
const fanOutProjectScope = !projectId && !isManager && !reviewOnly;
const knownProjects = fanOutProjectScope ? (projects.length > 0 ? projects : await projectsApi.list()) : [];
if (!current()) return;
const poolsRequest = loadAnnotationPoolPage({
annotation: annotationOperationsApi,
human: humanLoopApi,
scope: {
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
nodeId: requestedNodeId || undefined,
artifactId: requestedArtifactId || undefined,
},
view: managerAnnotationPool
? { kind: "admin", filters: managerPoolFilters }
: {
kind: pagedReviewPool ? "review" : "workspace",
pool: pagedReviewPool ? taskPoolView : undefined,
search: adminSearch,
capture: requestedCaptureDirectory,
category: taskStatusFilter,
acceptance: acceptanceWorkspace,
userId: currentUser?.id || "",
isManager,
reviewOnly,
trace: reviewOnly,
stageIds: humanItemStageIdsForMode(workspaceMode),
limit: taskPageLimit,
},
signal: controller.signal,
});
const [nextProjectMembers, nextWorkflows, nextTemplates, poolPage, nextWorkload, nextPackages, nextScopedRun] =
await Promise.all([
projectId
? projectsApi.listMembers(projectId, { signal: controller.signal })
: fanOutProjectScope
? Promise.allSettled(
knownProjects.map((p) => projectsApi.listMembers(p.id, { signal: controller.signal })),
).then((results) => results.flatMap((r) => (r.status === "fulfilled" ? r.value : [])))
: Promise.resolve([] as ProjectMember[]),
projectId
? projectsApi.listWorkflows(projectId, { signal: controller.signal })
: fanOutProjectScope
? Promise.allSettled(
knownProjects.map((p) => projectsApi.listWorkflows(p.id, { signal: controller.signal })),
).then((results) => results.flatMap((r) => (r.status === "fulfilled" ? r.value : [])))
: Promise.resolve([] as Workflow[]),
annotationOperationsApi.listTemplates(projectId || undefined, { signal: controller.signal }),
poolsRequest,
deferReviewReports
? Promise.resolve(null)
: annotationOperationsApi.workloadSummary(projectId || undefined, { signal: controller.signal }),
reviewOnly && workspaceMode !== "acceptance"
? Promise.resolve([] as DeliveryPackage[])
: deliveryPackagesApi.list(
{
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
status: projectPoolView === "all" ? undefined : "pending_acceptance",
},
{ signal: controller.signal },
),
isManager && requestedRunId ? runsApi.get(requestedRunId) : Promise.resolve(null),
]);
if (!current()) return;
const { tasks: nextTasks, pools: nextHumanPools } = poolPage;
taskPoolCursorRef.current = poolPage.taskCursor;
minePoolCursorRef.current = poolPage.mineCursor;
if (poolPage.poolCursors) reviewPoolCursorsRef.current = poolPage.poolCursors;
if (poolPage.counts) setAdminPoolTotals({ scope: projectDataScope, counts: poolPage.counts });
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: nextHumanPools.available.filter((i) => !submittedItemIdsRef.current.has(i.id)),
mine: nextHumanPools.mine.map((i) =>
submittedItemIdsRef.current.has(i.id) ? { ...i, status: "ready", currentStageId: "quality_review" } : i,
),
all: nextHumanPools.all,
reviewed: nextHumanPools.reviewed,
});
if (nextWorkload) setWorkload(nextWorkload);
setDeliveryPackages(nextPackages);
setScopedRun(nextScopedRun);
loadedProjectScope.current = projectDataScope;
projectLoadRecoveryAttemptRef.current = 0;
if (projectLoadRecoveryTimerRef.current !== null) {
window.clearTimeout(projectLoadRecoveryTimerRef.current);
projectLoadRecoveryTimerRef.current = null;
}
setProjectLoadRecoveryNotice("");
setProjectLoadError("");
} catch (loadError) {
if (!current()) return;
workSession.pauseContinuous("项目任务状态暂时无法核对;连续工作已暂停,请恢复连接后继续。");
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 (current()) {
setLoading(false);
setRefreshingProject(false);
}
}
}, [
currentUser?.id,
blindAnnotator,
projectId,
isManager,
projectDataScope,
reviewOnly,
acceptanceWorkspace,
deferReviewReports,
workspaceMode,
requestedArtifactId,
requestedNodeId,
requestedRunId,
requestedWorkflowId,
projectPoolView,
annotatorTaskView,
managerAnnotationPool,
managerPoolFilters,
pagedReviewPool,
taskPoolView,
adminSearch,
requestedCaptureDirectory,
taskStatusFilter,
]);
useEffect(() => {
if (!deferReviewReports) return;
let disposed = false;
setReviewAuxiliaryError("");
setReviewAuxiliaryLoading(true);
const reports = [];
if (tab === "workload")
reports.push(
annotationOperationsApi.workloadSummary(projectId || undefined).then((value) => {
if (!disposed) setWorkload(value);
}),
);
void Promise.allSettled(reports).then((results) => {
if (disposed) return;
setReviewAuxiliaryLoading(false);
if (results.some((r) => r.status === "rejected"))
setReviewAuxiliaryError("工作记录暂未加载完成,请刷新重试;当前任务可继续查看。");
});
return () => {
disposed = true;
};
}, [deferReviewReports, acceptanceWorkspace, projectDataScope, tab, projectLoadRetryVersion]);
useEffect(() => {
setRejectCursor("");
setRejectNextCursor("");
setRejects([]);
}, [projectDataScope]);
useEffect(() => {
if (tab !== "rejects") return;
let active = true;
setRejectLoading(true);
setRejectError("");
setRejects([]);
setRejectNextCursor("");
humanLoopApi
.listRejectsPage({
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
cursor: rejectCursor || undefined,
})
.then((result) => {
if (active) {
setRejects(result.items);
setRejectNextCursor(result.nextCursor);
}
})
.catch(() => {
if (active) setRejectError("退回记录加载失败,请重试。");
})
.finally(() => {
if (active) setRejectLoading(false);
});
return () => {
active = false;
};
}, [tab, projectDataScope, projectId, requestedWorkflowId, requestedRunId, rejectCursor, projectLoadRetryVersion]);
const applyReviewClaim = (item: HumanItem) => {
// The claim response is authoritative. Do not start a queue reload that
// would compete with detail/evidence requests for browser connections.
if (!acceptanceWorkspace && taskPoolView !== "mine") skipClaimPoolReload.current = projectDataScope;
++projectLoadRequestRef.current;
projectReadAbortRef.current?.abort();
poolPageAbortRef.current?.abort();
setLoading(false);
setRefreshingProject(false);
setDetail((current) =>
current?.humanItem?.id === item.id
? { ...current, humanItem: item, task: { ...current.task, assignedUserId: item.assignedUserId } }
: current,
);
setHumanPools((current) => ({
...current,
available: current.available.filter((i) => i.id !== item.id),
mine: [item, ...current.mine.filter((i) => i.id !== item.id)],
all: current.all.map((i) => (i.id === item.id ? item : i)),
}));
};
const retireReviewedItem = (itemId: string, taskId?: string) => {
++projectLoadRequestRef.current;
setHumanPools((current) => ({
...current,
available: current.available.filter((i) => i.id !== itemId),
mine: current.mine.filter((i) => i.id !== itemId),
all: current.all,
}));
if (taskId) setTasks((current) => current.filter((t) => t.id !== taskId));
setExpandedDeliveryPackageId((current) => (current === itemId ? "" : current));
};
useEffect(() => {
++projectLoadRequestRef.current;
++taskDetailRequestRef.current;
annotationMutationScopeRef.current.invalidate();
setSaving(false);
submittedItemIdsRef.current.clear();
setTasks([]);
setHumanPools(emptyHumanPools);
setSubmittedHumanItems([]);
setDetail(null);
setSelectedAnnotationTaskId("");
setReviewComment("");
setProblemSliceIds([]);
setTaskPoolView(defaultTaskPoolView());
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(() => {
if (skipClaimPoolReload.current === projectDataScope && taskPoolView === "mine") {
skipClaimPoolReload.current = "";
return;
}
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;
const initialWorkspace = confirmedAnnotationWorkspaceRef.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" });
setFrameTimelineFailure(null);
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);
if (
allowDefault &&
initialWorkspace?.taskId === task.id &&
confirmedAnnotationWorkspaceRef.current === initialWorkspace
) {
const workspace = initialWorkspace.workspace;
const baseline = annotationWorkspaceFingerprint(
workspace.sliceSegments,
workspace.operations,
workspace.segments,
workspace.statuses,
);
if (annotationBaselineRef.current === baseline) {
// Frame alignment initializes the system default; it is not a user
// edit. Rebase only the loaded snapshot, never absorb live edits.
const aligned = initializeFrameAlignedSlices(workspace.sliceSegments, initial, timeline, true);
annotationBaselineRef.current = annotationWorkspaceFingerprint(
aligned,
workspace.operations,
workspace.segments,
deriveSliceStatuses(aligned, workspace.segments, workspace.statuses),
);
}
}
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" });
setFrameTimelineFailure(annotationTimelineFailure(cause));
} finally {
parentSignal?.removeEventListener("abort", abort);
}
},
[],
);
useEffect(() => () => timelineAbortRef.current?.abort(), []);
const retrySourceValidation = async () => {
const task = detail?.task;
if (!task || !frameTimelineFailure?.retryAllowed || sourceValidationRetryTask) return;
if (!window.confirm("确认源数据已修复,并重新校验?现有标注保持不变。")) return;
setSourceValidationRetryTask(task.id);
try {
await annotationOperationsApi.retrySourceValidation(task.id);
if (selectedTaskDetailIDRef.current === task.id) await loadFrameTimeline(task);
} catch (cause) {
if (selectedTaskDetailIDRef.current === task.id) {
setTimelineState({ taskId: task.id, status: "error" });
setFrameTimelineFailure(annotationTimelineFailure(cause));
}
} finally {
setSourceValidationRetryTask((current) => (current === task.id ? "" : current));
}
};
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);
setFrameTimelineFailure(null);
setCombinedEditorPhase("slice");
annotationBaselineRef.current = "";
confirmedAnnotationWorkspaceRef.current = null;
return;
}
const controller = new AbortController();
const switchingTask = selectedTaskDetailIDRef.current !== selectedTaskId;
selectedTaskDetailIDRef.current = selectedTaskId;
if (switchingTask) {
confirmedAnnotationWorkspaceRef.current = null;
setDetail(null);
setSegments([]);
setSliceSegments([]);
setSliceStatuses({});
setAnnotationPlayhead(0);
setFrameTimeline(null);
setFrameTimelineFailure(null);
setCombinedEditorPhase("slice");
}
annotationOperationsApi
.getTask(selectedTaskId, controller.signal, taskPoolView === "reviewed")
.then((next) => {
if (
controller.signal.aborted ||
requestID !== taskDetailRequestRef.current ||
annotationMutationScopeRef.current.busy() ||
(!switchingTask && leaveDirtyRef.current)
)
return;
if (
detailRef.current?.task.id === next.task.id &&
detailRef.current.humanItem &&
next.humanItem &&
next.humanItem.version < detailRef.current.humanItem.version
)
return;
const savedWorkspace = annotationWorkspaceForAssignee(next.humanItem, currentUser?.id);
const discardedWorkspace = Boolean(
(next.humanItem?.subject?.payload?.sliceWorkflow as { discardedWorkspace?: boolean } | undefined)
?.discardedWorkspace,
);
let nextAnnotations = savedWorkspace
? savedWorkspace.segments
: discardedWorkspace
? []
: humanEditableAnnotationSegments(next.revisions);
const nextSlices = initialCaptureSlices(
next.task,
discardedWorkspace ? [] : next.sliceRevisions,
savedWorkspace?.sliceSegments,
).map((slice) => ({
...slice,
name: slice.deliveryDisposition === "discard" ? "" : slice.name?.trim() || "",
...(next.task.templateVersion >= 6 ? { taskLabelId: undefined, taskLabel: undefined } : {}),
}));
const nextOperations = savedWorkspace?.operations ?? [];
let nextStatuses = deriveSliceStatuses(nextSlices, nextAnnotations, savedWorkspace?.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 = annotationEditorPhase(next);
if (
next.task.continuousActions &&
nextPhase === "annotate" &&
next.humanItem?.assignedUserId === currentUser?.id &&
["claimed", "in_progress", "rework"].includes(next.humanItem.status)
) {
nextAnnotations = completeActionPartitions(nextSlices, nextAnnotations);
nextStatuses = deriveSliceStatuses(nextSlices, nextAnnotations, nextStatuses) as typeof nextStatuses;
}
confirmedAnnotationWorkspaceRef.current = {
taskId: next.task.id,
workspace: structuredClone(
annotationDraftFromHumanItem(next.humanItem) || {
sliceSegments: nextSlices,
operations: nextOperations,
segments: nextAnnotations,
statuses: nextStatuses,
},
),
};
setDetail(next);
setStageRecovery(null);
setSegments(nextAnnotations);
setSliceSegments(nextSlices);
setSliceOperations(nextOperations);
setSliceStatuses(nextStatuses);
setAnnotationPlayhead(nextSlices[0]?.start ?? next.task.clipStart ?? 0);
setCombinedEditorPhase(nextPhase);
if (next.humanItem) {
setHumanPools((current) => ({
...current,
available: current.available.map((item) =>
item.id === next.humanItem?.id
? {
...next.humanItem!,
reviewHistoryStatus: item.reviewHistoryStatus,
reviewHistory: item.reviewHistory,
}
: item,
),
mine: current.mine.map((item) =>
item.id === next.humanItem?.id
? {
...next.humanItem!,
reviewHistoryStatus: item.reviewHistoryStatus,
reviewHistory: item.reviewHistory,
}
: item,
),
all: current.all.map((item) =>
item.id === next.humanItem?.id
? {
...next.humanItem!,
reviewHistoryStatus: item.reviewHistoryStatus,
reviewHistory: item.reviewHistory,
}
: item,
),
}));
}
annotationBaselineRef.current = annotationWorkspaceFingerprint(
nextSlices,
nextOperations,
nextAnnotations,
nextStatuses,
);
clearEditHistory();
setProblemSliceIds([]);
setShowBatchSliceEditor(nextPhase === "slice");
if (sliceWorkflow?.status === "failed") {
if (!next.task.continuousActions) workSession.pauseContinuous("切片生成失败;请处理后恢复连续工作。");
setRandomClaimNotice("切片生成失败;该任务保留占位,可重试或继续其他任务。");
setError(`切片生成失败:${sliceWorkflow.error || "请核对当前切片后重试"}`);
} else {
setError((current) => (/^(切片生成失败|切片状态已更新|切片进度暂时无法读取)/.test(current) ? "" : current));
setRandomClaimNotice((current) => (current.startsWith("切片生成失败") ? "" : current));
}
if (switchingTask || timelineState.status !== "ready" || timelineState.taskId !== next.task.id)
void loadFrameTimeline(
next.task,
nextSlices,
!savedWorkspace &&
!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, "加载标注任务详情失败");
workSession.pauseContinuous(`无法读取当前任务:${msg};连续工作已暂停。`);
if (!workPage && msg.includes("current human stage role is required")) {
closeTaskAndReturnToPool();
} else {
setError(msg);
}
}
});
return () => controller.abort();
}, [currentUser?.id, selectedTaskId, taskPoolView, taskDetailRefreshVersion, loadFrameTimeline]);
const sliceGenerationFailed =
(detail?.humanItem?.subject?.payload?.sliceWorkflow as { status?: string } | undefined)?.status === "failed";
useEffect(() => {
if ((!sliceGenerationFailed && combinedEditorPhase !== "materializing") || !selectedTaskId) return;
const delay = sliceGenerationFailed ? 10_000 : 2_000;
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: "校验源数据",
waiting_source: "等待源数据校验资源",
slicing: "生成或复用切片",
publishing: "写入审核数据",
};
setProcessingNotice(
status.progress
? `${labels[status.progress.stage] || "正在处理"} · ${status.progress.completedSlices}/${status.progress.totalSlices} 个切片`
: "正在处理,等待后台结果",
);
const changed = sliceGenerationFailed
? Boolean(status.sliceStatus) && status.sliceStatus !== "failed"
: status.sliceStatus !== "processing" || status.needsRefresh;
if (changed && !annotationMutationScopeRef.current.busy()) {
if (leaveDirtyRef.current) {
setError("切片状态已更新,请先保存当前编辑后同步。");
} else {
setTaskDetailRefreshVersion((current) => current + 1);
return;
}
}
} catch {
if (controller.signal.aborted) return;
workSession.pauseContinuous("切片处理结果暂未确认;连续工作已暂停,当前任务保留。");
setError("切片进度暂时无法读取,正在重试;不会重复提交切片。");
}
timer = setTimeout(poll, delay);
};
timer = setTimeout(poll, delay);
return () => {
controller.abort();
clearTimeout(timer);
};
}, [combinedEditorPhase, selectedTaskId, taskDetailRefreshVersion, sliceGenerationFailed]);
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.templateVersion || 0) >= 6
? actionDictionary.items.map((item) => ({
id: item.code,
name: item.name,
description: item.description,
aliases: item.aliases,
color: item.color,
dictionary: dictionarySelection(item),
}))
: 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 generationSnapshotRef = useRef({
fingerprint: annotationFingerprint,
drafts: workbenchDrafts.length,
context: annotationMutationContextRef.current.current(),
});
if (
generationSnapshotRef.current.fingerprint !== annotationFingerprint ||
generationSnapshotRef.current.drafts !== workbenchDrafts.length ||
generationSnapshotRef.current.context !== annotationMutationContextRef.current.current()
)
generationSnapshotRef.current = {
fingerprint: annotationFingerprint,
drafts: workbenchDrafts.length,
context: annotationMutationContextRef.current.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 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 =
blindAnnotator && taskPoolView === "mine" && annotatorTaskView === "submitted"
? submittedHumanItems
: 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],
);
// Scope stage — mode visibility plus the capture-directory URL scope. It
// defines the pool tab totals (可领取/我的任务/…), so the panel list filters
// below must stay out of the counts (acceptance-fixes ticket 02: choosing a
// category such as 「待验收」zeroed the upper pool counts).
const matchesPoolScope = useCallback(
(item: HumanItem, pool: TaskPoolView) => {
if (
!(blindAnnotator && pool === "mine" && annotatorTaskView === "submitted") &&
!humanItemVisibleInMode(item, workspaceMode, pool)
)
return false;
if (!requestedCaptureDirectory) return true;
const task = tasks.find((t) => t.id === item.legacyTaskId);
return captureDirectoriesFromHumanTask(item, task).includes(requestedCaptureDirectory);
},
[workspaceMode, tasks, requestedCaptureDirectory, blindAnnotator, annotatorTaskView],
);
// List stage — panel search plus status category; scopes only the task list.
const matchesPoolListFilters = useCallback(
(item: HumanItem) => {
if (managerAnnotationPool || pagedReviewPool) return true;
const task = tasks.find((t) => t.id === item.legacyTaskId);
const directories = captureDirectoriesFromHumanTask(item, task);
if (
taskSearch &&
!`${directories.join(" ")} ${item.display?.projectName || ""}`.toLowerCase().includes(taskSearch.toLowerCase())
)
return false;
const status = task
? deriveDetailedTaskStatus(task, item)
: item.status === "accepted"
? "accepted"
: item.status === "rejected"
? "rework"
: "pending_acceptance";
return taskStatusFilter === "all" || status === taskStatusFilter;
},
[tasks, taskSearch, taskStatusFilter, managerAnnotationPool, pagedReviewPool],
);
const matchesPoolFilters = useCallback(
(item: HumanItem, pool: TaskPoolView) => matchesPoolScope(item, pool) && matchesPoolListFilters(item),
[matchesPoolScope, matchesPoolListFilters],
);
const visiblePoolItems = useMemo(() => {
// B03(spec §5.4-7):返工任务徽标置顶——先清自己的错再领新,其余保持服务端顺序(稳定排序)。
const filtered = poolItems.filter((item) => matchesPoolFilters(item, taskPoolView));
const reworkRank = (item: HumanItem) =>
item.currentStageId === "annotation_combined" && Number(item.reviewRound || 0) > 0 ? 0 : 1;
return filtered
.map((item, index) => ({ item, index }))
.sort((a, b) => reworkRank(a.item) - reworkRank(b.item) || a.index - b.index)
.map((entry) => entry.item);
}, [poolItems, taskPoolView, matchesPoolFilters]);
const prepackageAcceptanceItems = useMemo(
() => visiblePoolItems.filter((item) => item.currentStageId === "prepackage_acceptance"),
[visiblePoolItems],
);
useEffect(() => {
if (workspaceMode !== "acceptance" || !requestedAcceptanceId || loading || saving) return;
if (prepackageAcceptanceItems.some((item) => item.id === requestedAcceptanceId))
setExpandedDeliveryPackageId(requestedAcceptanceId);
}, [workspaceMode, requestedAcceptanceId, prepackageAcceptanceItems, loading, saving]);
const acceptanceListSelection = prepackageAcceptanceItems.find((item) => item.id === expandedDeliveryPackageId);
const acceptanceDetailSelection =
acceptancePoolDetail?.scope === projectDataScope &&
acceptancePoolDetail.item.id === acceptanceListSelection?.id &&
acceptancePoolDetail.item.version >= acceptanceListSelection.version
? acceptancePoolDetail.item
: null;
useEffect(() => {
if (!acceptanceListSelection || !isHumanPoolSummary(acceptanceListSelection)) return;
const controller = new AbortController();
setAcceptancePoolDetailError("");
void humanLoopApi
.getItem(acceptanceListSelection.id, { signal: controller.signal })
.then(({ item }) => {
if (!controller.signal.aborted) setAcceptancePoolDetail({ scope: projectDataScope, item });
})
.catch((cause) => {
if (!controller.signal.aborted) setAcceptancePoolDetailError(getActionErrorMessage(cause, "加载验收内容失败"));
});
return () => controller.abort();
}, [projectDataScope, acceptanceListSelection?.id, acceptanceListSelection?.version, acceptanceDetailRetry]);
const reviewSessionItem = reviewItemForSelection(
acceptanceListSelection,
acceptanceDetailSelection,
detail?.humanItem,
);
const reviewSessionEnabled = Boolean(
(workspaceMode === "quality" || workspaceMode === "clip-quality" || workspaceMode === "acceptance") &&
taskPoolView !== "reviewed" &&
reviewSessionItem?.assignedUserId === currentUser?.id &&
["claimed", "in_progress"].includes(reviewSessionItem?.status || ""),
);
const reviewSession = useReviewSession(reviewSessionItem?.id || "", currentUser?.id || "", reviewSessionEnabled);
const reviewReceiptSupported =
Boolean(reviewSession.snapshot) && reviewSession.snapshot?.decisionProtocol !== "legacy";
// Acceptance-fixes defect 5 (Lane B): production still carries confirm-only
// acceptance items materialized before the three-role loop (EditorSchema
// acceptance-statistics/v1, stage.ConfirmOnly). For that shape the server
// REQUIRES videoQuality/overallGrade/annotation accuracy+completeness on
// approve and forbids reject outright, while the strict pose UI sent none of
// the statistics — every 验收通过 click 400'd forever. The session's reported
// decision protocol is the item-shape signal; strict keeps the pose flow.
const openAcceptanceConfirmOnly =
workspaceMode === "acceptance" && reviewSessionEnabled && reviewSession.snapshot?.decisionProtocol === "legacy";
const reviewWriteLocked = Boolean(reviewSessionItem) && !reviewSession.writable;
const reviewDraft = useReviewDraft(
reviewSessionItem?.id || "",
currentUser?.id || "",
reviewSessionEnabled && reviewReceiptSupported,
reviewSession,
);
reviewDraftGuardRef.current = reviewDraft.canLeave;
const reviewDecision = useReviewDecision(
currentUser?.id || "",
projectId,
workspaceMode,
(request, receipt) =>
completeReviewDecision(request, receipt, {
message: request.decision === "approved" ? "原审核决定已核对完成。" : "原退回决定已核对完成。",
}).then(() => undefined),
(request) => reviewContinuation.prepareDecision(request.itemId),
);
// Layout display (reviewFocus) is deliberately not part of the continuation
// scope: switching between ordinary and focused display must not restart or
// pause the running queue, and only an explicit claim/continue may
// auto-start it. The explicit 返回任务池 return actions are not layout
// toggles: they still pause the queue (confirmed rule).
const reviewContinuationProjectId = useReviewProjectScope(
currentUser?.id || "",
projectId,
workspaceMode,
reviewSessionItem?.projectId || "",
);
const reviewEntryScope = `${currentUser?.id || ""}:${projectId}:${workspaceMode === "acceptance" ? "acceptance" : "quality"}:${reviewOnly}`;
const reviewEntryIntent = useReviewEntryIntent();
const reviewProjectResume = useRef<string | null>(null);
const reviewContinuation = useReviewContinuation({
userId: currentUser?.id || "",
projectId: workspaceMode === "acceptance" ? projectId : reviewContinuationProjectId,
stage: workspaceMode === "acceptance" ? "acceptance" : "quality",
enabled: reviewOnly,
currentItemId: reviewSessionEnabled ? reviewSessionItem?.id || "" : "",
sessionHeaders: reviewSession.headers,
sessionWritable: reviewSession.writable,
onControlLost: reviewSession.handleError,
onPaused: () => {
reviewProjectResume.current = null;
reviewEntryIntent.latch();
},
onOpenItem: (item) => {
const acceptance = item.currentStageId === "prepackage_acceptance";
const taskId = acceptance ? "" : item.legacyTaskId || "";
// A completed decision may still be unwinding. Mark the new selection
// synchronously so its cleanup cannot close the newly admitted task.
reviewSelectionRef.current = { task: taskId, acceptance: acceptance ? item.id : "" };
applyReviewClaim(item);
setTaskPoolView("mine");
setDetail(null);
setSelectedAnnotationTaskId(taskId);
setExpandedDeliveryPackageId(acceptance ? item.id : "");
const next = new URLSearchParams(searchParams);
next.set("projectId", projectId);
next.delete("sliceId");
next.delete("eventId");
if (acceptance) {
next.set("acceptanceId", item.id);
next.delete("taskId");
} else {
next.set("taskId", taskId);
next.delete("acceptanceId");
}
setSearchParams(next, { replace: true });
},
});
const completeReviewDecision = createReviewDecisionCompletion({
context: reviewActionContextRef.current,
isCurrent: (context: object) => reviewActionContextRef.current === context,
continuation: reviewContinuation,
view: {
isSelected: (request: ReviewDecisionRequest) =>
request.taskId
? reviewSelectionRef.current.task === request.taskId
: reviewSelectionRef.current.acceptance === request.itemId,
retire: retireReviewedItem,
close: (message: string) => closeTaskAndReturnToPool(message),
reload: () => {
void loadProject();
},
},
});
const reviewContinuousRunning = ["starting", "active", "waiting", "advancing"].includes(reviewContinuation.status);
// Keep the ordinary compact controls reachable whenever the queue was
// started in this page lifetime, even if no editable item is open right now
// (waiting after the last decision retired it, or paused before a manual
// resume). An invisible active/waiting queue must not be possible.
const reviewOrdinaryContinuationVisible =
!reviewFocused && taskPoolView !== "reviewed" && reviewOnly && (reviewSessionEnabled || reviewContinuation.engaged);
// Spec rule 10: an explicit claim/continue entry auto-starts the queue once,
// only after this page owns the review write lease and the task context is
// loaded. Refresh, direct URL and readonly preview never mark intent, and
// any pause latches the scope so recovery stays manual.
const reviewAutoEntryReady = Boolean(
reviewOnly &&
reviewSessionEnabled &&
// Legacy-protocol tasks keep manual-only review: an explicit entry must
// never send a continuation start the task cannot support, and the
// resulting session error would invalidate a usable legacy review.
reviewReceiptSupported &&
reviewSession.writable &&
!viewportPaused &&
!reviewWindowUndersized &&
!reviewDecision.pending &&
!reviewDraft.dirty &&
!reviewContinuation.busy &&
(workspaceMode === "acceptance"
? expandedDeliveryPackageId && reviewSessionItem && expandedDeliveryPackageId === reviewSessionItem.id
: detail?.humanItem && detail.humanItem.id === reviewSessionItem?.id),
);
const reviewEntryItemId = reviewSessionEnabled ? reviewSessionItem?.id || "" : "";
// Prune uses the item the user is actually navigating to, never the async
// detail/session state of the previous task: while entering B, a stale A
// context must neither consume nor drop B's fresh entry intent.
const reviewSelectedItemId =
workspaceMode === "acceptance"
? expandedDeliveryPackageId || requestedAcceptanceId
: selectedTaskId || requestedTaskId;
const reviewSelectedHumanItemId =
workspaceMode === "acceptance"
? reviewSelectedItemId
: detail?.humanItem && detail.humanItem.legacyTaskId === reviewSelectedItemId
? reviewSelectedItemId && detail.humanItem.id
: "";
useEffect(() => {
// Scope changes always clear a pending intent, even with no selection. A
// null selected item (still loading) only enforces the scope, so a lagging
// old detail cannot clear the fresh intent of the task being entered.
reviewEntryIntent.prune(reviewEntryScope, reviewSelectedHumanItemId || null);
}, [reviewSelectedHumanItemId, reviewEntryScope, reviewEntryIntent]);
useEffect(() => {
if (!reviewAutoEntryReady || reviewContinuousRunning) return;
if (!reviewEntryItemId) return;
if (!reviewEntryIntent.pendingFor(reviewEntryScope, reviewEntryItemId)) return;
reviewEntryIntent.consume(reviewEntryScope, reviewEntryItemId);
void reviewContinuation.start();
}, [
reviewAutoEntryReady,
reviewContinuousRunning,
reviewEntryItemId,
reviewEntryScope,
reviewEntryIntent,
reviewContinuation,
]);
useEffect(() => {
// Only an explicit filter change made while acceptance was running may
// resume the new scope. Refresh, manual/exception pauses never set this.
const pending = reviewProjectResume.current;
if (!pending) return;
if (
pending !== reviewEntryScope ||
!reviewOnly ||
workspaceMode !== "acceptance" ||
reviewWindowUndersized ||
viewportPaused
) {
reviewProjectResume.current = null;
return;
}
if (reviewSessionEnabled || reviewContinuation.busy || reviewDecision.pending) return;
reviewProjectResume.current = null;
void reviewContinuation.start();
}, [
reviewEntryScope,
reviewOnly,
workspaceMode,
reviewWindowUndersized,
viewportPaused,
reviewSessionEnabled,
reviewContinuation,
reviewDecision.pending,
]);
useEffect(() => {
// An undersized window suspends review continuation in both layouts (the
// 1413×615 bottom line is a review requirement, not focused-only); recovery
// always requires a manual continue. Annotation pages keep the existing
// focused/workPage-only viewportPaused semantics untouched.
if ((reviewFocused && viewportPaused) || (reviewOnly && reviewWindowUndersized))
reviewContinuation.pause("窗口空间不足,连续审查已暂停;恢复后请手动继续。");
}, [reviewFocused, viewportPaused, reviewOnly, reviewWindowUndersized]);
useEffect(() => {
// An explicit claim/continue clicked while the review window is already
// undersized must not fire later on resize-back: the pause effect's
// dimension deps do not change when the intent is marked, so latch a fresh
// intent immediately. Recovery from an undersized pause is always manual.
if (reviewOnly && reviewWindowUndersized && reviewEntryIntent.pending) reviewEntryIntent.latch();
}, [reviewOnly, reviewWindowUndersized, reviewEntryIntent]);
useEffect(() => {
if (reviewDecision.failureVersion) reviewContinuation.pause("正式决定失败或结果待核对,连续审查已暂停。");
}, [reviewDecision.failureVersion]);
const reviewAcceptanceEntries = (reviewSessionItem?.subject?.payload?.items || []) as Array<{
sourceHumanItemId?: string;
finalSlices?: SliceSegment[];
annotation?: AnnotationSegment[];
}>;
const reviewProblemLabel = (problem: ReviewProblem) => {
if (problem.scope === "task") return "整体任务问题";
const sourceIndex =
workspaceMode === "acceptance"
? reviewAcceptanceEntries.findIndex((entry) => entry.sourceHumanItemId === problem.sourceItemId)
: -1;
const slices = sourceIndex >= 0 ? reviewAcceptanceEntries[sourceIndex].finalSlices || [] : sliceSegments;
const actions = sourceIndex >= 0 ? reviewAcceptanceEntries[sourceIndex].annotation || [] : segments;
const sliceIndex = slices.findIndex((slice) => slice.id === problem.sliceId);
const actionIndex = actions
.filter((action) => {
const slice = slices[sliceIndex];
return slice && action.start >= slice.start && action.end <= slice.end;
})
.findIndex((action) => action.id === problem.actionId);
return `${sourceIndex >= 0 ? `来源 ${sourceIndex + 1} · ` : ""}切片 ${sliceIndex + 1}${problem.scope === "action" ? ` · 动作 ${actionIndex + 1}` : ""}`;
};
const reviewProblemNavigationSlice = (problem: ReviewProblem) => {
// Whole-task problems stay global; their frozen view anchor drives recall.
const anchor = problem.scope === "task" ? problem.viewAnchor : undefined;
const sourceItemId = anchor ? anchor.sourceItemId : problem.sourceItemId;
const sliceId = anchor ? anchor.sliceId : problem.sliceId;
if (workspaceMode !== "acceptance") return sliceId;
const sourceIndex = reviewAcceptanceEntries.findIndex((entry) => entry.sourceHumanItemId === sourceItemId);
const sliceIndex =
sourceIndex >= 0
? (reviewAcceptanceEntries[sourceIndex].finalSlices || []).findIndex((slice) => slice.id === sliceId)
: -1;
return sourceIndex >= 0 && sliceIndex >= 0 ? `${sourceIndex}:${sliceIndex + 1}` : undefined;
};
const [reworkSeekRequest, setReworkSeekRequest] = useState<{ time: number; revision: number } | null>(null);
const reworkSeekRevisionRef = useRef(0);
// 返工强调层包含区间完整的编辑器草稿;未完成终点选择不推定已修改。
const reworkEmphasisEligible = Boolean(
detail?.humanItem &&
detail.humanItem.currentStageId === "annotation_combined" &&
!detail.humanItem.pendingCombinedSubmissionId &&
(detail.humanItem.reviewRound || 0) >= 1 &&
["claimed", "rework", "in_progress"].includes(detail.humanItem.status) &&
workspaceMode === "annotate",
);
const reworkLiveActions = useMemo(
() => reworkActionsWithDrafts(segments, workbenchDrafts).actions,
[segments, workbenchDrafts],
);
const reworkEmphasisData = useReworkEmphasis(
detail?.humanItem?.id || "",
detail?.humanItem?.reviewRound || 0,
reworkEmphasisEligible,
sliceSegments,
reworkLiveActions,
);
const reworkEmphasis = reworkEmphasisEligible ? reworkEmphasisData.emphasis : null;
// QC 返修接收视图(票 08/09):强调层输入 = 已保存工作区(ADR 0006:31),与标注员侧
// 实时草稿语义分开;同一 getTask 读路径带出票 07 的送检结构变更摘要。
const reworkReceiveEligible = Boolean(
reviewSessionEnabled && reviewReceiptSupported && (reviewDraft.draft?.reviewRound || 0) >= 1 && detail?.task?.id,
);
const reworkReceive = useReworkReviewEmphasis(
reviewDraft.draft?.itemId || "",
reviewDraft.draft?.reviewRound || 0,
detail?.task?.id || "",
reworkReceiveEligible,
);
const reworkReceiveEmphasis = reworkReceiveEligible && reworkReceive.emphasis.active ? reworkReceive.emphasis : null;
// J/K 逐条跳意见(R2-Q5:a + 票 09 R1-Q5 双板块统一跳序):定位绑
// ReviewViewingController 现成原语,不搬 workbench 导航。
const reviewControllerRef = useRef<ReviewViewingController | null>(null);
const [reviewReworkFocus, setReviewReworkFocus] = useState<{
board: "baseline" | "current";
id: string;
round: number;
seq: number;
} | null>(null);
// 判定键 2(票 10,R1-Q7):仍有问题 → 聚焦该行行内备注输入;seq 单调递增
// 驱动意见栏对同一行重复触发也重新聚焦。
const [reviewVerdictNoteFocus, setReviewVerdictNoteFocus] = useState<{
opinionId: string;
seq: number;
} | null>(null);
const reviewReworkJumpIndexRef = useRef(-1);
// 双板块统一跳序:退回意见(左栏,jumpOrder 顺序)在前、本轮审核意见(右栏)在后。
const reviewWalkEntries = useMemo(
() =>
reworkReceiveEmphasis
? qcReworkWalk(reworkReceiveEmphasis, reviewDraft.draft?.problems || [], {
slices: reworkReceive.workspace?.slices || [],
actions: reworkReceive.workspace?.actions || [],
})
: [],
[reworkReceiveEmphasis, reviewDraft.draft?.problems, reworkReceive.workspace],
);
const seekReviewReworkEntry = (entry: {
opinion: ReworkOpinionView;
anchor: number | null;
sliceId: string | null;
actionId: string | null;
}) => {
const controller = reviewControllerRef.current;
if (!controller) return;
if (entry.actionId && controller.seekAction(entry.actionId)) return;
const anchor = typeof entry.anchor === "number" && entry.anchor >= 0 ? entry.anchor : null;
if (anchor != null) {
controller.seekTime(anchor);
return;
}
if (entry.sliceId) controller.seekSlice(entry.sliceId);
};
const onReviewReworkNavigate = (direction: 1 | -1) => {
const entries = reviewWalkEntries;
if (!entries.length) return;
const next = (((reviewReworkJumpIndexRef.current + direction) % entries.length) + entries.length) % entries.length;
reviewReworkJumpIndexRef.current = next;
const target = entries[next];
setReviewReworkFocus((current) => ({
board: target.board,
id: target.opinion.id,
round: target.opinion.round,
seq: (current?.seq || 0) + 1,
}));
seekReviewReworkEntry(target);
};
const locateReviewReworkOpinion = (opinion: ReworkOpinionView) => {
const entries = reviewWalkEntries;
const index = entries.findIndex(
(entry) => entry.board === "baseline" && entry.opinion.id === opinion.id && entry.opinion.round === opinion.round,
);
if (index < 0) return;
reviewReworkJumpIndexRef.current = index;
setReviewReworkFocus((current) => ({
board: "baseline",
id: opinion.id,
round: opinion.round,
seq: (current?.seq || 0) + 1,
}));
seekReviewReworkEntry(entries[index]);
};
const reworkReceiveSliceLabelOf = (sliceId: string | null) =>
reworkSliceLabelOf(reworkReceive.workspace?.slices || [], sliceId);
const reworkReceiveActionIndexOf = (actionId: string) =>
reworkActionIndexOf(reworkReceive.workspace?.slices || [], reworkReceive.workspace?.actions || [], actionId);
const handleReviewController = useCallback(
(controller: ReviewViewingController | null) => {
reviewControllerRef.current = controller;
reviewDraft.onController(controller);
},
[reviewDraft.onController],
);
// D7 判定(票 09 起挂在左栏意见行上):判定数据/提交走审查草稿(confirmations),
// 锁定条件与右栏审核意见面板一致。
const reviewVerdictLocked =
Boolean(reviewDecision.pending) || !reviewDraft.writable || reviewDraft.loading || !reviewDraft.draft;
const reviewVerdictOf = reviewDraft.confirmations.length
? (opinionId: string) => reviewDraft.confirmations.find((c) => c.opinionId === opinionId)
: undefined;
const reviewOnVerdict = (opinionId: string, resolved: boolean, note?: string) =>
reviewDraft.setConfirmation(opinionId, resolved, note ?? "");
// 判定键 1/2(票 10,R1-Q7):只作用于 J/K 聚焦的左栏(退回意见)行——右栏
// (本轮审核意见)与未聚焦时为空操作,避免给正在撰写的意见误落判定;
// 语义与行内判定按钮一致(锁定沿用、备注保留、1 清空备注),空备注的
// "仍有问题"由正式决定提交前拦截(useReviewDraft.prepareSubmit)。
const onReviewReworkVerdict = (resolved: boolean) => {
if (
reviewVerdictLocked ||
reviewReworkFocus?.board !== "baseline" ||
reviewReworkFocus.round !== reworkReceiveEmphasis?.round
)
return;
const focusId = reviewReworkFocus.id;
const latest =
reworkReceiveEmphasis?.jumpOrder.find(
(entry) => entry.opinion.id === focusId && entry.opinion.round === reworkReceiveEmphasis.round,
) || null;
if (!latest) return;
const previous = reviewVerdictOf?.(focusId);
reviewOnVerdict(focusId, resolved, resolved ? "" : previous && !previous.resolved ? previous.note || "" : "");
if (!resolved) setReviewVerdictNoteFocus((current) => ({ opinionId: focusId, seq: (current?.seq || 0) + 1 }));
};
const traceItem = reviewOnly && workspaceMode !== "acceptance" ? reviewSessionItem : null;
const reviewTrace = useReviewTrace(traceItem?.id || "", traceItem?.version || 0);
const reviewTracePanel = traceItem ? (
<ReviewTracePanel key={traceItem.id} {...reviewTrace} stageId={traceItem.currentStageId} />
) : null;
const reviewProblemPanel =
reviewSessionEnabled && reviewReceiptSupported ? (
<>
{reworkReceiveEmphasis?.changes && (
<ReworkChangesPanel
changes={reworkReceiveEmphasis.changes}
onLocate={(_sliceId, time, actionId) => {
const controller = reviewControllerRef.current;
if (!actionId || !controller?.seekAction(actionId)) controller?.seekTime(time);
}}
/>
)}
{reviewDraft.draft?.stageId === "quality_review" && reviewDraft.draft?.itemId && (
<AcceptanceMisreports
key={reviewDraft.draft.itemId}
itemId={reviewDraft.draft.itemId}
locked={reviewVerdictLocked}
onChange={reworkReceive.reload}
/>
)}
{reworkReceive.baselines
.filter((b) => b.round === reviewDraft.draft?.reviewRound)
.flatMap((b) => b.unlocatedProblems || [])
.map((p) => (
<div key={p.id} className="rounded border border-[color:var(--app-border)] p-3 space-y-2 text-sm">
<div className="font-medium">验收原文</div>
<p className="whitespace-pre-wrap">{p.text}</p>
<label className="flex gap-2 items-center">
<input
type="checkbox"
disabled={reviewVerdictLocked}
checked={Boolean(reviewVerdictOf?.(p.id)?.resolved)}
onChange={(event) =>
reviewOnVerdict(p.id, event.target.checked, event.target.checked ? "" : "按原意见处理")
}
/>
已解决
</label>
<textarea
aria-label="补充验收原文意见"
className="w-full rounded border bg-transparent p-2"
disabled={reviewVerdictLocked || Boolean(reviewVerdictOf?.(p.id)?.resolved)}
value={reviewVerdictOf?.(p.id)?.note || ""}
onChange={(event) => reviewOnVerdict(p.id, false, event.target.value)}
placeholder="补充意见"
/>
</div>
))}
{reworkReceiveEmphasis && (
<ReworkReceiveBanner
round={reworkReceiveEmphasis.round}
summary={reworkReceive.workspace?.structureChangeSummary || null}
/>
)}
{reworkReceiveEmphasis && reworkReceiveEmphasis.jumpOrder.length > 0 ? (
<div className="qc-review-dual-board" data-testid="qc-review-dual-board">
<ReworkOpinionRail
emphasis={reworkReceiveEmphasis}
focus={
reviewReworkFocus?.board === "baseline"
? { opinionId: reviewReworkFocus.id, round: reviewReworkFocus.round, seq: reviewReworkFocus.seq }
: null
}
onLocate={locateReviewReworkOpinion}
sliceLabelOf={reworkReceiveSliceLabelOf}
actionIndexOf={reworkReceiveActionIndexOf}
verdictOf={reviewVerdictOf}
onVerdict={reviewOnVerdict}
verdictLocked={reviewVerdictLocked}
noteFocus={reviewVerdictNoteFocus}
/>
<div className="qc-review-board-scroll" data-testid="qc-current-opinion-board">
<ReviewProblemPanel
review={reviewDraft}
writeLocked={Boolean(reviewDecision.pending)}
label={reviewProblemLabel}
onSelectProblem={(problem) => reviewDraft.selectProblem(problem, reviewProblemNavigationSlice(problem))}
focusedProblemId={reviewReworkFocus?.board === "current" ? reviewReworkFocus.id : null}
/>
</div>
</div>
) : (
<ReviewProblemPanel
review={reviewDraft}
writeLocked={Boolean(reviewDecision.pending)}
label={reviewProblemLabel}
onSelectProblem={(problem) => reviewDraft.selectProblem(problem, reviewProblemNavigationSlice(problem))}
/>
)}
</>
) : undefined;
useEffect(() => {
if (!reviewDraft.draft) return;
// ADR 0009:整体作用域意见不进镜像行与扁平化预览(历史冻结原文由显示层剥离)。
const visibleProblems = reviewDraft.draft.problems.filter((problem) => problem.scope !== "task");
const comment = visibleProblems.map((problem) => `${reviewProblemLabel(problem)}:${problem.text}`).join("\n");
if (workspaceMode === "acceptance") {
setPrepackageComments((current) => ({ ...current, [reviewDraft.draft!.itemId]: comment }));
return;
}
setReviewComment(comment);
setProblemSliceIds([
...new Set(visibleProblems.map((problem) => problem.sliceId).filter((id): id is string => Boolean(id))),
]);
}, [reviewDraft.draft, workspaceMode]);
const visibleDeliveryPackages = useMemo(
() =>
deliveryPackages.filter((item) => {
if (taskPoolView === "all") return true;
if (acceptanceWorkspace && item.status !== "pending_acceptance") return false;
if (taskPoolView === "mine") return item.assignedUserId === currentUser?.id;
return !item.assignedUserId;
}),
[currentUser?.id, deliveryPackages, taskPoolView, acceptanceWorkspace],
);
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,
sourceValidationStatus: poolItem?.sourceValidationStatus,
reviewHistoryStatus: poolItem?.reviewHistoryStatus,
reviewHistory: poolItem?.reviewHistory,
}
: 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(
() =>
managerAnnotationPool || pagedReviewPool
? visibleTasks
: filterAnnotationTasks(visibleTasks, taskContextById, taskSearch, taskStatusFilter),
[taskContextById, taskSearch, taskStatusFilter, visibleTasks, managerAnnotationPool, pagedReviewPool],
);
// Progressive rendering cap: a 17k-task pool renders fine in the store but
// freezes the tab when every card mounts at once. Render loaded pages in
// windows; review searches run on the server and badges count loaded rows.
const [taskRenderLimit, setTaskRenderLimit] = useState(200);
useEffect(() => {
setTaskRenderLimit(200);
}, [taskPoolView, taskSearch, taskStatusFilter, projectId, workspaceMode]);
const renderedVisibleTasks = useMemo(
() => filteredVisibleTasks.slice(0, taskRenderLimit),
[filteredVisibleTasks, taskRenderLimit],
);
// Server-side task pool paging: the initial load fetches the first window
// and "load more" pulls the next page through the opaque cursor.
const taskPageLimit = 200;
const taskPoolLoadMore = async () => {
if (reviewActionScopeRef.current !== projectDataScope) return;
const sidebar = blindAnnotator && taskPoolView === "mine";
const cursor = pagedReviewPool
? reviewPoolCursorsRef.current[taskPoolView]
: sidebar
? minePoolCursorRef.current
: taskPoolCursorRef.current;
if (taskPoolFetchOwnerRef.current || !cursor) return;
const owner = Symbol("pool-page");
const controller = new AbortController();
taskPoolFetchOwnerRef.current = owner;
const scope = projectDataScope;
const epoch = projectLoadRequestRef.current;
const current = () =>
!controller.signal.aborted &&
taskPoolFetchOwnerRef.current === owner &&
reviewActionScopeRef.current === scope &&
projectLoadRequestRef.current === epoch &&
(!pagedReviewPool || reviewPoolViewRef.current === taskPoolView);
setTaskPoolFetchBusy(true);
try {
poolPageAbortRef.current?.abort();
poolPageAbortRef.current = controller;
const page = await loadAnnotationPoolPage({
annotation: annotationOperationsApi,
human: humanLoopApi,
scope: {
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
nodeId: requestedNodeId || undefined,
artifactId: requestedArtifactId || undefined,
},
view: managerAnnotationPool
? { kind: "admin", filters: managerPoolFilters }
: sidebar
? { kind: "sidebar", annotationView: annotatorTaskView }
: pagedReviewPool
? {
kind: "review",
pool: taskPoolView,
search: adminSearch,
capture: requestedCaptureDirectory,
category: taskStatusFilter,
acceptance: acceptanceWorkspace,
isManager,
stageIds: humanItemStageIdsForMode(workspaceMode),
trace: reviewOnly,
limit: taskPageLimit,
}
: { kind: "workspace", limit: taskPageLimit },
cursor,
signal: controller.signal,
});
if (!current()) return;
setTaskPoolReadError("");
taskPoolCursorRef.current = page.taskCursor;
minePoolCursorRef.current = page.mineCursor;
if (page.poolCursors) reviewPoolCursorsRef.current = { ...reviewPoolCursorsRef.current, ...page.poolCursors };
if (page.counts) setAdminPoolTotals({ scope, counts: page.counts });
if (page.pools) {
const pool = managerAnnotationPool ? managerPoolFilters.pool : pagedReviewPool ? taskPoolView : "mine";
const items: HumanItem[] = page.pools[pool];
if (sidebar && annotatorTaskView === "submitted")
setSubmittedHumanItems((current) => [
...current,
...items.filter((item) => !current.some((old) => old.id === item.id)),
]);
else
setHumanPools((current) => ({
...current,
[pool]: [...current[pool], ...items.filter((item) => !current[pool].some((old) => old.id === item.id))],
}));
}
setTasks((current) => [...current, ...page.tasks.filter((item) => !current.some((old) => old.id === item.id))]);
setTaskRenderLimit((current) => current + taskPageLimit);
} catch (cause) {
if (current()) setTaskPoolReadError(getActionErrorMessage(cause, "加载更多任务失败,请重试"));
} finally {
// An obsolete response cannot release a newer page's busy indicator.
if (taskPoolFetchOwnerRef.current === owner) {
taskPoolFetchOwnerRef.current = null;
setTaskPoolFetchBusy(false);
}
}
};
const visibleHumanItemByTaskId = useMemo(
() =>
new Map(visiblePoolItems.filter((item) => item.legacyTaskId).map((item) => [item.legacyTaskId as string, item])),
[visiblePoolItems],
);
const poolCounts = useMemo(
// Admin tabs use scoped totals; review tabs count the loaded filtered rows.
() =>
managerAnnotationPool
? {
...(adminPoolTotals?.scope === projectDataScope
? adminPoolTotals.counts
: { available: 0, mine: 0, all: 0 }),
reviewed: 0,
}
: pagedReviewPool && reviewPoolTotals?.scope === projectDataScope
? reviewPoolTotals.counts
: poolTabCounts(humanPools, matchesPoolScope),
[
humanPools,
matchesPoolScope,
managerAnnotationPool,
adminPoolTotals,
projectDataScope,
pagedReviewPool,
reviewPoolTotals,
],
);
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 || (annotationDirty && detailRef.current?.task.id === selectedTaskId)) return;
let nextTaskId = "";
if (requestedTaskId && visibleTasks.some((item) => item.id === requestedTaskId)) nextTaskId = requestedTaskId;
else if (selectedTaskId && visibleTasks.some((item) => item.id === selectedTaskId)) nextTaskId = selectedTaskId;
// A completed/temporarily unreadable work task may leave My Tasks. Keep
// its result visible until explicit recovery or the fenced next-task entry.
if (!nextTaskId && workPage && detailRef.current?.task.id === selectedTaskId) return;
if (nextTaskId !== selectedTaskId) setSelectedAnnotationTaskId(nextTaskId);
}, [requestedTaskId, visibleTasks, loading, saving, selectedTaskId, annotationDirty]);
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);
// S6 follow-up: with the per-project fan-out skipped for unscoped managers,
// reassignment (eligibleAssignees) would lose its member roster. Load it on
// demand — exactly one request for the selected human item's project.
const scopedMembersProjectRef = useRef("");
const scopedMembersProjectId = selectedHumanItem?.projectId || "";
useEffect(() => {
if (projectId || !isManager || !scopedMembersProjectId) return;
if (scopedMembersProjectRef.current === scopedMembersProjectId) return;
scopedMembersProjectRef.current = scopedMembersProjectId;
let cancelled = false;
// Two requests for one project — still no per-project fan-out.
projectsApi
.listMembers(scopedMembersProjectId)
.then((members) => {
if (!cancelled) setProjectMembers(members);
})
.catch(() => {
// Roster stays empty; the assignee dropdown shows its empty state.
});
projectsApi
.listWorkflows(scopedMembersProjectId)
.then((scopedWorkflows) => {
if (!cancelled) {
setWorkflows((current) => {
// Merge: keep anything the scoped loader already provided.
const known = new Set(current.map((workflow) => workflow.id));
return [...current, ...scopedWorkflows.filter((workflow) => !known.has(workflow.id))];
});
}
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [projectId, isManager, scopedMembersProjectId]);
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 === "clip-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 stageResultUnknown = Boolean(
stageRecovery && stageRecovery.taskId === detail?.task.id && stageRecovery.userId === currentUser?.id,
);
const externalBufferTaskChanged = Boolean(detail?.task.id && externalBufferTaskId === detail.task.id);
const combinedSubmissionLocked = combinedSubmissionProcessing || stageResultUnknown || externalBufferTaskChanged;
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 || detail?.humanItem?.pendingCombinedSubmissionId) return undefined;
return {
stageName: latestRejectReview?.stage === "acceptance" ? "最终验收打回" : "切片与标注审核打回",
reasonCodes: latestRejectReview?.reasonCodes || [],
// ADR 0009:横幅显示层剥离历史「整体任务:」条目,冻结原文不动。
comment: stripTaskOpinionLines(
latestRejectReview?.comment ||
(detail?.humanItem?.cancellationReason
? `打回原因:${detail.humanItem.cancellationReason}`
: "该任务已被打回返工,请根据审核意见修改切片与描述。"),
),
problemSliceIds: latestRejectReview?.problemSliceIds || [],
};
}, [
detail?.humanItem?.cancellationReason,
detail?.humanItem?.pendingCombinedSubmissionId,
isReworkTask,
latestRejectReview,
]);
const currentAnnotationMutationContext = annotationMutationContextRef.current.current;
const sliceEditSessionRef = useRef(createSliceEditSession({ context: currentAnnotationMutationContext }));
useEffect(() => () => sliceEditSessionRef.current.invalidate(), []);
const annotationPersistence = createAnnotationPersistence({
scope: annotationMutationScopeRef.current,
context: currentAnnotationMutationContext,
adapter: {
waitForPending: () => autosave.waitForPending(),
version: () => detailRef.current?.humanItem?.version ?? 0,
item: () => detailRef.current?.humanItem,
read: (taskId: string) => annotationOperationsApi.getTask(taskId),
},
view: {
canWrite: () => annotationAuthoringRef.current && (!workPage || (workSession.active && workSession.owns())),
begin: () => {
++bufferReadEpochRef.current;
++taskDetailRequestRef.current;
setSaving(true);
setError("");
},
idle: () => setSaving(false),
blocked: () => setError("自动保存结果尚未确认,当前编辑已保留;请核对提示后再操作。"),
accept: ({ taskId, item, workspace, mode }) => {
setDetail((current) => (current ? { ...current, humanItem: item } : current));
setHumanPools((current) => ({
...current,
mine: current.mine.map((old) => (old.id === item.id ? item : old)),
}));
if (mode !== "draft")
confirmedAnnotationWorkspaceRef.current = { taskId, workspace: structuredClone(workspace) };
if (mode === "full") {
setSliceSegments(workspace.sliceSegments);
setSegments(workspace.segments);
setSliceStatuses(workspace.statuses);
setSliceOperations(workspace.operations);
}
annotationBaselineRef.current = annotationWorkspaceFingerprint(
workspace.sliceSegments,
workspace.operations,
workspace.segments,
workspace.statuses,
);
},
},
});
const beginAnnotationMutation = annotationPersistence.begin;
const endAnnotationMutation = annotationPersistence.end;
const handleAnnotationMutationError = async (
failure: unknown,
fallback: string,
taskId: string,
token: AnnotationMutationToken,
) => {
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return;
const message = getActionErrorMessage(failure, fallback);
workSession.pauseContinuous(`${message};连续工作已暂停,当前编辑保留。`);
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(
taskPoolView !== "reviewed" &&
selectedHumanItem &&
selectedHumanItem.assignedUserId === currentUser?.id &&
["claimed", "in_progress"].includes(selectedHumanItem.status),
);
const annotationAuthoring =
(workspaceMode === "clip" || workspaceMode === "annotate") &&
taskPoolView !== "reviewed" &&
(role === "annotator" || isManager) &&
(selectedClaimedByMe || isManager) &&
!["pending_quality", "pending_acceptance", "accepted"].includes(detail?.task.status || "") &&
(!detail?.humanItem ||
["annotation_combined", "split_annotation", "cut_adjustment", "semantic_annotation"].includes(
detail.humanItem.currentStageId,
)) &&
(!workPage || (workSession.active && workSession.owns()));
// Callbacks can outlive a render or pointer gesture. Check the current view
// again before changing annotations, independently of child control visibility.
const annotationAuthoringRef = useRef(annotationAuthoring);
annotationAuthoringRef.current = annotationAuthoring;
// A01 标注草稿自动保存:D1 触发(换片/20s 空闲/页面隐藏)、D4 草稿归并、D2 冲突横幅。
const [draftConflictAuthoritative, setDraftConflictAuthoritative] = useState<AnnotationTaskDetail | null>(null);
// 验收修复 C:切片重设面板会话标记——面板打开期间暂停草稿自动保存(快照引用
// 稳定),释放(Enter 应用/Esc)立即补存。workbench 按任务 key 重挂载,换任务
// 复位防残留 true 冻结自动保存。
const [sliceEditSessionOpen, setSliceEditSessionOpen] = useState(false);
useEffect(() => {
setSliceEditSessionOpen(false);
}, [detail?.task.id]);
const autosaveDraftsFingerprint = useMemo(() => workbenchDraftsFingerprint(workbenchDrafts), [workbenchDrafts]);
const autosaveWorkspaceDirty = Boolean(
detail && annotationBaselineRef.current && annotationFingerprint !== annotationBaselineRef.current,
);
const autosaveEnabled = Boolean(
annotationAuthoring &&
selectedClaimedByMe &&
detail?.humanItem?.currentStageId === "annotation_combined" &&
(combinedEditorPhase === "slice" || combinedEditorPhase === "annotate"),
);
const autosave = useAnnotationAutosave({
enabled: autosaveEnabled,
taskId: detail?.task.id,
userId: currentUser?.id,
workspaceDirty: autosaveWorkspaceDirty,
draftsFingerprint: autosaveDraftsFingerprint,
// 面板会话或任一冲突清单打开期间让路(验收修复 C):草稿留在工作台本地态,
// 面板快照引用保持稳定;释放下降沿立即补存(见下方 effect)。
isBlocked: () =>
saving ||
combinedSubmissionLocked ||
annotationMutationScopeRef.current.busy() ||
sliceEditSessionOpen ||
Boolean(sliceEditQuickConflict) ||
Boolean(sliceDragEditRef.current) ||
Boolean(sliceEditQuickApplyingRef.current),
buildSaveContext: () => {
const item = detailRef.current?.humanItem;
if (!item || !detailRef.current?.task) return null;
const statuses = sliceStatuses as Record<string, NonNullable<SliceSegment["annotationStatus"]>>;
return {
version: item.version,
sliceSegments: applySliceStatuses(
sliceSegments.map((slice) => ({ ...slice, taskLabelId: "", taskLabel: "" })),
statuses,
),
operations: sliceOperations,
segments: autosaveSegmentsWithDrafts(segments, workbenchDrafts),
statuses,
draftsFingerprint: autosaveDraftsFingerprint,
workspaceFingerprint: annotationFingerprint,
};
},
onApplied: ({ item, workspace, sentWorkspaceFingerprint }) => {
if (item.id !== detailRef.current?.humanItem?.id || workspace.userId !== currentUser?.id) return;
const currentVersion = detailRef.current?.humanItem?.version ?? 0;
if (!item || item.version < currentVersion) return;
if (
annotationWorkspaceMatches(workspace, {
sliceSegments,
segments: autosaveSegmentsWithDrafts(segments, workbenchDrafts),
statuses: sliceStatuses,
})
)
setSliceOperations(workspace.operations);
annotationPersistence.accept({
taskId: detailRef.current.task.id,
userId: workspace.userId,
item,
workspace,
mode: "draft",
});
// A server-normalized draft can omit empty client fields. Mark only the
// exact editor we sent as saved; never mark edits made in flight clean.
if (generationSnapshotRef.current.fingerprint === sentWorkspaceFingerprint)
annotationBaselineRef.current = sentWorkspaceFingerprint;
},
onExternalConflict: (authoritative) => {
if (authoritative.task.id === detailRef.current?.task.id) setDraftConflictAuthoritative(authoritative);
},
onVersionResync: (item) => {
if (item.id !== detailRef.current?.humanItem?.id) return;
const currentVersion = detailRef.current?.humanItem?.version ?? 0;
if (!item || item.version < currentVersion) return;
const savedItem = { ...item, display: item.display || detailRef.current?.humanItem?.display };
if (detailRef.current) detailRef.current = { ...detailRef.current, humanItem: savedItem };
setDetail((current) => (current ? { ...current, humanItem: savedItem } : current));
},
});
// 验收修复 C:面板/清单会话释放(Enter 应用或 Esc)的下降沿立即补一次草稿
// flush——会话期间 20s 空闲防抖可能已被让路吞掉,关闭即补保证草稿不悬空。
const sliceEditAutosavePaused = sliceEditSessionOpen || Boolean(sliceEditQuickConflict);
const sliceEditAutosavePausedRef = useRef(false);
useEffect(() => {
if (sliceEditSessionFlushEdge(sliceEditAutosavePausedRef.current, sliceEditAutosavePaused)) {
void autosave.flushNow("slice-edit-close");
}
sliceEditAutosavePausedRef.current = sliceEditAutosavePaused;
}, [sliceEditAutosavePaused, autosaveEnabled]);
const adoptServerDraft = () => window.location.reload();
const overwriteServerDraft = async () => {
if (!detail?.task.id) return;
try {
const fresh = await annotationOperationsApi.getTask(detail.task.id);
setDraftConflictAuthoritative(null);
await autosave.flushNow("conflict-overwrite", { versionOverride: fresh.humanItem?.version });
} catch {
setError("无法读取服务器最新状态,请刷新后重试。");
}
};
const submissionCheck = useMemo(() => {
if (!selectedClaimedByMe) {
return { canSubmit: false, reason: "当前任务尚未领取或已被释放" };
}
if (combinedSubmissionProcessing) {
return { canSubmit: false, reason: "正在提交中..." };
}
if (detail?.editorState?.canConfirmDescriptions === false) {
return { canSubmit: false, reason: "切片生成尚未完成,请先完成或恢复切片生成" };
}
if (sliceSegments.some((slice) => slice.deliveryDisposition !== "discard" && !slice.name?.trim())) {
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 (detail?.task.continuousActions) {
for (const slice of sliceSegments.filter((slice) => slice.deliveryDisposition !== "discard")) {
const actions = segments
.filter((segment) => segment.start >= slice.start && segment.end <= slice.end)
.sort((a, b) => a.start - b.start);
let cursor = slice.start;
for (const action of actions) {
if (Math.abs(action.start - cursor) > 0.000001)
return { canSubmit: false, reason: "动作区间存在空隙,请保存进度后重试" };
cursor = action.end;
}
if (Math.abs(cursor - slice.end) > 0.000001)
return { canSubmit: false, reason: "动作区间必须完整覆盖当前切片" };
}
}
if (
!detail?.task.continuousActions &&
segments.some((segment) => segment.status !== "invalid" && !segment.description?.trim())
) {
return { canSubmit: false, reason: "请填写已添加的描述,或删除未填写的描述区间" };
}
return { canSubmit: true, reason: "" };
}, [
selectedClaimedByMe,
combinedSubmissionProcessing,
sliceCoverage.complete,
annotationWorkspaceIssues,
sliceSegments,
segments,
exactFrameEditing,
frameBoundaries,
detail?.task.continuousActions,
detail?.editorState?.canConfirmDescriptions,
]);
const canCurrentUserClaimItem = useCallback((item: HumanItem | undefined) => item?.canClaim === true, []);
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 (!annotationAuthoringRef.current) return;
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[]) => {
if (!annotationAuthoringRef.current) return;
setSegments(next);
setSliceStatuses(
deriveSliceStatuses(sliceSegments, next, sliceStatuses) as Record<
string,
NonNullable<SliceSegment["annotationStatus"]>
>,
);
},
[sliceSegments, sliceStatuses],
);
const confirmedAnnotationWorkspace = (): AnnotationEditSnapshot["persisted"] | null => {
const confirmed = confirmedAnnotationWorkspaceRef.current;
return confirmed && confirmed.taskId === detailRef.current?.task.id ? structuredClone(confirmed.workspace) : null;
};
const recordAnnotationEdit = (before: AnnotationEditState, after: AnnotationEditState) => {
if (!annotationAuthoringRef.current) return;
if (saving || combinedSubmissionLocked || annotationMutationScopeRef.current.busy() || !selectedClaimedByMe) return;
const persisted = confirmedAnnotationWorkspace();
if (!persisted) return;
editHistoryRef.current.record({
before: { kind: "annotation", state: before, persisted },
after: { kind: "annotation", state: after, persisted },
});
};
const confirmAnnotationDescription = async (
nextSegments: AnnotationSegment[],
sliceId: string,
before?: AnnotationEditState,
restoring?: AnnotationEditSnapshot["persisted"],
) => {
if (!annotationAuthoringRef.current) return false;
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked) return false;
if (detail.editorState?.canConfirmDescriptions === false) {
setError("切片生成尚未完成,描述仍保留在编辑器中,请先完成或恢复切片生成。");
return false;
}
const taskId = detail.task.id;
let submittedVersion = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
const previousWorkspace = confirmedAnnotationWorkspace();
if (!previousWorkspace) {
setError("已保存标注尚未加载,请稍后重试。");
return false;
}
const nextStatuses = (restoring?.statuses ??
deriveSliceStatuses(sliceSegments, nextSegments, sliceStatuses)) as Record<
string,
NonNullable<SliceSegment["annotationStatus"]>
>;
const payload = restoring
? { ...restoring, version: submittedVersion }
: {
version: submittedVersion,
sliceSegments: applySliceStatuses(
sliceSegments.map((slice) => ({ ...slice, taskLabelId: "", taskLabel: "" })),
nextStatuses,
),
operations: sliceOperations,
segments: nextSegments.map((segment) => ({ ...segment, label: "", handedness: "" })),
statuses: nextStatuses,
};
const token = await beginAnnotationMutation(taskId);
if (!token) return false;
submittedVersion = token.version;
payload.version = submittedVersion;
try {
const result = await annotationPersistence.settle(token, {
write: () => annotationOperationsApi.confirmAnnotations(taskId, payload),
isApplied: (authoritative: AnnotationTaskDetail) => {
const workspace = annotationDraftFromHumanItem(authoritative.humanItem);
return Boolean(
authoritative.humanItem &&
authoritative.humanItem.version === submittedVersion + 1 &&
authoritative.humanItem.assignedUserId === currentUser?.id &&
authoritative.humanItem.currentStageId === detail.humanItem?.currentStageId &&
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;
const persisted = annotationDraftFromHumanItem(confirmedItem) || payload;
if (!annotationPersistence.accept({ taskId, userId: token.userId, item: confirmedItem, workspace: persisted }))
return false;
setSegments(nextSegments);
setSliceStatuses(nextStatuses);
if (before) {
editHistoryRef.current.record({
before: { kind: "annotation", state: before, persisted: previousWorkspace },
after: { kind: "annotation", state: { ...before, segments: nextSegments, editor: null }, persisted },
});
}
editHistoryRef.current.markPersisted();
annotationBaselineRef.current = annotationWorkspaceFingerprint(
sliceSegments,
sliceOperations,
nextSegments,
nextStatuses,
);
return true;
} finally {
endAnnotationMutation(token);
}
};
const sliceEditSnapshot = (sliceId: string, time?: number): SliceEditSnapshot => ({
slices: sliceSegments,
operations: sliceOperations,
segments,
statuses: sliceStatuses,
location: { sliceId, time: time ?? sliceSegments.find((slice) => slice.id === sliceId)?.start ?? 0 },
});
const quickSliceEditActionSnapshot = (baseSegments: AnnotationSegment[], baseSlices = sliceSegments) => {
const frozen = sliceEditSessionRef.current.freeze({
taskId: detail?.task.id || "",
slices: baseSlices,
actions: baseSegments,
drafts: workbenchDrafts,
});
return {
frozen,
taskId: frozen.taskId,
baseSegments,
actions: frozen.snapshot.actions as AnnotationSegment[],
draftsFingerprint: frozen.draftsFingerprint,
hasUnfinishedDrafts: frozen.hasUnfinishedDrafts,
};
};
const beginSliceBoundaryEdit = (sliceId: string) => {
if (!annotationAuthoringRef.current) return;
// 冲突清单开着时不接受新的边界拖动:一次只决一件事(待决快照不被打穿)。
if (sliceEditQuickConflict) return;
sliceDragEditRef.current = { before: sliceEditSnapshot(sliceId) };
};
// 拖动落定(票 05,spec §2 R2-Q3 拖动确认时机):整段手势合并为一条历史;释放点先跑
// 03 引擎扫描——无冲突立即生效(不进面板、不按 Enter,快路径保持快),落库前自检
// 状态白名单 +「动作完整落在恰好一个切片」(与 04 面板 Enter 同一管线);有冲突弹
// 04 同款冲突清单(同一键盘模型),Enter 落定、Esc 整体回退本次拖动(R1-Q4 不支持
// 部分应用)。旧三选卡不再承接拖动释放(06 票删除旧卡与非拖动调用方)。
const finishSliceBoundaryEdit = async () => {
const edit = sliceDragEditRef.current;
sliceDragEditRef.current = null;
if (!annotationAuthoringRef.current) return;
if (!edit?.after) return;
const draggedId = edit.before.location.sliceId;
const beforeSlice = edit.before.slices.find((item) => item.id === draggedId);
const currentSlice = sliceSegments.find((item) => item.id === draggedId);
if (beforeSlice && currentSlice && Math.abs(currentSlice.end - beforeSlice.end) > 1e-6) {
const beforeIndex = edit.before.slices.findIndex((item) => item.id === draggedId);
const following = beforeIndex >= 0 ? edit.before.slices[beforeIndex + 1] : undefined;
const prompt: SliceEditQuickConflict = {
entries: [],
baseSlices: edit.before.slices,
...quickSliceEditActionSnapshot(edit.before.segments, edit.before.slices),
pendingSlices: sliceSegments,
operation: {
type: "adjust",
segmentIds: following ? [draggedId, following.id] : [draggedId],
at: currentSlice.end,
},
anchorTime: currentSlice.end,
focusSliceId: draggedId,
dragEdit: edit,
};
const plan = planSliceEditDragRelease({
baseSlices: prompt.baseSlices,
pendingSlices: prompt.pendingSlices,
actions: prompt.actions,
});
if (plan.kind === "conflict") {
sliceDragEditRef.current = edit; // 清单落定时继续并入这条拖动编辑的历史(Esc 回退基线同源)
setSliceEditQuickConflict({
...prompt,
entries: plan.entries as SliceEditConflictEntry[],
autoFollows: plan.autoFollows as SliceEditAutoFollow[],
});
return;
}
// 无冲突也等待服务端原子保存;失败保留清单供重试或取消。
sliceDragEditRef.current = edit; // 持久化历史以拖动前快照为基线
const outcome = await applySliceEditQuickResolution(prompt, plan.resolution);
if (detailRef.current?.task.id !== prompt.taskId) return;
sliceDragEditRef.current = null;
if (outcome === "applied") return;
setSliceEditQuickConflict(prompt);
return;
}
recordSliceDragEdit(edit);
};
const recordSliceDragEdit = (edit: { before: SliceEditSnapshot; after?: SliceEditSnapshot }) => {
if (!annotationAuthoringRef.current) return;
const before = annotationWorkspaceFingerprint(edit.before.slices, [], edit.before.segments, edit.before.statuses);
const after = edit.after
? annotationWorkspaceFingerprint(edit.after.slices, [], edit.after.segments, edit.after.statuses)
: before;
if (before !== after) editHistoryRef.current.record({ before: edit.before, after: edit.after! });
else setSliceOperations(edit.before.operations);
};
const applySliceChange = (
next: SliceSegment[],
operation: Omit<SliceOperation, "before" | "after">,
candidateSegments = segments,
) => {
if (!annotationAuthoringRef.current) return false;
if (!exactFrameEditing) {
setError("统一帧范围尚未就绪,暂不能修改切片。");
return false;
}
if (saving || combinedSubmissionLocked || annotationMutationScopeRef.current.busy()) return false;
const sorted = [...next].sort((left, right) => left.start - right.start);
if (operation.type === "merge" || operation.type === "delete") {
const changed = sorted.filter(
(slice) =>
slice.sourceIds?.length &&
sliceSegments.some((old) => old.id === slice.id && (old.start !== slice.start || old.end !== slice.end)),
);
candidateSegments = candidateSegments.filter(
(segment) => !changed.some((slice) => segment.start < slice.end && segment.end > slice.start),
);
}
if (
JSON.stringify(sorted) === JSON.stringify(sliceSegments) &&
JSON.stringify(candidateSegments) === JSON.stringify(segments)
)
return false;
// Keep the complete workspace: dragging also moves touching description boundaries.
const sliceId = operation.segmentIds?.[0] || sliceSegments[0]?.id || "";
const before = sliceDragEditRef.current?.before ?? sliceEditSnapshot(sliceId, operation.at);
const nextOperations = [...before.operations, { ...operation, before: before.slices, after: sorted }];
const nextStatuses = deriveSliceStatuses(sorted, candidateSegments, sliceStatuses) as SliceEditSnapshot["statuses"];
const time = operation.at ?? sorted.find((slice) => slice.id === sliceId)?.start ?? before.location.time;
const affected = sorted.find((slice) => slice.id === sliceId) ?? sorted[sliceIndexAtPlayhead(sorted, time)];
const after: SliceEditSnapshot = {
slices: sorted,
operations: nextOperations,
segments: candidateSegments,
statuses: nextStatuses,
location: { sliceId: affected?.id || "", time },
};
if (sliceDragEditRef.current) sliceDragEditRef.current.after = after;
else editHistoryRef.current.record({ before, after });
setError("");
setSliceOperations(nextOperations);
setSliceSegments(sorted);
setSegments(candidateSegments);
setSliceStatuses(nextStatuses);
return true;
};
// —— 票 05(spec §2 R2-Q3):结构快捷入口的冲突清单落定/回退 ——
// 清单与无冲突快捷操作共享服务端原子应用:归档预览自检后发送原始动作,
// 等待权威工作区确认。失败保留清单与选择;拖动前快照作为一条持久化撤销历史。
const applySliceEditQuickResolution = async (
prompt: SliceEditQuickConflict,
resolution: { slices: SliceSegment[]; actions: AnnotationSegment[] },
) => {
if (
!annotationAuthoringRef.current ||
sliceEditQuickApplyingRef.current ||
detailRef.current?.task.id !== prompt.taskId
)
return "blocked";
const issues = checkSliceEditResolution(resolution, { baseSlices: prompt.baseSlices });
if (issues.length) {
setError(`切片改动未通过提交自检:${issues[0].message};请按 Esc 取消本次改动。`);
return "blocked";
}
if (!exactFrameEditing || saving || combinedSubmissionLocked || annotationMutationScopeRef.current.busy()) {
setError("当前状态暂不能应用切片改动,请稍后重试,或按 Esc 取消。");
return "blocked";
}
const before = prompt.dragEdit?.before ?? {
...sliceEditSnapshot(prompt.focusSliceId, prompt.anchorTime),
slices: prompt.baseSlices,
segments: prompt.baseSegments,
};
let nextActions = resolution.actions;
// Preserve the existing cancel-cut rule: merged regions return to pending.
if (prompt.operation.type === "merge" || prompt.operation.type === "delete") {
const changed = resolution.slices.filter(
(slice) =>
slice.sourceIds?.length &&
prompt.baseSlices.some((old) => old.id === slice.id && (old.start !== slice.start || old.end !== slice.end)),
);
nextActions = nextActions.filter(
(action) => !changed.some((slice) => action.start < slice.end && action.end > slice.start),
);
}
const unchanged =
JSON.stringify(resolution.slices) === JSON.stringify(prompt.baseSlices) &&
JSON.stringify(nextActions) === JSON.stringify(prompt.baseSegments);
const operations = [...before.operations, { ...prompt.operation, before: before.slices, after: resolution.slices }];
const taskId = detail?.task.id;
sliceEditQuickApplyingRef.current = prompt;
try {
// Send raw split pieces, not the client archive preview. The server owns
// canonical archives, CAS, audit and recovery for every entry point.
const committed = await sliceEditSessionRef.current.commit(prompt.frozen, {
current: () => ({
taskId: detailRef.current?.task.id,
slices: sliceSegments,
actions: segments,
drafts: workbenchDrafts,
}),
previewSlices: prompt.pendingSlices,
canApply: () => annotationAuthoringRef.current && !saving && !combinedSubmissionLocked,
apply: () => {
if (unchanged) {
if (prompt.dragEdit) setSliceOperations(prompt.dragEdit.before.operations);
return true;
}
return persistSliceEditApplication(
resolution.slices,
nextActions,
prompt.focusSliceId,
true,
operations,
before,
);
},
});
if (committed.status !== "applied" || detailRef.current?.task.id !== taskId) return "blocked";
return "applied";
} catch (cause) {
if (detailRef.current?.task.id === taskId)
setError(getActionErrorMessage(cause, "切片改动保存失败,选择和草稿已保留"));
return "blocked";
} finally {
if (sliceEditQuickApplyingRef.current === prompt) sliceEditQuickApplyingRef.current = null;
}
};
// 票 05:传给工作台的清单条目视图。useMemo 固定引用——工作台的播种 effect 依赖
// 这个 prop,行内对象会在页面每次重渲染(如播放头更新)时重置清单选择状态。
const sliceEditQuickConflictView = useMemo(
() =>
sliceEditQuickConflict
? {
entries: sliceEditQuickConflict.entries,
beforeSlices: sliceEditQuickConflict.baseSlices,
afterSlices: sliceEditQuickConflict.pendingSlices,
anchorTime: sliceEditQuickConflict.anchorTime,
autoFollows: sliceEditQuickConflict.autoFollows,
}
: null,
[sliceEditQuickConflict],
);
// 冲突清单 Enter(R2-Q2):未决条目按默认落定(03 引擎 resolver 语义),产物过自检
// 后原子落库;拖动来源整段手势 + 处置合并为一条可撤销历史。失败保留清单(重试/Esc)。
// 成功时返回焦点切片 id 供工作台选中(拆分来源为新片;拖动来源为被拖片)。
const handleSliceEditQuickConflictApply = async (decisions: Partial<Record<string, SliceEditChoice>>) => {
if (!annotationAuthoringRef.current) return;
const prompt = sliceEditQuickConflict;
if (!prompt) return;
// 经由具名输入绕开 JSDoc 推断的窄参数类型(引擎实现源是 JS + JSDoc,家族同款)。
const resolveInput = {
baseSlices: prompt.baseSlices,
pendingSlices: prompt.pendingSlices,
actions: prompt.actions,
choices: decisions,
};
const resolution = resolveSliceEditConflicts(resolveInput) as {
slices: SliceSegment[];
actions: AnnotationSegment[];
};
if ((await applySliceEditQuickResolution(prompt, resolution)) !== "applied") return;
sliceDragEditRef.current = null;
setSliceEditQuickConflict(null);
setError("");
return prompt.focusSliceId;
};
// 冲突清单 Esc(R2-Q3/R1-Q4):拖动来源整段回退到拖动前快照(边界回原位、不留
// 历史);拆分等未落库来源直接丢弃(改动从未发生)。
const handleSliceEditQuickConflictCancel = () => {
if (sliceEditQuickApplyingRef.current || saving) return;
const prompt = sliceEditQuickConflict;
if (!prompt) return;
setSliceEditQuickConflict(null);
if (!annotationAuthoringRef.current) {
sliceDragEditRef.current = null;
return;
}
setError("");
const edit = prompt.dragEdit;
if (!edit) return;
sliceDragEditRef.current = null;
const before = edit.before;
if (segments === prompt.baseSegments) {
// 干净路径(常态):拖动预览只改了切片几何,整段精确还原。
setSliceSegments(before.slices);
setSegments(before.segments);
setSliceStatuses(before.statuses);
setSliceOperations(before.operations);
} else {
// 清单期间有过其它编辑:只回滚边界几何(「边界停在原地」的承诺),
// 保留用户之后的修改,状态按当前动作重新推导。
setSliceSegments(before.slices);
setSliceStatuses(deriveSliceStatuses(before.slices, segments, sliceStatuses) as typeof sliceStatuses);
}
};
const adjustSlice = async (id: string, field: "start" | "end", value: number) => {
if (!annotationAuthoringRef.current) return;
// 冲突清单开着时冻结其它边界改动,防止待决快照被打穿。
if (sliceEditQuickConflict) return;
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 (
!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 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);
}
// 拖动进行中(beginSliceBoundaryEdit 已开快照):只挪切片几何,动作一律不动,
// 越界/贴边处置统一延迟到松手(finishSliceBoundaryEdit 落定),拖动途中不改写动作。
if (sliceDragEditRef.current) {
applySliceChange(next, { type: "adjust", segmentIds: affected }, segments);
return;
}
// 提交式挪动(slice 相 ←/→ 与 Shift 粗步进;票 06 起与拖动释放/拆分/垃圾桶同走
// 03 引擎管线——单一处置入口):无冲突立即生效(贴边无效自动跟随在 resolver 内),
// 有冲突弹 04 同款冲突清单,Esc = 本次挪动从未发生(边界停在原地)。
const prompt: SliceEditQuickConflict = {
entries: [],
baseSlices: sliceSegments,
...quickSliceEditActionSnapshot(segments),
pendingSlices: next,
operation: { type: "adjust", segmentIds: affected, at: value },
anchorTime: value,
focusSliceId: id,
dragEdit: null,
};
const plan = planSliceEditDragRelease({
baseSlices: prompt.baseSlices,
pendingSlices: prompt.pendingSlices,
actions: prompt.actions,
});
if (plan.kind === "conflict") {
setSliceEditQuickConflict({
...prompt,
entries: plan.entries as SliceEditConflictEntry[],
autoFollows: plan.autoFollows as SliceEditAutoFollow[],
});
return;
}
if (
(await applySliceEditQuickResolution(prompt, plan.resolution)) !== "applied" &&
detailRef.current?.task.id === prompt.taskId
)
setSliceEditQuickConflict(prompt);
};
const splitSlice = async (index: number, requestedAt = annotationPlayheadRef.current) => {
if (!annotationAuthoringRef.current) return;
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) return;
// 票 05 范围 4(单一处置入口):拆分点先过 03 引擎——无冲突照旧立即拆分(返回
// 新片供选中),有冲突(拆分点从动作内部穿过)弹 04 同款冲突清单,Enter 落定 /
// Esc 整体取消(改动未落库,直接丢弃)。
const prompt: SliceEditQuickConflict = {
entries: [],
baseSlices: sliceSegments,
...quickSliceEditActionSnapshot(segments),
pendingSlices: split.slices,
operation: { type: "split", segmentIds: [current.id], at },
anchorTime: at,
focusSliceId: split.selectedSliceId ?? current.id,
dragEdit: null,
};
const plan = planSliceEditDragRelease({
baseSlices: prompt.baseSlices,
pendingSlices: prompt.pendingSlices,
actions: prompt.actions,
});
if (plan.kind === "conflict") {
setSliceEditQuickConflict({
...prompt,
entries: plan.entries as SliceEditConflictEntry[],
autoFollows: plan.autoFollows as SliceEditAutoFollow[],
});
return; // 未应用:不选中新片(Enter 落定后经回调返回焦点片)
}
if ((await applySliceEditQuickResolution(prompt, plan.resolution)) === "applied") return split.selectedSliceId;
if (detailRef.current?.task.id === prompt.taskId) setSliceEditQuickConflict(prompt);
return undefined;
};
const mergeSlice = (index: number) => {
if (!annotationAuthoringRef.current) return;
const current = sliceSegments[index];
const nextItem = sliceSegments[index + 1];
if (!current || !nextItem) return;
const merged = mergeSlicePartitions(sliceSegments, index, "left");
if (merged) applySliceChange(merged.slices, { type: "merge", segmentIds: [current.id, nextItem.id] });
};
const deleteSlice = async (index: number) => {
if (!annotationAuthoringRef.current) return;
const target = sliceSegments[index];
const merged = target ? cancelSlicePartition(sliceSegments, index) : null;
if (!target || !merged) return;
// 垃圾桶合并(票 05 范围 4):并邻合并不产生冲突条目(03 引擎:合并≠挪动、贴边
// 不跟随),走同一条「扫描→自检→原子落库」管线保持单一处置入口;合并区域回到
// 未定义的既有语义由 applySliceChange 的 merge/delete 过滤承担,产物不变。
const prompt: SliceEditQuickConflict = {
entries: [],
baseSlices: sliceSegments,
...quickSliceEditActionSnapshot(segments),
pendingSlices: merged.slices,
operation: { type: "delete", segmentIds: [target.id] },
anchorTime: target.start,
focusSliceId: "",
dragEdit: null,
};
const plan = planSliceEditDragRelease({
baseSlices: prompt.baseSlices,
pendingSlices: prompt.pendingSlices,
actions: prompt.actions,
});
if (plan.kind === "conflict") {
setSliceEditQuickConflict({
...prompt,
entries: plan.entries as SliceEditConflictEntry[],
autoFollows: plan.autoFollows as SliceEditAutoFollow[],
});
return;
}
if (
(await applySliceEditQuickResolution(prompt, plan.resolution)) !== "applied" &&
detailRef.current?.task.id === prompt.taskId
)
setSliceEditQuickConflict(prompt);
};
const updateSliceName = (id: string, name: string, dictionary?: DictionarySelection) => {
if (!annotationAuthoringRef.current) return;
if (!exactFrameEditing || saving || combinedSubmissionLocked || annotationMutationScopeRef.current.busy()) return;
const slice = sliceSegments.find((item) => item.id === id);
if (
!slice ||
slice.deliveryDisposition === "discard" ||
(slice.name === name && JSON.stringify(slice.dictionary) === JSON.stringify(dictionary))
)
return;
const next = sliceSegments.map((item) => (item.id === id ? { ...item, name, dictionary } : item));
const before = sliceEditSnapshot(id);
editHistoryRef.current.record({ before, after: { ...before, slices: next } });
setSliceSegments(next);
};
const setSliceDisposition = async (
sliceId: string,
disposition: "keep" | "discard",
reason: { reason?: string; reasonLabelId?: string; reasonVersion?: number; reasonNote?: string },
recordHistory = true,
restorePreviousName = false,
restoreNameFromVersion?: number,
) => {
if (!annotationAuthoringRef.current) return false;
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return false;
const previousSlice = sliceSegments.find((slice) => slice.id === sliceId);
if (!previousSlice) return false;
let version = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
const location = { sliceId, time: annotationPlayheadRef.current };
const snapshot = (slice: SliceSegment): DispositionEditSnapshot => ({
kind: "disposition",
sliceId,
disposition: slice.deliveryDisposition === "discard" ? "discard" : "keep",
name: slice.name || "",
restoreNameFromVersion: version + 1,
reason: {
reason: slice.discardReason,
reasonLabelId: slice.discardReasonLabelId,
reasonVersion: slice.discardReasonVersion,
reasonNote: slice.discardReasonNote,
},
location,
});
const taskId = detail.task.id;
const token = await beginAnnotationMutation(taskId);
if (!token) return false;
version = token.version;
const before = snapshot(previousSlice);
try {
const payload = {
version: token.version,
sliceId,
disposition,
...(recordHistory && disposition === "keep" ? { resetToPending: true } : {}),
restorePreviousName,
...(restorePreviousName && restoreNameFromVersion ? { restoreNameFromVersion } : {}),
restoreClassifications: !recordHistory,
...reason,
sliceSegments,
segments,
operations: sliceOperations,
statuses: sliceStatuses,
};
const result = await annotationPersistence.settle(token, {
write: () => annotationOperationsApi.setSliceDisposition(taskId, payload),
isApplied: (authoritative: AnnotationTaskDetail) => {
const history = authoritative.humanItem?.subject?.payload?.sliceDispositionHistory as
| Array<{ sliceId?: string; actorUserId?: string; itemVersion?: number; after?: SliceSegment }>
| undefined;
const entry = history?.at(-1);
return (
authoritative.humanItem?.version === token.version + 1 &&
entry?.sliceId === sliceId &&
entry.actorUserId === currentUser?.id &&
entry.itemVersion === token.version + 1 &&
(entry.after?.deliveryDisposition || "keep") === disposition
);
},
});
if (result.status === "stale") return false;
if (result.status !== "confirmed") throw result.error;
const response = result.reconciled
? {
item: result.authoritative.humanItem,
workspace: annotationDraftFromHumanItem(result.authoritative.humanItem),
}
: result.response;
const workspace = annotationPersistence.accept({
taskId,
userId: token.userId,
item: response.item,
workspace: response.workspace,
mode: "full",
});
if (!workspace) return false;
if (recordHistory) {
editHistoryRef.current.markPersisted();
const savedSlice = workspace.sliceSegments.find((slice) => slice.id === sliceId);
if (savedSlice) editHistoryRef.current.record({ before, after: snapshot(savedSlice) });
}
return true;
} catch (error) {
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return false;
await handleAnnotationMutationError(error, "保存切片用途失败", taskId, token);
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return false;
throw error;
} finally {
endAnnotationMutation(token);
}
};
const persistSliceEditApplication = async (
nextSlices: SliceSegment[],
nextSegments: AnnotationSegment[],
focusSliceId: string,
recordHistory = true,
restoredOperations = sliceOperations,
historyBefore?: SliceEditSnapshot,
) => {
if (!annotationAuthoringRef.current) return null;
if (!detail?.humanItem || !selectedClaimedByMe || combinedSubmissionLocked || !exactFrameEditing) return null;
const taskId = detail.task.id;
const before = historyBefore ?? sliceEditSnapshot(focusSliceId);
const token = await beginAnnotationMutation(taskId);
if (!token) return null;
const applicationId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;
const payload = {
version: token.version,
applicationId,
restoreClassifications: !recordHistory,
sliceSegments: nextSlices,
segments: nextSegments,
operations: restoredOperations,
statuses: deriveSliceStatuses(nextSlices, nextSegments, sliceStatuses) as typeof sliceStatuses,
dispositions: sliceEditDispositionCommands(before.slices, nextSlices, {
resetRestoredActions: recordHistory,
restoredActions: nextSegments,
}),
};
try {
const result = await annotationPersistence.settle(token, {
write: () => annotationOperationsApi.applySliceEdit(taskId, payload),
isApplied: (authoritative: AnnotationTaskDetail) => {
const applied = authoritative.humanItem?.subject?.payload?.lastSliceEditApplication as
| { id?: string; actorUserId?: string; version?: number }
| undefined;
return (
authoritative.humanItem?.version === token.version + 1 &&
applied?.id === applicationId &&
applied.actorUserId === currentUser?.id &&
applied.version === token.version + 1
);
},
});
if (result.status === "stale") return null;
if (result.status !== "confirmed") {
setError(getActionErrorMessage(result.error, "切片改动保存失败,预览仍保留,请核对后重试"));
return null;
}
const item = result.reconciled ? result.authoritative.humanItem : result.response.item;
const workspace = result.reconciled
? annotationDraftFromHumanItem(item)
: normalizeAnnotationWorkspace(result.response.workspace);
if (!item || !workspace) {
setError("服务器返回的切片工作区无效,请刷新核对保存结果。");
return null;
}
if (!annotationPersistence.accept({ taskId, userId: token.userId, item, workspace, mode: "full" })) return null;
if (recordHistory) {
editHistoryRef.current.record({
before,
after: {
slices: workspace.sliceSegments,
segments: workspace.segments,
operations: workspace.operations,
statuses: workspace.statuses,
location: before.location,
},
});
editHistoryRef.current.markPersisted();
}
if (recordHistory) {
setWorkbenchDrafts([]);
setSliceEditAppliedRevision((revision) => revision + 1);
}
setError("");
return workspace;
} catch (cause) {
if (annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext()))
setError(getActionErrorMessage(cause, "切片改动保存失败,预览仍保留"));
return null;
} finally {
endAnnotationMutation(token);
}
};
const restorePersistedSliceEdit = async (snapshot: SliceEditSnapshot) => {
if (!annotationAuthoringRef.current) return null;
// Ticket 07(spec §3.5):结构编辑已在标注相解锁(票 02),持久化切片编辑的
// 撤销/重做在标注相也要经服务端快照恢复;物化/质检等阶段仍拒绝。
if (!detail?.humanItem || !selectedClaimedByMe || !["slice", "annotate"].includes(combinedEditorPhase)) return null;
if (sliceEditDispositionCommands(sliceSegments, snapshot.slices).length) {
return persistSliceEditApplication(
snapshot.slices,
snapshot.segments,
snapshot.location.sliceId,
false,
snapshot.operations,
);
}
const taskId = detail.task.id;
const version = detailRef.current?.humanItem?.version ?? detail.humanItem.version;
const payload = {
version,
sliceSegments: snapshot.slices,
operations: snapshot.operations,
segments: snapshot.segments,
statuses: snapshot.statuses,
};
const token = await beginAnnotationMutation(taskId);
if (!token) return null;
payload.version = token.version;
try {
const result = await annotationPersistence.settle(token, {
write: () => annotationOperationsApi.restoreSliceEdit(taskId, payload),
isApplied: (authoritative: AnnotationTaskDetail) => {
const workspace = annotationDraftFromHumanItem(authoritative.humanItem);
return Boolean(
authoritative.humanItem?.version === token.version + 1 &&
authoritative.humanItem.assignedUserId === currentUser?.id &&
authoritative.humanItem.currentStageId === detail.humanItem?.currentStageId &&
workspace &&
annotationWorkspaceMatches(workspace, payload),
);
},
});
if (result.status === "stale") return null;
if (result.status !== "confirmed") {
setError(
`${getActionErrorMessage(result.error, "恢复切片编辑失败")} 撤销历史和当前内容已保留,请核对服务器状态后重试。`,
);
return null;
}
const item = result.reconciled ? result.authoritative.humanItem : result.response.item;
const workspace = result.reconciled
? annotationDraftFromHumanItem(item)
: normalizeAnnotationWorkspace(result.response.workspace);
if (!item || !workspace) return null;
if (!annotationPersistence.accept({ taskId, userId: token.userId, item, workspace })) return null;
return workspace;
} finally {
endAnnotationMutation(token);
}
};
const restoreEdit = async (direction: "undo" | "redo") => {
if (!annotationAuthoringRef.current) return;
if (
!exactFrameEditing ||
!selectedClaimedByMe ||
saving ||
combinedSubmissionLocked ||
!["slice", "annotate"].includes(combinedEditorPhase) ||
annotationMutationScopeRef.current.busy() ||
sliceDragEditRef.current
)
return;
await editHistoryRef.current[direction](
async (
snapshot: SliceEditSnapshot | AnnotationEditSnapshot | DispositionEditSnapshot,
{ persisted }: { persisted: boolean },
) => {
if ("kind" in snapshot && snapshot.kind === "disposition") {
try {
// Replay through the explicit server operation so audit evidence,
// archived descriptions and CAS remain authoritative. Do not record
// the replay as a new edit; history advances only on confirmed success.
if (
!(await setSliceDisposition(
snapshot.sliceId,
snapshot.disposition,
snapshot.reason,
false,
snapshot.disposition === "keep" && Boolean(snapshot.name),
snapshot.restoreNameFromVersion,
))
)
return false;
setHistoryReveal({ ...snapshot.location, revision: ++historyRevealRevisionRef.current });
return true;
} catch {
return false;
}
}
if ("kind" in snapshot) {
const current = confirmedAnnotationWorkspace();
if (!current) return false;
if (!annotationWorkspaceMatches(current, snapshot.persisted)) {
// CAS uses only our latest confirmed version. A failed/conflicting write
// reads for reconciliation but never adopts another writer's version.
try {
if (
!(await confirmAnnotationDescription(
snapshot.persisted.segments,
snapshot.state.sliceId,
undefined,
snapshot.persisted,
))
)
return false;
} catch {
return false;
}
}
setSegments(snapshot.state.segments);
setSliceStatuses(deriveSliceStatuses(sliceSegments, snapshot.state.segments, snapshot.persisted.statuses));
setError("");
setHistoryReveal({
sliceId: snapshot.state.sliceId,
time: snapshot.state.time,
editor: snapshot.state.editor,
revealAnnotation: snapshot.state.revealAnnotation,
revision: ++historyRevealRevisionRef.current,
});
return true;
}
const workspace = persisted ? await restorePersistedSliceEdit(snapshot) : null;
if (persisted && !workspace) return false;
setSliceSegments(workspace?.sliceSegments ?? snapshot.slices);
setSliceOperations(workspace?.operations ?? snapshot.operations);
setSegments(workspace?.segments ?? snapshot.segments);
setSliceStatuses(workspace?.statuses ?? snapshot.statuses);
setError("");
setHistoryReveal({ ...snapshot.location, revision: ++historyRevealRevisionRef.current });
return true;
},
);
};
const alignCurrentSliceBoundaries = () => {
if (!annotationAuthoringRef.current) return;
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) });
};
// A request acceptance or transport error does not establish a stage transition.
// Read back through the existing API, preserving local edits if the result is unknown.
const reconcileStageOperation = async (
taskId: string,
kind: "slice" | "annotate",
token: AnnotationMutationToken,
failureMessage = "",
) => {
const owns = () => annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext());
try {
const next = await annotationOperationsApi.getTask(taskId);
if (!owns()) return;
setStageRecovery(null);
if (kind === "annotate") {
if (combinedSubmissionFinished(next)) {
setDetail(next);
clearEditHistory();
finishQualityHandoff(next);
void loadProject();
} else if (combinedSubmissionState(next.humanItem) === "processing") {
setDetail(next);
setCombinedSubmissionNotice("送检处理中…");
clearEditHistory();
} else {
workSession.pauseContinuous("送检未完成;当前任务已保留,请处理后恢复连续工作。");
setCombinedSubmissionNotice("");
setError(
(failureMessage || "送检尚未完成,已保留当前描述。") +
" 已核对服务器状态;若任务版本或归属变化,请刷新载入权威内容后继续。",
);
}
} else {
const workflow = next.humanItem?.subject?.payload?.sliceWorkflow as
| { status?: string; error?: string }
| undefined;
if (workflow?.status === "processing" || workflow?.status === "completed") {
setDetail(next);
clearEditHistory();
setCombinedEditorPhase("materializing");
setTaskDetailRefreshVersion((current) => current + 1);
} else {
workSession.pauseContinuous("切片生成未完成;当前任务已保留,请处理后恢复连续工作。");
setCombinedEditorPhase("slice");
setError(
(workflow?.error
? `切片生成失败:${workflow.error}`
: failureMessage || "切片生成未完成,已保留当前切片。") +
" 已核对服务器状态;若任务版本或归属变化,请刷新载入权威内容后继续。",
);
}
}
} catch (failure) {
if (!owns()) return;
setCombinedSubmissionNotice("");
workSession.pauseContinuous("阶段结果尚未确认;请先核对阶段结果,再恢复连续工作。");
setStageRecovery({
taskId,
userId: currentAnnotationMutationContext().userId,
kind,
message: `${failureMessage || getActionErrorMessage(failure, "暂时无法读取阶段状态")} 结果尚未确认,编辑已锁定、内容仍保留。请核对服务器结果后继续。`,
});
}
};
const retryStageReadback = async () => {
if (!stageRecovery || !stageResultUnknown || annotationMutationScopeRef.current.busy()) return;
const token = await beginAnnotationMutation(stageRecovery.taskId);
if (!token) return;
try {
await reconcileStageOperation(stageRecovery.taskId, stageRecovery.kind, token);
} finally {
endAnnotationMutation(token);
}
};
const generationHasUnsavedChanges = () =>
Boolean(
generationSnapshotRef.current.drafts ||
(annotationBaselineRef.current && generationSnapshotRef.current.fingerprint !== annotationBaselineRef.current),
);
const prepareGenerationSave = async () => {
if (!annotationAuthoringRef.current || combinedSubmissionLocked || saving) return false;
const ready = await prepareSavedAnnotationGeneration({
snapshot: () => generationSnapshotRef.current,
isDirty: generationHasUnsavedChanges,
waitForPending: () => autosave.waitForPending(),
save: () => autosave.flushNow("slice-confirmation"),
});
if (!ready) setError("当前编辑尚未保存,请核对保存状态后重试;已有内容仍保留。");
return ready;
};
const retryFailedSlices = async (mode = "retryFailed") => {
if (!detail?.humanItem) return;
const taskId = detail.task.id;
await retryAnnotationGeneration({
taskId,
mode,
canStart: () => selectedClaimedByMe && !generationHasUnsavedChanges() && !combinedSubmissionLocked && !saving,
prepare: prepareGenerationSave,
persistence: annotationPersistence,
owns: (token: AnnotationMutationToken) =>
annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext()),
api: annotationOperationsApi,
accepted: (response: { item: HumanItem }) => {
setDetail((current) => (current?.task.id === taskId ? { ...current, humanItem: response.item } : current));
clearEditHistory();
setError("");
setCombinedEditorPhase("materializing");
setTaskDetailRefreshVersion((value) => value + 1);
setRandomClaimNotice(
mode === "reconfirmSaved"
? "已按当前保存内容受理重新生成,切片、标注和分类将保留。"
: mode === "recoverExisting"
? "已受理恢复生成,已保存的切片和标注仍保留。"
: "已受理原失败快照重试;后台完成后可继续处理。",
);
},
conflict: async (message: string, token: AnnotationMutationToken) => {
setError(message);
// Refresh only server-owned action eligibility. Do not replace local
// editing, the saved version, or history on this rejected command.
try {
const next = await annotationOperationsApi.getTask(taskId);
if (annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext()))
setDetail((current) =>
current?.task.id === taskId ? { ...current, editorState: next.editorState } : current,
);
} catch {
// The rejection is definitive; a failed eligibility refresh does not
// turn it into an unknown mutation or discard the editor state.
}
},
reconcile: (failure: unknown, token: AnnotationMutationToken) =>
reconcileStageOperation(taskId, "slice", token, getActionErrorMessage(failure, "切片重试未完成,原内容仍保留")),
});
};
const confirmSlicesAndMaterialize = async () => {
if (!annotationAuthoringRef.current) return;
if (detail?.editorState?.canRecoverGeneration) {
await retryFailedSlices("recoverExisting");
return;
}
if (annotationGenerationConfirmationMode(detail?.editorState) === "reconfirmSaved") {
await retryFailedSlices("reconfirmSaved");
return;
}
if ((detail?.humanItem?.subject.payload?.sliceWorkflow as { status?: string } | undefined)?.status === "failed") {
await retryFailedSlices();
return;
}
if (
combinedSubmissionLocked ||
annotationMutationScopeRef.current.busy() ||
workbenchDrafts.length ||
combinedEditorPhase !== "slice"
)
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;
}
if (!(await prepareGenerationSave())) return;
const confirmationSlices = sliceSegments.map((slice) => ({
...slice,
name: slice.deliveryDisposition === "discard" ? "" : slice.name?.trim() || "",
taskLabelId: "",
taskLabel: "",
annotationStatus: "pending" as const,
}));
const token = await beginAnnotationMutation(detail.task.id);
if (!token) return;
try {
const response = await annotationOperationsApi.confirmSlices(detail.task.id, {
version: token.version,
sliceSegments: confirmationSlices,
sliceOperations,
changeReason: detail.sliceRevisions.length ? "重新确认切片" : "首次确认切片",
});
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return;
clearEditHistory();
setDetail((current) => (current ? { ...current, humanItem: response.item } : current));
if (response.item) {
setHumanPools((current) => ({
...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);
const confirmedSegments = response.preservesAnnotations ? segments : [];
const confirmedStatuses = response.preservesAnnotations
? sliceStatuses
: Object.fromEntries(confirmationSlices.map((slice) => [slice.id, "pending"]));
setSegments(confirmedSegments);
setSliceStatuses(confirmedStatuses);
setCombinedEditorPhase("materializing");
leaveDirtyRef.current = false;
setWorkbenchDrafts([]);
annotationBaselineRef.current = annotationWorkspaceFingerprint(
confirmationSlices,
sliceOperations,
confirmedSegments,
confirmedStatuses,
);
explicitBufferTask.current = "";
if (workPage && detail.task.continuousActions && workSession.isContinuous()) setNextAfterHandoff(detail.task.id);
setShowBatchSliceEditor(false);
setTaskDetailRefreshVersion((current) => current + 1);
} catch (confirmationError) {
await reconcileStageOperation(
detail.task.id,
"slice",
token,
getActionErrorMessage(confirmationError, "确认切片失败"),
);
} finally {
endAnnotationMutation(token);
}
};
// 票 06:首标「重新切片」提交(f980696f~1 取回)——经权威变更核对管线写
// resetSlices,未知结果驻留待核对;成功后回确认切片阶段并重建基线指纹。
const resetToSliceEditing = async () => {
if (!annotationAuthoringRef.current) return;
if (
!detail?.humanItem ||
!selectedClaimedByMe ||
combinedSubmissionLocked ||
combinedEditorPhase === "materializing"
)
return;
const taskId = detail.task.id;
const token = await beginAnnotationMutation(taskId);
if (!token) return;
const attempt =
pendingReslice?.taskId === taskId
? pendingReslice
: {
taskId,
version: detailRef.current?.humanItem?.version ?? detail.humanItem.version,
resetToUnifiedRange,
};
const submittedVersion = pendingReslice?.taskId === taskId ? attempt.version : token.version;
attempt.version = submittedVersion;
setResliceError("");
try {
const result = await annotationPersistence.settle(token, {
write: () =>
pendingReslice?.taskId === taskId
? Promise.reject(new Error("正在核对上次重切请求"))
: annotationOperationsApi.resetSlices(taskId, submittedVersion, attempt.resetToUnifiedRange),
isApplied: (authoritative: AnnotationTaskDetail) =>
sliceResetWasApplied(authoritative, submittedVersion, attempt.resetToUnifiedRange),
});
if (result.status === "stale") return;
if (result.status !== "confirmed") {
const base = getActionErrorMessage(result.error, "重新进入切片流程失败");
setPendingReslice(result.status === "unknown" ? attempt : null);
const message =
result.status === "unknown"
? `${base} 暂时无法核对服务器结果;现有切片和描述仍保留,请勿重复提交并稍后刷新。`
: `${base} 已核对服务器状态,本次重新切片未确认;现有切片和描述仍保留,请刷新载入权威内容后重试。`;
setResliceError(message);
setError(message);
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) {
setPendingReslice(attempt);
setResliceError("重切响应不完整,请核对结果;当前编辑仍保留。");
return;
}
clearEditHistory();
setPendingReslice(null);
setError("");
const nextSlices = workspace.sliceSegments;
confirmedAnnotationWorkspaceRef.current = { taskId, workspace: structuredClone(workspace) };
setDetail((current) => (current ? { ...current, humanItem: confirmedItem } : current));
if (confirmedItem) {
setHumanPools((current) => ({
...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 (!annotationAuthoringRef.current) return;
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([]);
clearEditHistory();
await loadProject();
} catch (saveError) {
setError(getActionErrorMessage(saveError, "提交切片校正失败"));
} finally {
setSaving(false);
}
};
const submitRevision = async () => {
if (!annotationAuthoringRef.current) return;
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 () => {
if (!annotationAuthoringRef.current) return;
// Preserve explicit blank actions; only structural and in-flight edits block handoff.
if (
!detail?.humanItem ||
!selectedClaimedByMe ||
sliceSegments.length === 0 ||
combinedSubmissionLocked ||
workbenchDrafts.length ||
combinedEditorPhase !== "annotate"
)
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 (detail.task.continuousActions && !submissionCheck.canSubmit) {
setError(submissionCheck.reason);
return;
}
if (
!detail?.task.continuousActions &&
segments.some((segment) => segment.status !== "invalid" && !segment.description?.trim())
) {
setError("请保存所有动作描述或明确设为无效");
return;
}
const candidates = invalidSliceConsolidationCandidates(sliceSegments, segments);
const consolidateInvalidSliceIds: string[] = [];
for (const candidate of candidates) {
if (
window.confirm(
`“${candidate.name}”中 ${formatAnnotationTime(candidate.invalidStart)}–${formatAnnotationTime(candidate.invalidEnd)}的无效动作单独占了一个切片。\n\n是否与前后同名切片合并为 ${formatAnnotationTime(candidate.start)}–${formatAnnotationTime(candidate.end)}的完整切片?全部动作描述、无效标记及时间保持不变。\n确定:合并外层;取消:保留原划分。`,
)
)
consolidateInvalidSliceIds.push(candidate.id);
}
if (
candidates.length &&
!window.confirm(
consolidateInvalidSliceIds.length
? `已选择 ${consolidateInvalidSliceIds.length} 处无损合并。提交后重新生成审核视频,原版本保留。确认提交质检?`
: "保留原切片划分,确认提交质检?",
)
)
return;
const currentTaskId = detail.task.id;
const token = await beginAnnotationMutation(currentTaskId);
if (!token) return;
clearEditHistory();
try {
const submission = await annotationOperationsApi.submitCombined(detail.task.id, {
consolidateInvalidSliceIds,
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: !detail.task.continuousActions,
changeReason: detail.task.currentRevision > 0 ? "逐片 JSON 描述返工" : "逐片 JSON 描述完成",
});
if (!annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext())) return;
if (submission.item) setDetail((current) => (current ? { ...current, humanItem: submission.item } : current));
if (submission.status === "processing" && submission.item?.pendingCombinedSubmissionId) {
setCombinedSubmissionNotice("送检处理中…");
leaveDirtyRef.current = false;
setWorkbenchDrafts([]);
annotationBaselineRef.current = annotationFingerprint;
explicitBufferTask.current = "";
if (workPage && detail.task.continuousActions && workSession.isContinuous()) setNextAfterHandoff(currentTaskId);
return;
}
await reconcileStageOperation(currentTaskId, "annotate", token);
} catch (saveError) {
if (annotationMutationScopeRef.current.owns(token, currentAnnotationMutationContext()))
workSession.pauseContinuous("提交请求结果未确认;连续工作已暂停,正在核对当前任务。");
await reconcileStageOperation(
currentTaskId,
"annotate",
token,
getActionErrorMessage(saveError, "提交切片与语义标注失败"),
);
} finally {
endAnnotationMutation(token);
}
};
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)) {
finishQualityHandoff(next);
void loadProject();
return;
}
if (combinedSubmissionState(next.humanItem) !== "processing") {
setCombinedSubmissionNotice("");
if (!next.task.continuousActions) workSession.pauseContinuous("送检处理失败;请处理后恢复连续工作。");
setRandomClaimNotice("送检处理失败;该任务保留占位,可重试或继续其他任务。");
setError("上次提交未完成,已保留描述。请确认任务状态后重新提交。");
void loadProject();
return;
}
} catch (failure) {
if (disposed) return;
workSession.pauseContinuous("送检结果暂未确认或权限已变化;连续工作已暂停,仍在核对当前任务。");
setCombinedSubmissionNotice(
getActionErrorMessage(failure, "暂时无法确认提交结果") + ";仍在核对中,编辑保持锁定,不会重复提交。",
);
// A role change or network failure does not prove success. Continue
// read-only polling so transient failures retain an automatic recovery path.
}
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) => {
if (!annotationAuthoringRef.current) return;
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) => {
if (!annotationAuthoringRef.current) return;
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) => {
if (!annotationAuthoringRef.current) return;
setSliceStatuses((current) => ({ ...current, [sliceId]: "pending" }));
};
const rejectAnnotationInput = async () => {
if (!annotationAuthoringRef.current) return;
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;
const scope = reviewActionContext;
if (scope !== reviewActionContextRef.current) return;
if (!(await reviewDraft.prepareSubmit())) return;
if (scope !== reviewActionContextRef.current) return;
const preparedDraft = reviewDraft.currentDraft();
let rejectionProblems = preparedDraft?.problems || [];
let unlocatedRejection: ReviewProblem[] = [];
if (
stage === "quality" &&
reviewReceiptSupported &&
preparedDraft?.modelVersion === 2 &&
isV5CombinedQuality &&
detail.humanItem &&
detail.humanItem.currentStageId === "quality_review" &&
detail.humanItem.reviewRound > 0
) {
try {
const { baseline } = await reworkApi.baseline(detail.humanItem.id, detail.humanItem.reviewRound);
if (scope !== reviewActionContextRef.current) return;
const resolved = new Set(preparedDraft.confirmations?.filter((c) => c.resolved).map((c) => c.opinionId));
const prior = (baseline?.problems || []).filter((p) => p.scope !== "task" && !resolved.has(p.id));
unlocatedRejection = (baseline?.unlocatedProblems || []).filter((p) => !resolved.has(p.id));
if (decision === "approved" && prior.length + unlocatedRejection.length > 0) {
setError("仍有原退回意见未确认解决,请逐条核对后再通过审核。");
return;
}
rejectionProblems = [...prior, ...rejectionProblems];
} catch (failure) {
if (scope === reviewActionContextRef.current)
setError(getActionErrorMessage(failure, "无法核对原退回意见,请重试"));
return;
}
}
// ADR 0009:整体作用域意见已隐藏,不进打回扁平化文本。
let currentComment =
preparedDraft?.modelVersion === 2
? (decision === "rejected" ? rejectionProblems : preparedDraft.problems)
.filter((p) => p.scope !== "task")
.map((p) => `${reviewProblemLabel(p)}:${p.text}`)
.join("\n")
: reviewComment;
if (decision === "rejected" && unlocatedRejection.length)
currentComment = [currentComment, ...unlocatedRejection.map((p) => p.text)].filter(Boolean).join("\n");
if (reviewSessionItem && !reviewSession.writable) {
setError("本页没有审查编辑权,请接管后继续。");
return;
}
// ADR 0009:审批门只统计可见(局部)问题——隐藏的存量整体意见不拦通过。
if (decision === "approved" && preparedDraft?.problems.some((p) => p.scope !== "task")) {
setError("请先处理已保存的问题,再通过审核。");
return;
}
if (decision === "rejected" && !rejectionProblems.some((p) => p.scope !== "task") && !currentComment.trim()) {
setError("打回必须填写原因,便于操作员按轮次返工。");
return;
}
let effectiveProblemSliceIds = [...problemSliceIds];
if (decision === "rejected" && effectiveProblemSliceIds.length === 0) {
const parsed = parseSegmentCommentsFromText(currentComment);
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);
}
}
const savingOperation = ++savingOperationRef.current;
setSaving(true);
setError("");
try {
const request: ReviewDecisionRequest = {
itemId: detail.humanItem?.id || detail.task.id,
taskId: detail.task.id,
title: captureTaskDisplayName(selectedHumanItem, detail.task),
decision,
scopeText:
decision === "rejected" ? "该任务退回标注员,按已保存问题修正。" : "该任务通过质检,进入后续审核流程。",
path: `/api/plugins/annotation-qa/tasks/${encodeURIComponent(detail.task.id)}/reviews`,
payload: {
...{
stage,
decision,
comment: currentComment,
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,
},
draftVersion: preparedDraft?.version ?? 0,
resultVersion: preparedDraft?.resultVersion || "",
},
};
const result = reviewReceiptSupported
? await reviewDecision.request(request, reviewSession.headers)
: await (async () => {
const { draftVersion: _draft, resultVersion: _result, ...payload } = request.payload;
await reviewDecisionApi.send(request.path, payload, reviewSessionItem ? reviewSession.headers() : {});
return { operationId: "" };
})();
if (!result) return;
if (scope !== reviewActionContextRef.current) return;
if (detail.humanItem) {
await completeReviewDecision(request, result, {
message: decision === "rejected" ? "任务已打回给标注员进行返工修改。" : "任务已审核通过,流转至下一阶段。",
onSelected: () => {
setReviewComment("");
setProblemSliceIds([]);
},
});
} else {
// Legacy task-only reviews have no human-item continuation contract.
if (reviewSelectionRef.current.task === detail.task.id) {
setReviewComment("");
setProblemSliceIds([]);
closeTaskAndReturnToPool(
decision === "rejected" ? "任务已打回给标注员进行返工修改。" : "任务已审核通过,流转至下一阶段。",
);
}
void loadProject();
}
} catch (saveError) {
if (scope !== reviewActionContextRef.current) return;
if (saveError instanceof APIError && saveError.code.startsWith("review_")) reviewSession.handleError(saveError);
setError(getActionErrorMessage(saveError, "提交审核决定失败"));
} finally {
if (savingOperationRef.current === savingOperation) 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) => {
const scope = reviewActionScopeRef.current;
const originSelection = JSON.stringify(reviewSelectionRef.current);
setSaving(true);
setError("");
try {
const claimed = await humanLoopApi.claim(item.id, item.version);
if (scope !== reviewActionScopeRef.current) return;
if (!reviewOnly) {
setSelectedAnnotationTaskId(task.id);
setTaskPoolView("mine");
await loadProject();
if (scope === reviewActionScopeRef.current) setTaskDetailRefreshVersion((v) => v + 1);
return;
}
applyReviewClaim(claimed);
if (originSelection !== JSON.stringify(reviewSelectionRef.current)) return;
// Claiming adds to My tasks without navigating away from the pool.
setTasks((current) =>
current.map((t) => (t.id === task.id ? { ...t, assignedUserId: claimed.assignedUserId } : t)),
);
} catch (cause) {
if (scope === reviewActionScopeRef.current)
setError(getActionErrorMessage(cause, "领取任务失败,任务可能已被其他成员领取"));
} finally {
// Unconditional: the UI blocks concurrent operations while saving, and a
// scope change mid-request must not leave saving wedged on (defect 6).
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 = await beginAnnotationMutation(detail.task.id);
if (!token) return;
try {
await humanLoopApi.release(detail.humanItem.id, token.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;
}
const scope = reviewActionScopeRef.current;
const originSelection = JSON.stringify(reviewSelectionRef.current);
setSaving(true);
setError("");
try {
const claimed = await humanLoopApi.claim(item.acceptanceHumanItemId, item.acceptanceHumanItemVersion);
if (scope !== reviewActionScopeRef.current) return;
applyReviewClaim(claimed);
if (originSelection !== JSON.stringify(reviewSelectionRef.current)) return;
setDeliveryPackages((current) =>
current.map((p) =>
p.id === item.id
? { ...p, assignedUserId: claimed.assignedUserId, acceptanceHumanItemVersion: claimed.version }
: p,
),
);
// Preserve the current pool so multiple tasks can be claimed.
} catch (cause) {
if (scope === reviewActionScopeRef.current) setError(getActionErrorMessage(cause, "领取验收任务失败"));
} finally {
// Unconditional: the UI blocks concurrent operations while saving, and a
// scope change mid-request must not leave saving wedged on (defect 6).
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) => {
const scope = reviewActionScopeRef.current;
const originSelection = JSON.stringify(reviewSelectionRef.current);
setSaving(true);
setError("");
try {
const claimed = await humanLoopApi.claim(item.id, item.version);
if (scope !== reviewActionScopeRef.current) return;
applyReviewClaim(claimed);
if (originSelection !== JSON.stringify(reviewSelectionRef.current)) return;
// Explicit Continue enters review; a claim alone preserves the pool.
return claimed;
} catch (cause) {
if (scope === reviewActionScopeRef.current) setError(getActionErrorMessage(cause, "领取包前最终验收失败"));
} finally {
// Unconditional: the UI blocks concurrent operations while saving, and a
// scope change mid-request must not leave saving wedged on (defect 6).
setSaving(false);
}
};
const randomClaimAcceptanceTask = async () => {
if (reviewRandomClaimFlight.current || randomClaimBusy || saving || loading) return;
if (!reviewDraftGuardRef.current()) return;
const scope = reviewActionScopeRef.current;
const selection = JSON.stringify(reviewSelectionRef.current);
const isCurrent = () =>
scope === reviewActionScopeRef.current && selection === JSON.stringify(reviewSelectionRef.current);
reviewRandomClaimFlight.current = true;
setRandomClaimBusy(true);
setRandomClaimNotice("");
try {
const candidates = await loadReviewClaimCandidates({
human: humanLoopApi,
filters: {
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
capture: requestedCaptureDirectory || undefined,
stageIds: ["prepackage_acceptance"],
},
isCurrent,
});
if (!isCurrent() || !candidates || !reviewDraftGuardRef.current()) return;
if (!candidates.length) {
setRandomClaimNotice("当前没有可领取的最终验收任务。");
return;
}
const item = candidates[Math.floor(Math.random() * candidates.length)];
const claimed = await claimPrepackageAcceptance(item);
if (!claimed || !isCurrent()) return;
setTaskPoolView("mine");
setSelectedAnnotationTaskId("");
setExpandedDeliveryPackageId(item.id);
const next = new URLSearchParams(searchParams);
next.set("acceptanceId", item.id);
next.delete("taskId");
setSearchParams(next, { replace: true });
} catch (cause) {
if (isCurrent()) setRandomClaimNotice(getActionErrorMessage(cause, "加载可领取任务失败,请重试"));
} finally {
reviewRandomClaimFlight.current = false;
setRandomClaimBusy(false);
}
};
const randomReviewClaimTask = async () => {
if (
reviewRandomClaimFlight.current ||
randomClaimBusy ||
isManager ||
!reviewOnly ||
acceptanceWorkspace ||
saving ||
loading
)
return;
if (!reviewDraftGuardRef.current()) return;
const scope = reviewActionScopeRef.current;
const selection = JSON.stringify(reviewSelectionRef.current);
const isCurrent = () =>
scope === reviewActionScopeRef.current && selection === JSON.stringify(reviewSelectionRef.current);
reviewRandomClaimFlight.current = true;
setRandomClaimBusy(true);
setRandomClaimNotice("");
try {
const candidates = await loadReviewClaimCandidates({
human: humanLoopApi,
filters: {
projectId: projectId || undefined,
workflowId: requestedWorkflowId || undefined,
runId: requestedRunId || undefined,
capture: requestedCaptureDirectory || undefined,
stageIds: humanItemStageIdsForMode(workspaceMode),
},
isCurrent,
});
if (!isCurrent() || !candidates || !reviewDraftGuardRef.current()) return;
if (!candidates.length) {
setRandomClaimNotice("当前暂无可领取的审核任务。");
return;
}
const candidate = candidates[Math.floor(Math.random() * candidates.length)];
const claimed = await humanLoopApi.claim(candidate.id, candidate.version);
if (!isCurrent()) return;
applyReviewClaim(claimed);
setTaskPoolView("mine");
setSelectedAnnotationTaskId(claimed.legacyTaskId || "");
setExpandedDeliveryPackageId("");
const next = new URLSearchParams(searchParams);
const claimProjectId = claimed.projectId || candidate.projectId || projectId;
if (claimProjectId) next.set("projectId", claimProjectId);
next.set("taskId", claimed.legacyTaskId || "");
next.delete("sliceId");
next.delete("eventId");
next.delete("acceptanceId");
setSearchParams(next, { replace: true });
} catch (cause) {
if (isCurrent()) setRandomClaimNotice(getActionErrorMessage(cause, "随机领取审核任务失败,请刷新后重试"));
} finally {
reviewRandomClaimFlight.current = false;
setRandomClaimBusy(false);
}
};
const decidePrepackageAcceptance = async (
item: HumanItem,
statistics: PrepackageAcceptanceStatistics,
decision: "approved" | "rejected",
strictThreeRole: boolean,
acceptanceComment = reviewComment,
) => {
const scope = reviewActionContext;
if (scope !== reviewActionContextRef.current) return;
if (!(await reviewDraft.prepareSubmit())) return;
if (scope !== reviewActionContextRef.current) return;
const preparedDraft = reviewDraft.currentDraft();
if (preparedDraft?.modelVersion === 2)
acceptanceComment = preparedDraft.problems.map((p) => `${reviewProblemLabel(p)}:${p.text}`).join("\n");
if (reviewSessionItem && !reviewSession.writable) {
setError("本页没有审查编辑权,请接管后继续。");
return;
}
if (decision === "approved" && (preparedDraft?.problems.length || 0) > 0) {
setError("请先处理已保存的问题,再通过验收。");
return;
}
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" && !preparedDraft?.problems.length && !acceptanceComment.trim()) {
setError("整包验收不通过必须填写问题说明。");
return;
}
if (decision === "approved" && strictThreeRole && acceptanceComment.trim()) {
// Previously this state only silently disabled the 验收通过 button; now
// the click itself explains the way out (acceptance-fixes defect 6).
// Strict-only: confirm-only legacy items cannot 打回 (server forbids
// reject on ConfirmOnly stages), so their comment rides along as the
// approval audit note instead (defect 5, Lane B).
setError("已填写验收意见:请先清空意见再通过,或改为「打回质检」提交意见。");
return;
}
const savingOperation = ++savingOperationRef.current;
setSaving(true);
setError("");
try {
const request: ReviewDecisionRequest = {
itemId: item.id,
title: captureTaskDisplayName(item, undefined),
decision,
scopeText:
decision === "rejected"
? `整批退回质检,影响全部 ${((item.subject?.payload?.items || []) as unknown[]).length} 个来源任务。`
: "验收通过,待打包",
path: `/api/human-items/${encodeURIComponent(item.id)}/decisions`,
payload: {
...{
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,
},
draftVersion: preparedDraft?.version ?? 0,
resultVersion: preparedDraft?.resultVersion || "",
},
};
const result = reviewReceiptSupported
? await reviewDecision.request(request, reviewSession.headers)
: await (async () => {
const { draftVersion: _draft, resultVersion: _result, ...payload } = request.payload;
await reviewDecisionApi.send(request.path, payload, reviewSessionItem ? reviewSession.headers() : {});
return { operationId: "" };
})();
if (!result) return;
if (scope !== reviewActionContextRef.current) return;
await completeReviewDecision(request, result, {
message: decision === "rejected" ? "验收结果已保存,已打回。" : "验收通过,待打包",
onSelected: () => setPrepackageComments((current) => ({ ...current, [item.id]: "" })),
});
} catch (confirmError) {
if (scope !== reviewActionContextRef.current) return;
if (confirmError instanceof APIError && confirmError.code.startsWith("review_"))
reviewSession.handleError(confirmError);
setError(
getActionErrorMessage(
confirmError,
decision === "rejected" ? "整包打回失败" : "确认最终验收失败;下游打包未释放",
),
);
} finally {
// Always release the shared saving flag unless a newer operation owns it;
// never couple this to reviewActionScope (see savingOperationRef note).
if (savingOperationRef.current === savingOperation) setSaving(false);
}
};
const selectProject = (nextProjectId: string) => {
if (!reviewDraftGuardRef.current()) return;
if (annotationDirty) {
setError("当前任务有未确认修改;请先放弃修改后再切换项目。");
return;
}
if (nextProjectId === projectId) return;
if (workspaceMode === "acceptance") {
const resume = reviewContinuousRunning || Boolean(reviewProjectResume.current);
reviewContinuation.pause("正在切换验收项目范围…");
if (resume) reviewProjectResume.current = `${currentUser?.id || ""}:${nextProjectId}:acceptance:${reviewOnly}`;
reviewSelectionRef.current = { task: "", acceptance: "" };
setExpandedDeliveryPackageId("");
setSelectedAnnotationTaskId("");
setDetail(null);
}
setProjectId(nextProjectId);
const next = new URLSearchParams(searchParams);
if (nextProjectId) next.set("projectId", nextProjectId);
else next.delete("projectId");
next.delete("taskId");
next.delete("acceptanceId");
next.delete("workflowId");
next.delete("capture");
next.delete("runId");
setSearchParams(next, { replace: true });
};
const selectWorkflow = (nextWorkflowId: string) => {
if (!reviewDraftGuardRef.current()) return;
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 (!reviewDraftGuardRef.current()) return;
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 = "") => {
if (!reviewDraftGuardRef.current()) return;
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");
next.delete("acceptanceId");
setSearchParams(next, { replace: true });
};
const finishQualityHandoff = (next: AnnotationTaskDetail) => {
++bufferReadEpochRef.current;
// This is an authoritative successful handoff, not a client eligibility guess.
if (blindAnnotator && annotatorTaskView === "active")
setHumanPools((current) => ({ ...current, mine: current.mine.filter((item) => item.id !== next.humanItem?.id) }));
if (!workPage) {
closeTaskAndReturnToPool("审核数据已生成,任务已提交质检。");
return;
}
const identity = `${currentUser?.id}:${projectId}:${next.task.id}:${next.humanItem?.currentRevision}`;
if (handledHandoffs.current.has(identity)) return;
handledHandoffs.current.add(identity);
annotationBaselineRef.current = "";
leaveDirtyRef.current = false;
setWorkbenchDrafts([]);
clearEditHistory();
setCombinedSubmissionNotice("审核数据已生成,任务已提交质检。");
explicitBufferTask.current = "";
if (workSession.hasContinuousIntent()) setNextAfterHandoff(next.task.id);
};
const selectTask = (taskId: string) => {
if (!reviewDraftGuardRef.current()) return;
if (taskId !== selectedTaskId && annotationDirty) {
setPendingTaskId(taskId);
return;
}
if (taskId && workPage && !workSession.active) {
void resumeOwnedTask(taskId);
return;
}
explicitBufferTask.current = taskId;
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 workPoolPath = `/plugins/annotation-qa/workflows/all/annotate?projectId=${encodeURIComponent(projectId)}`;
const manualTaskId = selectedTaskId || requestedTaskId;
const manualWorkPath = `/plugins/annotation-qa/workflows/all/annotate?projectId=${encodeURIComponent(projectId || requestedProjectId)}${manualTaskId ? `&taskId=${encodeURIComponent(manualTaskId)}` : ""}`;
const openWorkTask = (taskId: string, session: AnnotationWorkSession) => {
if (!workSession.activate(session)) return;
const params = new URLSearchParams({ projectId, taskId });
navigate(`/plugins/annotation-qa/workflows/all/work?${params.toString()}`);
setTaskPoolView("mine");
};
async function resumeOwnedTask(taskId: string) {
if (viewportBlocksDispatch() || !canAccessWorkspace || workEntryFlight.current) return;
const origin = claimContextRef.current;
workEntryFlight.current = true;
setWorkEntryBusy(true);
let session: AnnotationWorkSession | null = null;
try {
const acquisition = await workSession.acquire();
if (acquisition.status !== "acquired") return;
session = acquisition.session;
if (claimContextRef.current !== origin || !claimPermissionRef.current) return;
workSession.setContinuous(session, workSession.prefersContinuous());
explicitBufferTask.current = taskId;
openWorkTask(taskId, session);
} finally {
if (session && !session.active) workSession.release(session);
workEntryFlight.current = false;
setWorkEntryBusy(false);
}
}
const randomClaimTask = async (
enterWorkPage = false,
entryStillCurrent?: () => boolean,
session?: AnnotationWorkSession,
) => {
if (viewportBlocksDispatch()) return;
const origin = claimContextRef.current;
const taskOrigin = annotationMutationContextRef.current.current();
let requestSession = session;
const canContinue = () =>
enterWorkPage
? Boolean(entryStillCurrent?.())
: claimContextRef.current === origin &&
annotationMutationContextRef.current.current() === taskOrigin &&
!leaveDirtyRef.current &&
claimPermissionRef.current &&
(!requestSession || workSession.owns(requestSession));
if (!blindAnnotator || !projectId || !currentUser || randomClaimFlight.current || annotationDirty || !canContinue())
return;
const actorID = currentUser.id;
const selectedProject = projectId;
const key = `droboticflow.random-claim:${actorID}:${selectedProject}`;
randomClaimFlight.current = true;
setRandomClaimBusy(true);
setRandomClaimNotice("");
let requestId = "";
try {
if (!enterWorkPage) {
const acquisition = await workSession.acquire();
if (acquisition.status === "acquired") requestSession = acquisition.session;
// Manual HTTP claims rely on the server's atomic allocation and receipt.
// Unsupported coordination is not a held lock, and never enables /work.
else if (acquisition.status !== "unsupported" || workPage) return;
if (!canContinue()) return;
}
requestId = pendingClaimRequest(key);
if (viewportBlocksDispatch()) return;
if (!requestId) requestId = newAnnotationClaimRequestID();
// Fail closed if persistence is unavailable: a closed tab must never lose
// the logical request and allocate a second task when it is reopened.
localStorage.setItem(key, requestId);
randomClaimKeys.current[key] = requestId;
try {
sessionStorage.setItem(key, requestId);
} catch {}
const response = await annotationOperationsApi.randomClaim(selectedProject, requestId);
try {
forgetClaimRequest(key, requestId);
} catch {}
if (claimContextRef.current.userId !== actorID || claimContextRef.current.projectId !== selectedProject) return;
if (!response.item || !response.task) {
if (canContinue()) {
const message = response.message || "本项目暂无您可领取的标注任务";
setRandomClaimNotice(message);
workSession.pauseContinuous(`${message};连续工作已暂停,可稍后恢复。`);
}
return;
}
const item = response.item,
task = response.task;
// A confirmed allocation remains owned even if entry was cancelled by
// editing or switching tasks. Reconcile the pool without moving focus.
++bufferReadEpochRef.current;
setHumanPools((current) => ({ ...current, mine: [item, ...current.mine.filter((i) => i.id !== item.id)] }));
setTasks((current) => [task, ...current.filter((t) => t.id !== task.id)]);
if (!canContinue()) return;
if (
item.assignedUserId !== actorID ||
!["claimed", "in_progress", "rework"].includes(item.status) ||
!["annotation_combined", "semantic_annotation"].includes(item.currentStageId)
) {
const message = "已核对原领取结果,但该任务已完成或归属已变化;请核对我的任务后恢复连续工作。";
setRandomClaimNotice(message);
workSession.pauseContinuous(message);
void loadProject();
return;
}
++projectLoadRequestRef.current;
setLoading(false);
setProjectLoadError("");
setTaskPoolView("mine");
setAnnotatorTaskView("active");
if (enterWorkPage && session) openWorkTask(task.id, session);
else selectTask(task.id);
setRandomClaimNotice("已领取");
} catch (cause) {
if (
["claim_result_unavailable", "claim_candidate_taken", "annotation_buffer_full"].includes(
(cause as { code?: string }).code,
)
) {
// The server has definitively resolved this receipt as unavailable.
// Pause now; a new logical request still requires another explicit action.
try {
forgetClaimRequest(key, requestId);
} catch {}
}
if (
claimContextRef.current.userId === actorID &&
claimContextRef.current.projectId === selectedProject &&
canContinue()
) {
const message = getActionErrorMessage(cause, "领取结果暂未确认,请重试;同一次请求不会重复分配任务。");
setRandomClaimNotice(message);
workSession.pauseContinuous(`${message} 连续工作已暂停;恢复时沿用原请求编号核对。`);
}
} finally {
if (!enterWorkPage && requestSession && !requestSession.active) workSession.release(requestSession);
randomClaimFlight.current = false;
setRandomClaimBusy(false);
}
};
const claimTaskManually = async () => {
if (!workPage || workSession.active) return randomClaimTask();
if (viewportBlocksDispatch() || !canAccessWorkspace || workEntryFlight.current || annotationDirty) return;
const origin = claimContextRef.current;
workEntryFlight.current = true;
setWorkEntryBusy(true);
let session: AnnotationWorkSession | null = null;
try {
const acquisition = await workSession.acquire();
if (acquisition.status !== "acquired") return;
session = acquisition.session;
if (claimContextRef.current !== origin || !claimPermissionRef.current) return;
workSession.setContinuous(session, workSession.prefersContinuous());
const epoch = workSession.continuousEpoch();
await randomClaimTask(
true,
() =>
claimContextRef.current === origin &&
workSession.owns(session) &&
workSession.continuousEpoch() === epoch &&
claimPermissionRef.current,
session,
);
} finally {
if (session && !session.active) workSession.release(session);
workEntryFlight.current = false;
setWorkEntryBusy(false);
}
};
// Reconcile one account/project buffer without navigating or touching editor
// drafts. Requests already in flight are recorded even after an immediate pause.
const reconcileWorkBuffer = async (stillCurrent: () => boolean, refill = false) => {
if (!projectId || !currentUser || bufferFlight.current) return null;
const actorID = currentUser.id,
originProject = projectId,
origin = claimContextRef.current;
const sameScope = () =>
claimContextRef.current === origin && origin.userId === actorID && origin.projectId === originProject;
let snapshotEpoch = bufferReadEpochRef.current;
let allocationEpoch = snapshotEpoch;
bufferFlight.current = true;
try {
const key = `droboticflow.random-claim:${actorID}:${originProject}`;
const buffer = await refillAnnotationWorkBuffer({
refill,
readBuffer: () => {
snapshotEpoch = bufferReadEpochRef.current;
return annotationOperationsApi.workBufferSummary(originProject);
},
shouldContinue: () =>
(!detailRef.current || Boolean(detailRef.current.task.continuousActions)) &&
stillCurrent() &&
sameScope() &&
workSession.hasContinuousIntent() &&
!annotationMutationScopeRef.current.busy() &&
snapshotEpoch === bufferReadEpochRef.current &&
!viewportBlocksDispatch(),
claim: async () => {
allocationEpoch = bufferReadEpochRef.current;
const requestId = pendingClaimRequest(key) || newAnnotationClaimRequestID();
localStorage.setItem(key, requestId);
randomClaimKeys.current[key] = requestId;
try {
const response = await annotationOperationsApi.randomClaim(originProject, requestId, true);
forgetClaimRequest(key, requestId);
return response;
} catch (cause) {
if ((cause as { code?: string }).code !== "annotation_buffer_full") throw cause;
forgetClaimRequest(key, requestId);
return { item: null };
}
},
onClaim: ({ item, task }) => {
// Keep confirmed ownership even if the user switched to manual while
// the request was in flight; never allocate another item in that case.
if (!sameScope() || allocationEpoch !== bufferReadEpochRef.current) return;
++bufferReadEpochRef.current;
setHumanPools((pools) => ({ ...pools, mine: [item, ...pools.mine.filter((old) => old.id !== item.id)] }));
setTasks((tasks) => [task, ...tasks.filter((old) => old.id !== task.id)]);
},
});
if (!sameScope() || snapshotEpoch !== bufferReadEpochRef.current || annotationMutationScopeRef.current.busy())
return null;
// Only newly observed identities need a full record for the existing
// sidebar. Stable polls do not reload details or manufacture full items.
const known = new Set(humanPoolsSnapshotRef.current.mine.map((item) => item.id));
const discovered = buffer.enabled
? await Promise.all(
buffer.summaries
.filter((item) => !known.has(item.id))
.map(async (summary) => (await humanLoopApi.getItem(summary.id)).item),
)
: [];
if (!sameScope() || snapshotEpoch !== bufferReadEpochRef.current || annotationMutationScopeRef.current.busy())
return null;
setWorkBuffer(buffer);
if (!buffer.enabled) return buffer;
const managedIds = bufferManagedIdsRef.current;
setHumanPools((pools) => ({
...pools,
mine: reconcileAnnotationBufferSummaries(
[...pools.mine, ...discovered.filter((item) => !pools.mine.some((old) => old.id === item.id))],
buffer.summaries,
{
userId: actorID,
projectId: originProject,
managedIds,
},
),
}));
bufferManagedIdsRef.current = new Set(buffer.summaries.map((item) => item.id));
const current = detailRef.current;
if (
current?.task.continuousActions &&
current.humanItem &&
isOwnedRecoverableAnnotationItem(current.humanItem, originProject, actorID)
) {
const missing = !buffer.summaries.some((item) => item.id === current.humanItem?.id);
setExternalBufferTaskId(missing ? current.task.id : null);
if (missing && externalBufferTaskId !== current.task.id)
workSession.pauseContinuous("当前任务已离开个人任务池,编辑内容已保留,请核对任务状态。");
}
return buffer;
} finally {
bufferFlight.current = false;
}
};
const startWork = async (resumeOnly = false, advance = false) => {
if (viewportBlocksDispatch()) return;
if (
!blindAnnotator ||
!canAccessWorkspace ||
!projectId ||
!currentUser ||
!projects.some((project) => project.id === projectId) ||
loading ||
projectLoadError ||
annotationDirty ||
saving ||
randomClaimFlight.current ||
workEntryFlight.current
)
return;
const actorID = currentUser.id;
const selectedProject = projectId;
const taskSessionAtEntry = annotationMutationContextRef.current.current();
const claimSessionAtEntry = claimContextRef.current;
let continuousEpoch = workSession.continuousEpoch();
let session: AnnotationWorkSession | null = null;
const entryStillCurrent = () =>
claimContextRef.current === claimSessionAtEntry &&
workSession.continuousEpoch() === continuousEpoch &&
!leaveDirtyRef.current &&
workSession.owns(session) &&
claimPermissionRef.current &&
annotationMutationContextRef.current.current() === taskSessionAtEntry;
const deferEntryForViewport = () => {
if (!viewportBlocksDispatch()) return false;
const activeSession = session?.active ? session : null;
viewportDeferredEntryRef.current = {
resumeOnly,
// An inactive entry can release its lock while suspended. Preserve its
// intent, not its stale read response; Continue will acquire and reread.
isCurrent: () =>
claimContextRef.current === claimSessionAtEntry &&
annotationMutationContextRef.current.current() === taskSessionAtEntry &&
!leaveDirtyRef.current &&
claimPermissionRef.current &&
(!activeSession || (workSession.owns(activeSession) && workSession.hasContinuousIntent())),
};
return true;
};
viewportDeferredEntryRef.current = null;
workEntryFlight.current = true;
setWorkEntryBusy(true);
setRandomClaimNotice("");
try {
const acquisition = await workSession.acquire();
if (acquisition.status !== "acquired") return;
session = acquisition.session;
continuousEpoch = workSession.continuousEpoch();
if (!entryStillCurrent()) return;
workSession.setContinuous(session, workSession.prefersContinuous());
continuousEpoch = workSession.continuousEpoch();
const key = `droboticflow.random-claim:${actorID}:${selectedProject}`;
const unresolvedClaim = pendingClaimRequest(key);
if (unresolvedClaim && workSession.prefersContinuous()) {
// Resolve the previous logical claim before considering another task.
await randomClaimTask(true, entryStillCurrent, session);
return;
}
// Read ownership at the explicit entry action. A stale pool list must not
// cause another allocation, or reopen a task already handed to review.
const buffer =
(await reconcileWorkBuffer(
() => entryStillCurrent() && !viewportBlocksDispatch(),
workSession.prefersContinuous(),
)) || (await annotationOperationsApi.workBufferSummary(projectId));
if (!buffer || !entryStillCurrent() || deferEntryForViewport()) return;
const buffered = buffer.enabled && (!detailRef.current || Boolean(detailRef.current.task.continuousActions));
const mine = buffered
? buffer.summaries
: await humanLoopApi.listItems({ pluginId: "annotation-qa", projectId: selectedProject, pool: "mine" });
if (!entryStillCurrent() || deferEntryForViewport()) return;
const owned = mine.filter((item) => isOwnedRecoverableAnnotationItem(item, selectedProject, actorID));
const unfinished = buffered
? readyBufferedItems(
buffer.summaries.filter((item) => isOwnedRecoverableAnnotationItem(item, selectedProject, actorID)),
buffer.processing,
)
: owned;
const current = (!advance && unfinished.find((item) => item.legacyTaskId === selectedTaskId)) || unfinished[0];
if (current) {
const { task } = await annotationOperationsApi.getTaskSummary(current.legacyTaskId);
if (!entryStillCurrent() || deferEntryForViewport()) return;
++projectLoadRequestRef.current;
if (buffered) {
const { item } = await humanLoopApi.getItem(current.id);
if (!entryStillCurrent() || deferEntryForViewport()) return;
setHumanPools((pools) => ({ ...pools, mine: [item, ...pools.mine.filter((old) => old.id !== item.id)] }));
} else {
setHumanPools((pools) => ({ ...pools, mine: mine as HumanItem[] }));
}
setTasks((items) => [task, ...items.filter((item) => item.id !== task.id)]);
// A refresh resumes only persisted state, never the old editor/history.
if (workPage) {
clearEditHistory();
setDetail(null);
setTaskDetailRefreshVersion((version) => version + 1);
}
openWorkTask(task.id, session);
} else if (!buffered) {
if (resumeOnly) setRandomClaimNotice("没有可继续的已领取任务;可返回任务池开始工作。");
else if (workSession.prefersContinuous()) await randomClaimTask(true, entryStillCurrent, session);
else setRandomClaimNotice("手动接取");
} else {
workSession.activate(session);
setRandomClaimNotice(
buffer.summaries.some((item) => item.sourceValidationStatus === "failed")
? "源数据异常,待管理员处理。"
: buffer.occupied
? "已领取任务均在处理中或需要重试;等待就绪任务,不额外领取。"
: "公共池暂无可领取任务,可稍后继续。",
);
if (!workPage) navigate(`/plugins/annotation-qa/workflows/all/work?projectId=${encodeURIComponent(projectId)}`);
}
} catch (cause) {
if (entryStillCurrent()) {
const message = getActionErrorMessage(cause, "无法核对当前任务,请重试开始工作;尚未领取新任务。");
setRandomClaimNotice(message);
workSession.pauseContinuous(`${message} 连续工作已暂停。`);
}
} finally {
if (session && !session.active) workSession.release(session);
workEntryFlight.current = false;
setWorkEntryBusy(false);
}
};
// Run only after the authoritative stage mutation has settled. A single
// handoff queues one entry; owned-first entry and its origin/session fences
// remain responsible for choosing or claiming the next task.
useEffect(() => {
if (!nextAfterHandoff || saving || loading || workEntryBusy || randomClaimBusy || viewportBlocksDispatch()) return;
setNextAfterHandoff("");
if ((selectedTaskId !== nextAfterHandoff && nextAfterHandoff !== "buffer-waiting") || !workSession.isContinuous())
return;
if (!blindAnnotator || !canAccessWorkspace || projectLoadError) {
workSession.pauseContinuous("项目或标注权限已变化;连续工作已暂停,请核对后恢复。");
return;
}
void startWork(false, true);
}, [nextAfterHandoff, saving, loading, workEntryBusy, randomClaimBusy, viewportPaused]);
useEffect(() => {
if (
workPage &&
workSession.continuous &&
(!blindAnnotator || (!loading && !canAccessWorkspace) || projectLoadError)
)
workSession.pauseContinuous("项目或标注权限已变化;连续工作已暂停,请核对后恢复。");
}, [workPage, workSession.continuous, blindAnnotator, canAccessWorkspace, projectLoadError, loading]);
const resumeContinuousWork = async () => {
if (viewportBlocksDispatch()) return;
if (!blindAnnotator || !canAccessWorkspace) return;
// Enabling while editing must preserve the current drafts and history.
if (
workSession.active &&
workSession.owns() &&
selectedClaimedByMe &&
detail &&
!combinedSubmissionFinished(detail)
) {
const origin = claimContextRef.current;
const acquisition = await workSession.acquire();
if (acquisition.status === "acquired" && claimContextRef.current === origin && claimPermissionRef.current)
workSession.setContinuous(acquisition.session, workSession.prefersContinuous());
} else {
await startWork();
}
};
const toggleContinuousWork = async () => {
const enabled = !workSession.prefersContinuous();
try {
workSession.setContinuousEnabled(enabled);
if (!enabled) {
setNextAfterHandoff(null);
setRandomClaimNotice("已切换为手动接取");
} else {
await resumeContinuousWork();
}
} catch (cause) {
setRandomClaimNotice(
getActionErrorMessage(
cause,
enabled
? "无法保存工作模式,未开启自动接取。"
: "本次已停止自动接取,但未能保存选择;重新打开前请检查浏览器存储权限。",
),
);
}
};
useEffect(() => {
if (!blindAnnotator || !projectId || !canAccessWorkspace) return;
let disposed = false;
const origin = claimContextRef.current;
const refresh = async () => {
if (disposed || claimContextRef.current !== origin || workEntryFlight.current || randomClaimFlight.current)
return;
const epoch = workSession.continuousEpoch();
const mayContinue = () =>
!disposed &&
claimContextRef.current === origin &&
workSession.continuousEpoch() === epoch &&
workSession.isContinuous() &&
claimPermissionRef.current;
try {
const buffer = await reconcileWorkBuffer(mayContinue, workPage && mayContinue());
if (buffer && !buffer.enabled) {
window.clearInterval(timer);
return;
}
if (
!buffer ||
!buffer.enabled ||
(detailRef.current && !detailRef.current.task.continuousActions) ||
!mayContinue() ||
leaveDirtyRef.current ||
saving ||
annotationMutationScopeRef.current.busy()
)
return;
const selected = buffer.summaries.find((item) => item.legacyTaskId === selectedTaskId);
if (selectedTaskId && explicitBufferTask.current === selectedTaskId) return;
if (
(!selected || !readyBufferedItems([selected], buffer.processing).length) &&
readyBufferedItems(buffer.summaries, buffer.processing).length
) {
setNextAfterHandoff(selectedTaskId || "buffer-waiting");
}
} catch (cause) {
if (!disposed && claimContextRef.current === origin) {
setRandomClaimNotice(getActionErrorMessage(cause, "个人任务池状态暂未确认,请重试。"));
if (workBuffer.enabled || detailRef.current?.task.continuousActions)
workSession.pauseContinuous("个人任务池结果待核对,连续工作已暂停;已发请求保留原编号。");
}
}
};
void refresh();
const timer = window.setInterval(refresh, 3000);
return () => {
disposed = true;
window.clearInterval(timer);
};
}, [
projectId,
currentUser?.id,
blindAnnotator,
canAccessWorkspace,
workPage,
// Continuing the same task can navigate to a new location without changing
// its ID. Restart the poll with that location's claim scope; the previous
// effect must keep rejecting its own late responses.
location.key,
workSession.continuous,
selectedTaskId,
saving,
]);
const changeBufferCapacity = async (capacity: number) => {
if (!workBuffer.enabled) return;
const origin = claimContextRef.current;
setCapacityBusy(true);
try {
const buffer = await annotationOperationsApi.setWorkBufferCapacity(projectId, capacity);
if (claimContextRef.current !== origin) return;
setWorkBuffer(summarizeWorkBuffer(buffer));
const epoch = workSession.continuousEpoch();
if (workSession.isContinuous())
await reconcileWorkBuffer(
() =>
claimContextRef.current === origin && workSession.continuousEpoch() === epoch && workSession.isContinuous(),
true,
);
} catch (cause) {
if (claimContextRef.current === origin) setRandomClaimNotice(getActionErrorMessage(cause, "任务容量更新失败"));
} finally {
setCapacityBusy(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";
const focusedStageLayout =
workPage && workspaceLayout === "focused" && ["slice", "materializing", "annotate"].includes(combinedEditorPhase);
// 票 06(D1 修订版):首标(从未送检)才提供「重新切片」入口;判定与后端
// handleSliceResetCreate(fanyuV5CombinedSubmissionIsRework)逐字同口径——任务
// 修订栅栏、返修状态、非 system 修订任一命中即视为已送检;修订作者按
// strings.TrimSpace 归一后判 system,空作者同样阻断(否则按钮可见但点击吃 409)。
// 前端只做交互反馈,服务端闸门兜底。
const resliceEligible = Boolean(
detail &&
workspaceMode === "annotate" &&
detail.task.currentRevision === 0 &&
detail.task.status !== "rework" &&
!detail.revisions.some((revision) => revision.revision > 0 && revision.authorUserId.trim() !== "system"),
);
const recoverableWork = humanPools.mine.filter((item) =>
isOwnedRecoverableAnnotationItem(item, projectId, currentUser?.id),
);
const showViewportPrompt = viewportPaused && pendingTaskId === null && leaveBlocker.state !== "blocked";
// Rendered once, at the end of whichever top row the current layout shows.
const taskDiagnosticsLink = (
<a
className="annotation-task-diagnostics shrink-0 text-xs text-slate-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-300"
target="_blank"
rel="noopener noreferrer"
href={`/diagnostics?${new URLSearchParams({ itemId: reviewSessionItem?.id || detail?.humanItem?.id || selectedHumanItem?.id || "", taskId: detail?.task?.id || selectedTaskId || "" })}`}
>
当前任务连接诊断
</a>
);
const workspaceContent = (
<div
inert={showViewportPrompt || Boolean(reviewDecision.confirmation) || undefined}
aria-hidden={showViewportPrompt || Boolean(reviewDecision.confirmation) || undefined}
className="annotation-operations-page space-y-4"
data-review-focused={reviewFocused || undefined}
data-adaptive-slice={adaptiveSliceLayout || undefined}
data-work-page={workPage || undefined}
data-workspace-layout={workPage ? workspaceLayout : undefined}
data-workspace-stage={combinedEditorPhase}
data-workspace-compact={focusedStageLayout || undefined}
>
{reviewFocused && (
<div className="review-focus-heading">
<h1>{workspaceMode === "acceptance" ? "最终验收" : "质检审查"}</h1>
<span className="truncate">
{detail
? captureTaskDisplayName(selectedHumanItem, detail.task)
: captureTaskDisplayName(reviewSessionItem, undefined)}
</span>
<span
role="status"
className="review-continuation-status truncate text-base font-semibold"
title={reviewContinuation.message}
>
{reviewContinuation.message}
</span>
<button
type="button"
className="shrink-0 rounded border px-3 py-1"
title={
reviewSession.snapshot?.decisionProtocol === "legacy"
? "历史流程任务(仅确认验收)不支持连续审查,请直接在验收面板操作"
: undefined
}
disabled={
!reviewContinuousRunning &&
(reviewContinuation.busy ||
viewportPaused ||
reviewWindowUndersized ||
Boolean(reviewDecision.pending) ||
reviewSession.snapshot?.decisionProtocol === "legacy")
}
onClick={() => {
if (reviewContinuousRunning) reviewContinuation.pause();
else if (leaveDraftGuard("开始连续审查")) void reviewContinuation.start();
}}
>
{reviewContinuousRunning ? "暂停连续审查" : "开始/继续审查"}
</button>
<button
type="button"
className="shrink-0 rounded border px-3 py-1"
onClick={() => {
if (!leaveDraftGuard("返回任务池")) return;
reviewContinuation.pause();
const next = new URLSearchParams(searchParams);
next.delete("reviewFocus");
setSearchParams(next);
}}
>
返回任务池
</button>
{taskDiagnosticsLink}
</div>
)}
{draftGuardNotice && (
<div
role="alert"
data-testid="draft-guard-notice"
className="mb-2 flex flex-wrap items-center justify-between gap-2 rounded border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:bg-amber-950/40"
>
<span>{draftGuardNotice}</span>
<button type="button" className="underline" onClick={() => setDraftGuardNotice("")}>
知道了
</button>
</div>
)}
{reworkReceiveEligible && reworkReceive.error && (
<p role="alert">无法核对原退回意见:{userErrorMessage(reworkReceive.error)}。请重新打开任务后重试。</p>
)}
{reviewOnly && reviewDecision.message && (
<div
role="status"
className="review-decision-status rounded-lg border border-sky-500/40 bg-sky-500/10 px-4 py-3 text-base font-semibold text-sky-900 dark:text-sky-100"
>
<span>{userErrorMessage(reviewDecision.message)}</span>
{reviewDecision.pending && (
<>
<button
type="button"
className="ml-3 underline"
disabled={reviewDecision.busy}
onClick={() => void reviewDecision.reconcile()}
>
查看提交结果
</button>
{reviewDecision.canRetry && (
<button
type="button"
className="ml-3 underline"
disabled={
reviewDecision.busy ||
!reviewSession.writable ||
reviewSessionItem?.id !== reviewDecision.pending.itemId
}
onClick={() => reviewDecision.retry(reviewSession.headers)}
>
重试提交
</button>
)}
</>
)}
</div>
)}
{deferReviewReports && refreshingProject && (
<p role="status" data-testid="review-background-refresh" className="text-xs text-slate-500">
正在后台更新任务列表,当前任务可继续操作。
</p>
)}
{deferReviewReports && reviewAuxiliaryError && (
<p role="alert" className="text-sm text-amber-700">
{userErrorMessage(reviewAuxiliaryError)}
</p>
)}
{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-[color:var(--app-border)] bg-[color:var(--app-panel)] p-5 shadow-2xl"
>
<div className="text-base font-semibold text-[color:var(--app-text)]">当前任务有未确认修改</div>
<div className="mt-2 text-sm leading-6 text-slate-500 dark:text-gray-400">
离开将清空本次未确认的切片调整和各片未保存的描述草稿。
</div>
<div className="mt-5 flex justify-end gap-2">
<button
type="button"
onClick={cancelLeave}
autoFocus
className="rounded-lg border border-[color:var(--app-control-border)] px-4 py-2 text-sm text-slate-700 transition-colors hover:bg-slate-50 dark:text-gray-200 dark:hover:bg-white/5"
>
继续编辑
</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-700 transition-colors hover:bg-red-500/15 dark:text-red-200"
>
清空并切换
</button>
</div>
</div>
</div>
) : null}
{externalBufferTaskChanged && (
<div
role="alert"
className="rounded-lg border border-amber-500 bg-amber-50 p-3 text-sm text-amber-900"
data-testid="external-buffer-task-notice"
>
当前任务已不在个人待处理任务池中,可能已在其他页面送检或被重新分配。已暂停编辑和自动保存,当前内容保留。
请先复制未保存内容,再重新打开任务核对最新状态。
</div>
)}
<div className="annotation-workspace-heading space-y-3">
{blindAnnotator && projectId ? (
<div className="annotation-work-buffer flex flex-wrap items-center gap-2 text-xs" aria-label="个人任务容量">
{workBuffer.enabled && (!detail || detail.task.continuousActions)
? `个人任务池 ${workBuffer.occupied}/${workBuffer.capacity}`
: "工作模式"}
<AnnotationWorkModeToggle
enabled={workSession.continuousEnabled}
onToggle={() => void toggleContinuousWork()}
disabled={
loading ||
saving ||
(annotationDirty && !workSession.active) ||
workEntryBusy ||
randomClaimBusy ||
!canAccessWorkspace ||
workSession.unavailable ||
workSession.blocked
}
/>
{workBuffer.enabled && (!detail || detail.task.continuousActions) ? (
<>
<select
aria-label="任务池容量"
value={workBuffer.capacity}
disabled={capacityBusy}
onChange={(event) => void changeBufferCapacity(Number(event.target.value))}
className="rounded border px-2 py-1"
>
{[2, 3, 4, 5, 6, 7, 8].map((capacity) => (
<option key={capacity} value={capacity}>
容量 {capacity}
</option>
))}
</select>
</>
) : null}
{workPage && !workSession.active ? (
<button
type="button"
onClick={() => void claimTaskManually()}
disabled={
loading ||
saving ||
annotationDirty ||
workEntryBusy ||
randomClaimBusy ||
!canAccessWorkspace ||
workSession.unavailable ||
workSession.blocked
}
className="rounded border border-orange-500 px-3 py-1 font-semibold text-orange-600 disabled:opacity-50"
>
{randomClaimBusy ? "正在领取…" : "随机领取任务"}
</button>
) : null}
{workPage && workBuffer.summaries.length > 0 ? (
<select
aria-label="个人任务切换"
value={selectedTaskId}
onChange={(event) => selectTask(event.target.value)}
className="max-w-56 rounded border px-2 py-1"
>
<option value="">选择已领取任务</option>
{workBuffer.summaries.map((item) => {
const phase = { status: item.sliceStatus };
const taskName = item.display?.captureDirectories?.join("、") || "未识别Capture";
return (
<option key={item.id} value={item.legacyTaskId} title={taskName}>
{item.sourceValidationStatus
? `${item.sourceValidationStatus === "failed" ? "源数据异常" : "待校验"} · `
: phase?.status === "failed" || workBuffer.processing?.[item.id]?.status === "failed"
? "失败待重试 · "
: item.pendingCombinedSubmissionId
? "送检处理中 · "
: phase?.status === "processing"
? "切片生成中 · "
: ""}
{taskName}
</option>
);
})}
</select>
) : null}
</div>
) : null}
{workPage && workSession.active ? (
<section aria-label="连续工作" className={`${panelClass} space-y-3 p-4`}>
<p role="status" className="text-sm" title={workSession.pauseReason || undefined}>
{workSession.continuous ? "连续工作中" : workSession.pauseReason || "手动接取"}
</p>
</section>
) : null}
{workPage ? (
<div className="annotation-work-page-navigation flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-lg font-semibold">标注工作页</h1>
<p className="text-xs text-gray-500">
{projects.find((project) => project.id === projectId)?.name || "请选择项目"}
</p>
</div>
<div className="flex items-center gap-3">
{!reviewFocused && taskDiagnosticsLink}
<Link
onClick={() => workSession.pauseContinuous("已返回任务池,连续工作暂停。")}
to={workPoolPath}
className="rounded-lg border px-3 py-2 text-sm"
>
返回任务池
</Link>
</div>
</div>
) : (
<>
<h1 className="sr-only">{workspaceTitle}</h1>
<div className="flex items-end">
<div className="min-w-0 flex-1">
<PageSubnav compact items={annotationStageTabs} label="标注中心阶段导航" />
</div>
{!reviewFocused && (
<div className="flex min-h-8 shrink-0 items-start border-b border-slate-200 pl-3 dark:border-[#2a2b2f]">
{taskDiagnosticsLink}
</div>
)}
</div>
</>
)}
{!workPage || !selectedTaskId ? (
<div
className={cn(
"annotation-workspace-filters grid items-end gap-2",
// One track per rendered control, so the refresh icon never inherits a 1fr track.
isManager
? "md:grid-cols-2 xl:grid-cols-[minmax(170px,0.7fr)_auto_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.25fr)_auto]"
: blindAnnotator
? "md:grid-cols-[minmax(0,1fr)_auto_auto]"
: "md:grid-cols-2 xl:grid-cols-[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 px-3 py-2 text-sm text-slate-600 transition-colors hover:border-blue-500/60 hover:text-blue-600 dark:text-gray-300 dark:hover:text-white"
>
主动抽检
</Link>
) : null}
<label className="min-w-0 space-y-1 text-[11px] text-gray-500">
<span>1. 项目</span>
<select
className={inputClass}
aria-label="1. 项目"
value={projectId}
onChange={(event) => selectProject(event.target.value)}
disabled={workEntryBusy || 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-[11px] 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-[11px] 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>
)}
{!workPage && blindAnnotator && workspaceMode === "annotate" ? (
<button
type="button"
onClick={() => void startWork()}
disabled={
!projectId ||
loading ||
Boolean(projectLoadError) ||
!canAccessWorkspace ||
!projects.some((project) => project.id === projectId) ||
workEntryBusy ||
randomClaimBusy ||
workSession.blocked ||
workSession.unavailable ||
saving ||
annotationDirty
}
title={
annotationDirty
? "请先确认当前编辑,再进入工作页"
: "按任务池旁的工作模式进入;手动模式不会自动领取新任务"
}
className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
>
{workEntryBusy ? "正在进入…" : "开始工作"}
</button>
) : null}
<button
type="button"
onClick={() => setProjectLoadRetryVersion((v) => v + 1)}
className="inline-flex h-[38px] w-[38px] items-center justify-center justify-self-start rounded-lg border bg-[color:var(--app-panel)] text-slate-500 transition-colors hover:border-blue-500/60 hover:text-blue-600 dark:text-gray-300 dark:hover:text-white"
title="刷新"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</button>
</div>
) : null}
</div>
{!reviewOnly && (workSession.blocked || workSession.unavailable) ? (
<div role="status" className="space-y-3 rounded-xl border border-amber-500/30 bg-amber-500/10 p-4 text-sm">
{!workSession.supported ? (
<>
<p>连接不安全,无法开启连续工作。请使用 HTTPS 或返回手动工作台。</p>
{workPage ? (
<Link to={manualWorkPath} className="inline-block rounded-lg border px-3 py-2">
返回手动工作台
</Link>
) : null}
</>
) : workSession.coordinationError ? (
<p>当前页面暂时无法领取任务。</p>
) : (
<>
<p>任务正在其他页面编辑,请返回原页面。</p>
<button type="button" onClick={workSession.returnToActivePage} className="rounded-lg border px-3 py-2">
返回活动工作页
</button>
</>
)}
</div>
) : null}
{workPage && workSession.supported && !workSession.active ? (
<section aria-label="恢复工作会话" className={`${panelClass} space-y-4 p-5`}>
<h2 className="font-semibold">继续已领取任务</h2>
{loading ? <p>正在核对已领取任务…</p> : null}
{recoverableWork.map((item) => (
<button
key={item.id}
type="button"
aria-pressed={selectedTaskId === item.legacyTaskId}
disabled={workEntryBusy}
onClick={() => selectTask(item.legacyTaskId)}
className={cn(
"block w-full rounded-lg border p-3 text-left text-sm",
selectedTaskId === item.legacyTaskId && "border-blue-500 bg-blue-500/10",
)}
>
{captureTaskDisplayName(
item,
tasks.find((task) => task.id === item.legacyTaskId),
)}
<span className="ml-3 text-xs text-gray-500">
{workBuffer.summaries.find((summary) => summary.id === item.id)?.sourceValidationStatus === "failed"
? "源数据异常"
: "已领取"}{" "}
· {item.legacyTaskId}
</span>
</button>
))}
{!loading && !recoverableWork.length ? <p className="text-sm">当前没有可继续的已领取任务。</p> : null}
<button
type="button"
onClick={() => void startWork(true)}
disabled={
loading ||
Boolean(projectLoadError) ||
!projectId ||
!canAccessWorkspace ||
workEntryBusy ||
workSession.blocked ||
workSession.unavailable
}
className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
>
{workEntryBusy ? "正在核对…" : "继续工作"}
</button>
</section>
) : null}
{(workPage && randomClaimNotice) ||
(selectedClaimedByMe &&
(detail?.humanItem?.subject.payload?.sliceWorkflow as { status?: string } | undefined)?.status === "failed") ||
(stageResultUnknown && stageRecovery) ||
combinedSubmissionNotice ||
error ||
projectLoadError ||
taskPoolReadError ||
combinedSubmissionConflicted ||
projectLoadRecoveryNotice ? (
<details className="workspace-status-details" open>
<summary>
工作状态{error || projectLoadError || taskPoolReadError || stageResultUnknown ? " · 需处理" : ""}
</summary>
<div className="workspace-status-content">
{workPage && randomClaimNotice ? (
<p role="status" className="text-sm">
{userErrorMessage(randomClaimNotice)}
</p>
) : null}
{selectedClaimedByMe &&
(detail?.humanItem?.subject.payload?.sliceWorkflow as { status?: string } | undefined)?.status ===
"failed" ? (
<FailedSliceRecoveryNotice
onRetry={() => void retryFailedSlices()}
onReconfirmSaved={
detail?.editorState?.canReconfirmSavedGeneration === true
? () => void retryFailedSlices("reconfirmSaved")
: undefined
}
busy={saving || combinedSubmissionLocked}
blockedReason={
stageResultUnknown
? "请先核对上一次操作结果。"
: workbenchDrafts.length > 0
? "请先保存或取消当前描述。"
: workPage && (!workSession.active || !workSession.owns())
? "请先点击开始/继续工作,再重试。"
: ""
}
/>
) : null}
{stageResultUnknown && stageRecovery ? (
<div
role="alert"
className="flex items-center justify-between gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm"
>
<span>{userErrorMessage(stageRecovery.message)}</span>
<button
type="button"
disabled={saving}
onClick={() => void retryStageReadback()}
className="shrink-0 rounded border px-3 py-2 disabled:opacity-50"
>
核对阶段结果
</button>
</div>
) : null}
{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 || taskPoolReadError ? (
<div
role="alert"
className="rounded-xl border border-red-500/50 bg-red-50 px-4 py-3 text-sm font-medium leading-6 text-red-900 dark:bg-red-950/40 dark:text-red-100"
>
{(error || projectLoadError || taskPoolReadError)?.includes("project annotation membership is required")
? "您当前没有该任务所属项目的标注成员权限(或该任务所属项目已归档/移除)"
: error || projectLoadError || taskPoolReadError}
</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}
</div>
</details>
) : 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`}>
{rejectLoading && <p role="status">正在加载退回记录…</p>}
{rejectError && (
<p role="alert">
{rejectError}
<button onClick={() => setProjectLoadRetryVersion((v) => v + 1)}>重试</button>
</p>
)}
<button
className="mr-2 rounded border border-gray-500 px-3 py-1 text-sm disabled:opacity-40"
disabled={rejectLoading || !rejectCursor}
onClick={() => setRejectCursor("")}
>
返回首页
</button>
<button
className="mr-2 rounded border border-gray-500 px-3 py-1 text-sm disabled:opacity-40"
disabled={rejectLoading || !rejectNextCursor}
onClick={() => setRejectCursor(rejectNextCursor)}
>
下一页
</button>
<div className="flex items-center justify-between">
<div>
<div className="text-lg font-semibold text-white">拒绝区</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} · {stripTaskOpinionLines(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" && (!workPage || workSession.active) ? (
<div
className={cn(
"annotation-task-workspace grid grid-cols-[minmax(0,1fr)] gap-4",
!workPage && "xl:grid-cols-[220px_minmax(0,1fr)]",
)}
>
{!workPage ? (
<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",
"我的任务",
blindAnnotator && annotatorTaskView === "submitted"
? submittedHumanItems.length
: poolCounts.mine,
],
...(reviewOnly
? ([
["reviewed", workspaceMode === "acceptance" ? "我已验收" : "我已审核", poolCounts.reviewed],
] as const)
: []),
...(isManager ? ([["all", "全部任务", poolCounts.all]] as const) : []),
] as Array<[TaskPoolView, string, number]>
).map(([value, label, count]) => (
<button
key={value}
type="button"
onClick={() => {
if (!reviewDraftGuardRef.current()) return;
if (value === "reviewed") reviewContinuation.pause();
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}{" "}
{(managerAnnotationPool && adminPoolTotals?.scope !== projectDataScope) ||
(pagedReviewPool && reviewPoolTotals?.scope !== projectDataScope)
? "—"
: blindAnnotator && value === "available"
? claimableCount.projectId === projectId
? (claimableCount.count ?? "—")
: "—"
: count}
{/* Counts only loaded pages; a further page means more exist. */}
{blindAnnotator && value === "mine" && minePoolCursorRef.current ? "+" : ""}
</button>
))}
</div>
{blindAnnotator && (
<div className="mt-3 space-y-2" data-testid="project-random-claim">
<button
type="button"
onClick={() => void randomClaimTask()}
disabled={
!projectId || workEntryBusy || randomClaimBusy || annotationDirty || workSession.blocked
}
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">
{userErrorMessage(randomClaimNotice)}
</p>
)}
</div>
)}
{reviewOnly && !isManager && !acceptanceWorkspace && (
<div className="mt-3 space-y-2" data-testid="review-random-claim">
<button
type="button"
onClick={() => void randomReviewClaimTask()}
disabled={saving || loading || randomClaimBusy}
className="w-full rounded-lg bg-orange-500 px-3 py-2 font-semibold text-white disabled:opacity-50"
>
{randomClaimBusy ? "正在领取…" : "随机领取"}
</button>
{randomClaimNotice && (
<p role="status" className="break-words text-xs text-slate-600">
{userErrorMessage(randomClaimNotice)}
</p>
)}
</div>
)}
{reviewOnly && workspaceMode === "acceptance" && !isManager && (
<div className="mt-3 space-y-2" data-testid="acceptance-random-claim">
<button
type="button"
onClick={() => void randomClaimAcceptanceTask()}
disabled={loading || saving || randomClaimBusy || Boolean(projectLoadError)}
className="w-full rounded-lg bg-orange-500 px-3 py-2 font-semibold text-white disabled:opacity-50"
>
{randomClaimBusy ? "正在领取…" : "随机领取"}
</button>
{randomClaimNotice && (
<p role="status" className="break-words text-xs text-slate-600">
{userErrorMessage(randomClaimNotice)}
</p>
)}
</div>
)}
{(!blindAnnotator || taskPoolView === "mine") && (
<>
{blindAnnotator && taskPoolView === "mine" && (
<div className="mt-3 flex gap-2" aria-label="我的任务分类">
{(
[
["active", "待处理"],
["submitted", "已送检"],
] as const
).map(([value, label]) => (
<button
key={value}
type="button"
aria-pressed={annotatorTaskView === value}
className={cn(
"rounded-lg border px-3 py-2 text-xs",
annotatorTaskView === value
? "border-orange-500 bg-orange-50 text-orange-700"
: "border-[color:var(--app-border)]",
)}
onClick={() => {
if (annotationDirty) return;
setAnnotatorTaskView(value);
setTaskStatusFilter("all");
setTaskSearch("");
}}
>
{label}
</button>
))}
</div>
)}
<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);
if (managerAnnotationPool && event.target.value === "source_failed") setTaskPoolView("all");
}}
aria-label="按任务状态筛选"
>
<option value="all">
{blindAnnotator && annotatorTaskView === "active" ? "全部待处理状态" : "全部状态"}
</option>
{managerAnnotationPool && <option value="source_failed">源数据异常</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="rework_review">返工复审</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>
{pagedReviewPool && reviewPoolCountLoading && (
<div role="status" className="mt-2 text-xs text-slate-500">
任务数量加载中…
</div>
)}
{reviewPoolCountError && (
<div
role="alert"
data-testid="review-pool-count-error"
className="mt-2 flex flex-wrap items-center gap-2 text-xs text-red-600"
>
<span>{reviewPoolCountError}</span>
<button
type="button"
aria-label="重试任务数量"
disabled={reviewPoolCountLoading}
onClick={() => setReviewPoolCountRevision((value) => value + 1)}
className="underline"
>
重试
</button>
</div>
)}
<div className="annotation-task-list mt-3 max-h-[calc(100vh-330px)] space-y-1.5 overflow-auto pr-1">
{sidebarLoading && (
<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={taskPoolView !== "reviewed" && item.assignedUserId === currentUser?.id}
assignee={
users.find((user) => user.id === item.assignedUserId)?.name ||
(item.assignedUserId === currentUser?.id ? currentUser?.name || "" : "已领取")
}
claimable={
taskPoolView !== "reviewed" &&
!isManager &&
!item.assignedUserId &&
["ready", "rework", "submitted"].includes(item.status) &&
canCurrentUserClaimItem(item)
}
saving={saving}
onPreview={() => {
if (!leaveDraftGuard("打开其他任务")) return;
setSelectedAnnotationTaskId("");
setExpandedDeliveryPackageId(item.id);
const next = new URLSearchParams(searchParams);
next.set("acceptanceId", item.id);
next.delete("taskId");
setSearchParams(next, { replace: true });
}}
onClaim={() => void claimPrepackageAcceptance(item)}
onContinue={() => {
if (!reviewDraftGuardRef.current()) return;
// Continuing an owned acceptance task is an explicit
// continuous-review entry; header preview is not.
reviewEntryIntent.mark(reviewEntryScope, item.id);
setSelectedAnnotationTaskId("");
setExpandedDeliveryPackageId(item.id);
const next = new URLSearchParams(searchParams);
next.set("acceptanceId", item.id);
next.delete("taskId");
setSearchParams(next, { replace: true });
}}
/>
))}
{renderedVisibleTasks.map((task) => {
const poolItem = visibleHumanItemByTaskId.get(task.id);
const humanItem =
task.id === selectedTaskId && detail?.humanItem
? {
...detail.humanItem,
sourceValidationStatus: poolItem?.sourceValidationStatus,
reviewHistoryStatus: poolItem?.reviewHistoryStatus,
reviewHistory: poolItem?.reviewHistory,
}
: poolItem;
const livePhase = task.id === selectedTaskId ? combinedEditorPhase : undefined;
const detailedStatus = deriveDetailedTaskStatus(task, humanItem, livePhase);
const assignee = users.find((user) => user.id === humanItem?.assignedUserId);
const captureLabel = captureTaskDisplayName(humanItem, task);
const claimable = Boolean(
taskPoolView !== "reviewed" &&
humanItem &&
!humanItem.assignedUserId &&
["ready", "rework", "submitted"].includes(humanItem.status) &&
canCurrentUserClaimItem(humanItem),
);
const claimedByMe = Boolean(
taskPoolView !== "reviewed" &&
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 ||
detailedStatus === "rework_review" ||
isTaskPendingAcceptance ||
isTaskAccepted);
const taskAction = annotationTaskAction({
awaitingDownstream: taskPoolView !== "reviewed" && 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 transition-colors ${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="text-xs font-semibold leading-snug text-[color:var(--app-text)] [overflow-wrap:anywhere]"
title={captureLabel}
>
片段名:
<CaptureName name={captureLabel} />
</div>
<div className="mt-1.5 flex items-center justify-between gap-2">
<div className="min-w-0 truncate text-[11px] tabular-nums text-slate-500 dark:text-gray-500">
{formatAnnotationTime(task.clipStart)}–{formatAnnotationTime(task.clipEnd)}
</div>
{(() => {
switch (humanItem?.sourceValidationStatus || detailedStatus) {
case "failed":
return (
<span className="shrink-0 rounded-full border border-rose-500/50 px-2 py-0.5 text-[11px] font-semibold text-rose-700 dark:text-rose-300">
源数据异常
</span>
);
case "pending":
case "unverified":
return (
<span className="shrink-0 rounded-full border border-amber-500/50 px-2 py-0.5 text-[11px] font-semibold text-amber-700 dark:text-amber-300">
{humanItem.sourceValidationStatus === "pending" ? "校验中" : "待校验"}
</span>
);
case "submitting":
return (
<span className="shrink-0 rounded-full border border-amber-500/50 bg-amber-50 px-2 py-0.5 text-[11px] font-semibold text-amber-700 dark:bg-amber-500/20 dark:text-amber-300">
送检处理中
</span>
);
case "submission_conflicted":
return (
<span className="shrink-0 rounded-full border border-rose-500/50 bg-rose-50 px-2 py-0.5 text-[11px] font-semibold text-rose-700 dark:bg-rose-500/20 dark:text-rose-300">
送检待核对
</span>
);
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-[11px] font-semibold text-rose-700 dark:border-rose-500/40 dark:bg-rose-500/20 dark:text-rose-300">
<AlertCircle className="h-3 w-3" />
打回
</span>
);
case "rework_review":
return (
<span className="shrink-0 inline-flex items-center gap-1 rounded-full border border-amber-500/60 bg-amber-50 px-2 py-0.5 text-[11px] font-semibold text-amber-700 dark:border-amber-500/40 dark:bg-amber-500/20 dark:text-amber-300">
<AlertCircle className="h-3 w-3" />
返工复查
</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-[11px] font-semibold text-amber-700 dark:border-amber-500/40 dark:bg-amber-500/20 dark:text-amber-300">
<Loader2 className="h-3 w-3 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-[11px] 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-[11px] 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-[11px] 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-[11px] 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-[11px] 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-[11px] 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-[11px] font-semibold text-slate-600 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300">
待领取
</span>
);
}
})()}
</div>
{reviewOnly && <ReviewListTrace summary={poolItem?.traceSummary} />}
{taskPoolView === "reviewed" && (
<ReviewHistorySummary
history={poolItem?.reviewHistory}
currentRevision={humanItem?.currentRevision || task.currentRevision}
/>
)}
<div className="mt-1.5 text-[11px] leading-snug text-gray-500">
{detailedStatus === "rework_review" &&
(humanItem?.assignedUserId === currentUser?.id
? "当前:返工待复审 · 您已领取。"
: "当前:返工待复审。")}
{humanItem?.assignedUserId
? `领取人:${assignee?.name || humanItem.assignedUserId}`
: detailedStatus === "pending_quality"
? Number(humanItem?.reviewRound || 0) > 0
? "返工复查:核对修正与原退回意见"
: "待审核员领取质检"
: 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 {
// Resuming an owned review task is an
// explicit continuous-review entry; viewing
// is not.
if (reviewOnly && taskAction.kind === "resume" && humanItem)
reviewEntryIntent.mark(reviewEntryScope, humanItem.id);
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>
);
})}
{(filteredVisibleTasks.length > renderedVisibleTasks.length ||
taskPoolCursorRef.current ||
(pagedReviewPool && reviewPoolCursorsRef.current[taskPoolView]) ||
(blindAnnotator && taskPoolView === "mine" && minePoolCursorRef.current)) && (
<button
type="button"
data-testid="task-pool-show-more"
disabled={taskPoolFetchBusy}
className="w-full rounded border border-dashed border-slate-300 py-2 text-xs text-slate-500 hover:border-orange-400 hover:text-orange-600 disabled:opacity-50 dark:border-[#34363b] dark:text-gray-400"
onClick={() => {
if (filteredVisibleTasks.length > renderedVisibleTasks.length)
setTaskRenderLimit((current) => current + 200);
if (
taskPoolCursorRef.current ||
(pagedReviewPool && reviewPoolCursorsRef.current[taskPoolView]) ||
(blindAnnotator && taskPoolView === "mine" && minePoolCursorRef.current)
)
void taskPoolLoadMore();
}}
>
{taskPoolFetchBusy
? "正在加载更多任务…"
: `显示更多任务(已显示 ${renderedVisibleTasks.length + prepackageAcceptanceItems.length}${taskPoolCursorRef.current || (pagedReviewPool && reviewPoolCursorsRef.current[taskPoolView]) || (blindAnnotator && minePoolCursorRef.current) ? "+" : ""} 条)`}
</button>
)}
{!sidebarLoading &&
!projectLoadError &&
filteredVisibleTasks.length === 0 &&
prepackageAcceptanceItems.length === 0 ? (
<div className="py-8 text-center text-sm text-gray-500">
{visiblePoolItems.length
? reviewOnly && !isManager
? "任务池仍在加载,请稍候;若长时间无变化请刷新页面。"
: "任务关联数据缺失,请联系管理员核查。"
: taskSearch || taskStatusFilter !== "all"
? "没有符合筛选条件的任务"
: !isManager && !requestedRunId && taskPoolView === "available"
? memberPoolEmptyReason(
projectMembers,
currentUser?.id,
projectId,
workspaceMode === "acceptance"
? "acceptance_reviewer"
: workspaceMode === "quality" || workspaceMode === "clip-quality"
? "quality_reviewer"
: "annotator",
)
: blindAnnotator && annotatorTaskView === "submitted"
? "暂无已送检任务"
: scopedEmptyMessage}
</div>
) : null}
</div>
</>
)}
</div>
</div>
) : null}
<div className={`annotation-task-detail-panel ${panelClass} min-w-0 min-h-[615px] p-3`}>
{(reviewOrdinaryContinuationVisible ||
(reviewSessionEnabled && (!reviewFocused || !reviewSession.writable))) && (
<div
role="status"
className="review-session-status mb-2 flex flex-wrap items-center justify-between gap-2 rounded border border-slate-300 px-3 py-2 text-sm"
>
{reviewSessionEnabled && !reviewSession.writable && (
<span>{userErrorMessage(reviewSession.message)}</span>
)}
{reviewOrdinaryContinuationVisible && (
<span
role="status"
className="review-continuation-status truncate text-base font-semibold"
title={reviewContinuation.message}
>
{reviewContinuation.message}
</span>
)}
{reviewOrdinaryContinuationVisible && (
<button
type="button"
data-testid="review-continuation-toggle"
className="rounded border px-3 py-1"
title={
reviewSession.snapshot?.decisionProtocol === "legacy"
? "历史流程任务(仅确认验收)不支持连续审查,请直接在验收面板操作"
: undefined
}
disabled={
!reviewContinuousRunning &&
(reviewContinuation.busy ||
viewportPaused ||
reviewWindowUndersized ||
Boolean(reviewDecision.pending) ||
reviewSession.snapshot?.decisionProtocol === "legacy")
}
onClick={() => {
if (reviewContinuousRunning) reviewContinuation.pause();
else if (leaveDraftGuard("开始连续审查")) void reviewContinuation.start();
}}
>
{reviewContinuousRunning ? "暂停连续审查" : "开始/继续审查"}
</button>
)}
{reviewSessionEnabled && !reviewFocused && reviewReceiptSupported && (
<button
type="button"
className="rounded border px-3 py-1"
onClick={() => {
const next = new URLSearchParams(searchParams);
next.set("reviewFocus", "1");
setSearchParams(next);
}}
>
进入专注审查
</button>
)}
{reviewSessionEnabled && !reviewSession.writable && (
<button
type="button"
className="rounded border px-3 py-1"
onClick={() => void reviewSession.takeover()}
>
在本页接管审查
</button>
)}
</div>
)}
{prepackageAcceptanceItems
.filter((i) => i.id === expandedDeliveryPackageId)
.map((poolItem) => {
const item = isHumanPoolSummary(poolItem) ? acceptanceDetailSelection : poolItem;
if (!item)
return (
<div
key={poolItem.id}
role={acceptancePoolDetailError ? "alert" : "status"}
className="p-3 text-sm"
>
{acceptancePoolDetailError || "正在加载验收内容…"}
{acceptancePoolDetailError && (
<button
type="button"
className="ml-2 underline"
onClick={() => setAcceptanceDetailRetry((value) => value + 1)}
>
重试
</button>
)}
</div>
);
const stats = prepackageAcceptanceDrafts[item.id] || {
...emptyPrepackageAcceptanceStatistics,
headpose: "include",
handpose: "include",
};
const mine = item.assignedUserId === currentUser?.id;
return (
<FinalAcceptanceWorkspace
key={item.id}
item={item}
focusedLayout={reviewFocused}
cameraPreferenceKey={currentUser?.id || ""}
viewportSuspended={viewportPaused}
mine={mine}
writeLocked={taskPoolView === "reviewed" || reviewWriteLocked || Boolean(reviewDecision.pending)}
confirmOnlyLegacy={openAcceptanceConfirmOnly}
reviewProblemsPending={
reviewDraft.loading ||
reviewDraft.dirty ||
reviewDraft.saving ||
Boolean(reviewDraft.draft?.problems.some((problem) => problem.scope !== "task"))
}
reviewProblemPanel={reviewProblemPanel}
reviewTraceEnabled={reviewOnly}
onReviewNavigate={reviewDraft.onNavigate}
onReviewPositionChange={reviewDraft.onPosition}
onReviewController={reviewDraft.onController}
onReviewProblem={reviewDraft.beginProblem}
onReviewSave={() => {
if (!reviewDecision.pending) void reviewDraft.save();
}}
onReviewTimestampJump={reviewDraft.jumpTimestampProblem}
reviewTimestampOpinions={reviewDraft.timestampProblems.map((p) => ({
id: p.id,
sourceItemId: p.sourceItemId,
sliceId: p.sliceId,
timeBasis: p.timeBasis,
atSeconds: p.atSeconds ?? 0,
text: p.text,
}))}
onReviewTargetSwitch={(direction) => reviewDraft.switchTarget(direction)}
onReviewProblemEdit={() => reviewDraft.editSelected()}
onReviewProblemDelete={() => reviewDraft.requestDelete()}
onReviewEscape={reviewDraft.escape}
saving={saving}
error={userErrorMessage(error)}
timeZone={timeZone}
draft={stats}
comment={prepackageComments[item.id] || ""}
onDraftChange={(patch) =>
setPrepackageAcceptanceDrafts((current) => ({
...current,
[item.id]: { ...(current[item.id] || stats), ...patch },
}))
}
onCommentChange={(value) => {
if (!reviewWriteLocked) setPrepackageComments((current) => ({ ...current, [item.id]: value }));
}}
onApprove={() =>
void decidePrepackageAcceptance(
item,
stats,
"approved",
!openAcceptanceConfirmOnly,
prepackageComments[item.id] || "",
)
}
onReject={() =>
void decidePrepackageAcceptance(
item,
stats,
"rejected",
!openAcceptanceConfirmOnly,
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">
<div className="annotation-task-heading flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<div
className={cn(
"text-sm font-semibold text-[color:var(--app-text)]",
focusedStageLayout ? "truncate" : "[overflow-wrap:anywhere]",
)}
title={captureTaskDisplayName(selectedHumanItem, detail.task)}
>
片段名:
<CaptureName name={captureTaskDisplayName(selectedHumanItem, detail.task)} />
</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-600 hover:text-blue-700 dark:text-blue-300 dark: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-[11px] font-medium text-blue-700 dark: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 "submitting":
return (
<span 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-700 dark:text-amber-300">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
送检处理中(尚未进入质检)
</span>
);
case "submission_conflicted":
return (
<span className="rounded-full border border-rose-500/40 bg-rose-500/15 px-2.5 py-1 text-xs font-semibold text-rose-700 dark:text-rose-300">
送检未完成,请核对结果
</span>
);
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-700 dark:text-rose-300">
<AlertCircle className="h-3.5 w-3.5" />
<span>打回(需返工)</span>
</div>
);
case "rework_review":
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-700 dark:text-amber-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-700 dark: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-700 dark: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-700 dark: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="pt-2">
<button
type="button"
onClick={() => setTaskDetailRefreshVersion((current) => current + 1)}
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">
{(draftConflictAuthoritative || autosave.lastSavedAt || autosave.errorNotice) && (
<div className="mb-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-600 dark:text-gray-300">
{draftConflictAuthoritative ? (
<>
<span className="font-medium text-amber-600 dark:text-amber-300">
其他页面已保存较新草稿,请选择保留哪一份:
</span>
<button
type="button"
onClick={adoptServerDraft}
className="rounded-md border border-gray-300 bg-[color:var(--app-panel)] px-2 py-0.5 font-medium shadow-sm transition-colors hover:bg-gray-50 dark:border-[#34363b] dark:hover:border-gray-500"
>
载入服务端草稿(刷新)
</button>
<button
type="button"
onClick={() => void overwriteServerDraft()}
className="rounded-md border border-gray-300 bg-[color:var(--app-panel)] px-2 py-0.5 font-medium shadow-sm transition-colors hover:bg-gray-50 dark:border-[#34363b] dark:hover:border-gray-500"
>
用当前内容覆盖
</button>
<button
type="button"
onClick={() => setDraftConflictAuthoritative(null)}
className="rounded-md px-2 py-0.5 transition-colors hover:text-gray-900 dark:hover:text-white"
>
暂不处理
</button>
</>
) : (
<span className={autosave.errorNotice ? "text-amber-600 dark:text-amber-300" : undefined}>
{autosave.errorNotice ||
(autosave.dirty
? "当前有修改等待自动保存"
: `草稿已自动保存 ${new Date(autosave.lastSavedAt || 0).toLocaleTimeString("zh-CN", {
hour: "2-digit",
minute: "2-digit",
})}`)}
</span>
)}
</div>
)}
{reworkEmphasisEligible && reworkEmphasisData.unlocatedProblems.length > 0 && (
<section className="rounded border border-[color:var(--app-border)] p-3 text-sm space-y-2">
<h3 className="font-medium">验收原文</h3>
{reworkEmphasisData.unlocatedProblems.map((p) => (
<p key={p.id} className="whitespace-pre-wrap">
{p.text}
</p>
))}
</section>
)}
<CaptureAnnotationWorkbench
operationError={error || reworkEmphasisData.error}
operationNotice={
stageResultUnknown
? "正在核对送检结果,当前内容保留,请勿重复提交。"
: combinedSubmissionProcessing
? combinedSubmissionNotice || "送检处理中…"
: combinedSubmissionConflicted
? "送检未完成,当前内容保留;请核对服务器结果后继续。"
: combinedSubmissionNotice ||
(workspaceMode === "annotate" && detail.humanItem?.currentStageId === "quality_review"
? "已成功提交质检,可在“已送检”查看。"
: "")
}
key={`${detail.task.id}:${combinedEditorPhase}:${detail.humanItem?.currentStageId || ""}:${currentUser?.id || ""}`}
seekRequest={reworkSeekRequest}
reworkEmphasis={
reworkEmphasis as import("../lib/rework-emphasis-types").ReworkEmphasisView | null
}
onReworkSkipToggle={
reworkEmphasisEligible && !saving && !combinedSubmissionLocked && !reworkEmphasisData.saving
? (opinionId, skipped) => {
if (annotationAuthoringRef.current)
void reworkEmphasisData.toggleSkip(opinionId, skipped);
}
: undefined
}
onDraftsChange={setWorkbenchDrafts}
onSelectedSliceChange={() => autosave.notifySliceSwitch()}
onAnnotationDraftEdit={() => {
if (annotationAuthoringRef.current) editHistoryRef.current.invalidateRedo();
}}
adaptiveLayout={adaptiveSliceLayout}
focusedLayout={focusedStageLayout || reviewFocused}
viewportSuspended={viewportPaused || showResliceWarning}
taskId={detail.task.id}
cameraPreferenceKey={currentUser?.id || ""}
continuousActions={Boolean(detail.task.continuousActions)}
progressSaved={!annotationDirty}
onSaveProgress={(nextSegments) => confirmAnnotationDescription(nextSegments, "")}
frameTimelineStatus={frameTimelineStatus}
frameTimelineFailure={frameTimelineFailure}
sourceValidationRetrying={sourceValidationRetryTask === detail.task.id}
onRetrySourceValidation={() => void retrySourceValidation()}
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}
actionDictionaryLoading={actionDictionary.loading}
actionDictionaryError={actionDictionary.error}
onRefreshActionDictionary={actionDictionary.refresh}
sliceDictionary={sliceDictionary.items}
sliceDictionaryLoading={sliceDictionary.loading}
sliceDictionaryError={userErrorMessage(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={
combinedSubmissionProcessing
? "送检处理中"
: stageResultUnknown
? "正在核对送检结果"
: combinedSubmissionConflicted
? "送检未完成"
: statusLabels[detail.task.status] || "只读查看"
}
readOnly={
((workspaceMode === "clip" || workspaceMode === "annotate") && !annotationAuthoring) ||
taskPoolView === "reviewed" ||
(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) ||
combinedSubmissionLocked
}
isQualityReview={
taskPoolView !== "reviewed" &&
(workspaceMode === "quality" ||
workspaceMode === "acceptance" ||
workspaceMode === "clip-quality") &&
(selectedClaimedByMe || isManager) &&
detail.task.status !== "accepted"
}
captionsViewable={
(workspaceMode === "quality" ||
workspaceMode === "acceptance" ||
workspaceMode === "clip-quality") &&
Boolean(detail.task.assignedUserId || selectedHumanItem?.assignedUserId)
}
reviewMode={workspaceMode === "acceptance" ? "acceptance" : "quality"}
reviewRejectLabel={
reworkReceive.baselines.some(
(b) => b.round === reviewDraft.draft?.reviewRound && b.stageId === "quality_review",
)
? "退回标注员"
: undefined
}
reviewApprovalBlocked={
workspaceMode === "quality" &&
reworkReceiveEligible &&
(reworkReceive.loading ||
Boolean(reworkReceive.error) ||
reworkReceive.baselines.some(
(b) =>
b.round === reviewDraft.draft?.reviewRound &&
[...b.problems, ...(b.unlocatedProblems || [])].some(
(p) => !reviewDraft.confirmations.some((c) => c.opinionId === p.id && c.resolved),
),
))
}
reviewWriteLocked={reviewWriteLocked || Boolean(reviewDecision.pending)}
reviewReadOnlyNotice={
reviewSessionEnabled && !reviewSession.writable
? "本页只读,点上方「在本页接管审查」后可审核"
: ""
}
reviewProblemPanel={reviewProblemPanel}
reviewTracePanel={reviewTracePanel}
onReviewNavigate={reviewDraft.onNavigate}
onReviewPositionChange={reviewDraft.onPosition}
onReviewController={handleReviewController}
onReviewReworkNavigate={
reworkReceiveEmphasis?.jumpOrder.length ? onReviewReworkNavigate : undefined
}
onReviewReworkVerdict={
reworkReceiveEmphasis?.jumpOrder.length ? onReviewReworkVerdict : undefined
}
reviewReworkEmphasis={reworkReceiveEmphasis}
onReviewProblem={reviewDraft.beginProblem}
onReviewSave={() => {
if (!reviewDecision.pending) void reviewDraft.save();
}}
onReviewTimestampJump={reviewDraft.jumpTimestampProblem}
reviewTimestampOpinions={reviewDraft.timestampProblems.map((p) => ({
id: p.id,
sourceItemId: p.sourceItemId,
sliceId: p.sliceId,
timeBasis: p.timeBasis,
atSeconds: p.atSeconds ?? 0,
text: p.text,
}))}
onReviewTargetSwitch={(direction) => reviewDraft.switchTarget(direction)}
onReviewProblemEdit={() => reviewDraft.editSelected()}
onReviewProblemDelete={() => reviewDraft.requestDelete()}
onReviewEscape={reviewDraft.escape}
reviewComment={
workspaceMode === "quality" ||
workspaceMode === "acceptance" ||
workspaceMode === "clip-quality"
? reviewComment
: ""
}
onReviewCommentChange={(value) => {
if (!reviewWriteLocked) setReviewComment(value);
}}
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}
discardReasons={discardReasons.items}
discardReasonsAllowManual={discardReasons.allowManual}
discardReasonsLoading={discardReasons.loading}
discardReasonsError={userErrorMessage(discardReasons.error)}
onRefreshDiscardReasons={discardReasons.refresh}
onSliceDispositionChange={setSliceDisposition}
onSliceBoundaryChange={adjustSlice}
onMergeSliceBoundary={(sliceId, direction) => {
const index = sliceSegments.findIndex((slice) => slice.id === sliceId);
const current = sliceSegments[index],
following = sliceSegments[index + 1];
if (combinedEditorPhase !== "slice" || !current || !following) return;
const merged = mergeSlicePartitions(
sliceSegments,
index,
direction === "shrink" ? "right" : "left",
);
if (merged)
applySliceChange(merged.slices, {
type: "merge",
segmentIds: [current.id, following.id],
at: direction === "shrink" ? current.start : following.end,
});
}}
onSliceBoundaryEditStart={beginSliceBoundaryEdit}
onSliceBoundaryEditEnd={finishSliceBoundaryEdit}
sliceEditQuickConflict={sliceEditQuickConflictView}
onSliceEditQuickConflictApply={handleSliceEditQuickConflictApply}
onSliceEditQuickConflictCancel={handleSliceEditQuickConflictCancel}
sliceEditAppliedRevision={sliceEditAppliedRevision}
sliceEditSession={sliceEditSessionRef.current}
onSliceEditSessionChange={setSliceEditSessionOpen}
onApplySliceEdit={async (nextSlices, nextSegments, focusSliceId) =>
Boolean(await persistSliceEditApplication(nextSlices, nextSegments, focusSliceId))
}
onAnnotationEdit={recordAnnotationEdit}
onHistoryCommand={restoreEdit}
historyReveal={historyReveal}
onSplitSlice={(sliceIndex, at) => {
setAnnotationPlayhead(at);
return splitSlice(sliceIndex, at);
}}
onDeleteSlice={deleteSlice}
onConfirmSlices={() => void confirmSlicesAndMaterialize()}
confirmSlicesLabel={
annotationGenerationConfirmationMode(detail.editorState) === "recoverExisting"
? "恢复生成并保留标注"
: annotationGenerationConfirmationMode(detail.editorState) === "reconfirmSaved"
? RECONFIRM_SAVED_GENERATION_LABEL
: undefined
}
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={
resliceEligible
? () => {
setResetToUnifiedRange(
pendingReslice?.taskId === detail.task.id ? pendingReslice.resetToUnifiedRange : true,
);
setResliceError("");
setShowResliceWarning(true);
}
: undefined
}
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 || stageResultUnknown}
initialSliceId={requestedSliceId}
onReturnToPool={() => {
// An explicit return to the pool stops the queue in the
// ordinary layout too (the focused heading's 返回任务池
// already pauses); layout display toggles never do.
reviewContinuation.pause();
if (workPage) navigate(workPoolPath);
else 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">
{selectedTaskId
? "正在加载当前任务…"
: workPage
? combinedSubmissionNotice
? "已送检"
: "暂无当前任务"
: 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) }))
}
/>
<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}
{deferReviewReports && reviewAuxiliaryLoading && tab === "workload" && <p role="status">正在加载工作记录…</p>}
{tab === "workload" ? (
<Suspense fallback={<p role="status">正在加载工作记录视图…</p>}>
<WorkforceStatisticsPanel
items={workload.items}
totals={workload.totals}
from={workload.from}
to={workload.to}
projectId={projectId || undefined}
surface="workload"
collapsedByDefault={false}
/>
</Suspense>
) : 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-[color:var(--app-panel)] p-6 shadow-2xl">
<div className="flex items-center gap-3 text-red-600 dark: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-slate-600 dark:text-gray-300">
两种方式都会清空片内动作划分、描述和无效判断,返回切片编辑。此操作成功后不能通过撤销恢复。
</p>
<fieldset
disabled={saving || pendingReslice?.taskId === detail?.task.id}
className="mt-4 space-y-3 text-sm text-[color:var(--app-text)]"
>
<label className="flex items-start gap-2">
<input
type="radio"
name="reslice-mode"
checked={resetToUnifiedRange}
autoFocus
onChange={() => setResetToUnifiedRange(true)}
className="mt-1"
/>
<span>
全部重置
<span className="block text-xs text-slate-500 dark:text-gray-400">
清空切片划分、名称和舍弃判断,恢复为一整段。
</span>
</span>
</label>
<label className="flex items-start gap-2">
<input
type="radio"
name="reslice-mode"
checked={!resetToUnifiedRange}
onChange={() => setResetToUnifiedRange(false)}
className="mt-1"
/>
<span>
保留外层切片
<span className="block text-xs text-slate-500 dark:text-gray-400">
保留切片边界、名称和舍弃原因,清空片内动作。
</span>
</span>
</label>
</fieldset>
{resliceError && (
<p role="alert" className="mt-3 text-sm text-red-600 dark:text-red-300">
{userErrorMessage(resliceError)}
</p>
)}
<div className="mt-6 flex justify-end gap-3">
<button
type="button"
onClick={() => setShowResliceWarning(false)}
className="rounded-lg border border-[color:var(--app-control-border)] px-4 py-2 text-sm text-slate-700 transition-colors hover:bg-slate-50 dark:text-gray-300 dark:hover:bg-white/5"
>
取消
</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
? "正在核对…"
: pendingReslice?.taskId === detail?.task.id
? "核对重切结果"
: "清空标注并重新切片"}
</button>
</div>
</div>
</div>
) : null}
</div>
);
return (
<>
{showViewportPrompt && (
<div className="fixed inset-0 z-[90] flex items-center justify-center bg-black/80 p-4">
<section
role="dialog"
aria-modal="true"
aria-label="工作区已暂停"
className="w-full max-w-lg rounded-xl border bg-[color:var(--app-panel)] p-5 shadow-2xl"
>
<h2 className="text-lg font-semibold">工作区已暂停</h2>
<p className="my-3 text-sm">
专注视图需要至少 1413 × 615 CSS
像素。请扩大窗口或降低浏览器缩放,然后主动继续。当前任务与草稿已保留,已发出的请求仍在核对。
</p>
<p className="mb-4 text-sm">
当前内容区:{viewportSize.width} × {viewportSize.height}。继续后视频仍保持暂停。
</p>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={viewportTooSmall}
onClick={() => {
setReviewViewportLatched(false);
workSession.setViewportSuspended(false);
const deferred = viewportDeferredEntryRef.current;
viewportDeferredEntryRef.current = null;
if (deferred) {
if (deferred.isCurrent()) void startWork(deferred.resumeOnly);
} else if (workSession.hasContinuousIntent() && detail && combinedSubmissionFinished(detail)) {
setNextAfterHandoff(detail.task.id);
}
}}
className="rounded-lg bg-blue-600 px-3 py-2 text-white disabled:opacity-40"
>
继续当前工作
</button>
<Link
onClick={() => workSession.pauseContinuous("已返回任务池,连续工作暂停。")}
to={reviewFocused ? `${location.pathname}?projectId=${encodeURIComponent(projectId)}` : workPoolPath}
className="rounded-lg border px-3 py-2"
>
返回任务池
</Link>
</div>
</section>
</div>
)}
{workspaceContent}
<ReviewDecisionDialog
decision={reviewDecision}
canSubmit={reviewSession.writable && !viewportPaused && !reviewDraft.dirty}
problems={reviewDraft.draft?.problems || []}
problemLabel={reviewProblemLabel}
onProblem={(problem) => {
reviewDecision.cancel();
reviewDraft.selectProblem(problem, reviewProblemNavigationSlice(problem));
}}
/>
</>
);
}