Files
aigc-home/e2e/hel849.cjs
T
2026-10-25 20:26:23 +08:00

540 lines
20 KiB
JavaScript

const { chromium } = require(
process.env.PLAYWRIGHT_MODULE_PATH || "playwright",
);
const fs = require("node:fs"),
assert = require("node:assert/strict");
const OUT = "../evidence/hel849",
WEB = "http://127.0.0.1:15259",
API = "http://127.0.0.1:18259";
const phase = process.env.HEL849_PHASE || "after";
const report = { phase, checks: [], states: [], errors: [] };
const ok = (name, pass) => {
report.checks.push({ name, pass: !!pass });
assert(pass, name);
console.log("PASS", name);
};
const api = async (p, b, method) => {
const r = await fetch(API + p, {
method: method || (b ? "POST" : "GET"),
headers: { "Content-Type": "application/json" },
body: b ? JSON.stringify(b) : undefined,
});
assert(r.ok, await r.clone().text());
const t = await r.text();
return t ? JSON.parse(t) : null;
};
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
fs.mkdirSync(`${OUT}/${phase}`, { recursive: true });
const project = await api("/api/projects", {
title: "下拉回归项目 · 海岸来信",
idea: "隔离测试",
});
for (let i = 0; i < 35; i++)
await api("/api/projects", {
title: `长列表项目 ${i.toString().padStart(2, "0")} · 很长很长的项目名称用于确认截断和菜单避边`,
idea: "隔离测试",
});
const config = await api("/api/settings");
await api("/api/settings", {
llm_profiles: [
...config.llm_profiles.map((p) => ({ ...p, api_key: "" })),
...Array.from({ length: 35 }, (_, i) => ({
id: `model-${i}`,
name: `隔离模型 ${i} · 很长的模型名称与版本号`,
base_url: "http://127.0.0.1:19259/v1",
model: "isolated",
api_key: "",
})),
],
});
const skills = await api("/api/agent/skills?all=true");
const enabled = skills.filter((s) => s.is_enabled);
ok("real builtin skills available", enabled.length > 0);
const browser = await chromium.launch({
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
const ctx = await browser.newContext({
viewport: { width: 1440, height: 900 },
recordVideo: { dir: `${OUT}/${phase}/video` },
});
await ctx.tracing.start({
screenshots: true,
snapshots: true,
sources: true,
});
const p = await ctx.newPage();
p.on("pageerror", (e) => report.errors.push(e.stack));
p.setDefaultTimeout(10000);
await ctx.addInitScript(() => {
localStorage.setItem("aigc-lang", "zh");
localStorage.setItem("aigc-motion", "off");
});
try {
await p.goto(WEB + "/agents");
await p.getByLabel("任务想法").waitFor();
await pause(400);
for (const [width, height] of process.env.HEL849_QUICK
? []
: [
[1440, 900],
[1366, 768],
[1280, 720],
])
for (const theme of ["night", "day", "grade", "bluehour"]) {
await p.setViewportSize({ width, height });
await p.evaluate((theme) => {
document.documentElement.dataset.theme = theme;
window.dispatchEvent(
new StorageEvent("storage", { key: "aigc-theme", newValue: theme }),
);
}, theme);
await pause(100);
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-closed.png`,
});
for (const label of ["绑定项目", "任务模型", "任务技能"]) {
const control = p.getByRole("combobox", { name: label, exact: true });
await control.hover();
if (phase === "after")
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-${label}-hover.png`,
});
await control.focus();
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-${label}-focus.png`,
});
await control.click();
await pause(100);
report.states.push(
await control.evaluate(
(e, { theme, width, height, label }) => ({
theme,
width,
height,
label,
url: location.href,
title: document.title,
dataTheme: document.documentElement.dataset.theme,
tag: e.tagName,
expanded: e.getAttribute("aria-expanded"),
focus: document.activeElement === e,
style: {
background: getComputedStyle(e).backgroundColor,
color: getComputedStyle(e).color,
},
menu: document
.querySelector(".pill-menu")
?.getBoundingClientRect()
.toJSON(),
}),
{ theme, width, height, label },
),
);
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-${label}-open.png`,
});
if (phase === "after")
ok(
`${theme}-${width}-${label} menu avoids primary action`,
await p.locator(".pill-menu").evaluate((e) => {
const m = e.getBoundingClientRect(),
b = document
.querySelector(".big-input .primary")
.getBoundingClientRect();
return (
m.right <= b.left ||
m.left >= b.right ||
m.bottom <= b.top ||
m.top >= b.bottom
);
}),
);
await p.keyboard.press("Escape");
}
if (phase === "after") {
const skill = p.getByRole("combobox", {
name: "任务技能",
exact: true,
});
await skill.click();
await p.getByRole("option").nth(1).click();
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-selected.png`,
});
await skill.click();
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-selected-open.png`,
});
await p.keyboard.press("Escape");
}
console.log("CAPTURE", phase, theme, width, height);
}
if (phase === "before") {
const projectSelect = p.getByLabel("绑定项目");
await projectSelect.selectOption(String(project.id));
ok(
"native project binds real id",
(await projectSelect.inputValue()) === String(project.id),
);
await p.getByLabel("任务模型").selectOption("model-1");
await pause(300);
ok(
"native model persists",
(await api("/api/settings")).agent_llm_assignments.main === "model-1",
);
ok(
"native dropdown is browser controlled",
(await p.locator(".big-input select").count()) === 3,
);
} else {
const projectControl = p.getByRole("combobox", {
name: "绑定项目",
exact: true,
}),
model = p.getByRole("combobox", { name: "任务模型", exact: true }),
skill = p.getByRole("combobox", { name: "任务技能", exact: true });
await projectControl.click();
await p.getByRole("option", { name: project.title, exact: true }).click();
ok(
"click selects real project and returns focus",
(await projectControl.getAttribute("title")) ===
`绑定:${project.title}` &&
(await projectControl.evaluate((e) => e === document.activeElement)),
);
const selectedTitle = await projectControl.getAttribute("title");
await projectControl.press("ArrowDown");
await projectControl.press("End");
ok(
"long list scrolls to keyboard candidate",
await p.locator(".pill-menu").evaluate((e) => e.scrollTop > 0),
);
ok(
"navigation alone leaves project unchanged",
(await projectControl.getAttribute("title")) === selectedTitle,
);
await projectControl.press("Escape");
ok(
"Esc cancels and returns focus",
(await projectControl.getAttribute("title")) === selectedTitle &&
(await projectControl.evaluate(
(e) => e === document.activeElement,
)) &&
(await p.locator(".pill-menu").count()) === 0,
);
await projectControl.press(" ");
ok(
"Space opens listbox",
(await projectControl.getAttribute("aria-expanded")) === "true",
);
await projectControl.press("Home");
await projectControl.press("Enter");
ok(
"Enter confirms sandbox with focus restored",
(await projectControl.getAttribute("title")) === "绑定:沙盒" &&
(await projectControl.evaluate((e) => e === document.activeElement)),
);
await projectControl.press("ArrowDown");
await projectControl.press("End");
await projectControl.press("Enter");
ok(
"long selected project is constrained and full title retained",
await projectControl.evaluate(
(e) => e.getBoundingClientRect().width <= 220 && e.title.length > 30,
),
);
await p.screenshot({ path: `${OUT}/${phase}/long-selected.png` });
await projectControl.click();
await p.getByRole("option", { name: project.title, exact: true }).click();
await projectControl.click();
await p.getByRole("heading", { name: "阶段助手" }).click();
ok(
"outside click closes without committing",
(await p.locator(".pill-menu").count()) === 0 &&
(await projectControl.getAttribute("title")) === selectedTitle,
);
await projectControl.focus();
await p.keyboard.press("Tab");
ok(
"Tab reaches model",
await model.evaluate((e) => e === document.activeElement),
);
await model.press("ArrowDown");
await model.press("End");
await model.press("ArrowUp");
await model.press("Home");
await model.press("Escape");
await p.route("**/api/settings", async (route) => {
if (["POST", "PATCH", "PUT"].includes(route.request().method())) {
await pause(650);
}
await route.continue();
});
await model.click();
await p
.getByRole("option", {
name: "隔离模型 1 · 很长的模型名称与版本号",
exact: true,
})
.click();
await p.waitForFunction(() =>
[...document.querySelectorAll(".big-input [role=combobox]")].every(
(e) => e.disabled,
),
);
ok(
"busy disables all three selectors",
(await p.locator(".big-input [role=combobox]:disabled").count()) === 3,
);
await projectControl.dispatchEvent("click");
await projectControl.dispatchEvent("keydown", { key: "ArrowDown" });
ok(
"disabled selectors cannot open",
(await p.locator(".pill-menu").count()) === 0,
);
await p.screenshot({ path: `${OUT}/${phase}/busy.png` });
await model.waitFor({ state: "visible" });
await p.waitForFunction(
() => !document.querySelector('[aria-label="任务模型"]').disabled,
);
ok(
"model assignment persisted",
(await api("/api/settings")).agent_llm_assignments.main === "model-1",
);
await p.reload();
await p.getByLabel("任务想法").waitFor();
await pause(300);
ok(
"model survives reload",
(await model.getAttribute("title")).includes("隔离模型 1"),
);
await projectControl.click();
await p.getByRole("option", { name: project.title, exact: true }).click();
await skill.click();
await p
.getByRole("option")
.filter({ hasText: enabled[0].name })
.first()
.click();
await p.getByLabel("任务想法").fill("HEL849 隔离发送与上传回归");
await p
.locator(".big-input input[type=file]")
.setInputFiles({
name: "reference.txt",
mimeType: "text/plain",
buffer: Buffer.from("HEL849 isolated reference"),
});
await p.waitForFunction(() =>
document
.querySelector(".big-input")
.textContent.includes("参考材料 · 1"),
);
const beforeTitle = await skill.getAttribute("title");
for (const theme of ["night", "day", "grade", "bluehour"]) {
await p.evaluate((theme) => {
window.dispatchEvent(
new StorageEvent("storage", { key: "aigc-theme", newValue: theme }),
);
}, theme);
ok(
theme + " retains draft/project/model/skill/upload",
(await p.getByLabel("任务想法").inputValue()).includes("HEL849") &&
(await projectControl.getAttribute("title")) === selectedTitle &&
(await skill.getAttribute("title")) === beforeTitle &&
(await model.getAttribute("title")).includes("隔离模型 1") &&
(await p.locator(".big-input").innerText()).includes(
"参考材料 · 1",
),
);
}
await projectControl.click();
await p.setViewportSize({ width: 900, height: 600 });
await pause(100);
report.small = await p
.locator(".pill-menu")
.evaluate((e) => ({
menu: e.getBoundingClientRect().toJSON(),
trigger: document
.querySelector("[aria-label=绑定项目]")
.getBoundingClientRect()
.toJSON(),
view: { w: innerWidth, h: innerHeight, v: visualViewport.height },
scroll: e.scrollHeight,
}));
await p.screenshot({ path: `${OUT}/${phase}/small.png` });
console.log("SMALL", JSON.stringify(report.small));
ok(
"small window menu stays within viewport",
await p.locator(".pill-menu").evaluate((e) => {
const r = e.getBoundingClientRect();
return (
r.left >= 7 &&
r.right <= innerWidth - 7 &&
r.top >= 7 &&
r.bottom <= innerHeight - 7
);
}),
);
await p.locator(".agent-home").evaluate((e) => (e.scrollTop = 200));
await pause(100);
ok(
"scroll keeps menu anchored",
await p.locator(".pill-menu").evaluate((e) => {
const r = e.getBoundingClientRect();
return r.top >= 7 && r.bottom <= innerHeight - 7;
}),
);
await p.keyboard.press("Escape");
await p.setViewportSize({ width: 1440, height: 900 });
const cdp = await ctx.newCDPSession(p);
await cdp.send("Emulation.setPageScaleFactor", { pageScaleFactor: 1.5 });
await projectControl.click();
await pause(100);
ok(
"150% browser page scale uses visual viewport bounds",
await p.locator(".pill-menu").evaluate((e) => {
const r = e.getBoundingClientRect(),
v = visualViewport;
return (
r.left >= v.offsetLeft &&
r.right <= v.offsetLeft + v.width + 1 &&
r.top >= v.offsetTop &&
r.bottom <= v.offsetTop + v.height + 1
);
}),
);
await p.keyboard.press("Escape");
await cdp.send("Emulation.setPageScaleFactor", { pageScaleFactor: 1 });
for (const name of ["完整", "克制", "关闭"]) {
await p.locator('.sidebar-bottom button[title="主题"]').click();
await p
.locator(".theme-motion")
.getByRole("button", { name, exact: true })
.click();
await p.keyboard.press("Escape");
const state = await p
.locator(".orb")
.evaluate((e) => ({
display: getComputedStyle(e).display,
rings: [...e.querySelectorAll(".ring")].map((r) => ({
animation: getComputedStyle(r).animationName,
play: getComputedStyle(r).animationPlayState,
})),
}));
report.states.push({ motion: name, ...state });
ok(
name + " preserves approved orb and double rings",
state.rings.length === 2 &&
(name === "关闭"
? state.display === "none"
: state.display !== "none"),
);
ok(
name + " preserves input state",
(await projectControl.getAttribute("title")) === selectedTitle &&
(await skill.getAttribute("title")) === beforeTitle,
);
}
const sent = p.waitForRequest(
(r) =>
/\/api\/agent\/sessions\/\d+\/messages$/.test(r.url()) &&
r.method() === "POST",
);
await p.getByRole("button", { name: "开始任务", exact: true }).click();
const request = await sent;
const payload = request.postDataJSON();
report.sentPayload = payload;
ok(
"real send payload includes chosen skill",
payload.mentions.some(
(m) => m.type === "skill" && m.name === enabled[0].dir,
),
);
ok(
"real send retains uploaded reference",
payload.attachments.length === 1 &&
payload.attachments[0].name === "reference.txt",
);
const sid = Number(new URL(p.url()).searchParams.get("session"));
const session = await api("/api/agent/sessions/" + sid);
ok(
"real session bound to chosen project",
session.project_id === project.id,
);
await p.waitForFunction(() => {
const e = document.querySelector('[aria-label="成果项目"]');
return e && !e.disabled;
});
await p
.getByLabel("成果项目", { exact: true })
.selectOption(String(project.id));
await p.getByLabel("成果阶段", { exact: true }).selectOption("assets");
await p.getByRole("button", { name: "保存草稿", exact: true }).click();
await pause(200);
const results = await api("/api/results/deliverables?session_id=" + sid);
ok(
"result project/stage selectors still save real draft",
results[0].project_id === project.id &&
results[0].stage_key === "assets",
);
await p.locator(".composer .editor").waitFor();
const editor = p.locator(".composer .editor");
await editor.fill("/");
await editor.press("End");
await editor.press(enabled[0].name[0]);
await p.locator(".mention-menu").waitFor();
ok(
"slash skill menu still opens",
(await p.locator(".mention-menu [role=option]").count()) > 0,
);
await p.keyboard.press("Escape");
await api("/api/workflows", {
name: "HEL849 test workflow",
kind: "image",
workflow_json: {
1: {
class_type: "CLIPTextEncode",
inputs: { text: "test" },
_meta: { title: "(Input:prompt)" },
},
9: {
class_type: "SaveImage",
inputs: { images: "x" },
_meta: { title: "(Output:image)" },
},
},
});
await p.reload();
await editor.waitFor();
await editor.fill("@");
await editor.press("End");
await editor.press("H");
await p.locator(".mention-menu").waitFor();
ok(
"workflow menu still opens",
(await p.locator(".mention-menu [role=option]").count()) > 0,
);
await p.keyboard.press("Escape");
// Existing Omni consumers share the enhanced selector; ensure route is still usable.
await p.goto(WEB + "/agents?legacy=1");
await p.locator(".agent-rail").waitFor();
ok(
"legacy agent route still available",
(await p.locator(".agent-rail").count()) === 1,
);
}
ok("no browser exceptions", report.errors.length === 0);
} finally {
fs.writeFileSync(
`${OUT}/${phase}-report.json`,
JSON.stringify(report, null, 2),
);
await ctx.tracing.stop({ path: `${OUT}/${phase}/trace.zip` });
await ctx.close();
await browser.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});