From e94a8d2c14e2d78e4778c7faca905129e244b5fb Mon Sep 17 00:00:00 2001 From: d-robotics Date: Wed, 28 Oct 2026 09:09:10 -0700 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20Integrate=20projected=20annotation?= =?UTF-8?q?=20buffer=20summary=20polling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .scratch/poll-pool-optimization/work.md | 10 ++ docs/annotation-operations.md | 4 +- internal/api/annotation_work_buffer.go | 25 ++++- .../annotation_work_buffer_display_test.go | 2 +- internal/domain/human_loop.go | 3 +- internal/store/annotation_work_buffer.go | 40 +++++++- .../annotation_work_buffer_mongo_test.go | 19 ++++ internal/store/human_loop.go | 9 +- internal/store/store.go | 1 + src/lib/annotation-work-mode.js | 17 +++- src/pages/AnnotationOperations.tsx | 96 +++++++++++++------ src/services/api/annotation-operations.ts | 45 +++++++++ .../annotation-buffer-reconciliation.test.mjs | 53 ++++++++-- .../annotation-buffer-summary.test.mjs | 48 ++++++++++ tests/frontend/annotation-work-entry.test.mjs | 3 +- tests/frontend/annotation-work-mode.test.mjs | 21 ++++ 16 files changed, 343 insertions(+), 53 deletions(-) create mode 100644 tests/frontend/annotation-buffer-summary.test.mjs diff --git a/.scratch/poll-pool-optimization/work.md b/.scratch/poll-pool-optimization/work.md index a4a313ad..35a8532e 100644 --- a/.scratch/poll-pool-optimization/work.md +++ b/.scratch/poll-pool-optimization/work.md @@ -14,3 +14,13 @@ Risk: mixed-version response compatibility, permissions, in-flight workflow reco - Local isolated Mongo regression passed, including deduplicated query count, foreign-organization rejection, missing batch handling, stable poll ledger version and capacity update. - Targeted API regressions passed: continuation, annotation buffer, display cache and legacy display fallback. The varied deterministic fixture keeps the same task count; legacy/summary gzip sizes were 12,579/331 bytes (97.4% reduction). This is synthetic response evidence, not production capacity acceptance. - Remaining: frontend summary integration and task projection, broader display batching, exact pool query measurements and the approved 81-user repeated soak comparison. No push, PR or deployment performed. + +## 2026-10-28 summary polling integration + +- The annotation page now polls `view=summary` into an independent snapshot type. Legacy server responses and capacity PUT responses are explicitly converted. The 3-second interval is unchanged. +- Existing full records retain their subject/draft payload; newly observed task IDs are hydrated once for sidebar compatibility. Explicit work entry still loads a full task. Scope/epoch/mutation fences are rechecked after hydration. +- Added an explicit store summary method with an inclusion projection for state, ownership, slice phase and processing status. Claim reservation and default/PUT paths retain full behavior. Existing name-cache misses deliberately use original item inputs for historical nested capture names; no new cross-request cache was added. +- Verification: 27 targeted frontend tests passed (entry, reconciliation, refill and mixed-version conversion); TypeScript/architecture passed; isolated Mongo summary/ledger tests and targeted API tests passed. Stable polls retain ledger versions and exclude large payload and processing-job input. +- Go baseline gate passed with 68 known failures, no additions. Frontend gate still fails two source guards: `review-target-interaction.test.mjs :: source guard: resident editor binds the selected target with a tier label` and `scope-cycle-inline-editor.test.mjs :: source guard: resident inline editor promotes into edit state on focus`. Both reproduce unchanged at HEAD 8cdd2d79 in a separate archived baseline. The baseline full gate also had a temporary-copy local-stack/version failure and a hung devboot test that was terminated; these are not claimed as passes. Initial sandbox frontend run also needed termination of devboot before rerunning outside the sandbox. +- Global format check reports four untouched files: ReviewHistorySummary.tsx, WorkforceStatisticsPanel.tsx, useAnnotationOutputData.ts, useReviewContinuation.ts. Modified frontend files were formatted; git diff --check passes. No baseline files were altered to hide failures. +- Pending: browser end-to-end validation of this integration, batch/projected display fallback refinement, actual pool p95 and the specified repeated 81-user soak. This is not a release/capacity acceptance. No push, PR or deployment. diff --git a/docs/annotation-operations.md b/docs/annotation-operations.md index fcbfbe08..1ab5c7ef 100644 --- a/docs/annotation-operations.md +++ b/docs/annotation-operations.md @@ -142,6 +142,4 @@ The annotation work-buffer GET accepts `view=summary`. Its response uses state. Each summary includes task identity, ownership, stage, version, review round, claimed time, pending submission, slice status/phase and display labels. Disabled buffers return an empty summary array. PUT and default GET retain their -old contracts. Summaries must never replace editor details or drafts. This -endpoint is not yet enabled by the frontend; database and frontend buffer -optimization remain pending. +old contracts. Summaries must never replace editor details or drafts. The frontend polls this summary endpoint and converts legacy full responses when paired with an older server. It loads full records when entering work, keeping summaries separate from editor data. Mongo reads use an inclusion projection; name-cache misses still load the original item to preserve historical nested capture-name precedence. Stable summary polls retain the existing no-ledger-write behavior. diff --git a/internal/api/annotation_work_buffer.go b/internal/api/annotation_work_buffer.go index d9913f1d..783648c3 100644 --- a/internal/api/annotation_work_buffer.go +++ b/internal/api/annotation_work_buffer.go @@ -170,7 +170,12 @@ func (s *server) handleAnnotationWorkBuffer(w http.ResponseWriter, r *http.Reque } } segment = time.Now() - buffer, err := s.store.AnnotationWorkBuffer(r.Context(), p.User.OrganizationID, p.User.ID, projectID, capacity) + readBuffer := s.store.AnnotationWorkBuffer + summary := r.Method == http.MethodGet && r.URL.Query().Get("view") == "summary" + if summary { + readBuffer = s.store.AnnotationWorkBufferSummary + } + buffer, err := readBuffer(r.Context(), p.User.OrganizationID, p.User.ID, projectID, capacity) storeMs = time.Since(segment).Milliseconds() if err != nil { renderError(w, 500, err) @@ -184,11 +189,25 @@ func (s *server) handleAnnotationWorkBuffer(w http.ResponseWriter, r *http.Reque buffer.Items[index].Display = display continue } - if err := resolver.enrichItem(r.Context(), &buffer.Items[index]); err != nil { + displayItem := buffer.Items[index] + if summary { + // Historical capture names may be nested anywhere in the subject. + // On a display-cache miss preserve the old resolver's exact inputs. + full, err := s.store.GetHumanItem(r.Context(), displayItem.ID) + if err != nil { + renderError(w, 500, err) + return + } + if full != nil { + displayItem = *full + } + } + if err := resolver.enrichItem(r.Context(), &displayItem); err != nil { renderError(w, http.StatusInternalServerError, err) return } - s.workBufferDisplays.set(key, buffer.Items[index].Display, segment) + buffer.Items[index].Display = displayItem.Display + s.workBufferDisplays.set(key, displayItem.Display, segment) } enrichMs = time.Since(segment).Milliseconds() processing := map[string]any{} diff --git a/internal/api/annotation_work_buffer_display_test.go b/internal/api/annotation_work_buffer_display_test.go index abae6ed6..ee6aae1a 100644 --- a/internal/api/annotation_work_buffer_display_test.go +++ b/internal/api/annotation_work_buffer_display_test.go @@ -99,8 +99,8 @@ func TestAnnotationBufferSummaryIsExplicitAndKeepsStatus(t *testing.T) { t.Fatal(err) } base := "/api/plugins/annotation-qa/work-buffer?projectId=" + f.task.ProjectID - old := f.request(http.MethodGet, base, f.annotator, nil) compact := f.request(http.MethodGet, base+"&view=summary", f.annotator, nil) + old := f.request(http.MethodGet, base, f.annotator, nil) if old.Code != 200 || compact.Code != 200 { t.Fatalf("responses %d %d", old.Code, compact.Code) } diff --git a/internal/domain/human_loop.go b/internal/domain/human_loop.go index 7790dbb7..dc79924e 100644 --- a/internal/domain/human_loop.go +++ b/internal/domain/human_loop.go @@ -348,7 +348,8 @@ type HumanItemQuery struct { Cursor *HumanItemCursor ListProjection bool // IdentityProjection is server-only and excludes all task payloads. - IdentityProjection bool + IdentityProjection bool + BufferSummaryProjection bool // TaskListProjection serves the annotation-tasks list path: it drops the // heavy payload sub-documents like ListProjection but keeps // annotationDraft, which the handler reads to derive task progress. diff --git a/internal/store/annotation_work_buffer.go b/internal/store/annotation_work_buffer.go index 34cb7eac..28a78a21 100644 --- a/internal/store/annotation_work_buffer.go +++ b/internal/store/annotation_work_buffer.go @@ -58,7 +58,8 @@ func (s *MemoryStore) AnnotationWorkBuffer(_ context.Context, org, user, project // The single-document CAS ledger also protects standalone Mongo. Pending claim // intents retain their slot across process restarts; only a definitive conflict // or handoff frees it. A receipt retry reuses the same slot even after downsizing. -func (s *MongoStore) annotationBuffer(ctx context.Context, org, user, project string, capacity int, reserve *HumanClaimReceipt) (AnnotationWorkBuffer, error) { +func (s *MongoStore) annotationBuffer(ctx context.Context, org, user, project string, capacity int, reserve *HumanClaimReceipt, summary ...bool) (AnnotationWorkBuffer, error) { + compact := len(summary) > 0 && summary[0] key := bufferKey(org, user, project) collection := s.db.Collection("annotationWorkBuffers") for { @@ -83,7 +84,7 @@ func (s *MongoStore) annotationBuffer(ctx context.Context, org, user, project st // The "active" view bounds the scan to the actor's assigned open // annotation items, a superset of occupiesAnnotationBuffer; matching // latestAuthorUserId would read the actor's whole authored history. - items, err := s.ListHumanItems(ctx, org, domain.HumanItemQuery{ProjectID: project, PluginID: "annotation-qa", ActorUserID: user, AnnotationView: "active", ListProjection: true}) + items, err := s.ListHumanItems(ctx, org, domain.HumanItemQuery{ProjectID: project, PluginID: "annotation-qa", ActorUserID: user, AnnotationView: "active", ListProjection: true, BufferSummaryProjection: compact}) if err != nil { return old, err } @@ -130,7 +131,7 @@ func (s *MongoStore) annotationBuffer(ctx context.Context, org, user, project st next.Slots[request] = id continue } - slotItems, e := s.ListHumanItems(ctx, org, domain.HumanItemQuery{IDs: []string{id}, ListProjection: true}) + slotItems, e := s.ListHumanItems(ctx, org, domain.HumanItemQuery{IDs: []string{id}, ListProjection: true, BufferSummaryProjection: compact}) var item *domain.HumanItemRecord if len(slotItems) > 0 { item = &slotItems[0] @@ -231,3 +232,36 @@ func (s *MongoStore) annotationBufferBatches(ctx context.Context, ids []string) } return result, cursor.Err() } + +func (s *MongoStore) AnnotationWorkBufferSummary(ctx context.Context, org, user, project string, capacity int) (AnnotationWorkBuffer, error) { + return s.annotationBuffer(ctx, org, user, project, capacity, nil, true) +} +func (s *MemoryStore) AnnotationWorkBufferSummary(ctx context.Context, org, user, project string, capacity int) (AnnotationWorkBuffer, error) { + out, err := s.AnnotationWorkBuffer(ctx, org, user, project, capacity) + for i := range out.Items { + out.Items[i] = annotationBufferProjectionClone(out.Items[i]) + } + return out, err +} +func annotationBufferProjectionClone(item domain.HumanItemRecord) domain.HumanItemRecord { + result := domain.HumanItemRecord{ID: item.ID, OrganizationID: item.OrganizationID, ProjectID: item.ProjectID, WorkflowID: item.WorkflowID, RunID: item.RunID, BatchID: item.BatchID, PluginID: item.PluginID, LegacyTaskID: item.LegacyTaskID, AssignedUserID: item.AssignedUserID, CurrentStageID: item.CurrentStageID, Status: item.Status, Version: item.Version, ReviewRound: item.ReviewRound, ClaimedAt: item.ClaimedAt, PendingCombinedSubmissionID: item.PendingCombinedSubmissionID} + if item.ProcessingJob != nil { + result.ProcessingJob = &domain.AnnotationProcessingJob{Status: item.ProcessingJob.Status, Kind: item.ProcessingJob.Kind, Error: item.ProcessingJob.Error} + } + phase, ok := item.Subject.Payload["sliceWorkflow"].(map[string]any) + if !ok { + if value, valid := item.Subject.Payload["sliceWorkflow"].(bson.M); valid { + phase = map[string]any(value) + } + } + if phase != nil { + selected := map[string]any{} + for _, key := range []string{"status", "phase"} { + if value, exists := phase[key]; exists { + selected[key] = clone(value) + } + } + result.Subject.Payload = map[string]any{"sliceWorkflow": selected} + } + return result +} diff --git a/internal/store/annotation_work_buffer_mongo_test.go b/internal/store/annotation_work_buffer_mongo_test.go index 365d0c65..27c0ce38 100644 --- a/internal/store/annotation_work_buffer_mongo_test.go +++ b/internal/store/annotation_work_buffer_mongo_test.go @@ -89,6 +89,25 @@ func TestMongoAnnotationWorkBufferPollIsReadOnly(t *testing.T) { t.Fatalf("buffer = %+v", first) } settled := version() + _, err = db.Collection("humanItems").UpdateOne(ctx, bson.M{"id": "active"}, bson.M{"$set": bson.M{"subject.payload.large": strings.Repeat("x", 1024*1024), "subject.payload.sliceWorkflow": bson.M{"status": "completed", "phase": "annotate", "large": strings.Repeat("y", 1024)}, "processingJob": bson.M{"kind": "slice", "status": "failed", "error": "fixture", "input": bson.M{"large": "private"}}}}) + must(err) + for n := 0; n < 3; n++ { + summary, err := s.AnnotationWorkBufferSummary(ctx, org, user, project, 0) + must(err) + if summary.Occupied != first.Occupied || len(summary.Items) != 1 { + t.Fatalf("summary membership changed: %+v", summary) + } + got := summary.Items[0] + if got.ID != "active" || got.Subject.Payload["large"] != nil || got.ProcessingJob == nil || got.ProcessingJob.Input != nil || got.ProcessingJob.Error != "fixture" { + t.Fatalf("summary projection invalid: %+v", got) + } + encoded, err := bson.Marshal(got) + must(err) + if len(encoded) > 4096 { + t.Fatalf("projected item retained payload: %d", len(encoded)) + } + } + for n := 0; n < 3; n++ { again, err := s.AnnotationWorkBuffer(ctx, org, user, project, 0) must(err) diff --git a/internal/store/human_loop.go b/internal/store/human_loop.go index 275939c5..fa48ffe9 100644 --- a/internal/store/human_loop.go +++ b/internal/store/human_loop.go @@ -252,6 +252,10 @@ func (store *MemoryStore) ListHumanItems(_ context.Context, organizationID strin for i := range items { items[i] = domain.HumanItemRecord{ID: items[i].ID} } + } else if query.BufferSummaryProjection { + for i := range items { + items[i] = annotationBufferProjectionClone(items[i]) + } } else if query.ListProjection || query.TaskListProjection { keysRemoved := humanItemPayloadKeysRemoved(query) for index := range items { @@ -679,6 +683,9 @@ func humanItemListProjection(query domain.HumanItemQuery) bson.M { if query.IdentityProjection { return bson.M{"_id": 0, "id": 1} } + if query.BufferSummaryProjection { + return bson.M{"_id": 0, "id": 1, "organizationId": 1, "projectId": 1, "workflowId": 1, "runId": 1, "batchId": 1, "pluginId": 1, "legacyTaskId": 1, "assignedUserId": 1, "currentStageId": 1, "status": 1, "version": 1, "reviewRound": 1, "claimedAt": 1, "pendingCombinedSubmissionId": 1, "processingJob.status": 1, "processingJob.kind": 1, "processingJob.error": 1, "subject.payload.sliceWorkflow.status": 1, "subject.payload.sliceWorkflow.phase": 1} + } projection := bson.M{"processingJob.input": 0} for _, key := range humanItemPayloadKeysRemoved(query) { projection["subject.payload."+key] = 0 @@ -758,7 +765,7 @@ func (store *MongoStore) ListHumanItems(ctx context.Context, organizationID stri if query.Limit > 0 { findOptions.SetLimit(int64(query.Limit)) } - if query.IdentityProjection || query.ListProjection || query.TaskListProjection { + if query.IdentityProjection || query.BufferSummaryProjection || query.ListProjection || query.TaskListProjection { findOptions.SetProjection(humanItemListProjection(query)) } filter := humanItemMongoFilter(organizationID, query) diff --git a/internal/store/store.go b/internal/store/store.go index addfb943..e3f26eca 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -315,6 +315,7 @@ type Store interface { CountAnnotationClaimCandidates(context.Context, string, AnnotationClaimCountQuery) (int, error) GetHumanClaimReceipt(context.Context, string) (*HumanClaimReceipt, error) AnnotationWorkBuffer(context.Context, string, string, string, int) (AnnotationWorkBuffer, error) + AnnotationWorkBufferSummary(context.Context, string, string, string, int) (AnnotationWorkBuffer, error) CommitHumanClaim(context.Context, HumanClaimCommit) (*domain.HumanItemRecord, error) GetHumanItem(context.Context, string) (*domain.HumanItemRecord, error) UpsertHumanItem(context.Context, domain.HumanItemRecord) error diff --git a/src/lib/annotation-work-mode.js b/src/lib/annotation-work-mode.js index f1446ec6..5d4b7b23 100644 --- a/src/lib/annotation-work-mode.js +++ b/src/lib/annotation-work-mode.js @@ -44,7 +44,7 @@ export async function refillAnnotationWorkBuffer({ readBuffer, claim, shouldCont let attempt = 0; refill && buffer.enabled && - !hasDirectedAnnotationRework(buffer.items) && + !hasDirectedAnnotationRework(buffer.summaries ?? buffer.items) && buffer.occupied < buffer.capacity && attempt < attempts && shouldContinue(); @@ -56,7 +56,7 @@ export async function refillAnnotationWorkBuffer({ readBuffer, claim, shouldCont buffer = await readBuffer(); if ( !response.item || - previous.items.some((item) => item.id === response.item.id) || + (previous.summaries ?? previous.items).some((item) => item.id === response.item.id) || buffer.occupied <= previous.occupied ) break; @@ -80,3 +80,16 @@ export function reconcileAnnotationBufferItems(items, bufferItems, { userId, pro }), ]; } + +// Summary polls update lifecycle fields only on already-loaded records. Never +// manufacture a full item or replace its subject/editor payload with a summary. +export function reconcileAnnotationBufferSummaries(items, summaries, scope) { + const existing = new Map(items.map((item) => [item.id, item])); + const loaded = summaries.flatMap((summary) => { + const item = existing.get(summary.id); + if (!item) return []; + const { sliceStatus, slicePhase, ...state } = summary; + return [{ ...item, ...state }]; + }); + return reconcileAnnotationBufferItems(items, loaded, scope); +} diff --git a/src/pages/AnnotationOperations.tsx b/src/pages/AnnotationOperations.tsx index fa64881a..499df85b 100644 --- a/src/pages/AnnotationOperations.tsx +++ b/src/pages/AnnotationOperations.tsx @@ -62,7 +62,7 @@ import { useProjectSliceDictionary } from "../hooks/useProjectSliceDictionary"; import { refillAnnotationWorkBuffer, hasDirectedAnnotationRework, - reconcileAnnotationBufferItems, + reconcileAnnotationBufferSummaries, } from "../lib/annotation-work-mode.js"; import { useAnnotationWorkSession, type AnnotationWorkSession } from "../hooks/useAnnotationWorkSession"; import { alignSliceTimeline, initializeFrameAlignedSlices, sliceTimelineIssue } from "../lib/annotation-timeline.js"; @@ -123,7 +123,12 @@ import type { } from "../types"; import { useUser } from "../context/UserContext"; import { useTimeZone } from "../context/TimeZoneContext"; -import { annotationOperationsApi, type AnnotationWorkBuffer } from "../services/api/annotation-operations"; +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"; @@ -366,7 +371,11 @@ const emptyPrepackageAcceptanceStatistics = { type PrepackageAcceptanceStatistics = typeof emptyPrepackageAcceptanceStatistics; type AnnotationMutationToken = { id: number; taskId: string; userId: string }; -function isOwnedRecoverableAnnotationItem(item: HumanItem, projectId: string, userId: string | undefined) { +function isOwnedRecoverableAnnotationItem( + item: Pick, + projectId: string, + userId: string | undefined, +) { return Boolean( item.projectId === projectId && item.assignedUserId === userId && @@ -376,9 +385,8 @@ function isOwnedRecoverableAnnotationItem(item: HumanItem, projectId: string, us ); } -function readyBufferedItems(items: HumanItem[], processing: Record = {}) { - const phase = (item: HumanItem) => - item.subject?.payload?.sliceWorkflow as { status?: string; phase?: string } | undefined; +function readyBufferedItems(items: AnnotationBufferSummary[], processing: Record = {}) { + const phase = (item: AnnotationBufferSummary) => ({ status: item.sliceStatus, phase: item.slicePhase }); return items .filter( (item) => @@ -1069,14 +1077,16 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: setTaskPoolView((current) => (current === "reviewed" ? current : "mine")); }, [blindAnnotator, reviewOnly, requestedTaskId, requestedAcceptanceId, workPage, requestedReviewItemOwned]); const [randomClaimBusy, setRandomClaimBusy] = useState(false); - const [workBuffer, setWorkBuffer] = useState({ + const humanPoolsSnapshotRef = useRef(humanPools); + humanPoolsSnapshotRef.current = humanPools; + const [workBuffer, setWorkBuffer] = useState({ enabled: false, capacity: 2, occupied: 0, - items: [], + summaries: [], }); useEffect(() => { - setWorkBuffer({ enabled: false, capacity: 2, occupied: 0, items: [] }); + setWorkBuffer({ enabled: false, capacity: 2, occupied: 0, summaries: [] }); }, [projectId, currentUser?.id]); const bufferReadEpochRef = useRef(0); const bufferManagedIdsRef = useRef(new Set()); @@ -5668,7 +5678,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: refill, readBuffer: () => { snapshotEpoch = bufferReadEpochRef.current; - return annotationOperationsApi.workBuffer(originProject); + return annotationOperationsApi.workBufferSummary(originProject); }, shouldContinue: () => (!detailRef.current || Boolean(detailRef.current.task.continuousActions)) && @@ -5702,6 +5712,18 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: 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); @@ -5709,20 +5731,24 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const managedIds = bufferManagedIdsRef.current; setHumanPools((pools) => ({ ...pools, - mine: reconcileAnnotationBufferItems(pools.mine, buffer.items, { - userId: actorID, - projectId: originProject, - managedIds, - }), + 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.items.map((item) => item.id)); + 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.items.some((item) => item.id === current.humanItem?.id); + 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("当前任务已离开个人任务池,编辑内容已保留,请核对任务状态。"); @@ -5803,21 +5829,32 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: (await reconcileWorkBuffer( () => entryStillCurrent() && !viewportBlocksDispatch(), workSession.prefersContinuous(), - )) || (await annotationOperationsApi.workBuffer(projectId)); + )) || (await annotationOperationsApi.workBufferSummary(projectId)); if (!buffer || !entryStillCurrent() || deferEntryForViewport()) return; const buffered = buffer.enabled && (!detailRef.current || Boolean(detailRef.current.task.continuousActions)); const mine = buffered - ? buffer.items + ? 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(owned, buffer.processing) : owned; + 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; - setHumanPools((pools) => ({ ...pools, mine })); + 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) { @@ -5948,11 +5985,11 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: annotationMutationScopeRef.current.busy() ) return; - const selected = buffer.items.find((item) => item.legacyTaskId === selectedTaskId); + const selected = buffer.summaries.find((item) => item.legacyTaskId === selectedTaskId); if (selectedTaskId && explicitBufferTask.current === selectedTaskId) return; if ( (!selected || !readyBufferedItems([selected], buffer.processing).length) && - readyBufferedItems(buffer.items, buffer.processing).length + readyBufferedItems(buffer.summaries, buffer.processing).length ) { setNextAfterHandoff(selectedTaskId || "buffer-waiting"); } @@ -5992,7 +6029,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: try { const buffer = await annotationOperationsApi.setWorkBufferCapacity(projectId, capacity); if (claimContextRef.current !== origin) return; - setWorkBuffer(buffer); + setWorkBuffer(summarizeWorkBuffer(buffer)); const epoch = workSession.continuousEpoch(); if (workSession.isContinuous()) await reconcileWorkBuffer( @@ -6318,7 +6355,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: {randomClaimBusy ? "正在领取…" : "随机领取任务"} ) : null} - {workPage && workBuffer.items.length > 0 ? ( + {workPage && workBuffer.summaries.length > 0 ? (