mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-12-05 21:00:15 +08:00
351 lines
20 KiB
JavaScript
351 lines
20 KiB
JavaScript
import assert from "node:assert/strict"
|
|
import { readFile, stat } from "node:fs/promises"
|
|
import path from "node:path"
|
|
import { fileURLToPath } from "node:url"
|
|
import { chromium } from "playwright-core"
|
|
import { LANGUAGE_OPTIONS, LANGUAGE_STORAGE_KEY } from "../src/i18n/language.ts"
|
|
import { enUS } from "../src/i18n/locales/en-US.ts"
|
|
import { frFR } from "../src/i18n/locales/fr-FR.ts"
|
|
import { zhCN } from "../src/i18n/locales/zh-CN.ts"
|
|
import { emptySessionOverviewFixture } from "./fixtures/task-analysis.ts"
|
|
|
|
if (!process.env.CHROME_BIN) throw new Error("请设置 CHROME_BIN,并先执行 npm run build")
|
|
const dist = path.resolve(fileURLToPath(new URL("../dist/", import.meta.url)))
|
|
await stat(path.join(dist, "index.html"))
|
|
const origin = "http://localization.test"
|
|
const browser = await chromium.launch({
|
|
executablePath: process.env.CHROME_BIN,
|
|
args: ["--no-sandbox", "--disable-dev-shm-usage"],
|
|
})
|
|
const languages = process.env.LANGUAGE
|
|
? LANGUAGE_OPTIONS.filter(({ value }) => value === process.env.LANGUAGE)
|
|
: LANGUAGE_OPTIONS
|
|
assert.ok(languages.length, "LANGUAGE 必须是支持的语言代码")
|
|
const widths = process.env.WIDTH ? [Number(process.env.WIDTH)] : [1440, 390, 320]
|
|
const dictionaries = Object.fromEntries(await Promise.all(languages.map(async ({ value }) =>
|
|
[value, Object.values(await import("../src/i18n/locales/" + value + ".ts"))[0]]
|
|
)))
|
|
const types = {
|
|
".html": "text/html", ".js": "text/javascript", ".css": "text/css",
|
|
".woff2": "font/woff2", ".svg": "image/svg+xml", ".png": "image/png",
|
|
".webp": "image/webp",
|
|
}
|
|
const overviewResponse = {
|
|
"/api/admin/v1/statistics/models/overview": { days: [] },
|
|
"/api/admin/v1/statistics/session-reporting/members/overview": {
|
|
total_members: 0, days: [],
|
|
last_7d: { active_members: 0 }, previous_7d: { active_members: 0 },
|
|
last_24h: { active_members: 0 }, previous_24h: { active_members: 0 },
|
|
},
|
|
"/api/admin/v1/statistics/session-reporting/sessions/overview":
|
|
emptySessionOverviewFixture(new Date("2026-11-03T12:00:00Z")),
|
|
}
|
|
|
|
async function fixture(language, width, authenticated = true, {
|
|
storedLanguage = language, allowPasswordLogin = false,
|
|
} = {}) {
|
|
const context = await browser.newContext({
|
|
viewport: { width, height: 900 }, locale: language, reducedMotion: "reduce",
|
|
storageState: { cookies: [], origins: [{
|
|
origin,
|
|
localStorage: storedLanguage === null ? [] : [{ name: LANGUAGE_STORAGE_KEY, value: storedLanguage }],
|
|
}] },
|
|
})
|
|
const state = { failNetwork: false, networkReads: 0 }
|
|
const user = { id: "admin", name: "测试管理员", email: "admin@example.com", role: "admin", status: "active", joined_at: "2026-01-01T00:00:00Z" }
|
|
await context.route("**/*", async (route) => {
|
|
const request = route.request()
|
|
const endpoint = new URL(request.url()).pathname
|
|
if (endpoint.startsWith("/api/")) {
|
|
if (allowPasswordLogin && endpoint === "/api/auth/v1/login" && request.method() === "POST") {
|
|
authenticated = true
|
|
return route.fulfill({ json: user })
|
|
}
|
|
assert.equal(request.method(), "GET", "此检查不应发起写请求:" + endpoint)
|
|
let body = { items: [] }
|
|
if (endpoint.endsWith("/session")) body = { authenticated, user: authenticated ? user : null }
|
|
else if (endpoint.endsWith("/branding")) body = { product_name: "测试团队" }
|
|
else if (endpoint.endsWith("/license/status")) body = { state: "valid" }
|
|
else if (Object.hasOwn(overviewResponse, endpoint)) body = overviewResponse[endpoint]
|
|
else if (endpoint === "/api/auth/v1/clients") body = { clients: [{ client_id: "monkeyai-web" }] }
|
|
else if (endpoint.endsWith("/settings/client_access_policy")) body = { clients: { "monkeyai-web": true } }
|
|
else if (endpoint.endsWith("/settings/member_resource_policy")) body = {
|
|
value: Object.fromEntries(["model", "kb", "skill", "expert", "connector", "rule"]
|
|
.map((kind) => [kind, { write: "allow", share: "allow" }])),
|
|
}
|
|
else if (endpoint.endsWith("/methods")) body = { password_enabled: true, email_code_enabled: true, email_code_auto_registration_enabled: false }
|
|
else if (endpoint.endsWith("/providers")) body = { providers: [] }
|
|
else if (endpoint.endsWith("/users")) body = { users: [user] }
|
|
else if (endpoint.endsWith("/groups")) body = { groups: [{
|
|
id: "00000000-0000-0000-0000-000000000000", parent_id: null,
|
|
name: "测试团队", member_ids: [user.id], actions: ["add-subgroup"], allow_add_members: true,
|
|
}] }
|
|
else if (/\/settings\/(model_network|mcp)$/.test(endpoint)) {
|
|
state.networkReads++
|
|
if (state.failNetwork) return route.fulfill({ status: 503, json: {} })
|
|
body = { value: { blocked_cidrs: [] } }
|
|
}
|
|
return route.fulfill({ json: body })
|
|
}
|
|
let file = path.resolve(dist, "." + endpoint)
|
|
assert.ok(file === dist || file.startsWith(dist + path.sep), "静态资源路径必须位于构建目录内")
|
|
if (!(await stat(file).catch(() => null))?.isFile()) file = path.join(dist, "index.html")
|
|
return route.fulfill({ contentType: types[path.extname(file)] || "application/octet-stream", body: await readFile(file) })
|
|
})
|
|
const page = await context.newPage()
|
|
page.setDefaultTimeout(10000)
|
|
const errors = []
|
|
page.on("pageerror", (error) => errors.push(error.message))
|
|
return { context, page, state, errors }
|
|
}
|
|
|
|
async function bounds(page, label) {
|
|
const size = await page.evaluate(() => ({
|
|
actual: document.documentElement.scrollWidth, viewport: innerWidth,
|
|
}))
|
|
assert.ok(size.actual <= size.viewport + 1, label + ":页面出现水平溢出 " + JSON.stringify(size))
|
|
}
|
|
|
|
async function unclipped(locator, label) {
|
|
await locator.first().waitFor({ state: "visible" })
|
|
const clipped = await locator.evaluateAll((elements) => elements
|
|
.filter((element) => element.checkVisibility() && element.getBoundingClientRect().width > 0)
|
|
.filter((element) => element.scrollWidth > element.clientWidth + 1)
|
|
.map((element) => ({ text: element.textContent, actual: element.scrollWidth, available: element.clientWidth })))
|
|
assert.deepEqual(clipped, [], label + ":文案被截断")
|
|
}
|
|
|
|
async function switchLanguage(page, from, language) {
|
|
await page.getByRole("button", { name: from.language.change, exact: true }).click()
|
|
await page.getByRole("menuitemradio", { name: language.label, exact: true }).click()
|
|
await page.waitForFunction((language) => document.documentElement.lang === language, language.value)
|
|
assert.equal(await page.locator("html").getAttribute("dir"), language.value === "ar" ? "rtl" : "ltr")
|
|
assert.equal(await page.evaluate((key) => localStorage.getItem(key), LANGUAGE_STORAGE_KEY), language.value)
|
|
}
|
|
|
|
async function checkCommunity(page, language, label) {
|
|
const footer = page.locator('[data-slot="sidebar-footer"]')
|
|
const chinese = language === "zh-CN" || language === "zh-TW"
|
|
const { community, communityHint } = dictionaries[language].navigation
|
|
const trigger = footer.getByRole(chinese ? "button" : "link", { name: community, exact: true })
|
|
await unclipped(trigger, label + " / 社区入口")
|
|
if (chinese) {
|
|
assert.match(community, /微信/)
|
|
assert.equal(await footer.locator('a[href*="discord.gg"]').count(), 0)
|
|
} else {
|
|
assert.match(community, /Discord/)
|
|
assert.equal(await trigger.getAttribute("href"), "https://discord.gg/2pPmuyr4pP")
|
|
}
|
|
await trigger.hover()
|
|
const panel = page.locator(chinese ? '[data-slot="popover-content"]' : '[data-slot="tooltip-content"]')
|
|
.filter({ hasText: communityHint })
|
|
await panel.locator("img").evaluate((image) => image.decode())
|
|
await page.mouse.move(0, 0)
|
|
await panel.waitFor({ state: "hidden" })
|
|
}
|
|
|
|
async function checkEntryLanguage() {
|
|
const entryDictionaries = { "en-US": enUS, "zh-CN": zhCN, "fr-FR": frFR }
|
|
const option = (value) => LANGUAGE_OPTIONS.find((language) => language.value === value)
|
|
const languageToggle = Object.values(entryDictionaries)
|
|
.map(({ language }) => 'header button[aria-label=' + JSON.stringify(language.change) + ']')
|
|
.join(", ")
|
|
|
|
async function observe(page, id, screen, language, route, stored = language) {
|
|
const dictionary = entryDictionaries[language]
|
|
const controls = {
|
|
landing: [page.locator('header a[href="/login"]'), dictionary.login.submit, "text"],
|
|
login: [page.locator('form button[type="submit"]'), dictionary.login.submit, "text"],
|
|
chooser: [page.locator('a[href="/admin/"]'), dictionary.app.openTeamConsole, "aria-label"],
|
|
console: [page.locator(languageToggle), dictionary.language.change, "aria-label"],
|
|
}
|
|
const [control, expected, labelType] = controls[screen]
|
|
// Locate the first usable control without filtering by the expected language.
|
|
await control.waitFor({ state: "visible" })
|
|
assert.ok(await control.isEnabled(), id)
|
|
const label = labelType === "text" ? await control.innerText() : await control.getAttribute(labelType)
|
|
assert.equal(label, expected, id)
|
|
assert.equal(await page.locator("html").getAttribute("lang"), language, id)
|
|
await page.waitForURL(origin + route)
|
|
assert.equal(page.url(), origin + route, id)
|
|
if (screen === "console") {
|
|
const breadcrumb = await page.locator('[data-slot="breadcrumb-page"]').innerText()
|
|
assert.equal(breadcrumb, route === dashboard ? dictionary.pages.overview.title : dictionary.pages.security.title, id)
|
|
}
|
|
assert.equal(await page.evaluate((key) => localStorage.getItem(key), LANGUAGE_STORAGE_KEY), stored, id)
|
|
if (process.env.SCREENSHOT_DIR) {
|
|
await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, "entry-" + id + ".png"), animations: "disabled" })
|
|
}
|
|
console.log("PASS entry " + id + ": " + screen + " / " + language + " / " + JSON.stringify(label) + " / " + route)
|
|
return control
|
|
}
|
|
|
|
async function scenario({ locale = "zh-CN", authenticated = false, ...options }, exercise) {
|
|
const { context, page, errors } = await fixture(locale, 1440, authenticated, options)
|
|
try {
|
|
assert.equal(await page.evaluate(() => navigator.language), locale)
|
|
await exercise(page)
|
|
assert.deepEqual(errors, [], "entry-language browser errors")
|
|
} catch (error) {
|
|
console.error("Entry fixture failure", { url: page.url(), errors, text: (await page.locator("body").innerText()).slice(0, 1200) })
|
|
throw error
|
|
} finally { await context.close() }
|
|
}
|
|
|
|
const entry = "/?lang=en-US"
|
|
const dashboard = "/admin/statistics/overview"
|
|
await scenario({ storedLanguage: null, allowPasswordLogin: true }, async (page) => {
|
|
await page.goto(origin + entry)
|
|
await (await observe(page, "01-fresh-landing", "landing", "en-US", "/")).click()
|
|
await observe(page, "02-signed-out-login", "login", "en-US", "/login")
|
|
await page.reload()
|
|
const submit = await observe(page, "03-login-reloaded", "login", "en-US", "/login")
|
|
await page.getByLabel(enUS.login.email, { exact: true }).fill("admin@example.com")
|
|
await page.getByLabel(enUS.login.password, { exact: true }).fill("fixture-password")
|
|
await submit.click()
|
|
await (await observe(page, "04-after-sign-in", "chooser", "en-US", "/login")).click()
|
|
await observe(page, "05-after-sign-in-console", "console", "en-US", dashboard)
|
|
})
|
|
await scenario({ authenticated: true }, async (page) => {
|
|
await page.goto(origin + entry)
|
|
await (await observe(page, "06-signed-in-saved-chinese", "landing", "en-US", "/")).click()
|
|
await (await observe(page, "07-signed-in-chooser", "chooser", "en-US", "/login")).click()
|
|
await observe(page, "08-signed-in-console", "console", "en-US", dashboard)
|
|
})
|
|
await scenario({}, async (page) => {
|
|
await page.goto(origin + "/admin/settings/security?lang=en-US")
|
|
await observe(page, "09-protected-route-redirect", "login", "en-US", "/login")
|
|
})
|
|
await scenario({ storedLanguage: null }, async (page) => {
|
|
await page.goto(origin + "/login")
|
|
await observe(page, "10-no-param-browser-chinese", "login", "zh-CN", "/login", null)
|
|
})
|
|
await scenario({ locale: "en-US", storedLanguage: "zh-CN" }, async (page) => {
|
|
await page.goto(origin + "/login")
|
|
await observe(page, "11-no-param-saved-chinese", "login", "zh-CN", "/login")
|
|
const invalid = "/login?lang=en-INVALID&source=github#login"
|
|
await page.goto(origin + invalid)
|
|
await observe(page, "12-invalid-param", "login", "zh-CN", invalid)
|
|
})
|
|
await scenario({ authenticated: true }, async (page) => {
|
|
const preserved = "/admin/settings/security?source=github&tag=a&tag=b#settings"
|
|
await page.goto(origin + preserved.replace("&tag=a", "&lang=en-US&tag=a"))
|
|
await observe(page, "13-preserved-url", "console", "en-US", preserved)
|
|
await switchLanguage(page, enUS, option("zh-CN"))
|
|
await observe(page, "14-manual-chinese", "console", "zh-CN", preserved)
|
|
await page.reload()
|
|
await observe(page, "15-manual-chinese-reloaded", "console", "zh-CN", preserved)
|
|
await switchLanguage(page, zhCN, option("fr-FR"))
|
|
await observe(page, "16-manual-french", "console", "fr-FR", preserved)
|
|
await page.reload()
|
|
await observe(page, "17-manual-french-reloaded", "console", "fr-FR", preserved)
|
|
})
|
|
}
|
|
|
|
try {
|
|
await checkEntryLanguage()
|
|
for (const width of widths) {
|
|
for (const language of languages) {
|
|
const dictionary = dictionaries[language.value]
|
|
const label = language.value + " / " + width
|
|
const { context, page, errors } = await fixture(language.value, width)
|
|
try {
|
|
await page.goto(origin + "/admin/settings/security")
|
|
await page.getByText(dictionary.pages.security.model.title, { exact: true }).waitFor()
|
|
await page.evaluate(() => document.fonts.ready)
|
|
assert.equal(await page.locator("html").getAttribute("lang"), language.value)
|
|
assert.equal(await page.locator("html").getAttribute("dir"), language.value === "ar" ? "rtl" : "ltr")
|
|
await bounds(page, label)
|
|
if (width < 768) await page.locator('[data-slot="sidebar-trigger"]').click()
|
|
const sidebar = page.locator('[data-slot="sidebar-content"]')
|
|
await sidebar.waitFor()
|
|
await checkCommunity(page, language.value, label)
|
|
for (const section of ["statistics", "usageRecords", "aiResources", "billingManagement", "systemSettings"]) {
|
|
const trigger = sidebar.getByRole("button", { name: dictionary.sections[section], exact: true })
|
|
if (await trigger.getAttribute("aria-expanded") !== "true") await trigger.click()
|
|
await unclipped(sidebar.locator('[data-slot="sidebar-menu-sub-button"] > span'), label + " / " + section)
|
|
await unclipped(trigger.locator(":scope > span"), label + " / 主导航")
|
|
}
|
|
if (width < 768) {
|
|
const box = await page.locator('[data-mobile="true"]').boundingBox()
|
|
assert.ok(box && box.x >= -1 && box.x + box.width <= width + 1, label + ":移动导航越界")
|
|
if (language.value === "ar") assert.ok(Math.abs(box.x + box.width - width) <= 1, "RTL 导航应位于右侧")
|
|
await page.keyboard.press("Escape")
|
|
} else {
|
|
assert.equal(await page.locator('[data-slot="sidebar-container"]').getAttribute("data-side"), language.value === "ar" ? "right" : "left")
|
|
}
|
|
await page.goto(origin + "/admin/settings/members")
|
|
await page.getByRole("button", { name: dictionary.pages.membersAndGroups.bulk.addMember, exact: true }).click()
|
|
const dialog = page.getByRole("dialog")
|
|
await dialog.waitFor()
|
|
await dialog.getByRole("tab", { name: dictionary.pages.membersAndGroups.bulk.addOne, exact: true }).waitFor()
|
|
await unclipped(dialog.getByRole("tab"), label + " / 添加成员选项")
|
|
await dialog.getByRole("tab", { name: dictionary.pages.membersAndGroups.bulk.addMany, exact: true }).click()
|
|
await unclipped(dialog.getByRole("tab"), label + " / 批量添加选项")
|
|
const dialogBox = await dialog.boundingBox()
|
|
assert.ok(dialogBox && dialogBox.x >= -1 && dialogBox.x + dialogBox.width <= width + 1, label + ":成员弹窗越界")
|
|
const close = dialog.locator('button[data-slot="dialog-close"]')
|
|
const closeBox = await close.boundingBox()
|
|
assert.equal(await dialog.evaluate((element) => getComputedStyle(element).direction), language.value === "ar" ? "rtl" : "ltr", label + ":弹窗方向错误")
|
|
if (language.value === "ar") {
|
|
for (const target of [page.locator("body"), dialog.locator('[data-slot="dialog-title"]')]) {
|
|
const fontFamily = await target.evaluate((element) => getComputedStyle(element).fontFamily)
|
|
assert.ok(fontFamily.includes("Noto Sans Arabic Variable") && fontFamily.includes("Noto Sans SC Variable"), label + ":阿拉伯语及中文回退字体缺失;" + fontFamily)
|
|
}
|
|
}
|
|
const centeredClose = closeBox.x + closeBox.width / 2 - (dialogBox.x + dialogBox.width / 2)
|
|
assert.ok(language.value === "ar" ? centeredClose < 0 : centeredClose > 0,
|
|
label + ":关闭按钮应处于文字结束侧;" + JSON.stringify(await close.evaluate((element) => {
|
|
const style = getComputedStyle(element)
|
|
return { direction: style.direction, left: style.left, right: style.right, insetInlineEnd: style.insetInlineEnd }
|
|
})))
|
|
await bounds(page, label + " / 成员弹窗")
|
|
if (process.env.SCREENSHOT_DIR && width === 320 && ["de-DE", "ar"].includes(language.value)) {
|
|
await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, "localization-" + language.value + "-320.png"), animations: "disabled" })
|
|
}
|
|
assert.deepEqual(errors, [], label + ":浏览器运行错误")
|
|
console.log("通过:导航、成员弹窗及方向 / " + label)
|
|
} catch (error) {
|
|
console.error("失败场景:" + label, { pageErrors: errors, text: (await page.locator("body").innerText()).slice(0, 1200) })
|
|
throw error
|
|
} finally { await context.close() }
|
|
}
|
|
}
|
|
for (const language of languages) {
|
|
const dictionary = dictionaries[language.value]
|
|
const { context, page, errors } = await fixture("zh-CN", 390, false)
|
|
try {
|
|
await page.goto(origin + "/login?oauth_error=admin_role_required")
|
|
const toast = page.locator('ol[aria-live="polite"] > li')
|
|
await toast.getByText(zhCN.login.oauthAdminRequired, { exact: true }).waitFor()
|
|
await toast.evaluate((element) => { element.dataset.localizationProbe = "same-toast" })
|
|
await switchLanguage(page, zhCN, language)
|
|
await toast.getByText(dictionary.login.oauthAdminRequired, { exact: true }).waitFor()
|
|
assert.equal(await toast.count(), 1, "切换语言不应重复创建提示")
|
|
assert.equal(await toast.getAttribute("data-localization-probe"), "same-toast", "应更新已存在的提示而非替换")
|
|
await bounds(page, language.value + " / 登录")
|
|
assert.deepEqual(errors, [], language.value + ":登录页面运行错误")
|
|
console.log("通过:已保存提示即时切换 / " + language.value)
|
|
} finally { await context.close() }
|
|
|
|
const saved = await fixture("zh-CN", 390)
|
|
try {
|
|
saved.state.failNetwork = true
|
|
await saved.page.goto(origin + "/admin/settings/security")
|
|
const alerts = saved.page.getByRole("alert")
|
|
await alerts.first().getByText(zhCN.webUi.requestFailed, { exact: true }).waitFor()
|
|
assert.equal(await alerts.count(), 2)
|
|
const reads = saved.state.networkReads
|
|
await switchLanguage(saved.page, zhCN, language)
|
|
await alerts.first().getByText(dictionary.webUi.requestFailed, { exact: true }).waitFor()
|
|
assert.equal(await alerts.last().innerText(), dictionary.webUi.requestFailed)
|
|
assert.equal(saved.state.networkReads, reads, "更新已保存错误不应重新请求接口")
|
|
assert.deepEqual(saved.errors, [])
|
|
console.log("通过:已保存错误无重新请求切换 / " + language.value)
|
|
} finally { await saved.context.close() }
|
|
}
|
|
console.log("本轮验收范围:十语言导航和成员弹窗、窄屏与 RTL、已保存提示和错误;使用模拟接口,不代表全站业务端到端验收。")
|
|
} finally {
|
|
await browser.close()
|
|
}
|