🛠️ Restore manual annotation on HTTP without bypassing work locks
This commit is contained in:
parent
7585b43f0c
commit
7ed51d3227
@ -2,6 +2,14 @@
|
||||
|
||||
选择项目后点击“开始工作”,即可在当前标签页连续标注。系统先续做本人未完成任务,没有时才在有权限的项目与供应商范围内随机领取;领取前不能挑选视频。
|
||||
|
||||
## 连接方式与手动模式
|
||||
|
||||
独立工作页和连续领取需要支持 Web Locks 的安全连接,例如 HTTPS;浏览器也将本机 localhost 视为安全上下文。普通 HTTP 连接下会显示“当前连接使用手动模式;独立工作页和连续领取需安全连接”。此时在原工作台点击“随机领取任务”,从“我的任务”继续切片、标注、保存和送检;送检后手动领取下一条。
|
||||
|
||||
手动模式保留服务端任务归属、版本检查和领取请求重试,但不提供多页面互斥。不要同时在多个页面编辑同一任务。直接打开 HTTP 工作页时,点击“返回手动工作台”会保留原项目和任务,不会释放或重新领取。领取结果未知时再次点击“随机领取任务”,沿用原请求编号核对结果。
|
||||
|
||||
浏览器支持页面锁、但锁被另一页占用或协调出错时,不会降级绕过锁;按提示返回活动页或刷新重试。
|
||||
|
||||
## 进入、停止与退出
|
||||
|
||||
首次进入默认使用专注视图:平台导航收起,左侧是同步双视频、播放控制和时间轴,右侧是当前切片或动作描述编辑区。页面顶部始终保留“切回原布局”和“返回任务池”。
|
||||
@ -10,7 +18,7 @@
|
||||
|
||||
“返回任务池”会执行原有离开保护。若有未保存草稿,选择继续编辑可返回当前工作;确认离开会丢弃页面中未保存的编辑。刷新、关闭标签页或重新打开后,必须显式点击“继续工作”,只恢复服务端已经保存的内容,不能恢复浏览器草稿与撤销历史。
|
||||
|
||||
同一账号、同一项目只能有一个活动工作页。第二个标签页提示已有活动页时,返回原页继续;原页退出或关闭后再恢复。不要通过反复开页重复领取。
|
||||
安全连接下,同一浏览器的同源标签页中,同一账号、同一项目只能有一个活动工作页。第二个标签页提示已有活动页时,返回原页继续;原页退出或关闭后再恢复。不要通过反复开页重复领取。
|
||||
|
||||
## 切片:确认名称后生成
|
||||
|
||||
@ -58,6 +66,8 @@
|
||||
|
||||
工作中的布局切换是当前页面内的回退。源码恢复则使用本地标签 `codex/annotation-keyboard-baseline-20260918`,指向 `54a35afad95d77b1f23c955f9c4671cae83a664d`;完整备份位于忽略目录 `local-data/backups/annotation-keyboard-baseline-20260918.bundle`。标签指向及 bundle 完整历史已再次核验。恢复前应由维护人员保留当前改动并另建检出进行核对。
|
||||
|
||||
本轮 PR 意见修改前的新工作页另有备份:标签 `codex/annotation-workspace-pre-review-20260918` 指向 `7585b43f0c14b29015541fc3a33d914227ce4366`;完整历史包为 `local-data/backups/annotation-workspace-pre-review-20260918.bundle`,不覆盖上述旧版快捷键备份。
|
||||
|
||||
Git 标签和 bundle 只恢复代码,不能恢复数据库、下载的视频、浏览器未保存草稿或撤销记录。这些数据须分别备份与恢复。本次没有执行代码回退、数据库回滚、远端推送或公司环境部署。
|
||||
|
||||
本地验收包括真实 590×480 双视频、五档 CSS 内容区、四档窗口及真实浏览器缩放、实际保存和送检。16:9 / 9:16 使用合成素材验证比例适配;浏览器派发的组合输入检查不代表原生操作系统中文输入法验收。物理显示器、操作系统缩放、原生输入法及公司部署环境尚未全面实测。旧本地验收任务的文件产物不可用,因此该页仅核对了布局与面板隔离,未完成媒体加载验证。详细证据、已有测试债与运行方式见[整体验收报告](verification/annotation-workspace-layout/acceptance-results.md)及[全套检查结果](verification/annotation-workspace-layout/full-suite-results.md)。
|
||||
|
||||
@ -5,6 +5,10 @@ export type AnnotationWorkSession = {
|
||||
readonly active: boolean;
|
||||
};
|
||||
|
||||
type AcquisitionResult =
|
||||
| { status: "acquired"; session: AnnotationWorkSession }
|
||||
| { status: "unsupported" | "blocked" | "error" | "stale" };
|
||||
|
||||
type OwnedSession = AnnotationWorkSession & {
|
||||
active: boolean;
|
||||
continuous: boolean;
|
||||
@ -38,7 +42,8 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work
|
||||
// viewport recovery. The latch belongs to this page/scope, not the lock.
|
||||
const viewportRef = useRef({ scope, suspended: false });
|
||||
if (viewportRef.current.scope !== scope) viewportRef.current = { scope, suspended: false };
|
||||
const [observation, setObservation] = useState({ scope: "", blocked: false, unavailable: false });
|
||||
const supported = Boolean(navigator.locks);
|
||||
const [observation, setObservation] = useState({ scope: "", blocked: false, error: false });
|
||||
const channelRef = useRef<BroadcastChannel | null>(null);
|
||||
|
||||
const owns = useCallback((session?: AnnotationWorkSession | null) => {
|
||||
@ -59,7 +64,7 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work
|
||||
const refresh = async () => {
|
||||
const version = ++queryVersion;
|
||||
if (!scope || !navigator.locks) {
|
||||
if (!disposed) setObservation({ scope, blocked: false, unavailable: Boolean(scope) });
|
||||
if (!disposed) setObservation({ scope, blocked: false, error: false });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@ -68,10 +73,10 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work
|
||||
setObservation({
|
||||
scope,
|
||||
blocked: !owns() && Boolean(locks.held?.some((lock) => lock.name === scope)),
|
||||
unavailable: false,
|
||||
error: false,
|
||||
});
|
||||
} catch {
|
||||
if (!disposed && version === queryVersion) setObservation({ scope, blocked: false, unavailable: true });
|
||||
if (!disposed && version === queryVersion) setObservation({ scope, blocked: false, error: true });
|
||||
}
|
||||
};
|
||||
const update = () => {
|
||||
@ -118,20 +123,21 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work
|
||||
};
|
||||
}, [scope, workPage, owns]);
|
||||
|
||||
const acquire = useCallback(async (): Promise<AnnotationWorkSession | null> => {
|
||||
const acquire = useCallback(async (): Promise<AcquisitionResult> => {
|
||||
const identity = identityRef.current;
|
||||
if (!identity.scope || !navigator.locks) return null;
|
||||
if (owns()) return ownedSession;
|
||||
if (!identity.scope) return { status: "stale" };
|
||||
if (!navigator.locks) return { status: "unsupported" };
|
||||
if (owns()) return { status: "acquired", session: ownedSession };
|
||||
return new Promise((resolve) => {
|
||||
void navigator.locks
|
||||
.request(identity.scope, { ifAvailable: true }, async (lock) => {
|
||||
if (identityRef.current !== identity) {
|
||||
resolve(null);
|
||||
resolve({ status: "stale" });
|
||||
return;
|
||||
}
|
||||
if (!lock) {
|
||||
setObservation({ scope: identity.scope, blocked: true, unavailable: false });
|
||||
resolve(null);
|
||||
setObservation({ scope: identity.scope, blocked: true, error: false });
|
||||
resolve({ status: "blocked" });
|
||||
return;
|
||||
}
|
||||
let unlock: () => void;
|
||||
@ -146,14 +152,15 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work
|
||||
ownedSession = session;
|
||||
notify();
|
||||
channelRef.current?.postMessage("changed");
|
||||
resolve(session);
|
||||
setObservation({ scope: identity.scope, blocked: false, error: false });
|
||||
resolve({ status: "acquired", session });
|
||||
await held;
|
||||
})
|
||||
.catch(() => {
|
||||
if (identityRef.current === identity) {
|
||||
setObservation({ scope: identity.scope, blocked: false, unavailable: true });
|
||||
setObservation({ scope: identity.scope, blocked: false, error: true });
|
||||
}
|
||||
resolve(null);
|
||||
resolve({ status: identityRef.current === identity ? "error" : "stale" });
|
||||
});
|
||||
});
|
||||
}, [owns]);
|
||||
@ -219,7 +226,9 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work
|
||||
isContinuous,
|
||||
active: owns() && Boolean(ownedSession?.active),
|
||||
blocked: observation.scope === scope && observation.blocked && !owns(),
|
||||
unavailable: observation.scope === scope && observation.unavailable,
|
||||
supported,
|
||||
coordinationError: observation.scope === scope && observation.error,
|
||||
unavailable: !supported || (observation.scope === scope && observation.error),
|
||||
acquire,
|
||||
owns,
|
||||
activate,
|
||||
|
||||
@ -574,6 +574,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
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;
|
||||
@ -3188,6 +3189,8 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
};
|
||||
|
||||
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 });
|
||||
@ -3210,6 +3213,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
: claimContextRef.current === origin &&
|
||||
annotationMutationContextRef.current.current() === taskOrigin &&
|
||||
!leaveDirtyRef.current &&
|
||||
claimPermissionRef.current &&
|
||||
(!requestSession || workSession.owns(requestSession));
|
||||
if (!blindAnnotator || !projectId || !currentUser || randomClaimFlight.current || annotationDirty || !canContinue())
|
||||
return;
|
||||
@ -3222,8 +3226,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
let requestId = "";
|
||||
try {
|
||||
if (!enterWorkPage) {
|
||||
requestSession = (await workSession.acquire()) || undefined;
|
||||
if (!requestSession || !canContinue()) return;
|
||||
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;
|
||||
@ -3345,8 +3353,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
setWorkEntryBusy(true);
|
||||
setRandomClaimNotice("");
|
||||
try {
|
||||
session = await workSession.acquire();
|
||||
if (!session || !entryStillCurrent()) return;
|
||||
const acquisition = await workSession.acquire();
|
||||
if (acquisition.status !== "acquired") return;
|
||||
session = acquisition.session;
|
||||
if (!entryStillCurrent()) return;
|
||||
if (!resumeOnly) workSession.setContinuous(session, true);
|
||||
const key = `droboticflow.random-claim:${actorID}:${selectedProject}`;
|
||||
const unresolvedClaim = pendingClaimRequest(key);
|
||||
@ -3435,9 +3445,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
// Enabling while editing must preserve the current drafts and history.
|
||||
if (selectedClaimedByMe && detail && !combinedSubmissionFinished(detail)) {
|
||||
const origin = claimContextRef.current;
|
||||
const session = await workSession.acquire();
|
||||
if (session && claimContextRef.current === origin && claimPermissionRef.current)
|
||||
workSession.setContinuous(session, true);
|
||||
const acquisition = await workSession.acquire();
|
||||
if (acquisition.status === "acquired" && claimContextRef.current === origin && claimPermissionRef.current)
|
||||
workSession.setContinuous(acquisition.session, true);
|
||||
} else {
|
||||
await startWork();
|
||||
}
|
||||
@ -3697,8 +3707,18 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
|
||||
{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.unavailable ? (
|
||||
<p>当前浏览器无法安全协调工作页,请在支持浏览器页面锁的安全连接中重试。</p>
|
||||
{!workSession.supported ? (
|
||||
<>
|
||||
<p>当前连接使用手动模式;独立工作页和连续领取需安全连接。</p>
|
||||
<p>可在原工作台随机领取、从我的任务继续、保存和提交;手动模式不提供多页面互斥。</p>
|
||||
{workPage ? (
|
||||
<Link to={manualWorkPath} className="inline-block rounded-lg border px-3 py-2">
|
||||
返回手动工作台
|
||||
</Link>
|
||||
) : null}
|
||||
</>
|
||||
) : workSession.coordinationError ? (
|
||||
<p>页面协调失败,尚未领取新任务。请刷新后重试;不会绕过页面锁。</p>
|
||||
) : (
|
||||
<>
|
||||
<p>此账号在本项目已有活动工作页。请切换回该页面继续,避免同时编辑。</p>
|
||||
@ -3754,7 +3774,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
{workPage && !workSession.active ? (
|
||||
{workPage && workSession.supported && !workSession.active ? (
|
||||
<section aria-label="恢复工作会话" className={`${panelClass} space-y-4 p-5`}>
|
||||
<h2 className="font-semibold">继续已领取任务</h2>
|
||||
<p className="text-sm text-gray-500">
|
||||
@ -4014,7 +4034,9 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void randomClaimTask()}
|
||||
disabled={!projectId || workEntryBusy || randomClaimBusy || annotationDirty}
|
||||
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 ? "正在领取…" : "随机领取任务"}
|
||||
|
||||
341
tests/browser/annotation-http-manual.mjs
Normal file
341
tests/browser/annotation-http-manual.mjs
Normal file
@ -0,0 +1,341 @@
|
||||
// Local API + real Edge acceptance. A non-loopback hostname is genuinely insecure;
|
||||
// no browser security override or fake lock success is used for the HTTP path.
|
||||
// Requires a create-once pr-review-http fixture project with empty annotation tasks.
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync, mkdirSync } from "node:fs";
|
||||
import { chromium } from "playwright";
|
||||
import { createServer } from "vite";
|
||||
|
||||
const prefix = process.env.REVIEW_FIXTURE_PREFIX || "pr-review-http";
|
||||
assert.match(prefix, /^pr-review-http(?:-[a-z0-9]+)?$/);
|
||||
const project = `project-${prefix}`;
|
||||
const owned = `annotation-task-${prefix}-annotate-primary`;
|
||||
const other = `annotation-task-${prefix}-annotate-delayed`;
|
||||
const output = "local-data/verification/pr-review-20260918";
|
||||
mkdirSync(output, { recursive: true });
|
||||
const credentials = JSON.parse(
|
||||
readFileSync("local-data/verification/annotation-workspace-layout/local-auth.json", "utf8"),
|
||||
);
|
||||
const server = await createServer({
|
||||
logLevel: "silent",
|
||||
// Freeze file watching during acceptance, including docs written by other agents.
|
||||
server: {
|
||||
host: "127.0.0.1",
|
||||
port: 5174,
|
||||
strictPort: true,
|
||||
hmr: false,
|
||||
watch: { ignored: ["**/*"] },
|
||||
allowedHosts: ["annotation-http.test"],
|
||||
},
|
||||
});
|
||||
await server.listen();
|
||||
const browser = await chromium.launch({
|
||||
executablePath:
|
||||
process.env.PLAYWRIGHT_EXECUTABLE_PATH || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
headless: true,
|
||||
args: ["--no-proxy-server", "--host-resolver-rules=MAP annotation-http.test 127.0.0.1"],
|
||||
});
|
||||
const http = "http://annotation-http.test:5174";
|
||||
const secure = "http://127.0.0.1:5174";
|
||||
const path = (mode, task = "") =>
|
||||
`/plugins/annotation-qa/workflows/all/${mode}?projectId=${project}${task ? `&taskId=${task}` : ""}`;
|
||||
const button = (page, name) => page.getByRole("button", { name, exact: true });
|
||||
const claims = [];
|
||||
const errors = [];
|
||||
let page;
|
||||
async function login(context, base) {
|
||||
const tab = await context.newPage();
|
||||
tab.setDefaultTimeout(20000);
|
||||
tab.on("pageerror", (e) => errors.push(e.message));
|
||||
tab.on("request", (r) => {
|
||||
if (r.url().endsWith("/random-claims") && r.method() === "POST") claims.push(r.postDataJSON());
|
||||
});
|
||||
await tab.goto(base);
|
||||
assert.equal(
|
||||
await tab.evaluate(
|
||||
async (data) =>
|
||||
(
|
||||
await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
).status,
|
||||
credentials,
|
||||
),
|
||||
200,
|
||||
);
|
||||
return tab;
|
||||
}
|
||||
const read = async (page, task) =>
|
||||
page.evaluate(async (id) => {
|
||||
const r = await fetch(`/api/human-items/${id.replace("annotation-task-", "human-item-")}`);
|
||||
if (!r.ok) throw new Error(`readback ${r.status}`);
|
||||
return (await r.json()).item;
|
||||
}, task);
|
||||
const bench = (page) => page.getByTestId("capture-annotation-workbench");
|
||||
const post = (page, suffix) =>
|
||||
page.waitForResponse((r) => r.url().endsWith(suffix) && r.request().method() === "POST", { timeout: 60000 });
|
||||
const media = (page) =>
|
||||
page.waitForFunction(
|
||||
() =>
|
||||
document.querySelectorAll("video").length === 2 &&
|
||||
[...document.querySelectorAll("video")].every((v) => v.readyState >= 2),
|
||||
null,
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
const boundaries = (item) =>
|
||||
item.subject.payload.annotationWorkspace.sliceSegments.map(
|
||||
({ id, start, end, startTimestampUs, endTimestampUs }) => ({ id, start, end, startTimestampUs, endTimestampUs }),
|
||||
);
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
|
||||
page = await login(context, http);
|
||||
assert.deepEqual(await page.evaluate(() => ({ secure: isSecureContext, locks: typeof navigator.locks })), {
|
||||
secure: false,
|
||||
locks: "undefined",
|
||||
});
|
||||
// A slow project read must not erase the bookmarked identity in the fallback link.
|
||||
let resumeProjects;
|
||||
const projectGate = new Promise((resolve) => {
|
||||
resumeProjects = resolve;
|
||||
});
|
||||
await page.route(/\/(?:claim-projects|projects)(?:\?.*)?$/, async (route) => {
|
||||
await projectGate;
|
||||
await route.continue();
|
||||
});
|
||||
await page.goto(http + path("work", owned));
|
||||
const earlyFallback = page.getByRole("link", { name: "返回手动工作台", exact: true });
|
||||
await earlyFallback.waitFor();
|
||||
const earlyHref = await earlyFallback.getAttribute("href");
|
||||
resumeProjects();
|
||||
assert.equal(earlyHref, path("annotate", owned));
|
||||
await earlyFallback.click();
|
||||
console.log("PASS slow project loading preserves bookmarked project/task in immediate manual return");
|
||||
await page.goto(http + path("annotate", owned));
|
||||
await bench(page).waitFor();
|
||||
await page.getByText("当前连接使用手动模式;独立工作页和连续领取需安全连接。", { exact: true }).waitFor();
|
||||
assert.ok(await button(page, "开始工作").isDisabled());
|
||||
const initial = await read(page, owned);
|
||||
assert.equal(
|
||||
(initial.subject.payload.annotationWorkspace.segments || []).length,
|
||||
0,
|
||||
"requires empty descriptions before discard",
|
||||
);
|
||||
await media(page);
|
||||
await button(page, "舍弃片段").click();
|
||||
await page.getByRole("textbox", { name: "舍弃原因", exact: true }).fill("HTTP零描述回归");
|
||||
let response = post(page, "/slice-dispositions");
|
||||
await button(page, "确认舍弃").click();
|
||||
const discardedResponse = await response;
|
||||
assert.ok(discardedResponse.ok());
|
||||
const discarded = await read(page, owned);
|
||||
assert.equal(discarded.version, initial.version + 1);
|
||||
assert.deepEqual(boundaries(discarded), boundaries(initial));
|
||||
assert.equal(discarded.assignedUserId, initial.assignedUserId);
|
||||
assert.ok(
|
||||
discarded.subject.payload.annotationWorkspace.sliceSegments.some(
|
||||
(s) => s.deliveryDisposition === "discard" && s.discardReason === "HTTP零描述回归",
|
||||
),
|
||||
);
|
||||
await page.reload();
|
||||
await bench(page).waitFor();
|
||||
await button(page, "恢复为保留").click();
|
||||
response = post(page, "/slice-dispositions");
|
||||
await button(page, "确认恢复").click();
|
||||
assert.ok((await response).ok());
|
||||
await page.reload();
|
||||
await bench(page).waitFor();
|
||||
const restored = await read(page, owned);
|
||||
assert.equal(restored.version, initial.version + 2);
|
||||
assert.equal((restored.subject.payload.annotationWorkspace.segments || []).length, 0);
|
||||
assert.deepEqual(boundaries(restored), boundaries(initial));
|
||||
assert.equal(restored.assignedUserId, initial.assignedUserId);
|
||||
assert.ok(
|
||||
restored.subject.payload.annotationWorkspace.sliceSegments.every((s) => s.deliveryDisposition !== "discard"),
|
||||
);
|
||||
console.log("PASS empty descriptions → discard → refresh → restore → refresh; boundaries/ownership preserved");
|
||||
|
||||
await page.goto(http + path("work", owned));
|
||||
const fallback = page.getByRole("link", { name: "返回手动工作台", exact: true });
|
||||
await fallback.waitFor();
|
||||
assert.equal(await bench(page).count(), 0);
|
||||
assert.equal(await fallback.getAttribute("href"), path("annotate", owned));
|
||||
await fallback.click();
|
||||
await bench(page).waitFor();
|
||||
assert.equal((await read(page, owned)).version, restored.version);
|
||||
assert.equal(claims.length, 0);
|
||||
console.log("PASS direct HTTP /work returns explicitly to same project/task without release or claim");
|
||||
|
||||
// Unknown response: let the real server allocate, lose only its response, retry.
|
||||
let allocation;
|
||||
await page.route(
|
||||
"**/random-claims",
|
||||
async (route) => {
|
||||
const r = await route.fetch({
|
||||
url: route.request().url().replace(http, secure),
|
||||
headers: { ...(await route.request().allHeaders()), host: "annotation-http.test:5174" },
|
||||
});
|
||||
assert.ok(r.ok());
|
||||
allocation = await r.json();
|
||||
await route.abort("failed");
|
||||
},
|
||||
{ times: 1 },
|
||||
);
|
||||
await button(page, "随机领取任务").click();
|
||||
await page
|
||||
.getByTestId("project-random-claim")
|
||||
.getByRole("status")
|
||||
.filter({ hasText: /Failed to fetch|领取结果暂未确认/ })
|
||||
.waitFor();
|
||||
assert.equal(claims.length, 1);
|
||||
assert.ok(allocation.task.id.startsWith(`annotation-task-${prefix}-pool-`));
|
||||
await button(page, "随机领取任务").click();
|
||||
await page.waitForURL((u) => u.searchParams.get("taskId") === allocation.task.id);
|
||||
await bench(page).waitFor();
|
||||
assert.equal(claims.length, 2);
|
||||
assert.equal(claims[0].requestId, claims[1].requestId);
|
||||
assert.equal((await read(page, allocation.task.id)).assignedUserId, initial.assignedUserId);
|
||||
console.log("PASS real HTTP manual claim and unknown response replay use the same requestId and one allocation");
|
||||
|
||||
// The original manual workbench can save and submit with the real API.
|
||||
await media(page);
|
||||
await button(page, "新增动作描述").click();
|
||||
await bench(page).focus();
|
||||
for (let n = 0; n < 6; n++) {
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await page.waitForTimeout(100);
|
||||
}
|
||||
await button(page, "确认结束点").click();
|
||||
await page.getByRole("textbox", { name: "动作描述", exact: true }).fill("HTTP手动标注保存与送检");
|
||||
response = post(page, "/annotation-confirmations");
|
||||
await button(page, "确认保存描述").click();
|
||||
assert.ok((await response).ok());
|
||||
const saved = await read(page, allocation.task.id);
|
||||
assert.ok(saved.subject.payload.annotationWorkspace.segments.some((s) => s.description === "HTTP手动标注保存与送检"));
|
||||
await page.reload();
|
||||
await bench(page).waitFor();
|
||||
await button(page, "完成任务并提交质检").click();
|
||||
response = post(page, "/combined-submissions");
|
||||
await button(page, "确认送检").click();
|
||||
assert.ok((await response).ok());
|
||||
let completed;
|
||||
for (let n = 0; n < 180; n++) {
|
||||
completed = await read(page, allocation.task.id);
|
||||
if (completed.currentStageId === "quality_review") break;
|
||||
await page.waitForTimeout(1000);
|
||||
}
|
||||
assert.equal(completed.currentStageId, "quality_review");
|
||||
assert.equal(claims.length, 2, "HTTP manual completion must not auto-claim");
|
||||
console.log("PASS HTTP manual save → reload/My Tasks → submit → authoritative quality_review without automatic next");
|
||||
|
||||
// Hold an actual allocation response while the user switches task.
|
||||
await page.goto(http + path("annotate", owned));
|
||||
await bench(page).waitFor();
|
||||
let deliver, started;
|
||||
const held = new Promise((resolve) => {
|
||||
started = resolve;
|
||||
});
|
||||
const release = new Promise((resolve) => {
|
||||
deliver = resolve;
|
||||
});
|
||||
let lateTask;
|
||||
await page.route(
|
||||
"**/random-claims",
|
||||
async (route) => {
|
||||
const r = await route.fetch({
|
||||
url: route.request().url().replace(http, secure),
|
||||
headers: { ...(await route.request().allHeaders()), host: "annotation-http.test:5174" },
|
||||
});
|
||||
lateTask = (await r.json()).task.id;
|
||||
started();
|
||||
await release;
|
||||
await route.fulfill({ response: r });
|
||||
},
|
||||
{ times: 1 },
|
||||
);
|
||||
await button(page, "随机领取任务").click();
|
||||
await held;
|
||||
await page.locator(`article[data-task-id="${other}"]`).getByTestId("annotation-task-card").click();
|
||||
await page.waitForURL((u) => u.searchParams.get("taskId") === other);
|
||||
deliver();
|
||||
await page.waitForResponse((r) => r.url().endsWith("/random-claims"));
|
||||
await bench(page).waitFor();
|
||||
assert.equal(new URL(page.url()).searchParams.get("taskId"), other);
|
||||
assert.equal((await read(page, lateTask)).assignedUserId, initial.assignedUserId);
|
||||
console.log("PASS late HTTP allocation retains server ownership without replacing the selected task");
|
||||
await context.close();
|
||||
|
||||
// A real secure-context lock in another tab must block manual fallback.
|
||||
const locksContext = await browser.newContext({ viewport: { width: 1440, height: 900 } });
|
||||
page = await login(locksContext, secure);
|
||||
assert.equal(await page.evaluate(() => isSecureContext && !!navigator.locks), true);
|
||||
await page.goto(secure + path("annotate", owned));
|
||||
await bench(page).waitFor();
|
||||
await button(page, "开始工作").click();
|
||||
await page.waitForURL(/\/work\?/);
|
||||
await bench(page).waitFor();
|
||||
await button(page, "完成当前任务后停止").click();
|
||||
const second = await locksContext.newPage();
|
||||
await second.goto(secure + path("annotate", other));
|
||||
await bench(second).waitFor();
|
||||
await second.getByText("此账号在本项目已有活动工作页。请切换回该页面继续,避免同时编辑。", { exact: true }).waitFor();
|
||||
assert.ok(await button(second, "随机领取任务").isDisabled());
|
||||
assert.ok(await button(second, "开始工作").isDisabled());
|
||||
// The query may race another owner; acquire must still fail on the actual lock.
|
||||
const racing = await locksContext.newPage();
|
||||
await racing.addInitScript(() => {
|
||||
navigator.locks.query = async () => ({ held: [], pending: [] });
|
||||
});
|
||||
let racingClaims = 0;
|
||||
racing.on("request", (r) => {
|
||||
if (r.method() === "POST" && r.url().endsWith("/random-claims")) racingClaims++;
|
||||
});
|
||||
await racing.goto(secure + path("annotate", other));
|
||||
await bench(racing).waitFor();
|
||||
await button(racing, "随机领取任务").click();
|
||||
await racing.getByText("此账号在本项目已有活动工作页。请切换回该页面继续,避免同时编辑。", { exact: true }).waitFor();
|
||||
assert.equal(racingClaims, 0);
|
||||
await racing.close();
|
||||
console.log("PASS actual lock-acquisition conflict blocks allocation even when query misses the owner");
|
||||
await page.close();
|
||||
await button(second, "开始工作").waitFor();
|
||||
await second.waitForFunction(() =>
|
||||
[...document.querySelectorAll("button")].some((b) => b.textContent === "开始工作" && !b.disabled),
|
||||
);
|
||||
await button(second, "开始工作").click();
|
||||
await second.waitForURL(/\/work\?/);
|
||||
await bench(second).waitFor();
|
||||
console.log("PASS real secure Web Locks two-tab exclusion and owner-close recovery");
|
||||
await locksContext.close();
|
||||
|
||||
// Fault injection only for the browser API error path, never used to pass HTTP.
|
||||
const failedContext = await browser.newContext();
|
||||
await failedContext.addInitScript(() => {
|
||||
navigator.locks.request = () => Promise.reject(new DOMException("Injected coordination failure", "AbortError"));
|
||||
});
|
||||
page = await login(failedContext, secure);
|
||||
await page.goto(secure + path("annotate", owned));
|
||||
await bench(page).waitFor();
|
||||
const beforeError = claims.length;
|
||||
await button(page, "随机领取任务").click();
|
||||
await page.getByText("页面协调失败,尚未领取新任务。请刷新后重试;不会绕过页面锁。", { exact: true }).waitFor();
|
||||
assert.equal(claims.length, beforeError);
|
||||
assert.equal(
|
||||
await page.getByText("当前连接使用手动模式;独立工作页和连续领取需安全连接。", { exact: true }).count(),
|
||||
0,
|
||||
);
|
||||
console.log("PASS supported-but-failed lock coordination does not fall back or allocate");
|
||||
assert.deepEqual(errors, []);
|
||||
await page.screenshot({ path: `${output}/http-manual-final.png` });
|
||||
console.log("PASS all HTTP manual/secure coordination acceptance");
|
||||
} catch (error) {
|
||||
if (page && !page.isClosed()) {
|
||||
await page.screenshot({ path: `${output}/http-manual-error.png` });
|
||||
console.error((await page.locator("body").innerText()).slice(-9000));
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.close();
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user