droboticflow/tests/browser/review-trace.mjs
2026-11-19 11:35:20 +08:00

212 lines
9.3 KiB
JavaScript

import { browserExecutableOptions } from "../../scripts/lib/browser-executable.mjs";
import assert from "node:assert/strict";
import fs from "node:fs";
import { execFileSync } from "node:child_process";
import { chromium } from "playwright";
import { createServer } from "vite";
const api = process.env.REVIEW_TRACE_API;
assert.match(api, /^http:\/\/127\.0\.0\.1:\d+$/);
const out = "local-data/test-results/review-trace";
fs.mkdirSync(out, { recursive: true });
// The API fixture references placeholder source bytes. Editing intentionally
// requires decoded media, so serve a real isolated video instead of that file.
execFileSync("ffmpeg", [
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"lavfi",
"-i",
"color=c=black:s=160x90:r=30:d=10",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
`${out}/synthetic.mp4`,
]);
const media = fs.readFileSync(`${out}/synthetic.mp4`);
const vite = await createServer({
cacheDir: "local-data/test-results/vite-review-trace",
server: { host: "127.0.0.1", port: 5206, strictPort: true, proxy: { "/api": { target: api, changeOrigin: true } } },
});
let browser;
const errors = [];
let blockPoolReads = false;
const unexpectedPoolReads = [];
const sessionWrites = [];
const continuationWrites = [];
const mode = process.env.REVIEW_TRACE_MODE || "quality";
const selection =
mode === "quality" ? `taskId=${process.env.REVIEW_TRACE_TASK}` : `acceptanceId=${process.env.REVIEW_TRACE_ITEM}`;
try {
await vite.listen();
browser = await chromium.launch({
...browserExecutableOptions(),
headless: true,
args: ["--no-proxy-server"],
});
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
page.setDefaultTimeout(15000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", (route) => {
const u = new URL(route.request().url());
if (u.hostname !== "127.0.0.1") return route.abort();
if (u.pathname.endsWith("/frame-timeline")) {
// Matches the generated 10s/30fps source; no production source facts are inferred.
return route.fulfill({
json: {
camera: "left",
frameCount: 300,
originTimestampUs: 0,
coverageEndTimestampUs: 10000000,
boundariesSeconds: Array.from({ length: 301 }, (_, i) => i / 30),
rangeStartSecond: 0,
rangeEndSecond: 10,
},
});
}
if (u.pathname.endsWith("/subject-content")) {
const range = /^bytes=(\d+)-(\d*)$/.exec(route.request().headers().range || "");
const start = range ? Number(range[1]) : 0;
const end = range?.[2] ? Math.min(Number(range[2]), media.length - 1) : media.length - 1;
return route.fulfill({
status: range ? 206 : 200,
contentType: "video/mp4",
headers: {
"Accept-Ranges": "bytes",
...(range ? { "Content-Range": `bytes ${start}-${end}/${media.length}` } : {}),
},
body: media.subarray(start, end + 1),
});
}
if (u.pathname.endsWith("/review-continuation") && route.request().method() === "POST")
continuationWrites.push(route.request().postDataJSON()?.action);
if (u.pathname.endsWith("/review-session") && route.request().method() === "POST")
sessionWrites.push(route.request().postDataJSON()?.action);
if (
blockPoolReads &&
["/api/human-items", "/api/human-item-summaries", "/api/human-item-counts"].includes(u.pathname)
) {
unexpectedPoolReads.push(u.search);
return route.fulfill({ status: 503, json: { error: "Synthetic pool outage during layout change" } });
}
if (u.pathname.startsWith("/worker-api/")) return route.fulfill({ json: { status: "ok" } });
return route.continue();
});
for (const focused of [false, true]) {
await page.goto(
`http://127.0.0.1:5206/plugins/annotation-qa/workflows/all/${mode}?projectId=${process.env.REVIEW_TRACE_PROJECT}&pool=mine&${selection}${focused ? "&reviewFocus=1" : ""}`,
);
const panel = page.getByTestId("review-trace-panel");
try {
await panel.waitFor();
await panel.getByRole("listitem").first().waitFor();
} catch (e) {
console.log(await page.locator("body").innerText());
throw e;
}
const latest = panel.getByRole("list", { name: "最近流转" });
await latest.getByText(mode === "acceptance" ? "质检通过" : "审核退回", { exact: true }).waitFor();
assert.equal(await panel.locator("details ol li").count(), 2);
assert.equal(await page.getByTestId("review-source-strip").count(), 0, "no full-width source strip");
const source = panel.getByTestId("review-trace-source");
const summary = await panel.locator("summary").innerText();
if (mode === "acceptance") {
assert.match(summary, /V3[\s\S]*质检退回 1[\s\S]*验收退回 0/);
assert.match(await source.innerText(), /验收员[\s\S]*首次提交[\s\S]*2026-01-02/);
assert.equal(await source.getByText("审核员", { exact: true }).count(), 0);
assert.equal(await latest.getByText("领取任务", { exact: true }).count(), 1);
} else {
for (const label of ["标注员", "供应商", "首次提交", "审核员", "验收员", "标注员ID"])
assert.equal(await source.getByText(label, { exact: true }).count(), 1, label);
assert.match(summary, /V\d+[\s\S]*打回 \d+/);
}
const pb = await panel.boundingBox(),
side = await panel.evaluate((node) => node.parentElement.getBoundingClientRect().toJSON());
assert.ok(pb.y - side.y <= 72, "trace card at top of side column");
assert.ok(pb.x > 800, "trace card in right column");
await panel.locator("summary").click();
assert.equal(await panel.locator("details").getAttribute("open"), null);
await panel.locator("summary").click();
await panel.getByRole("button", { name: /查看完整记录/ }).click();
assert.ok((await panel.locator("dialog ol li").count()) >= 3);
await page.keyboard.press("Escape");
assert.equal(await panel.locator("dialog").getAttribute("open"), null);
if (!focused && (mode === "quality" || process.env.REVIEW_TRACE_RECEIPT === "true")) {
const focusButton = page.getByRole("button", { name: "进入专注审查", exact: true });
await focusButton.waitFor();
if (mode === "quality") {
await page.getByTestId("review-continuation-toggle").click();
await page.getByText("连续审查中", { exact: true }).first().waitFor();
}
const continuationBefore = continuationWrites.length;
const editor = page.getByRole("textbox", { name: "审查问题说明", exact: true });
if (mode === "quality") {
await page.waitForFunction(() => !document.querySelector('[data-testid="frame-timeline-status"]'));
await page.waitForFunction(() =>
[...document.querySelectorAll("video,movi-player")].some((video) => video.readyState >= 2 && !video.seeking),
);
await editor.click();
await editor.fill("Synthetic unsaved opinion retained across focus entry");
}
const before = sessionWrites.length;
blockPoolReads = true;
await focusButton.click();
await page.locator('.annotation-operations-page[data-review-focused="true"]').waitFor();
await page.waitForTimeout(500);
assert.deepEqual(unexpectedPoolReads, [], "layout entry must not reload the task pool");
await panel.waitFor();
if (mode === "quality")
assert.equal(
await editor.inputValue(),
"Synthetic unsaved opinion retained across focus entry",
"unsaved opinion survives layout entry",
);
assert.ok(
!sessionWrites.slice(before).some((a) => ["release", "acquire", "takeover"].includes(a)),
"layout entry must retain the review lease",
);
if (mode === "quality") {
const renewal = await page.waitForResponse(
(response) => {
const request = response.request();
return (
new URL(response.url()).pathname.endsWith("/review-continuation") &&
request.method() === "POST" &&
request.postDataJSON()?.action === "renew"
);
},
{ timeout: 15000 },
);
assert.equal(renewal.status(), 200, "continuation renew succeeds after focus entry");
await page.getByText("连续审查中", { exact: true }).first().waitFor();
assert.ok(
!continuationWrites.slice(continuationBefore).includes("pause"),
"focus entry must not pause a running queue",
);
assert.equal(await editor.inputValue(), "Synthetic unsaved opinion retained across focus entry");
await page.getByRole("button", { name: "取消修改", exact: true }).click();
}
await page.getByRole("button", { name: "返回任务池", exact: true }).first().click();
await focusButton.waitFor();
if (mode === "quality") await page.getByText("连续审查已暂停", { exact: true }).first().waitFor();
await page.waitForTimeout(300);
assert.deepEqual(unexpectedPoolReads, [], "layout exit must not reload the task pool");
blockPoolReads = false;
}
await page.screenshot({ path: `${out}/${mode}-${focused ? "focused" : "normal"}.png`, fullPage: true });
}
assert.deepEqual(errors, []);
console.log(JSON.stringify({ result: "passed", modes: 2, errors }));
} finally {
await browser?.close();
await vite.close();
}