droboticflow/tests/browser/review-drafts.mjs

206 lines
9.7 KiB
JavaScript

import { browserExecutableOptions } from "../../scripts/lib/browser-executable.mjs";
// Actual HTTP application/API with transport failure injection only.
import { chromium } from "playwright";
import fs from "node:fs/promises";
import assert from "node:assert/strict";
const dir = process.env.REVIEW_DRAFT_FIXTURES || "local-data/verification/review-focused-20260922";
const base = process.env.REVIEW_DRAFT_URL || "http://review-session.test:5178";
const mode = process.env.REVIEW_DRAFT_MODE || "quality";
const hostname = new URL(base).hostname;
const fixtures = JSON.parse(await fs.readFile(`${dir}/fixture-index.json`, "utf8"));
const item = fixtures[mode][0];
const state = JSON.parse(
await fs.readFile(`${dir}/fixture-${mode === "quality" ? "qc" : "acceptance"}-auth.json`, "utf8"),
);
state.cookies = state.cookies.map((cookie) => ({ ...cookie, domain: hostname }));
const browser = await chromium.launch({
...browserExecutableOptions(),
headless: true,
args: [`--host-resolver-rules=MAP ${hostname} 127.0.0.1`, "--no-proxy-server"],
});
try {
const context = await browser.newContext({ storageState: state, viewport: { width: 1600, height: 1000 } });
const page = await context.newPage();
page.setDefaultTimeout(20000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const url = `${base}/plugins/annotation-qa/workflows/all/${mode}?projectId=${fixtures.projectId}${item.taskId ? `&taskId=${item.taskId}` : ""}`;
const open = async (p) => {
await p.goto(url);
await p.getByRole("button", { name: /^我的任务/ }).click();
if (mode === "acceptance")
await p
.getByTestId("acceptance-task-card")
.first()
.getByRole("button", { name: /^预览 / })
.click();
await p
.getByRole("status")
.filter({ hasText: /本页可编辑审查意见|本页只读/ })
.waitFor();
const take = p.getByRole("button", { name: "在本页接管审查", exact: true });
if (await take.count()) await take.click();
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
await p.getByRole("button", { name: "保存批注", exact: true }).waitFor();
await p.getByRole("button", { name: "保存批注", exact: true }).isEnabled();
};
await open(page);
const waitForPicture = async () => {
await page.waitForFunction(() => {
const videos = [...document.querySelectorAll("video")].filter((video) => video.getBoundingClientRect().width > 0);
return videos.length > 0 && videos.every((video) => video.readyState >= 2 && !video.seeking);
});
// 04 removed the raw-record JSON block; wait for the caption full text instead.
await page.getByLabel("当前画面标注原文").locator("p").first().waitFor();
};
const panel = page.getByRole("region", { name: "审查问题草稿" });
const input = page.getByRole("textbox", { name: "审查问题说明", exact: true });
const read = () =>
page.evaluate(async (id) => {
const r = await fetch(`/api/human-items/${id}/review-draft`);
if (!r.ok) throw Error(`readback ${r.status}`);
return r.json();
}, item.humanItemId);
// New contract (spec 已确认行为 2/4): entry starts with F, scope via radiogroup, Enter reaches text.
const scope = panel.getByRole("radiogroup", { name: "问题范围" });
const startEntry = async (scopeName) => {
// F is a workbench shortcut: focus a non-activating workbench control so the keydown reaches it.
await page
.getByTestId("capture-annotation-workbench")
.first()
.getByRole("button", { name: "上一帧", exact: true })
.focus();
// F fixes the actual ready frame; wait for decodable media first.
await page.waitForFunction(() => {
const videos = [...document.querySelectorAll("video")].filter((v) => v.getBoundingClientRect().width > 0);
return videos.length > 0 && videos.every((v) => v.readyState >= 2 && !v.seeking);
});
await page.keyboard.press("f");
await scope.waitFor();
// Clicking a radio confirms that scope directly; Enter on the default radio confirms 动作.
if (scopeName) await scope.getByRole("radio", { name: scopeName, exact: true }).click();
else await scope.getByRole("radio", { name: "动作", exact: true }).press("Enter");
await page.waitForFunction(() => document.activeElement?.getAttribute("aria-label") === "审查问题说明");
};
const savedList = panel.getByRole("listbox", { name: "已保存问题" });
await startEntry("整体");
const note = `${mode} 整体复核 ${Date.now()}`;
await input.fill(note);
await panel.getByRole("button", { name: "保存批注", exact: true }).click();
await panel
.getByRole("status")
.filter({ hasText: /^已保存$/ })
.waitFor();
let saved = (await read()).draft;
assert.ok(saved.problems.some((p) => p.scope === "task" && p.text === note));
await open(page);
// Save clears the input and exits editing; refresh lists the entry without auto-editing it.
assert.equal(await input.inputValue(), "", "saved problem is not auto-edited after refresh");
await waitForPicture();
await startEntry();
const actionNote = `${mode} 当前画面问题 ${Date.now()}`;
await input.fill(actionNote);
await input.press("Control+Enter");
await panel
.getByRole("status")
.filter({ hasText: /^已保存$/ })
.waitFor();
saved = (await read()).draft;
const action = saved.problems.find((p) => p.text === actionNote);
assert.ok(action && ["action", "slice"].includes(action.scope));
assert.ok(action.sliceId);
if (mode === "acceptance") assert.ok(action.sourceItemId);
if (mode === "acceptance") {
const sliceButtons = page.locator('[aria-label="验收切片选择"]').getByRole("button");
await sliceButtons.nth(3).click();
assert.equal(await sliceButtons.nth(3).getAttribute("aria-pressed"), "true");
await waitForPicture();
await startEntry();
const secondNote = `第二来源同名动作 ${Date.now()}`;
await input.fill(secondNote);
await panel.getByRole("button", { name: "保存批注", exact: true }).click();
await panel
.getByRole("status")
.filter({ hasText: /^已保存$/ })
.waitFor();
saved = (await read()).draft;
const second = saved.problems.find((p) => p.text === secondNote);
assert.ok(second?.sourceItemId && second.sourceItemId !== action.sourceItemId);
assert.equal(second.sliceId, action.sliceId, "same display slice IDs remain separated by source");
await open(page);
await savedList.getByRole("option").filter({ hasText: secondNote }).click();
assert.equal(await input.inputValue(), "", "click recalls only, never auto-edits");
await savedList.getByRole("option").filter({ hasText: actionNote }).click();
assert.equal(await input.inputValue(), "");
}
// Unsaved text survives pure recall clicks; only F/Enter-edit/leaving asks to save or discard.
await startEntry();
await input.fill("未保存的文字必须保留");
await savedList.getByRole("option").filter({ hasText: note }).click();
assert.equal(await input.inputValue(), "未保存的文字必须保留", "recall while typing keeps unsaved text");
await input.press("Escape");
await page.route("**/review-draft", (route) =>
route.request().method() === "PUT" ? route.abort("failed") : route.continue(),
);
await startEntry();
await input.fill("模拟断网后保留的批注");
await panel.getByRole("button", { name: "保存批注", exact: true }).click();
// Inline failed save keeps the editor open with its text and surfaces an error alert.
await panel.getByRole("alert").waitFor();
assert.equal(await input.inputValue(), "模拟断网后保留的批注");
await page.unroute("**/review-draft");
await input.fill("断网之后新增的文字,不能替代未核对的原操作");
await panel.getByRole("button", { name: "保存批注", exact: true }).click();
await panel.getByText(/之前的文字已保存/).waitFor();
saved = (await read()).draft;
assert.ok(
saved.problems.some((p) => p.text === "模拟断网后保留的批注"),
"retry reconciles original intent before new text",
);
assert.equal(await input.inputValue(), "断网之后新增的文字,不能替代未核对的原操作");
await panel.getByRole("button", { name: "保存批注", exact: true }).click();
await panel
.getByRole("status")
.filter({ hasText: /^已保存$/ })
.waitFor();
saved = (await read()).draft;
assert.ok(saved.problems.some((p) => p.text === "断网之后新增的文字,不能替代未核对的原操作"));
await startEntry();
await input.fill("另一页接管后仍应看见的未保存文字");
const other = await context.newPage();
await open(other);
await page
.getByRole("status")
.filter({ hasText: /失去编辑权/ })
.waitFor();
assert.equal(await input.inputValue(), "另一页接管后仍应看见的未保存文字");
assert.equal(await input.getAttribute("readonly"), "");
await page.screenshot({ path: `${dir}/draft-${mode}-lost-control.png`, fullPage: true });
await other.screenshot({ path: `${dir}/draft-${mode}-restored.png`, fullPage: true });
assert.deepEqual(errors, []);
await fs.writeFile(
`${dir}/review-draft-${mode}-browser.json`,
JSON.stringify(
{
mode,
ordinaryHTTP: await page.evaluate(() => !window.isSecureContext),
saveReadback: true,
refreshRecovery: true,
target: action,
failedSaveRetained: true,
unsavedTargetGuard: true,
takeoverTextRetained: true,
},
null,
2,
),
);
console.log(
`${mode}: saved/readback, refresh, scoped target, unsaved guard, failed-save retention, takeover text retention passed`,
);
await context.close();
} finally {
await browser.close();
}