⏸️ Defer owned task entry until explicit viewport recovery

This commit is contained in:
d-robotics 2026-09-18 09:24:20 +08:00
parent cb74444e0d
commit 972721e20c
2 changed files with 118 additions and 5 deletions

View File

@ -729,6 +729,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
const [randomClaimBusy, setRandomClaimBusy] = useState(false);
const randomClaimFlight = 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("");
@ -3323,6 +3324,23 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
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("");
@ -3346,12 +3364,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
// 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 mine = await humanLoopApi.listItems({ pluginId: "annotation-qa", projectId, pool: "mine" });
if (!entryStillCurrent()) return;
if (!entryStillCurrent() || deferEntryForViewport()) return;
const unfinished = mine.filter((item) => isOwnedRecoverableAnnotationItem(item, selectedProject, actorID));
const current = unfinished.find((item) => item.legacyTaskId === selectedTaskId) || unfinished[0];
if (current) {
const { task } = await annotationOperationsApi.getTaskSummary(current.legacyTaskId);
if (!entryStillCurrent()) return;
if (!entryStillCurrent() || deferEntryForViewport()) return;
++projectLoadRequestRef.current;
setHumanPools((pools) => ({ ...pools, mine }));
setTasks((items) => [task, ...items.filter((item) => item.id !== task.id)]);
@ -4805,10 +4823,13 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
disabled={viewportTooSmall}
onClick={() => {
workSession.setViewportSuspended(false);
// Entry may have been suspended while reading the owned pool,
// before it could dispatch a claim. Requeue that handoff only.
if (workSession.hasContinuousIntent() && detail && combinedSubmissionFinished(detail))
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"
>

View File

@ -0,0 +1,92 @@
// Real read-only entry regression: a delayed owned-pool/summary read must not
// select another task while viewport suspension is latched. Continue rereads
// authority; unlike already-dispatched random claims, these reads allocate nothing.
import assert from "node:assert/strict";
import { chromium } from "playwright";
const browser = await chromium.launch({
executablePath: "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
headless: true,
args: ["--no-proxy-server"],
});
const context = await browser.newContext({
storageState: "local-data/verification/annotation-workspace-layout/auth.json",
viewport: { width: 1280, height: 640 },
});
const page = await context.newPage();
page.setDefaultTimeout(15000);
const base = "http://127.0.0.1:5173";
const project = "project-workspace-viewport-submit";
const oldTask = "annotation-task-workspace-viewport-submit-annotate-primary";
const ownedTask = "annotation-task-workspace-viewport-submit-pool-01";
const button = (name) => page.getByRole("button", { name, exact: true });
const resumeOnly = process.env.VIEWPORT_RESUME_ONLY === "1";
const writes = [];
page.on("request", (r) => {
if (r.method() !== "GET") writes.push(new URL(r.url()).pathname);
});
const read = async (task) => {
const r = await context.request.get(`${base}/api/human-items/${task.replace("annotation-task-", "human-item-")}`);
assert.ok(r.ok());
return (await r.json()).item;
};
try {
const before = [await read(oldTask), await read(ownedTask)];
for (const boundary of process.env.VIEWPORT_ENTRY_BOUNDARY
? [process.env.VIEWPORT_ENTRY_BOUNDARY]
: ["pool", "summary"]) {
await page.goto(`${base}/plugins/annotation-qa/workflows/all/work?projectId=${project}&taskId=${oldTask}`);
await page.getByRole("button").filter({ hasText: ownedTask }).waitFor();
if (await button("进入专注视图").count()) await button("进入专注视图").click();
const priorURL = page.url();
let done, release, settle;
const server = new Promise((r) => (done = r)),
held = new Promise((r) => (release = r)),
settled = new Promise((r) => (settle = r));
const target =
boundary === "pool"
? (url) => url.pathname === "/api/human-items" && url.searchParams.get("pool") === "mine"
: (url) => url.pathname.endsWith(`/tasks/${ownedTask}`) && url.searchParams.get("view") === "summary";
await page.route(target, async (route) => {
const response = await route.fetch();
assert.ok(response.ok());
done();
await held;
await route.fulfill({ response });
settle();
});
await button(resumeOnly ? "继续工作" : "核对领取结果并开始连续工作").click();
await server;
await page.setViewportSize({ width: 1279, height: 640 });
await page.getByRole("dialog", { name: "工作区已暂停" }).waitFor();
release();
await settled;
await page.unroute(target);
await page.waitForTimeout(500);
assert.equal(page.url(), priorURL, `${boundary} response cannot switch the current task under suspension`);
assert.equal(
await page.getByTestId("capture-annotation-workbench").count(),
0,
`${boundary} response cannot mount a new editor under suspension`,
);
await page.setViewportSize({ width: 1280, height: 640 });
await page.waitForTimeout(300);
assert.equal(page.url(), priorURL, "size restoration alone does not continue owned-task entry");
await button("继续当前工作").click();
await page.waitForURL(new RegExp(`taskId=${ownedTask}`));
await page.getByTestId("capture-annotation-workbench").waitFor();
assert.ok(
await button(resumeOnly ? "开始连续工作" : "完成当前任务后停止").isVisible(),
"explicit Continue preserves the requested continuous intent",
);
assert.equal(writes.length, 0, "owned-first recovery never claims or writes");
console.log("PASS deferred real owned entry at", boundary);
}
assert.deepEqual(
[(await read(oldTask)).version, (await read(ownedTask)).version],
before.map((i) => i.version),
);
console.log("PASS public versions unchanged", JSON.stringify(before.map((i) => ({ id: i.id, version: i.version }))));
} finally {
await context.close();
await browser.close();
}