droboticflow-new/tests/browser/acceptance-pool-loading.mjs
2026-09-29 06:34:38 -07:00

197 lines
9.1 KiB
JavaScript

// Actual app/API wrapper with local synthetic responses only.
import assert from "node:assert/strict";
import { createServer } from "vite";
import { chromium } from "playwright";
const server = await createServer({ server: { host: "127.0.0.1", port: 5198, strictPort: true } });
await server.listen();
const base = server.resolvedUrls.local[0];
const browser = await chromium.launch({
executablePath: process.env.BROWSER_PATH || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
headless: true,
args: ["--no-proxy-server"],
});
const deferred = () => {
let resolve;
const promise = new Promise((r) => (resolve = r));
return { promise, resolve };
};
async function fixture(role, { holdProject = false, failLegacy = false } = {}) {
const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
const page = await ctx.newPage();
page.setDefaultTimeout(30000);
const held = deferred(),
reports = deferred();
const calls = [],
errors = [];
const user = { id: "reviewer", role, status: "active", organizationId: "org", name: "Test reviewer" };
const project = (id) => ({ id, name: id, status: "active", organizationId: "org" });
const item = (projectId, stage) => ({
id: `${projectId}-${stage}`,
organizationId: "org",
pluginId: "annotation-qa",
projectId,
workflowId: "workflow",
runId: "run",
version: 1,
currentRevision: 1,
createdAt: stage === "acceptance" ? "2026-09-28T00:00:00Z" : "2026-09-29T00:00:00Z",
currentStageId: stage,
status: stage === "acceptance" ? "claimed" : "ready",
assignedUserId: stage === "acceptance" ? user.id : undefined,
legacyTaskId: stage === "acceptance" ? `${projectId}-legacy` : undefined,
processingProfile: "raw_human",
display: { projectName: projectId, captureDirectories: [`${projectId}-${stage}`] },
subject: { payload: { captureDirectory: `${projectId}-${stage}`, items: [] } },
});
page.on("pageerror", (e) => errors.push(e.message));
await ctx.route("**/*", async (route) => {
const req = route.request(),
url = new URL(req.url()),
path = url.pathname;
if (!path.startsWith("/api/") && !path.startsWith("/worker-api/")) return route.continue();
const json = (data) => route.fulfill({ json: data });
calls.push({ path, query: Object.fromEntries(url.searchParams), method: req.method() });
assert.equal(req.method(), "GET", "queue verification must not write");
if (path === "/api/auth/me") return json({ user, organization: { id: "org", name: "Synthetic" } });
if (path === "/api/plugins")
return json({ items: [{ enabled: true, manifest: { id: "annotation-qa", name: "标注", version: "1" } }] });
if (path.includes("ready") || path.includes("health"))
return json({ ready: true, status: "ok", buildCommit: "test" });
if (path === "/api/projects") return json({ items: [project("project-a"), project("project-b")] });
if (path.endsWith("/members") && path.startsWith("/api/projects/"))
return json({ items: [{ id: "member", projectId: path.split("/")[3], userId: user.id, roles: [role] }] });
if (path.endsWith("/workflows"))
return json({ items: [{ id: "workflow", name: "Workflow", nodes: [], edges: [] }] });
if (path === "/api/human-rejects" || path.endsWith("/workload-summary")) {
await reports.promise;
return json({ items: [], eventCount: 0 });
}
if (path === "/api/plugins/annotation-qa/tasks") {
const projectId = url.searchParams.get("projectId") || "project-a";
return json({
items: [
{
id: `${projectId}-legacy`,
projectId,
organizationId: "org",
workflowId: "workflow",
runId: "run",
templateId: "template",
templateVersion: 6,
currentRevision: 1,
status: "pending_acceptance",
humanStageId: "acceptance",
assignedUserId: user.id,
clipStart: 0,
clipEnd: 10,
},
],
});
}
if (path === "/api/human-items") {
const projectId = url.searchParams.get("projectId") || "project-a";
const stage = url.searchParams.get("stageId"),
pool = url.searchParams.get("pool");
if (holdProject && projectId === "project-a") await held.promise;
if (failLegacy && stage === "acceptance") return route.fulfill({ status: 403, json: { error: "legacy denied" } });
const items = [item(projectId, "prepackage_acceptance"), item(projectId, "acceptance")]
.filter((i) => !stage || i.currentStageId === stage)
.filter((i) => pool === "all" || (pool === "mine" ? i.assignedUserId === user.id : !i.assignedUserId));
return json({ items });
}
return json({ items: [], labelIds: [], sliceLabelIds: [] });
});
const close = async () => {
held.resolve();
reports.resolve();
await ctx.close();
};
return { page, calls, errors, held, reports, close };
}
try {
for (const role of ["admin", "acceptance_reviewer"]) {
const f = await fixture(role);
try {
await f.page.goto(base + "plugins/annotation-qa/workflows/all/acceptance?projectId=project-a", {
waitUntil: "domcontentloaded",
});
const available = f.page.getByTestId("human-task-pool-available");
const mine = f.page.getByTestId("human-task-pool-mine");
await available.filter({ hasText: /1/ }).waitFor();
await mine.filter({ hasText: /1/ }).waitFor();
const poolCalls = () => f.calls.filter((r) => r.path === "/api/human-items");
const initial = poolCalls().length;
const expected = role === "admin" ? 2 : 4;
assert.equal(new Set(poolCalls().map((r) => `${r.query.pool}:${r.query.stageId}`)).size, expected);
assert.ok(initial <= expected * 2, "only the initial React development StrictMode replay may duplicate requests");
assert.ok(poolCalls().every((r) => ["acceptance", "prepackage_acceptance"].includes(r.query.stageId)));
assert.ok(poolCalls().every((r) => (role === "admin" ? r.query.pool === "all" : r.query.pool !== "all")));
assert.equal(
f.calls.filter((r) => r.path === "/api/human-rejects" || r.path.endsWith("/workload-summary")).length,
0,
);
await mine.click();
await f.page.locator('[data-task-id="project-a-legacy"]').waitFor();
if (role === "admin") await f.page.getByTestId("human-task-pool-all").click();
await available.click();
await f.page
.locator(".annotation-task-list")
.getByRole("button", { name: /project-a-prepackage_acceptance/ })
.waitFor();
await f.page.waitForTimeout(200);
assert.equal(poolCalls().length, initial, "switching pools must not reload the project");
if (role === "admin") {
const view = f.page.getByRole("combobox", { name: "当前工作台视图" });
await view.selectOption("workload");
await f.page.getByText("正在加载工作记录…", { exact: true }).waitFor();
assert.equal(f.calls.filter((r) => r.path.endsWith("/workload-summary")).length, 1);
await view.selectOption("queue");
await available.filter({ hasText: /1/ }).waitFor();
await view.selectOption("rejects");
await f.page.waitForTimeout(100);
assert.equal(f.calls.filter((r) => r.path === "/api/human-rejects").length, 1);
await view.selectOption("queue");
assert.equal(poolCalls().length, initial, "slow reports do not reload or block the task pool");
}
assert.deepEqual(f.errors, []);
console.log("PASS", role, "scoped stages, legacy task, permissions, stable pool navigation, deferred reports");
} finally {
await f.close();
}
}
const stale = await fixture("admin", { holdProject: true });
try {
await stale.page.goto(base + "plugins/annotation-qa/workflows/all/acceptance?projectId=project-a", {
waitUntil: "domcontentloaded",
});
await stale.page.getByRole("combobox", { name: "1. 项目", exact: true }).selectOption("project-b");
await stale.page.getByTestId("human-task-pool-available").filter({ hasText: /1/ }).waitFor();
stale.held.resolve();
await stale.page.waitForTimeout(250);
assert.ok(
(await stale.page.locator(".annotation-task-list").innerText()).includes("project-b-prepackage_acceptance"),
);
assert.ok(!(await stale.page.locator(".annotation-task-list").innerText()).includes("project-a-"));
console.log("PASS stale project responses cannot overwrite current acceptance pool");
} finally {
await stale.close();
}
const failed = await fixture("acceptance_reviewer", { failLegacy: true });
try {
await failed.page.goto(base + "plugins/annotation-qa/workflows/all/acceptance?projectId=project-a", {
waitUntil: "domcontentloaded",
});
await failed.page.getByRole("alert").filter({ hasText: "任务加载失败" }).waitFor();
assert.equal(await failed.page.getByRole("button", { name: "领取任务", exact: true }).count(), 0);
console.log("PASS legacy stage failure is reported, not silently accepted as an empty pool");
} finally {
await failed.close();
}
} finally {
await browser.close();
await server.close();
}