线上紧急修复 round7-9:审核工作台加载、随机领取入口、视频进度条 #39
@ -622,6 +622,18 @@ func (server *server) handleAnnotationTasksList(writer http.ResponseWriter, requ
|
||||
artifactID := strings.TrimSpace(request.URL.Query().Get("artifactId"))
|
||||
rawLimit := strings.TrimSpace(request.URL.Query().Get("limit"))
|
||||
rawCursor := strings.TrimSpace(request.URL.Query().Get("cursor"))
|
||||
// ids=a,b,c serves pool-item joins: the client's pool page already decided
|
||||
// which human items it can see, so the task fetch targets exactly their
|
||||
// legacyTaskIds instead of a newest-first window that may not contain
|
||||
// them (the join regression behind 任务关联数据缺失).
|
||||
requestedIDs := []string{}
|
||||
if rawIDs := strings.TrimSpace(request.URL.Query().Get("ids")); rawIDs != "" {
|
||||
for _, id := range strings.Split(rawIDs, ",") {
|
||||
if id = strings.TrimSpace(id); id != "" {
|
||||
requestedIDs = append(requestedIDs, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
var cursorCreatedAt, cursorID string
|
||||
if rawCursor != "" {
|
||||
payload, cursorErr := base64.RawURLEncoding.DecodeString(rawCursor)
|
||||
@ -647,8 +659,11 @@ func (server *server) handleAnnotationTasksList(writer http.ResponseWriter, requ
|
||||
if parsed, issue := parseDatabaseBrowserPageQuery(rawLimit, "limit", 0, 1, 10000); issue == nil && rawLimit != "" {
|
||||
limit = int64(parsed)
|
||||
}
|
||||
if len(requestedIDs) > 0 {
|
||||
limit = 0
|
||||
}
|
||||
items, err := server.store.ListAnnotationTasksFiltered(request.Context(), server.requestOrganizationID(request), store.AnnotationTaskFilter{
|
||||
ProjectID: projectID, Status: string(status), SupplierID: supplierID, WorkflowID: workflowID, RunID: runID, NodeID: nodeID, ArtifactID: artifactID,
|
||||
ProjectID: projectID, Status: string(status), SupplierID: supplierID, WorkflowID: workflowID, RunID: runID, NodeID: nodeID, ArtifactID: artifactID, IDs: requestedIDs,
|
||||
Limit: limit, CursorCreatedAt: cursorCreatedAt, CursorID: cursorID,
|
||||
})
|
||||
listTasksMs = time.Since(segment).Milliseconds()
|
||||
@ -844,7 +859,7 @@ func (server *server) handleAnnotationTasksList(writer http.ResponseWriter, requ
|
||||
response := map[string]any{"items": filtered}
|
||||
// Pagination metadata appears only for explicitly limited requests so the
|
||||
// legacy unbounded body stays byte-compatible.
|
||||
if limit > 0 && len(items) == int(limit) {
|
||||
if limit > 0 && len(requestedIDs) == 0 && len(items) == int(limit) {
|
||||
last := items[len(items)-1]
|
||||
payload, encodeErr := json.Marshal(map[string]string{"createdAt": last.CreatedAt, "id": last.ID})
|
||||
if encodeErr == nil {
|
||||
@ -880,7 +895,7 @@ func (server *server) handleAnnotationTaskGet(writer http.ResponseWriter, reques
|
||||
return
|
||||
}
|
||||
if linkedHumanItem != nil && !annotationManager(principal) && !server.canAccessCurrentHumanStage(request.Context(), request, *linkedHumanItem) && !isAuthor && !server.canReadReviewedHumanItem(request.Context(), request, *linkedHumanItem) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "current human stage role is required", "code": "current_human_stage_role_required"})
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "current human stage role is required"})
|
||||
return
|
||||
}
|
||||
item.ContinuousActions = server.continuousActionsForItem(request.Context(), linkedHumanItem)
|
||||
@ -1188,7 +1203,7 @@ func (server *server) handleAnnotationTaskFrameTimelineGet(writer http.ResponseW
|
||||
}
|
||||
principal, _ := currentPrincipal(request)
|
||||
if linkedHumanItem != nil && !annotationManager(principal) && !server.canAccessCurrentHumanStage(request.Context(), request, *linkedHumanItem) && !server.canReadReviewedHumanItem(request.Context(), request, *linkedHumanItem) {
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "current human stage role is required", "code": "current_human_stage_role_required"})
|
||||
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "current human stage role is required"})
|
||||
return
|
||||
}
|
||||
camera := strings.ToLower(strings.TrimSpace(request.URL.Query().Get("camera")))
|
||||
|
||||
@ -129,18 +129,28 @@ func (s *server) handleAnnotationClaimCount(w http.ResponseWriter, r *http.Reque
|
||||
renderError(w, 500, err)
|
||||
return
|
||||
}
|
||||
// One batched read for every candidate's batch instead of a per-candidate
|
||||
// point lookup (12k+ lookups on the legacy-batch organization).
|
||||
batchIDs := make([]string, 0, len(candidates))
|
||||
seenBatchIDs := make(map[string]struct{}, len(candidates))
|
||||
for _, c := range candidates {
|
||||
if _, seen := seenBatchIDs[c.BatchID]; !seen {
|
||||
seenBatchIDs[c.BatchID] = struct{}{}
|
||||
batchIDs = append(batchIDs, c.BatchID)
|
||||
}
|
||||
}
|
||||
batchRecords, err := s.store.ListHumanBatchAccessRecords(r.Context(), p.User.OrganizationID, batchIDs)
|
||||
if err != nil {
|
||||
renderError(w, 500, err)
|
||||
return
|
||||
}
|
||||
batches := map[string]*domain.HumanBatchRecord{}
|
||||
for index := range batchRecords {
|
||||
batches[batchRecords[index].ID] = &batchRecords[index]
|
||||
}
|
||||
count := 0
|
||||
for _, c := range candidates {
|
||||
b, loaded := batches[c.BatchID]
|
||||
if !loaded {
|
||||
b, err = s.store.GetHumanBatch(r.Context(), c.BatchID)
|
||||
if err != nil {
|
||||
renderError(w, 500, err)
|
||||
return
|
||||
}
|
||||
batches[c.BatchID] = b
|
||||
}
|
||||
b := batches[c.BatchID]
|
||||
legacy := domain.AnnotationTaskRecord{ID: c.LegacyTaskID, ProjectID: c.ProjectID, SupplierID: c.SupplierID, ProcessingScope: c.ProcessingScope, ProcessingProfile: c.ProcessingProfile}
|
||||
legacy.SupplierPool = b != nil && b.ProcessingProfile == domain.ProcessingProfileRawHuman && domain.IsFanyuV58ThreeRoleHumanLoop(b.Stages)
|
||||
if !membershipHasRole(members, legacy, domain.AnnotationRoleAnnotator) || (c.SupplierID != "" && !suppliers[c.SupplierID]) {
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -176,6 +177,19 @@ func parseHumanItemQuery(request *http.Request) (domain.HumanItemQuery, *validat
|
||||
WorkflowID: values.Get("workflowId"), RunID: values.Get("runId"), CurrentStageID: values.Get("stageId"),
|
||||
Status: domain.HumanItemStatus(values.Get("status")),
|
||||
}
|
||||
// stageIds=a,b,c pushes the role workspace's stage set into the store
|
||||
// query. The single-value stageId stays supported; combining both merges
|
||||
// the sets.
|
||||
if raw := strings.TrimSpace(values.Get("stageIds")); raw != "" {
|
||||
for _, stage := range strings.Split(raw, ",") {
|
||||
if stage = strings.TrimSpace(stage); stage != "" {
|
||||
query.StageIDs = append(query.StageIDs, stage)
|
||||
}
|
||||
}
|
||||
}
|
||||
if query.CurrentStageID != "" && !slices.Contains(query.StageIDs, query.CurrentStageID) {
|
||||
query.StageIDs = append(query.StageIDs, query.CurrentStageID)
|
||||
}
|
||||
// Reject malformed cursors like the runs endpoint instead of silently
|
||||
// falling back to the first page.
|
||||
cursor, err := decodeHumanItemCursor(values.Get("cursor"))
|
||||
|
||||
@ -333,6 +333,11 @@ type HumanItemQuery struct {
|
||||
// endpoint so Mongo skips rows the handler would drop anyway.
|
||||
UnassignedOnly bool
|
||||
Statuses []HumanItemStatus
|
||||
// StageIDs pushes a multi-stage filter into the store query. Role pools
|
||||
// (available/all) previously filtered stages in-memory only, which left
|
||||
// the database sorting the whole unassigned backlog (17k docs, ~7s per
|
||||
// fetch round) before the handler dropped almost every row.
|
||||
StageIDs []string
|
||||
}
|
||||
|
||||
type HumanRejectQuery struct {
|
||||
|
||||
@ -180,6 +180,21 @@ func (store *MemoryStore) ListAnnotationTasksFiltered(_ context.Context, organiz
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
matches := func(value string, expected string) bool { return expected == "" || value == expected }
|
||||
// An explicit ID set serves pool-item joins (see MongoStore).
|
||||
if len(filter.IDs) > 0 {
|
||||
wanted := make(map[string]bool, len(filter.IDs))
|
||||
for _, id := range filter.IDs {
|
||||
wanted[id] = true
|
||||
}
|
||||
items := make([]domain.AnnotationTaskRecord, 0, len(wanted))
|
||||
for _, item := range store.annotationTasks {
|
||||
if wanted[item.ID] && annotationOrganizationMatches(item.OrganizationID, organizationID) {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
sortAnnotationRecords(items, func(item domain.AnnotationTaskRecord) string { return item.CreatedAt })
|
||||
return items, nil
|
||||
}
|
||||
items := make([]domain.AnnotationTaskRecord, 0)
|
||||
for _, item := range store.annotationTasks {
|
||||
if annotationOrganizationMatches(item.OrganizationID, organizationID) &&
|
||||
@ -656,6 +671,10 @@ type AnnotationTaskFilter struct {
|
||||
RunID string
|
||||
NodeID string
|
||||
ArtifactID string
|
||||
// IDs requests a specific task-ID set (pool-item joins). When set, the
|
||||
// other equality filters and the cursor are ignored and the id_unique
|
||||
// index serves the lookup directly.
|
||||
IDs []string
|
||||
// Limit caps the page size (0 = unbounded, the legacy behavior).
|
||||
Limit int64
|
||||
// Cursor resumes strictly after (CreatedAt, ID) in the descending order.
|
||||
@ -691,7 +710,18 @@ func (store *MongoStore) ListAnnotationTasksFiltered(ctx context.Context, organi
|
||||
extra["artifactId"] = filter.ArtifactID
|
||||
}
|
||||
query := mongoAnnotationFilter(organizationID, extra)
|
||||
if filter.CursorID != "" {
|
||||
// An explicit ID set serves pool-item joins: the caller's pool page
|
||||
// decides which tasks it needs, so fetch exactly those (id_unique index)
|
||||
// instead of re-deriving them through the cursor window.
|
||||
if len(filter.IDs) > 0 {
|
||||
ids := make(bson.A, 0, len(filter.IDs))
|
||||
for _, id := range filter.IDs {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
query["id"] = bson.M{"$in": ids}
|
||||
delete(query, "$or")
|
||||
}
|
||||
if len(filter.IDs) == 0 && filter.CursorID != "" {
|
||||
cursorTail := bson.A{bson.M{"createdAt": bson.M{"$lt": filter.CursorCreatedAt}}, bson.M{"createdAt": filter.CursorCreatedAt, "id": bson.M{"$lt": filter.CursorID}}}
|
||||
query["$or"] = cursorTail
|
||||
}
|
||||
|
||||
@ -594,6 +594,13 @@ func humanItemMongoFilter(organizationID string, query domain.HumanItemQuery) bs
|
||||
if query.CurrentStageID != "" {
|
||||
filter["currentStageId"] = query.CurrentStageID
|
||||
}
|
||||
if len(query.StageIDs) > 0 {
|
||||
stages := make(bson.A, 0, len(query.StageIDs))
|
||||
for _, stage := range query.StageIDs {
|
||||
stages = append(stages, stage)
|
||||
}
|
||||
filter["currentStageId"] = bson.M{"$in": stages}
|
||||
}
|
||||
if query.Status != "" {
|
||||
filter["status"] = query.Status
|
||||
}
|
||||
@ -889,7 +896,7 @@ func (store *MongoStore) ListHumanBatchAccessRecords(ctx context.Context, organi
|
||||
if len(ids) == 0 {
|
||||
return []domain.HumanBatchRecord{}, nil
|
||||
}
|
||||
cursor, err := store.humanBatches.Find(ctx, bson.M{"organizationId": normalizedOrganizationID(organizationID), "id": bson.M{"$in": ids}}, options.Find().SetProjection(bson.M{"_id": 0, "id": 1, "organizationId": 1, "projectId": 1, "stages": 1, "processingProfile": 1, "sourceBatchId": 1, "processingScope": 1, "requirePrePackageAcceptance": 1}))
|
||||
cursor, err := store.humanBatches.Find(ctx, bson.M{"organizationId": normalizedOrganizationID(organizationID), "id": bson.M{"$in": ids}}, options.Find().SetProjection(bson.M{"_id": 0, "id": 1, "organizationId": 1, "projectId": 1, "stages": 1, "processingProfile": 1, "status": 1, "sourceBatchId": 1, "processingScope": 1, "requirePrePackageAcceptance": 1}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -908,7 +915,7 @@ func (store *MemoryStore) ListHumanBatchAccessRecords(ctx context.Context, organ
|
||||
return nil, err
|
||||
}
|
||||
if b != nil && b.OrganizationID == normalizedOrganizationID(organizationID) {
|
||||
items = append(items, domain.HumanBatchRecord{ID: b.ID, OrganizationID: b.OrganizationID, ProjectID: b.ProjectID, Stages: b.Stages, ProcessingProfile: b.ProcessingProfile, SourceBatchID: b.SourceBatchID, ProcessingScope: b.ProcessingScope, RequirePrePackageAcceptance: b.RequirePrePackageAcceptance})
|
||||
items = append(items, domain.HumanBatchRecord{ID: b.ID, OrganizationID: b.OrganizationID, ProjectID: b.ProjectID, Stages: b.Stages, ProcessingProfile: b.ProcessingProfile, Status: b.Status, SourceBatchID: b.SourceBatchID, ProcessingScope: b.ProcessingScope, RequirePrePackageAcceptance: b.RequirePrePackageAcceptance})
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
|
||||
@ -69,6 +69,19 @@ const EVENT_BRIDGE: Array<[keyof MoviVideoEventMap, string]> = [
|
||||
|
||||
const BOOLEAN_ATTRIBUTES = new Set(["nohotkeys", "controls", "muted", "playsinline"]);
|
||||
|
||||
// Retry delays (ms) used to find the shadow <video> the vendored element
|
||||
// builds when its player initializes; see the forwarding-gap note below.
|
||||
const INNER_BRIDGE_RETRY_DELAYS = [80, 250, 700, 1800];
|
||||
// Shadow-video events the vendored 0.4.1 dist fails to re-dispatch on the
|
||||
// host, mapped to the MoviVideoEventMap props consumers registered.
|
||||
const INNER_BRIDGE_EVENTS = ["timeupdate", "seeking", "seeked", "waiting"] as const;
|
||||
const INNER_EVENT_MAP: Record<(typeof INNER_BRIDGE_EVENTS)[number], keyof MoviVideoEventMap> = {
|
||||
timeupdate: "onTimeUpdate",
|
||||
seeking: "onSeeking",
|
||||
seeked: "onSeeked",
|
||||
waiting: "onWaiting",
|
||||
};
|
||||
|
||||
/**
|
||||
* `<movi-player>` with the decoding chain this platform needs:
|
||||
* native `<video>` (the E′ direct presigned path) first, movi's
|
||||
@ -166,6 +179,7 @@ export const MoviVideo = React.forwardRef<HTMLVideoElement, MoviVideoProps>(func
|
||||
const element = elementRef.current;
|
||||
if (!element) return;
|
||||
const handlers: Array<[string, EventListener]> = [];
|
||||
let innerCleanup: (() => void) | null = null;
|
||||
const add = (name: string, listener: EventListener) => {
|
||||
element.addEventListener(name, listener);
|
||||
handlers.push([name, listener]);
|
||||
@ -234,9 +248,61 @@ export const MoviVideo = React.forwardRef<HTMLVideoElement, MoviVideoProps>(func
|
||||
});
|
||||
});
|
||||
add("error", () => reportMoviStats({ kind: "playback-error", src: plainSrc }));
|
||||
|
||||
// Forwarding gap in the vendored 0.4.1 dist: the custom element
|
||||
// re-dispatches play/pause/ended/playing/canplay/loadedmetadata/
|
||||
// durationchange/progress on the host, but NOT timeupdate (nor
|
||||
// seeking/seeked/waiting) from its shadow <video>. Verified against
|
||||
// the dist with an instrumented page: the shadow video fires ~4
|
||||
// timeupdate/s during playback while the host receives none, so any
|
||||
// UI driven by onTimeUpdate — the workbench playhead, slice-end
|
||||
// enforcement — only moves when the app re-reads currentTime on
|
||||
// pause. The same gap strands the workbench seek queue: it settles
|
||||
// on the host "seeked" event, which never fires, leaving the
|
||||
// transport stuck in 定位中 and blocking play. Bridge these events
|
||||
// from the shadow video, presenting the host as currentTarget:
|
||||
// consumers treat currentTarget as their master element and read the
|
||||
// proxied media properties off it.
|
||||
let innerVideo: HTMLVideoElement | null = null;
|
||||
const innerListener: EventListener = (event) => {
|
||||
const handler = handlersRef.current[INNER_EVENT_MAP[event.type]];
|
||||
if (handler) handler({ currentTarget: element } as { currentTarget: HTMLVideoElement });
|
||||
if (event.type === "timeupdate" && endAt !== null) {
|
||||
const current = Number((element as HTMLMediaElement).currentTime);
|
||||
if (Number.isFinite(current) && current >= endAt - 0.002) {
|
||||
(element as HTMLMediaElement).pause();
|
||||
}
|
||||
}
|
||||
};
|
||||
const attachInner = () => {
|
||||
if (innerVideo) return;
|
||||
const inner = (element as HTMLElement & { shadowRoot?: ShadowRoot | null }).shadowRoot?.querySelector(
|
||||
"video",
|
||||
);
|
||||
if (!inner) return;
|
||||
innerVideo = inner;
|
||||
for (const name of INNER_BRIDGE_EVENTS) inner.addEventListener(name, innerListener);
|
||||
};
|
||||
const innerRetryTimers: number[] = [];
|
||||
const scheduleInnerRetries = () => {
|
||||
// The shadow <video> is built when the player initializes; retry
|
||||
// briefly rather than holding a long-lived observer.
|
||||
for (const delay of INNER_BRIDGE_RETRY_DELAYS) {
|
||||
innerRetryTimers.push(window.setTimeout(attachInner, delay));
|
||||
}
|
||||
};
|
||||
attachInner();
|
||||
scheduleInnerRetries();
|
||||
innerCleanup = () => {
|
||||
for (const timer of innerRetryTimers) window.clearTimeout(timer);
|
||||
if (innerVideo) {
|
||||
for (const name of INNER_BRIDGE_EVENTS) innerVideo.removeEventListener(name, innerListener);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return () => {
|
||||
innerCleanup?.();
|
||||
for (const [name, listener] of handlers) element.removeEventListener(name, listener);
|
||||
};
|
||||
}, [mode, plainSrc, endAt]);
|
||||
|
||||
@ -505,6 +505,19 @@ function humanItemVisibleInMode(item: HumanItem, mode: WorkspaceMode, poolView?:
|
||||
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 {
|
||||
@ -1007,20 +1020,60 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
// eligibility is enforced server-side (403 surfaces as a toast), so the
|
||||
// cross-project membership prefetch buys nothing on this path.
|
||||
const fanOutProjectScope = !projectId && !isManager && !reviewOnly;
|
||||
const taskScopeFilters = {
|
||||
projectId: projectId || undefined,
|
||||
workflowId: requestedWorkflowId || undefined,
|
||||
runId: requestedRunId || undefined,
|
||||
nodeId: requestedNodeId || undefined,
|
||||
artifactId: requestedArtifactId || undefined,
|
||||
};
|
||||
const humanFilters = {
|
||||
pluginId: "annotation-qa",
|
||||
projectId: projectId || undefined,
|
||||
workflowId: requestedWorkflowId || undefined,
|
||||
runId: requestedRunId || undefined,
|
||||
};
|
||||
// Review workspaces push their stage set into the pool query so the
|
||||
// database never sorts the whole unassigned backlog (17k docs) before
|
||||
// the role filter drops almost every row.
|
||||
const reviewStageIds = humanItemStageIdsForMode(workspaceMode);
|
||||
const poolsRequest = acceptanceWorkspace
|
||||
? humanLoopApi.listAcceptancePools(humanFilters, currentUser?.id || "", isManager)
|
||||
: Promise.all([
|
||||
humanLoopApi.listItems({ ...humanFilters, pool: "available" }),
|
||||
humanLoopApi.listItems({ ...humanFilters, pool: "mine" }),
|
||||
humanLoopApi.listItems({ ...humanFilters, pool: "available", ...(reviewStageIds ? { stageIds: reviewStageIds } : {}) }),
|
||||
humanLoopApi.listItems({ ...humanFilters, pool: "mine", ...(reviewStageIds ? { stageIds: reviewStageIds } : {}) }),
|
||||
isManager ? humanLoopApi.listItems({ ...humanFilters, pool: "all" }) : Promise.resolve([]),
|
||||
reviewOnly ? humanLoopApi.listItems({ ...humanFilters, pool: "reviewed" }) : Promise.resolve([]),
|
||||
]).then(([available, mine, all, reviewed]) => ({ available, mine, all, reviewed }));
|
||||
// Task acquisition splits by workspace: review workspaces join to the
|
||||
// pool page's legacyTaskIds (the pool decides visibility; a newest-first
|
||||
// task window can miss pool items entirely — the 任务关联数据缺失
|
||||
// regression), while annotator/manager workspaces keep the newest-first
|
||||
// window with progressive paging.
|
||||
const tasksRequest = (async () => {
|
||||
if (reviewOnly && !isManager) {
|
||||
const pools = await poolsRequest;
|
||||
const ids = [
|
||||
...new Set(
|
||||
[...pools.available, ...pools.mine, ...pools.reviewed]
|
||||
.map((item) => item.legacyTaskId)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
),
|
||||
].slice(0, 1000);
|
||||
taskPoolCursorRef.current = "";
|
||||
if (!ids.length) return [] as AnnotationTaskRecord[];
|
||||
return (await annotationOperationsApi.listTasksPage({ ...taskScopeFilters, ids })).items;
|
||||
}
|
||||
return annotationOperationsApi
|
||||
.listTasksPage({
|
||||
...taskScopeFilters,
|
||||
limit: taskPageLimit,
|
||||
})
|
||||
.then((page) => {
|
||||
taskPoolCursorRef.current = page.nextCursor || "";
|
||||
return page.items;
|
||||
});
|
||||
})();
|
||||
const [
|
||||
nextProjectMembers,
|
||||
nextWorkflows,
|
||||
@ -1047,19 +1100,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
)
|
||||
: Promise.resolve([] as Workflow[]),
|
||||
annotationOperationsApi.listTemplates(projectId || undefined),
|
||||
annotationOperationsApi
|
||||
.listTasksPage({
|
||||
projectId: projectId || undefined,
|
||||
workflowId: requestedWorkflowId || undefined,
|
||||
runId: requestedRunId || undefined,
|
||||
nodeId: requestedNodeId || undefined,
|
||||
artifactId: requestedArtifactId || undefined,
|
||||
limit: taskPageLimit,
|
||||
})
|
||||
.then((page) => {
|
||||
taskPoolCursorRef.current = page.nextCursor || "";
|
||||
return page.items;
|
||||
}),
|
||||
tasksRequest,
|
||||
poolsRequest,
|
||||
deferReviewReports ? Promise.resolve(null) : annotationOperationsApi.workloadSummary(projectId || undefined),
|
||||
deferReviewReports
|
||||
@ -1565,7 +1606,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
if (requestID === taskDetailRequestRef.current && (loadError as Error)?.name !== "AbortError") {
|
||||
const msg = getActionErrorMessage(loadError, "加载标注任务详情失败");
|
||||
workSession.pauseContinuous(`无法读取当前任务:${msg};连续工作已暂停。`);
|
||||
if (!workPage && loadError instanceof APIError && loadError.code === "current_human_stage_role_required") {
|
||||
if (!workPage && msg.includes("current human stage role is required")) {
|
||||
closeTaskAndReturnToPool();
|
||||
} else {
|
||||
setError(msg);
|
||||
@ -1726,6 +1767,16 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
() => poolItems.filter((item) => matchesPoolFilters(item, taskPoolView)),
|
||||
[poolItems, taskPoolView, matchesPoolFilters],
|
||||
);
|
||||
// Random claim draws from the available pool regardless of the active pool
|
||||
// tab, so the entry stays usable from "mine"/"reviewed" views too.
|
||||
const availableClaimableItems = useMemo(
|
||||
() => humanPools.available.filter((item) => humanItemVisibleInMode(item, workspaceMode, "available")),
|
||||
[humanPools.available, workspaceMode],
|
||||
);
|
||||
const claimablePrepackageAcceptanceItems = useMemo(
|
||||
() => availableClaimableItems.filter((item) => item.currentStageId === "prepackage_acceptance"),
|
||||
[availableClaimableItems],
|
||||
);
|
||||
const prepackageAcceptanceItems = useMemo(
|
||||
() => visiblePoolItems.filter((item) => item.currentStageId === "prepackage_acceptance"),
|
||||
[visiblePoolItems],
|
||||
@ -3917,18 +3968,17 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
applyReviewClaim(claimed);
|
||||
if (originSelection !== JSON.stringify(reviewSelectionRef.current)) return;
|
||||
// Explicit Continue enters review; a claim alone preserves the pool.
|
||||
return true;
|
||||
return claimed;
|
||||
} catch (cause) {
|
||||
if (scope === reviewActionScopeRef.current) setError(getActionErrorMessage(cause, "领取包前最终验收失败"));
|
||||
return false;
|
||||
} finally {
|
||||
if (scope === reviewActionScopeRef.current) setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const randomClaimAcceptanceTask = async () => {
|
||||
if (randomClaimBusy || saving || taskPoolView === "reviewed") return;
|
||||
const candidates = prepackageAcceptanceItems.filter(
|
||||
if (randomClaimBusy || saving) return;
|
||||
const candidates = claimablePrepackageAcceptanceItems.filter(
|
||||
(item) =>
|
||||
!item.assignedUserId && ["ready", "submitted", "rework"].includes(item.status) && canCurrentUserClaimItem(item),
|
||||
);
|
||||
@ -3954,6 +4004,41 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
}
|
||||
};
|
||||
|
||||
const randomReviewClaimTask = async () => {
|
||||
if (isManager || !reviewOnly || acceptanceWorkspace || saving || loading) return;
|
||||
if (!reviewDraftGuardRef.current()) return;
|
||||
const candidates = availableClaimableItems.filter(
|
||||
(item) =>
|
||||
!item.assignedUserId && ["ready", "rework", "submitted"].includes(item.status) && canCurrentUserClaimItem(item),
|
||||
);
|
||||
const candidate = candidates[Math.floor(Math.random() * candidates.length)];
|
||||
if (!candidate) {
|
||||
setRandomClaimNotice("当前暂无可领取的审核任务。");
|
||||
return;
|
||||
}
|
||||
setRandomClaimBusy(true);
|
||||
setRandomClaimNotice("");
|
||||
try {
|
||||
const claimed = await humanLoopApi.claim(candidate.id, candidate.version);
|
||||
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) {
|
||||
setRandomClaimNotice(getActionErrorMessage(cause, "随机领取审核任务失败,请刷新后重试"));
|
||||
} finally {
|
||||
setRandomClaimBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const decidePrepackageAcceptance = async (
|
||||
item: HumanItem,
|
||||
statistics: PrepackageAcceptanceStatistics,
|
||||
@ -5357,16 +5442,34 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{reviewOnly && workspaceMode === "acceptance" && taskPoolView === "available" && (
|
||||
{reviewOnly && !isManager && !acceptanceWorkspace && (
|
||||
<div className="mt-3 space-y-2" data-testid="review-random-claim">
|
||||
<p className="text-xs text-slate-500">从可领取池随机领取一条并直接进入审核,支持全部项目。</p>
|
||||
<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">
|
||||
<p className="text-xs text-slate-500">从当前项目可验收任务中随机领取一条。</p>
|
||||
<p className="text-xs text-slate-500">随机领取一条最终验收任务,支持全部项目。</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void randomClaimAcceptanceTask()}
|
||||
disabled={!projectId || loading || saving || randomClaimBusy || Boolean(projectLoadError)}
|
||||
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 ? "正在领取…" : "随机领取验收任务"}
|
||||
{randomClaimBusy ? "正在领取…" : "随机领取"}
|
||||
</button>
|
||||
{randomClaimNotice && (
|
||||
<p role="status" className="break-words text-xs text-slate-600">
|
||||
@ -5645,7 +5748,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
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"
|
||||
|
||||
@ -18,10 +18,14 @@ import { apiRequest } from "./client";
|
||||
import { decodeAnnotationTimeline } from "../../lib/annotation-timeline-wire.js";
|
||||
import { normalizeAnnotationWorkspace, normalizeAnnotationTaskDetail } from "../../lib/annotation-workspace.js";
|
||||
|
||||
const query = (values: Record<string, string | number | undefined>) => {
|
||||
const query = (values: Record<string, string | number | string[] | undefined>) => {
|
||||
const params = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (value !== undefined && value !== "") params.set(key, String(value));
|
||||
if (Array.isArray(value)) {
|
||||
if (value.length) params.set(key, value.join(","));
|
||||
} else if (value !== undefined && value !== "") {
|
||||
params.set(key, String(value));
|
||||
}
|
||||
}
|
||||
const encoded = params.toString();
|
||||
return encoded ? `?${encoded}` : "";
|
||||
@ -129,8 +133,13 @@ export const annotationOperationsApi = {
|
||||
artifactId?: string;
|
||||
limit?: number;
|
||||
cursor?: string;
|
||||
/** Explicit task-ID set for pool-item joins (comma-joined). */
|
||||
ids?: string[];
|
||||
} = {},
|
||||
) => apiRequest<{ items: AnnotationTaskRecord[]; nextCursor?: string; hasMore?: boolean }>(`/api/plugins/annotation-qa/tasks${query(filters)}`),
|
||||
) =>
|
||||
apiRequest<{ items: AnnotationTaskRecord[]; nextCursor?: string; hasMore?: boolean }>(
|
||||
`/api/plugins/annotation-qa/tasks${query(filters)}`,
|
||||
),
|
||||
getTask: (id: string, signal?: AbortSignal, history = false) =>
|
||||
apiRequest<AnnotationTaskDetail>(`/api/plugins/annotation-qa/tasks/${id}${history ? "?view=history" : ""}`, {
|
||||
signal,
|
||||
|
||||
@ -9,6 +9,8 @@ type HumanItemFilters = {
|
||||
workflowId?: string;
|
||||
runId?: string;
|
||||
stageId?: string;
|
||||
/** Multi-stage pushdown (comma-joined server-side) for role pools. */
|
||||
stageIds?: string[];
|
||||
status?: HumanItemStatus;
|
||||
pool?: "available" | "mine" | "all" | "reviewed";
|
||||
/** Server default is 500 (max 1000); pass explicitly for larger pools. */
|
||||
@ -17,10 +19,14 @@ type HumanItemFilters = {
|
||||
cursor?: string;
|
||||
};
|
||||
|
||||
const queryString = (filters: Record<string, string | number | undefined>) => {
|
||||
const queryString = (filters: Record<string, string | number | string[] | undefined>) => {
|
||||
const params = new URLSearchParams();
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== "") params.set(key, String(value));
|
||||
if (Array.isArray(value)) {
|
||||
if (value.length) params.set(key, value.join(","));
|
||||
} else if (value !== undefined && value !== "") {
|
||||
params.set(key, String(value));
|
||||
}
|
||||
});
|
||||
const query = params.toString();
|
||||
return query ? `?${query}` : "";
|
||||
|
||||
@ -16,7 +16,8 @@ test("annotation workbench separates available, mine, and administrator task poo
|
||||
assert.match(source, /我的任务/);
|
||||
assert.match(source, /全部任务/);
|
||||
assert.match(source, /data-testid="acceptance-random-claim"/);
|
||||
assert.match(source, /随机领取验收任务/);
|
||||
assert.match(source, /\{randomClaimBusy \? "正在领取…" : "随机领取"\}/);
|
||||
assert.match(source, /claimablePrepackageAcceptanceItems/);
|
||||
assert.match(source, /管理员任务改派/);
|
||||
assert.match(source, /humanLoopApi\.assign/);
|
||||
assert.match(source, /problemSliceIds/);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user