droboticflow-new/tests/browser/annotation-frame-initialization-entry.mjs
2026-09-18 17:32:26 +08:00

136 lines
6.0 KiB
JavaScript

// Real browser/API regression: loading an untouched default slice must not
// block entry to the work page. No task writes or random claims are permitted.
import assert from "node:assert/strict";
import fs from "node:fs";
import { chromium } from "playwright";
const base = process.env.ANNOTATION_BASE_URL || "http://127.0.0.1:5173";
const project = process.env.ANNOTATION_PROJECT_ID;
const task = process.env.ANNOTATION_TASK_ID;
const item = process.env.ANNOTATION_ITEM_ID;
assert.ok(
project && task && item && process.env.ANNOTATION_STORAGE_STATE,
"Provide an owned, untouched slice task and authenticated state",
);
const args = ["--no-proxy-server"];
if (process.env.ANNOTATION_ALLOW_INSECURE_ORIGIN === "true")
args.push(`--unsafely-treat-insecure-origin-as-secure=${new URL(base).origin}`);
const browser = await chromium.launch({
executablePath:
process.env.PLAYWRIGHT_EXECUTABLE_PATH || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
headless: true,
args,
});
try {
const context = await browser.newContext({
storageState: process.env.ANNOTATION_STORAGE_STATE,
viewport: { width: 1440, height: 900 },
});
const read = async () => {
const response = await context.request.get(`${base}/api/human-items/${item}`);
assert.ok(response.ok());
return (await response.json()).item;
};
const before = await read();
assert.ok(!before.subject.payload.annotationWorkspace?.sliceSegments?.length, "Use a task without saved slice edits");
const page = await context.newPage();
page.setDefaultTimeout(20000);
const writes = [],
errors = [],
results = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("dialog", (dialog) => dialog.accept());
await page.route("**/api/**", async (route) => {
const request = route.request();
if (!["GET", "HEAD"].includes(request.method()) && /\/tasks\/|\/human-items\/|random-claims/.test(request.url())) {
writes.push({ method: request.method(), path: new URL(request.url()).pathname });
await route.abort();
} else await route.fallback();
});
const button = (name) => page.getByRole("button", { name, exact: true });
const dirty = () => page.getByText("请先确认当前编辑,再领取新任务。", { exact: true });
const pool = `${base}/plugins/annotation-qa/workflows/all/annotate?projectId=${project}&taskId=${task}`;
for (const retry of [false, true]) {
let releaseFrames;
const gate = new Promise((resolve) => {
releaseFrames = resolve;
});
let first = true;
await page.route("**/frame-timeline?*", async (route) => {
if (retry && first) {
first = false;
// 502/503/504 are automatically retried by the API client. A terminal
// read failure exercises the explicit frame-range retry button.
await route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ error: "Intentional browser-only read failure" }),
});
return;
}
const response = await route.fetch();
await gate;
await route.fulfill({ response });
});
await page.goto(pool);
const bench = page.getByTestId("capture-annotation-workbench");
await bench.waitFor({ timeout: 60000 });
if (retry) await button("重试加载统一帧范围").click();
assert.equal(await dirty().count(), 0, "Initial task metadata is not an edit");
releaseFrames();
await page.getByTestId("frame-timeline-status").waitFor({ state: "hidden", timeout: 90000 });
await page.waitForFunction(
() => {
const videos = [...document.querySelectorAll("video")];
return videos.length === 2 && videos.every((video) => video.readyState >= 2);
},
null,
{ timeout: 90000 },
);
const result = {
retry,
enabled: await button("开始工作").isEnabled(),
dirtyWarning: await dirty().count(),
title: await button("开始工作").getAttribute("title"),
};
results.push(result);
console.log(JSON.stringify(result));
assert.ok(result.enabled, "Untouched default alignment must allow entering work mode");
assert.equal(result.dirtyWarning, 0, "Automatic frame alignment is not a user edit");
await page.unroute("**/frame-timeline?*");
// A genuine split must still block entry. Undo restores the aligned default.
const slider = page.getByRole("slider", { name: "Capture 播放位置", exact: true });
const rect = await slider.boundingBox();
await slider.click({ position: { x: Math.round(rect.width / 4), y: rect.height / 2 } });
await bench.focus();
await page.keyboard.press("c");
await dirty().waitFor();
assert.equal(await button("开始工作").isEnabled(), false, "Real unsaved edits retain the leave guard");
await page.keyboard.press("Control+z");
await dirty().waitFor({ state: "hidden" });
assert.ok(await button("开始工作").isEnabled(), "Undo to the initialized default is clean again");
await button("开始工作").click();
await page.waitForURL((url) => url.pathname.endsWith("/work"));
assert.equal(new URL(page.url()).searchParams.get("taskId"), task, "Continue the selected owned task");
await bench.waitFor();
assert.equal(context.pages().length, 1);
await page.getByRole("link", { name: "返回任务池", exact: true }).click();
await page.waitForURL((url) => url.pathname.endsWith("/annotate"));
}
const after = await read();
assert.equal(after.version, before.version);
assert.deepEqual(after.subject.payload.annotationWorkspace, before.subject.payload.annotationWorkspace);
assert.deepEqual(writes, []);
assert.deepEqual(errors, []);
const result = { results, versionUnchanged: before.version, writes, errors };
if (process.env.ANNOTATION_RESULT_PATH)
fs.writeFileSync(process.env.ANNOTATION_RESULT_PATH, JSON.stringify(result, null, 2));
console.log(
"PASS default initialization, retry, real dirty guard, undo and same-task work entry",
JSON.stringify(result),
);
} finally {
await browser.close();
}