From 92380ebab68b2c9d2fc88198ba1673aab1b9ad5a Mon Sep 17 00:00:00 2001 From: zhanjunhao <642307404@qq.com> Date: Tue, 17 Nov 2026 14:48:50 +0800 Subject: [PATCH] =?UTF-8?q?chore(tooling):=20=E5=AF=B9=E9=BD=90=E5=8D=8F?= =?UTF-8?q?=E4=BD=9C=E8=A7=84=E8=8C=83=E4=B8=8E=E6=B5=8F=E8=A7=88=E5=99=A8?= =?UTF-8?q?=E9=AA=8C=E6=94=B6=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 验证:713 项单测、8 视口环境、代码及格式检查通过;未运行生产构建。 --- AGENTS.md | 54 ++-- CLAUDE.md | 54 ++-- README.md | 22 +- docs/CHANGELOG.md | 32 ++ docs/README.md | 6 +- docs/standards/DEV_STANDARDS.md | 44 ++- docs/ui/GLOBAL_UI_BASELINE.md | 52 +++- package-lock.json | 24 +- package.json | 12 +- playwright.config.js | 123 +++----- scripts/browser-capture.mjs | 59 ++++ scripts/browser-environment.mjs | 81 ++++++ scripts/playwright-focus-guard.mjs | 322 +++++++++++++++++++++ scripts/playwright-reporter.mjs | 75 +++++ scripts/playwright-runner-focus.mjs | 197 +++++++++++++ scripts/playwright-runtime.mjs | 149 ++++++++++ scripts/playwright-test.mjs | 69 +++++ scripts/preview-dist.mjs | 41 +++ scripts/run-acceptance.mjs | 65 +++++ scripts/run-playwright.mjs | 91 ++++++ scripts/test-playwright-environment.mjs | 86 ++++++ scripts/ui-review/config.json | 19 ++ scripts/verify-build.mjs | 56 ++++ src/pages/Recharge/AmountCard.jsx | 1 - src/pages/Recharge/RechargeV2.jsx | 2 - src/pages/Setting/AmountOptionsManager.jsx | 1 - test/unit/playwright-config.test.js | 279 ++++++++++++++++++ test/unit/playwright-focus-guard.test.js | 122 ++++++++ test/unit/playwright-preview.test.js | 103 +++++++ tests/environment.test.js | 8 +- 30 files changed, 2089 insertions(+), 160 deletions(-) create mode 100644 scripts/browser-capture.mjs create mode 100644 scripts/browser-environment.mjs create mode 100644 scripts/playwright-focus-guard.mjs create mode 100644 scripts/playwright-reporter.mjs create mode 100644 scripts/playwright-runner-focus.mjs create mode 100644 scripts/playwright-runtime.mjs create mode 100644 scripts/playwright-test.mjs create mode 100644 scripts/preview-dist.mjs create mode 100644 scripts/run-acceptance.mjs create mode 100644 scripts/run-playwright.mjs create mode 100644 scripts/test-playwright-environment.mjs create mode 100644 scripts/ui-review/config.json create mode 100644 scripts/verify-build.mjs create mode 100644 test/unit/playwright-config.test.js create mode 100644 test/unit/playwright-focus-guard.test.js create mode 100644 test/unit/playwright-preview.test.js diff --git a/AGENTS.md b/AGENTS.md index d16cc77e..d5bc222a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,8 +1,6 @@ # 项目协作规范(AGENTS.md · Codex 默认入口) -> **规范版本**:v3.2 · **最后更新**:2026-11-13 · `AGENTS.md`(Codex)与 `CLAUDE.md`(Claude Code)第 0–9 节逐字一致,仅标题与第 10 节不同。 -> -> **不要重复加载全文**:同一会话已读过本文件或任何 `docs/` 文档,不再全文重读;细节按第 6 节索引定向读取。 +> 第 0–9 节为公共规则,第 10 节保留工具差异。 ## 0. 最高优先级:资源、扫描、Git、安全与授权(不得删减或弱化) @@ -20,17 +18,17 @@ ## 1. 按需加载 -- 本文件常驻上下文,只放长期规则与索引;细节按第 6 节定向读取,不把 `docs/` 内容复制进来。 -- 读取顺序:本文件 → `docs/README.md` → 目标文档摘要卡 → 目标章节 → 相关源码。 -- 同一会话已读过的文档不再全文重读;需要细节时先搜索章节标题,再读指定行段。 -- 章节编号、标题与顺序保持稳定;修改只动相关段落,版本与日期只在头部维护。 -- 输出优先用表格和清单;引用写 `路径:行号`,不粘贴大段文件内容。 +- 已由会话加载的入口不再重读;不为获取公共规则再加载另一入口。细节按第 6 节索引直达目标文档摘要卡、目标章节与相关源码,不复制 `docs/` 全文。 +- 仅首次接手、不确定规范归属或维护文档目录时读 `docs/README.md`;已定位目标时不重复经过索引。 +- 记录已读路径与章节;未变内容不重读,文件变化只补读相关差异。上下文压缩 / 交接时保留目标、授权边界、已读索引、已改文件、验证结果与待办,恢复后定向续作。 +- 保持标题、章节顺序与措辞稳定,局部修改;版本与日期只在第 9 节维护。任务状态、临时地址、日志和验证报告写入忽略目录,不追加到入口前缀。 +- 所有面向用户的说明、提问与交付使用简体中文;代码、命令、路径与报错保持原样并按需解释,引用用路径与行号,不粘贴大段原文。 ## 2. 项目速览 - **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。 -- **环境**:Node ≥ 22.13、npm 10.9.9;别名 `@` → `src`;开发地址以 `dev.log` 最后一个 `Local:` 为准。 -- **启动链路**:`index.html` → `src/index.jsx` → `components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。 +- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。 +- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发地址以 `dev.log` 最后一个 `Local:` 为准。 - **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。 - **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。 - **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。 @@ -38,13 +36,17 @@ | 命令 | 用途 | | --- | --- | -| `npm run dev` | 开发服务(输出写入 `dev.log`) | +| `npm ci` | 按 lock 安装依赖;会重建 `node_modules`,已有可用依赖时无需为文档检查重装 | +| `npm run dev` | 开发服务;脚本不自动写日志,启动方须按基线第 6 节将输出写入 `dev.log` | | `npm run eslint` / `npm run lint` | ESLint(零警告)/ Prettier 检查 | | `npm test -- --test-concurrency=1` | 串行单测(`src/`、`tests/`、`test/unit/`) | | `npm run check:ui` | UI 依赖、lock 图、品牌图标 hash 审计 | -| `npm run test:e2e` | Playwright 验收(用例在本地忽略目录 `e2e/`) | +| `npm run test:e2e -- --list` / `npm run test:e2e` | 配置与用例发现 / Playwright 执行;用例在本地忽略目录 `e2e/`,执行前见第 7 节 | | `npm run i18n:status` / `npm run i18n:lint` | 语言包检查 | | `npm run build` | 生产构建(验收构建见第 7 节) | +| `npm run check` | 依次执行 UI 审计、ESLint、串行单测、构建;不含 Prettier,默认写入 `dist/`,不能替代临时目录验收流程 | + +Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd` / `npx.cmd` 避免执行策略拦截,不修改安全设置。 ## 3. 规则优先级 @@ -88,6 +90,7 @@ | 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` | | 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` | | 历史改动与回滚 | `docs/CHANGELOG.md` | +| Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 | 无需读文档即可遵守的长期状态: @@ -99,29 +102,32 @@ ## 7. 开发、验收与交付 1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。 -2. **服务与浏览器**:复用已运行服务,Base URL 只取 `dev.log` 最后一个 `Local:`;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行。 -3. **覆盖**:浅深主题 × 桌面 1920×1000 / 移动 393×851;正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。 +2. **服务与浏览器**:复用已运行服务,Base URL 只取 `dev.log` 最后一个 `Local:`;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。 +3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851;正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。 4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。 5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。 +6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。 ## 8. 禁止事项 -- 未经授权修改业务代码;纯 UI 任务改请求、载荷、状态、路由、权限、计费、登录或新增功能。 -- 新增 ConfigProvider、主题状态或存储 key;引入被禁依赖;手改生成的品牌图标资产。 -- JSX 硬编码颜色、全局 `!important`;无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。 +- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。 - 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。 - 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。 -- 输出或提交密码、Cookie、令牌、`.env*` 的值、storageState、截图与报告。 -- 把 `docs/` 全文复制进本文件,或在同一会话重复全文加载已读文档。 +- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git;本地脱敏报告按第 7 节交付。 ## 9. 维护 -- `AGENTS.md` 与 `CLAUDE.md` 第 0–9 节必须逐字一致,修改后校验(无输出即一致):`diff <(sed -n '/^## 0\./,/^## 10\./p' AGENTS.md) <(sed -n '/^## 0\./,/^## 10\./p' CLAUDE.md)`。 -- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落并更新头部版本与日期。 +- `AGENTS.md` 与 `CLAUDE.md` 第 0–9 节必须逐字一致;标题与第 10 节分别维护,不整文件覆盖另一份。维护时执行开发规范第 12.4 节的一致性校验。 + +- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 +> 规范版本:v3.4 · 更新:2026-11-17 + ## 10. 工具差异(本节允许不同) -- 本文件是 Codex 默认入口;`CLAUDE.md` 是 Claude Code 入口,两者第 0–9 节相同,不必互相重复读取。 -- 网页操作、验收与截图优先使用项目 Playwright 配置;不把 computer-use 作为默认工具,Playwright 失败先排查服务地址、元素定位、等待条件、浏览器环境与登录状态。 -- 代码检索用 `rg` 并限定目录(如 `rg <词> src docs`);不要对仓库根目录执行无过滤的递归 `ls` / `find`。 +- 本文件供通用 Agent / Codex 使用;已加载时按第 1 节续作。 +- 网页操作优先使用项目 Playwright;computer-use 不作为默认工具,失败排查见 UI 基线第 7.1 节。 +- 代码检索优先 `rg` 并限定目录(如 `rg <词> src docs`),遵守第 0 节扫描边界。 +- 按当前 Codex 会话实际提供的工具执行;沙箱、审批、技能和可用浏览器能力以运行环境为准,本文件不授予额外权限。遇到更深目录的 `AGENTS.md` 时,先读取适用范围内的补充约束。 +- 仅在用户明确要求时使用子代理,并传递任务范围、第 0 节规则与验收要求。 diff --git a/CLAUDE.md b/CLAUDE.md index 51a8fb7a..5dc1e541 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,8 +1,6 @@ # 项目协作规范(CLAUDE.md · Claude Code 默认入口) -> **规范版本**:v3.2 · **最后更新**:2026-11-13 · `AGENTS.md`(Codex)与 `CLAUDE.md`(Claude Code)第 0–9 节逐字一致,仅标题与第 10 节不同。 -> -> **不要重复加载全文**:同一会话已读过本文件或任何 `docs/` 文档,不再全文重读;细节按第 6 节索引定向读取。 +> 第 0–9 节为公共规则,第 10 节保留工具差异。 ## 0. 最高优先级:资源、扫描、Git、安全与授权(不得删减或弱化) @@ -20,17 +18,17 @@ ## 1. 按需加载 -- 本文件常驻上下文,只放长期规则与索引;细节按第 6 节定向读取,不把 `docs/` 内容复制进来。 -- 读取顺序:本文件 → `docs/README.md` → 目标文档摘要卡 → 目标章节 → 相关源码。 -- 同一会话已读过的文档不再全文重读;需要细节时先搜索章节标题,再读指定行段。 -- 章节编号、标题与顺序保持稳定;修改只动相关段落,版本与日期只在头部维护。 -- 输出优先用表格和清单;引用写 `路径:行号`,不粘贴大段文件内容。 +- 已由会话加载的入口不再重读;不为获取公共规则再加载另一入口。细节按第 6 节索引直达目标文档摘要卡、目标章节与相关源码,不复制 `docs/` 全文。 +- 仅首次接手、不确定规范归属或维护文档目录时读 `docs/README.md`;已定位目标时不重复经过索引。 +- 记录已读路径与章节;未变内容不重读,文件变化只补读相关差异。上下文压缩 / 交接时保留目标、授权边界、已读索引、已改文件、验证结果与待办,恢复后定向续作。 +- 保持标题、章节顺序与措辞稳定,局部修改;版本与日期只在第 9 节维护。任务状态、临时地址、日志和验证报告写入忽略目录,不追加到入口前缀。 +- 所有面向用户的说明、提问与交付使用简体中文;代码、命令、路径与报错保持原样并按需解释,引用用路径与行号,不粘贴大段原文。 ## 2. 项目速览 - **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。 -- **环境**:Node ≥ 22.13、npm 10.9.9;别名 `@` → `src`;开发地址以 `dev.log` 最后一个 `Local:` 为准。 -- **启动链路**:`index.html` → `src/index.jsx` → `components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。 +- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。 +- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发地址以 `dev.log` 最后一个 `Local:` 为准。 - **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。 - **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。 - **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。 @@ -38,13 +36,17 @@ | 命令 | 用途 | | --- | --- | -| `npm run dev` | 开发服务(输出写入 `dev.log`) | +| `npm ci` | 按 lock 安装依赖;会重建 `node_modules`,已有可用依赖时无需为文档检查重装 | +| `npm run dev` | 开发服务;脚本不自动写日志,启动方须按基线第 6 节将输出写入 `dev.log` | | `npm run eslint` / `npm run lint` | ESLint(零警告)/ Prettier 检查 | | `npm test -- --test-concurrency=1` | 串行单测(`src/`、`tests/`、`test/unit/`) | | `npm run check:ui` | UI 依赖、lock 图、品牌图标 hash 审计 | -| `npm run test:e2e` | Playwright 验收(用例在本地忽略目录 `e2e/`) | +| `npm run test:e2e -- --list` / `npm run test:e2e` | 配置与用例发现 / Playwright 执行;用例在本地忽略目录 `e2e/`,执行前见第 7 节 | | `npm run i18n:status` / `npm run i18n:lint` | 语言包检查 | | `npm run build` | 生产构建(验收构建见第 7 节) | +| `npm run check` | 依次执行 UI 审计、ESLint、串行单测、构建;不含 Prettier,默认写入 `dist/`,不能替代临时目录验收流程 | + +Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd` / `npx.cmd` 避免执行策略拦截,不修改安全设置。 ## 3. 规则优先级 @@ -88,6 +90,7 @@ | 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` | | 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` | | 历史改动与回滚 | `docs/CHANGELOG.md` | +| Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 | 无需读文档即可遵守的长期状态: @@ -99,30 +102,31 @@ ## 7. 开发、验收与交付 1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。 -2. **服务与浏览器**:复用已运行服务,Base URL 只取 `dev.log` 最后一个 `Local:`;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行。 -3. **覆盖**:浅深主题 × 桌面 1920×1000 / 移动 393×851;正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。 +2. **服务与浏览器**:复用已运行服务,Base URL 只取 `dev.log` 最后一个 `Local:`;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。 +3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851;正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。 4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。 5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。 +6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。 ## 8. 禁止事项 -- 未经授权修改业务代码;纯 UI 任务改请求、载荷、状态、路由、权限、计费、登录或新增功能。 -- 新增 ConfigProvider、主题状态或存储 key;引入被禁依赖;手改生成的品牌图标资产。 -- JSX 硬编码颜色、全局 `!important`;无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。 +- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。 - 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。 - 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。 -- 输出或提交密码、Cookie、令牌、`.env*` 的值、storageState、截图与报告。 -- 把 `docs/` 全文复制进本文件,或在同一会话重复全文加载已读文档。 +- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git;本地脱敏报告按第 7 节交付。 ## 9. 维护 -- `AGENTS.md` 与 `CLAUDE.md` 第 0–9 节必须逐字一致,修改后校验(无输出即一致):`diff <(sed -n '/^## 0\./,/^## 10\./p' AGENTS.md) <(sed -n '/^## 0\./,/^## 10\./p' CLAUDE.md)`。 -- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落并更新头部版本与日期。 +- `AGENTS.md` 与 `CLAUDE.md` 第 0–9 节必须逐字一致;标题与第 10 节分别维护,不整文件覆盖另一份。维护时执行开发规范第 12.4 节的一致性校验。 + +- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 +> 规范版本:v3.4 · 更新:2026-11-17 + ## 10. 工具差异(本节允许不同) -- 本文件是 Claude Code 默认入口,会话启动时自动加载;不要再用 Read 全文读取本文件或 `AGENTS.md`(两者第 0–9 节相同)。 -- 文件检索用 Glob / Grep 并限定 `path`(如 `src`、`docs`);不要在 Bash 中对仓库根目录执行 `find`、`grep -r`、`ls -R`;同一轮并行读取不超过 4 个文件。 -- 用户级 `~/.claude/CLAUDE.md` 要求关注内存与 CPU、控制并发,与第 0 节第 11 条一致;启动浏览器、构建、全量测试前先检查可用内存。 -- 子代理与工作流只在用户明确要求时使用;委派时把第 0 节规则写入任务说明。 +- 本文件是 Claude Code 项目记忆入口;已加载时按第 1 节续作,进入子目录时留意适用的 `CLAUDE.md`。 +- 文件检索优先 Glob / Grep 并限定路径,用 Read 分段读取;Bash 同样遵守第 0 节扫描边界。 +- 用户级记忆、项目 / 本地设置、权限、hooks、MCP 与技能以当前 Claude Code 实际加载项为准;不假定他人机器存在相同的 `~/.claude/CLAUDE.md` 或插件,不把本机授权写成团队默认权限,不提交本地凭据或放宽权限来绕过失败。 +- 子代理与工作流只在用户明确要求时使用;委派时传递任务范围、第 0 节规则与验收要求。 diff --git a/README.md b/README.md index fbdbe7a5..dc65d6ac 100644 --- a/README.md +++ b/README.md @@ -152,9 +152,11 @@ monkey-ai-web/ 提交前至少运行 `npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1` 与 `git diff --check`;涉及依赖或图标时加跑 `npm run check:ui`。`npm run build` 只执行构建,不包含检查与测试。i18n 提取与同步会修改语言包,提交前核对 diff。 +纯文档改动只检查变更文件的 Prettier、`git diff --check` 与相关链接 / 命令。`npm run check` 不包含 Prettier,且会构建到 `dist/`;Agent 验收构建须先获授权并输出到临时目录。Windows PowerShell 可用 `npm.cmd` / `npx.cmd` 避免执行策略拦截;终端编码、Web 请求和提交格式见 `docs/standards/DEV_STANDARDS.md` 第 12 节。`npm run dev` 本身不生成 `dev.log`,启动方须重定向输出,详见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。 + ### 本地 Playwright 登录配置 -本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`;账号密码只保存在该本地忽略文件,不写入脚本或提交。运行时由 Node 加载到环境变量: +本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`;写入真实凭据前,用 `git ls-files -- .env.playwright.local` 确认未跟踪(应无输出),再用 `git check-ignore -- .env.playwright.local` 确认已忽略(应输出路径)。已跟踪文件不会因新增忽略规则而解除跟踪;检查不满足时先记录风险,跟踪与历史处置另行授权,不向该文件写入真实凭据。账号密码不写入脚本或提交。运行时由 Node 加载到环境变量: ```powershell node --env-file=.env.playwright.local e2e/auth-login/run.mjs @@ -164,6 +166,24 @@ node --env-file=.env.playwright.local e2e/auth-login/run.mjs 脚本从 `dev.log` 最后一个 `Local:` 提取并验证系统地址,使用本机 Chrome 离屏串行执行企业 A/B 状态判定、真实 UI 登录、后台主体断言、个人端全新 Context 登录和 UI 退出。企业 A 路径先填写企业名称并点击“下一步”,B 路径直接填写登录名和密码;不可覆盖的路径单独记录。后续搜索按钮验收拦截非 GET 写请求;截图、脱敏失败记录与供后续用例复用的 storageState 保存在 `report/auth-login-<时间>/`,均为本地忽略产物。storageState 含会话凭据,不上传、不提交;登录规则见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。 +Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;本项目 runner 默认端口为 4176,避免与 weelink 的 4175 冲突。配置读取 `scripts/ui-review/config.json`,用例通过 `scripts/playwright-test.mjs` 的公共 fixture 后台建页并守护焦点。独立脚本使用 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()`,两类流程保留各自执行策略。前台激活或探测失败会记录并停止,离屏不保证绝无瞬时激活。环境变量和截图口径见 [全局基线第 7.1 节](docs/ui/GLOBAL_UI_BASELINE.md#71-工具)。 + +| 命令 / 参数 | 用途与默认值 | +| --- | --- | +| `npm run test:e2e:headless` | 无头运行;本地默认有头离屏,CI 强制无头 | +| `npm run test:e2e:extended` | 全部 8 视口;也可设置 `PW_EXTENDED_LAYOUT=1` | +| `npm run test:e2e:dist` | 验证已有静态产物并严格启动 4176;不自动构建 | +| `npm run test:acceptance -- <参数>` | 串行单测、临时目录构建、产物校验、强制 local-dist/4176 测试 | +| `npm run test:e2e:environment` | 隔离验证 8 视口、手机 UA/触摸/DPR、CSS 截图;不代表业务验收 | +| `npm run test:e2e:report` | 打开最新完整 HTML 报告;仅人工使用 | +| `PW_WORKERS` | 默认 1,只接受正安全整数;保留串行优先策略 | +| `PW_TARGET` / `PW_BASE_URL` | 默认 local-dev / `http://127.0.0.1:4176/`;remote 必填 URL | +| `PW_VIDEO` / `PW_REQUIRE_ALL` | 默认 0;开启失败保留视频 / 全部通过约束 | + +`UI_VISUAL_OFFSCREEN=0` 仅限人工本地可视化调试时临时使用。Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式(或 `UI_VISUAL_OFFSCREEN=1`),避免弹出 UI 或依赖显示环境。配置会拦截 CI、无头及已识别的 Codex/Claude Agent 标记;其他自动化调用方也必须遵守此约定。 + +Trace、失败截图、CI JUnit 在 `test-results//`,HTML 在 `playwright-report//`,历史产物不自动清理。`PW_*` 不自动读取 Vite `.env*`;终端赋值只传递给当前会话的子进程。静态截图可使用 `scripts/browser-capture.mjs` 的 `captureStatic()`;已有视觉基线保留,不自动更新。 + ## 7. 构建与部署 ```bash diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8047cfdb..1aef56e7 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,6 +10,14 @@ ## 2026-11-17 +### 工具 · 两项目浏览器环境与报告隔离 + +- **范围**:Playwright 配置、设备共享模块、公共 fixture、启动与产物校验脚本、测试命令和对应文档。 +- **变更**:端口改为 4176;精确锁定 Playwright 1.64.1;统一设备、默认离屏、滚动条和截图策略;环境开关与 workers 严格校验;runner 接入后台建页及焦点守护;Trace、HTML、JUnit 按运行编号隔离;补齐严格 preview 与临时构建验收入口。 +- **影响**:现有业务断言和视觉基线保留;本地忽略的 e2e 用例已迁移公共导入,新增用例应使用相同入口。历史截图和报告不重写;环境改变后的像素比较需重新采集并人工复核,不能自动更新基线。 +- **回滚**:仅还原本次配置、工具、依赖锁定及文档段落;本地用例按本次迁移清单还原导入与页面创建,不覆盖其他已有改动。 +- **关联**:README、`docs/ui/GLOBAL_UI_BASELINE.md` 第 7.1 节。 + ### 修复 · 九语言翻译覆盖与国际化检查 - **范围**:`src/i18n/locales/` 九份语言包、相关页面与组件文案、价格说明及国际化回归测试。 @@ -18,6 +26,30 @@ - **回滚**:按本次文件差异还原语言包、文案调用、固定技术文字模块及对应测试,保留原有工作区修改;无需数据迁移。 - **关联**:`i18next.config.js`、`src/i18n/locale-coverage.test.js`、`test/unit/i18n-render-regressions.test.js`。 +### 文档 · Agent 公共规则与工具入口对齐 + +- **范围**:`AGENTS.md`、`CLAUDE.md`、`README.md`、`docs/README.md`、开发规范与 UI 全局基线。 +- **变更**:公共第 0–9 节保持一致,第 10 节分别说明工具边界;补齐 Windows 执行、提交格式、命令副作用与一致性校验,修正开发日志、凭据文件跟踪假设与 Playwright 默认值说明。经 10 轮审查,版本信息后置、重复规则归位、校验代码下沉,按任务与小节定向读取并保留上下文交接索引。 +- **影响**:不修改业务逻辑、依赖或测试配置;保留已有焦点守卫相关修改。优化减少入口体积与前缀扰动,不保证服务端缓存命中率;逐轮记录和验证证据保存在 Git 忽略的 `report/agent-doc-alignment/`。 +- **回滚**:仅还原上述文档中本次条目及相关段落,保留任务开始前已有修改;无需数据迁移。 +- **关联**:开发规范第 12 节、两份入口文档第 2、7、9、10 节。 + +### 工具 · 有头 Chrome 焦点守卫 + +- **范围**:本地 Playwright 验收工具链(`scripts/playwright-focus-guard.mjs`、`playwright.config.js`),不涉及业务代码。 +- **变更**:新增 `launchFocusSafe()`:唯一页面、拦截 `context.newPage()` / `page.bringToFront()`、页内拦截 `window.open` 与 `target="_blank"`、额外页面自动关闭、无现成页面时用 CDP `Target.createTarget({ background: true })` 建页、`checkpoint()` 以 Windows 前台进程判定后台状态并记录启动激活 / 二次激活 / 无法确认;`UI_VISUAL_OFFSCREEN=1` 复用同一组离屏与防后台节流参数;新增单测 `test/unit/playwright-focus-guard.test.js`。 +- **影响**:守卫启动的页面内 `window.open` 返回 `null`,新窗口链接不跳转,只记录到 `blockedPopups()`;`npm run test:e2e` 仍由夹具按用例建页,严格焦点约束需改用守卫脚本。 +- **回滚**:还原上述两个文件与单测,删除 `GLOBAL_UI_BASELINE.md` 第 7.1.1 节及 README、`AGENTS.md` / `CLAUDE.md` 第 7 节的对应说明。 +- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 7.1.1 节。 + +### 修复 · `npm test` 在环境测试后无法退出 + +- **范围**:`tests/environment.test.js` 中两条启动 Vite 开发服务的用例,不涉及业务代码与 `vite.config.js`。 +- **变更**:Vite 5.4 合并配置时会丢弃内联的 `server.watch: null`,导致 chokidar 递归监听整个仓库,`server.close()` 后仍残留数千个文件监听句柄,进程不退出。现在“开发服务转换”用例先读取真实配置,再以 `configFile: false` 传入并设 `watch: null`;代理用例同样关闭监听。 +- **影响**:断言不变;该文件约 8 秒结束,全量单测 686 条通过(约 137 秒)。 +- **回滚**:`git checkout <提交>^ -- tests/environment.test.js`。 +- **关联**:无。 + ## 2026-11-16 ### 修复 · 筛选卡纯色背景、模型名称搜索与三中心表格固定列 diff --git a/docs/README.md b/docs/README.md index 2a0b91a4..47f5ba07 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # 文档索引 -> 状态:有效 · 更新:2026-11-11 · 版本:v4.0 +> 状态:有效 · 更新:2026-11-17 · 版本:v4.1 本项目前端规范的入口。规范分三层:开发与组件规范(`standards/`)、外壳与页面规范(`ui/`)、变更记录(`CHANGELOG.md`)。通用样式只写在 `UI_COMPONENT_STANDARDS.md`,页面规范只记录差异。 @@ -46,11 +46,11 @@ ## 阅读与维护 -- 同一会话已读过的文档不重复全文加载;单次读取超过约 300 行时分段读,并发读取不超过 4 个文件;用“路径 + 章节号”引用,不复制全文。 +- 同一会话已读过的文档不重复全文加载,变化时仅补读相关差异;已知规范归属时按入口第 6 节直达目标章节,无需重复读取本索引。上下文交接保留已读路径与章节;单次读取超过约 300 行时分段读,并发读取不超过 4 个文件;用“路径 + 章节号”引用,不复制全文。 - 新文档按下列模板编写:开发与组件规范放 `standards/`,页面规范放 `ui/` 并命名为 `<范围>_SPEC.md`;同时登记本文“速查”和“文档清单”,并在 `AGENTS.md` / `CLAUDE.md` 第 6 节加一行索引。 - 同一组件规则被两个以上页面使用时,写进 `UI_COMPONENT_STANDARDS.md`,页面规范只保留差异。 - 改造、迁移、优化与回归的过程记录、截图与报告不建文档,只放 Git 忽略的 `report/`、`logs/`;`CHANGELOG.md` 只记录对现状仍有影响的功能与修复。 -- 修改规范只动相关段落,并更新状态行的日期与版本;每季度检查一次过期内容、失效路径与 `UI_COMPONENT_STANDARDS.md` 第 16 节的收敛进度。 +- 修改规范只动相关段落,并更新状态行的日期与版本(Agent 入口放在第 9 节,保持前缀稳定);每季度检查一次过期内容、失效路径与 `UI_COMPONENT_STANDARDS.md` 第 16 节的收敛进度。 - 规范类文档的表格由 Prettier 按紧凑格式输出(`.prettierrc.mjs` 的 overrides),提交前运行 `npx prettier --check <文件>`。 ```markdown diff --git a/docs/standards/DEV_STANDARDS.md b/docs/standards/DEV_STANDARDS.md index cc6f77a3..03bc8694 100644 --- a/docs/standards/DEV_STANDARDS.md +++ b/docs/standards/DEV_STANDARDS.md @@ -1,6 +1,6 @@ # 统一开发与 Ant Design CRUD 规范 -> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-11 · 版本:v2.1 +> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-17 · 版本:v2.2 新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。 @@ -290,6 +290,8 @@ pagination={{ ## 12. 代码风格与提交前检查 +### 12.1 检查与构建 + - Prettier:`singleQuote`、`jsxSingleQuote`,换行 LF;规范类文档使用紧凑表格(`.prettierrc.mjs` 的 overrides)。 - ESLint:许可证头、`no-undef`、未使用 import 报错、Hooks 规则、禁用 UI 库导入,`--max-warnings=0`。 @@ -301,9 +303,45 @@ npm run check:ui # 改依赖、图标或 UI 库导入时 git diff --check ``` -构建验证需用户同意,输出到临时目录且不覆盖 `dist/`(见 `AGENTS.md` 第 7 节)。 +构建验证需用户同意,输出到临时目录且不覆盖 `dist/`(见当前 Agent 入口第 7 节,无需加载另一入口)。 -提交前自检: +纯文档改动只需检查变更文件的 Prettier、`git diff --check` 与涉及的链接、命令、公共规则一致性;上述全量代码检查适用于代码变更。`npm run check` 不含 Prettier,且最后执行默认输出到 `dist/` 的构建,不直接用于临时目录验收。 + +### 12.2 提交与暂存 + +- 只在用户要求时 commit / push;提交前检查 `git status --short`、`git diff` 与 `git diff --cached`,只暂存当前任务文件,不使用 `git add .` 混入其他修改。 +- 新提交使用 `type(scope): 中文说明`,scope 可省略;type 选 `feat`、`fix`、`docs`、`refactor`、`test`、`chore`、`perf`、`build`、`ci`、`revert`,例如 `docs(agent): 对齐公共规范与工具差异`。这是协作约定,`package.json` 未配置 commitlint;不假定本机另有 Git hook 强制校验。 +- 提交说明写变更原因与实际验证结果;不写未完成的验证。默认不 amend、不强推、不重置工作区,提交后核对提交内容与剩余改动。 + +### 12.3 Windows 执行约定 + +- 每条 PowerShell 命令开头显式设置 `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;`,包括 `-NoProfile` 子进程;读取 UTF-8 文件用 `Get-Content -Encoding UTF8`。通过 Bash 调用 PowerShell 同样处理;cmd 命令先运行 `chcp 65001 >nul`。Python 使用 `python -X utf8`,隔离模式使用 `python -I -X utf8`。 +- PowerShell 若拦截 `npm.ps1` / `npx.ps1`,改用 `npm.cmd` / `npx.cmd`;不修改执行策略或 Windows 安全设置,不自动确认或抑制脚本安全警告。 +- Windows PowerShell 5.1 的每个 `Invoke-WebRequest`(含别名)必须显式包含 `-UseBasicParsing -TimeoutSec 30`;优先使用完整命令名。原生 curl 仅用 `curl.exe --connect-timeout 10 --max-time 30`。执行已有下载脚本前检查调用,补齐参数;依赖旧 HTML DOM 的调用方应先迁移到合适的解析器,不擅自删除 DOM 依赖。不为验证下载而运行下载脚本,检查状态、内容或预期哈希。 +- CPU / 内存用 `Get-CimInstance Win32_Processor` / `Win32_OperatingSystem`,避免依赖本地化名称的 `Get-Counter`;提交内存不足或无法确认资源门槛时不启动重型任务。任务结束只清理本任务启动的进程,保留已运行服务和他人进程。 +- 调用 `reg.exe`、`netsh` 等原生程序前同样设置 UTF-8;使用 PowerShell 的 `&` 调用,不用 `cmd /c` 嵌套引号。内联 Node 脚本含引号时优先用 here-string 管道传入 `node`,避免 PowerShell 5.1 参数转义丢失。 + +### 12.4 Agent 入口一致性校验 + +PowerShell 校验成功输出 `公共规则一致`;不一致或缺少章节边界时退出码为 1: + +```powershell +[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8; +@' +const fs = require('node:fs'); +const common = (p) => { + const s = fs.readFileSync(p, 'utf8').replace(/\r\n/g, '\n'); + const a = s.indexOf('\n## 0.'); + const b = s.indexOf('\n## 10.'); + if (a < 0 || b <= a) throw Error(p + ': missing section boundary'); + return s.slice(a, b); +}; +if (common('AGENTS.md') !== common('CLAUDE.md')) throw Error('Common rules differ'); +console.log('公共规则一致'); +'@ | node +``` + +### 12.5 提交前自检 - [ ] 改动的流程可只用键盘完成,焦点始终可见,纯图标按钮有 `aria-label`。 - [ ] 新的异步界面同时实现了加载、空数据、失败三种状态。 diff --git a/docs/ui/GLOBAL_UI_BASELINE.md b/docs/ui/GLOBAL_UI_BASELINE.md index 8f5c884c..952cb881 100644 --- a/docs/ui/GLOBAL_UI_BASELINE.md +++ b/docs/ui/GLOBAL_UI_BASELINE.md @@ -1,6 +1,6 @@ # 后台 UI 全局基线 -> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v3.4 +> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-17 · 版本:v3.6 后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。 @@ -16,7 +16,7 @@ | 滚动条 | 全站 6px,`#8b8b8b`,悬停 `#636363`,页面不得单独设置 | | 装饰 | 无设计依据不加渐变、玻璃、发光、浮起与动效 | | 登录关卡 | 真实 UI 登录,企业先于个人,凭据只经环境变量(第 6 节) | -| 验收 | 浅深主题 × 1920×1000 / 393×851,有头离屏串行,模拟与真实分开记录(第 7 节) | +| 验收 | 浅深主题 × 1920×1000 / 393×851,有头离屏串行,唯一页面不抢焦点,模拟与真实分开记录(第 7 节) | **相关代码**:`src/styles/{user-center,center-layout,org-page,prototype}.css`、`src/index.css`、`src/components/layout/` @@ -111,7 +111,7 @@ - 状态 A:一个企业输入框 +“下一步”。先填企业名称,点击“下一步”,等“企业内登录名”“密码”“登录”出现后再填凭据;不得把登录名当企业名,不得跳过企业查询。 - 状态 B:已出现登录名、密码与“登录”。直接填写凭据,保留已解析的企业上下文。 4. 个人端:新建无企业 Cookies / Storage 的 Context,进入 `{Base URL}/login`,按页面原有协议勾选与登录,确认用户中心侧栏与主体渲染后保存 storageState。 -5. 凭据只经环境变量传入:企业 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`,普通个人 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS`,超管 `UI_ADMIN_USER` / `UI_ADMIN_PASS`。本机可通过 Git 忽略的 `.env.playwright.local` 加载,不要求用户在每次任务中重新提供;不得输出其值,不写入脚本、日志、截图注释、报告或提交;登录阶段不录 trace / HAR。本地入口和账号选择参数见 `README.md` 的“本地 Playwright 登录配置”。 +5. 凭据只经环境变量传入:企业 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`,普通个人 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS`,超管 `UI_ADMIN_USER` / `UI_ADMIN_PASS`。本机可通过确认未跟踪且已忽略的 `.env.playwright.local` 加载,不要求用户在每次任务中重新提供;不得输出其值,不写入脚本、日志、截图注释、报告或提交;登录阶段不录 trace / HAR。本地入口、跟踪 / 忽略检查和账号选择参数见 `README.md` 的“本地 Playwright 登录配置”。 6. 失败时截图,记录 `dev.log` 尾部与失败请求(密码、Cookie、token、ticket 脱敏),写入风险;不盲目重试,不改登录业务代码。 7. 结束时通过顶栏用户菜单“退出登录”,确认回到登录页(当前为 `/org/login`)且受保护路由不再渲染。 @@ -119,10 +119,52 @@ ### 7.1 工具 -- 优先使用项目 Playwright 配置(`playwright.config.js`:`testDir: ./e2e`、`workers: 1`)与本机 Chrome(`channel: 'chrome'`)。无人值守设置 `UI_VISUAL_OFFSCREEN=1`(有头离屏,不抢前台输入);要求不启动有头窗口时可用无头模式并在报告注明。 -- 运行前从 `dev.log` 提取 Local URL 设为 `PLAYWRIGHT_BASE_URL`。Playwright 失败先排查服务地址、元素定位、等待条件、浏览器环境与登录状态。 +- 优先使用项目 Playwright 配置(`playwright.config.js`:`testDir: ./e2e`、`workers` 默认 1,可由正整数 `PW_WORKERS` 覆盖)与本机 Chrome(`channel: 'chrome'`)。默认离屏,保留 `UI_VISUAL_OFFSCREEN=1`(只降低可见干扰,不保证没有瞬时焦点激活);要求不启动有头窗口时可用无头模式并在报告注明。 +- 运行前从 `dev.log` 最后一个 `Local:` 提取地址;runner 复用服务时设 `PW_TARGET=remote` + `PW_BASE_URL`,不会启动或关闭已有服务。专项脚本是否接收 `PLAYWRIGHT_BASE_URL` 以其实现为准,不能用它替代 runner 的 `PW_BASE_URL`。Playwright 失败先排查服务地址、元素定位、等待条件、浏览器环境与登录状态。 +- 默认 runner 为浅色、1920×1080 / 360×800,本地有头、CI 无头,`webServer.reuseExistingServer=false`;默认执行不等于完成第 7.3 节浅深主题与规范视口矩阵,须在用例或专项脚本补足。严格有头焦点约束见第 7.1.1 节。 - `e2e/` 为本地忽略目录,验收脚本不随仓库分发;新增脚本同样放在该目录。 +#### 7.1.1 浏览器焦点约束(有头 Chrome) + +目标是不干扰用户桌面焦点。脚本统一通过 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()` 启动,它已内置以下约束: + +| 约束 | 要求与实现 | +| --- | --- | +| 唯一页面 | 全程只用启动时已有的一个标签页,访问新地址用 `page.goto` / `browser_navigate`;`context.newPage()` 被拦截并抛错 | +| 禁止新建 / 切换 | 不调用 `browser_tabs new` / `select`、`context.newPage()`、`page.bringToFront()`;标签页管理只允许 `browser_tabs list` / `close`。应用自开的 `window.open` 与 `target="_blank"` 链接在页内拦截并记录;仍出现的额外页面立即关闭,不切换 | +| 禁止系统级输入 | 只用页面级操作(`click`、`fill`、`type`、`goto`、`evaluate`),不用系统级鼠标键盘模拟、窗口激活或最小化 | +| 后台建页 | 启动后若没有现成页面,只能用 CDP `Target.createTarget` 并传 `{ background: true, newWindow: false }` | +| 换账号 / 视口 / 主题 | 同一页面内用 `resetSession(origins)` 清 Cookie 与存储;视口用 `setViewportSize`,主题用 `emulateMedia`;需要 `isMobile` / `hasTouch` 时关闭后重启(计为新的启动) | +| 启动激活 | 启动时窗口若获得前台,记录“启动焦点激活事件”后继续,不做任何再次激活的操作 | +| 状态断言 | 关键步骤后调用 `checkpoint(label)`:以 Windows 前台窗口所属进程比对本次 profile 的 `chrome.exe`;`document.hasFocus()` 受 Playwright 焦点模拟影响恒为 true,只记录不判定。后台 → 前台记录“二次焦点激活”并暂停;无法确认时记录“无法确认后台状态”并暂停,不得宣称“已保证后台运行” | + +- runner 用例从 `scripts/playwright-test.mjs` 导入 `test` / `expect`,公共 fixture 以 CDP `Target.createTarget({ background: true })` 创建当前 Context 的唯一页面,禁止 `browser.newContext` / `browser.newPage` / `context.newPage` / `page.bringToFront`,意外新页面立即关闭并判失败。页面创建后和用例结束后探测焦点;前台激活或状态未确认会记录并停止。独立脚本仍通过 `launchFocusSafe()`,在关键步骤调用 `checkpoint()`。 +- 交付说明写明焦点日志结论(是否出现启动激活、二次激活、无法确认),不把未检测的运行写成“后台运行”。 + +#### 7.1.2 runner 环境与产物约定 + +`UI_VISUAL_OFFSCREEN=0` 仅限人工本地可视化调试时临时使用。Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式(或 `UI_VISUAL_OFFSCREEN=1`),避免弹出 UI 或依赖显示环境。配置会拦截 CI、无头及已识别的 Codex/Claude Agent 标记;其他自动化调用方也必须遵守此约定。 + +| 配置 | 约定 | +| --- | --- | +| 设备源 | `scripts/ui-review/config.json` → `scripts/browser-environment.mjs`;与 weelink 的设备结构和 Playwright 1.64.1 保持一致,各项目独立保存 | +| 视口 | 默认 1920×1080、360×800;扩展增加 768×1024、1024×768、1366×768、1440×900、2560×1440、3840×2160 | +| 手机 | Pixel 5 UA、触摸、移动模式和 DPR 2.75;viewport 覆盖为 360×800,screen 沿用模板;平板仅为桌面设备的平板尺寸 | +| 本地目标 | `PW_TARGET=local-dev` 默认启动 `http://127.0.0.1:4176/`,weelink 使用 4175;开发和预览均严格占用指定端口,禁止静默回退 | +| 目标切换 | `local-dist` 先校验静态入口与引用资源,再启动 Vite preview;`remote` 必须提供 `PW_BASE_URL`,不启动服务 | +| 窗口 | 本地默认有头离屏;`PW_HEADLESS=1` 无头,CI 强制无头;隐藏滚动条并禁用后台降频 | +| 并发 | 默认单 worker、文件内不拆分;`PW_WORKERS` 只接受正安全整数,不代表动态内存调度 | +| 布尔变量 | `PW_HEADLESS`、`PW_EXTENDED_LAYOUT`、`PW_VIDEO`、`PW_REQUIRE_ALL`、`UI_VISUAL_OFFSCREEN` 仅接受 `0` / `1`,未设采用默认值 | +| 产物 | `test-results//` 保存 Trace、CSS 像素失败截图、CI JUnit;`playwright-report//` 保存 HTML,均不自动清理 | +| 运行编号 | 自动生成并由 worker 继承;手设 `PW_RUN_ID` 须为唯一的安全目录名,字母/数字/短横线/下划线,最长 100 字符 | +| 静态截图 | 新采集使用 `captureStatic()`:等待字体与可见图片、CSS 像素、禁用动画/过渡、隐藏光标;行为测试不全局关闭动画 | +| 视觉基线 | 保留已有 `toHaveScreenshot()` 断言和用例级阈值;不会自动更新基线。既有截图、坐标及历史报告不缩放重写,环境变化后新比较须重采 | +| 专项覆盖 | 现有用例可以显式覆盖 viewport、主题和 DPR,执行结果须标明实际环境;默认 runner 不替代第 7.3 节的规范矩阵 | + +`PW_*` 来自启动进程环境,不自动加载 Vite `.env*`;凭据仍按第 6 节与 README 单独加载。环境指纹第 2 版包含共享上下文、公共启动参数和 CSS 截图口径,不等于锁定系统字体与 Chrome 版本。Service Worker 仍由各流程决定:runner 沿用默认允许,独立守卫流程保留阻止。 + +常用入口:`npm run test:e2e:headless`、`test:e2e:extended`、`test:e2e:dist`、`test:e2e:environment`。`test:e2e:report` 自动找到最新完整报告,也可传指定目录。`npm run test:acceptance -- ` 先串行单测,再构建到系统临时目录、校验产物、强制 local-dist/4176 测试,结束后清理本次临时构建,不覆盖工作区 dist;已有依赖真实后端或登录态的用例仍需配置好环境,不等于自动完成真实业务验收。 + ### 7.2 分阶段 1. 企业端:真实 UI 登录 → 逐菜单双主题 → 表格、筛选、分页、弹窗、抽屉、表单的正常与失败状态 → UI 退出。 diff --git a/package-lock.json b/package-lock.json index bf52be27..1c9c18be 100644 --- a/package-lock.json +++ b/package-lock.json @@ -52,7 +52,7 @@ "xlsx": "^0.18.5" }, "devDependencies": { - "@playwright/test": "^1.64.1", + "@playwright/test": "1.64.1", "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.21", "esbuild": "0.21.5", @@ -1334,13 +1334,13 @@ } }, "node_modules/@playwright/test": { - "version": "1.65.0", - "resolved": "https://registry.npmmirror.com/@playwright/test/-/test-1.65.0.tgz", - "integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==", + "version": "1.64.1", + "resolved": "https://registry.npmmirror.com/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.65.0" + "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -9733,13 +9733,13 @@ } }, "node_modules/playwright": { - "version": "1.65.0", - "resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.65.0.tgz", - "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", + "version": "1.64.1", + "resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.65.0" + "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -9749,9 +9749,9 @@ } }, "node_modules/playwright-core": { - "version": "1.65.0", - "resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.65.0.tgz", - "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", + "version": "1.64.1", + "resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/package.json b/package.json index db4d4f20..39d697aa 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "test": "node scripts/test.mjs", "test:e2e": "playwright test", "test:e2e:headed": "playwright test --headed", - "test:e2e:report": "playwright show-report", + "test:e2e:report": "node scripts/run-playwright.mjs report", "lint": "prettier . --check", "lint:fix": "prettier . --write", "check": "npm run check:ui && npm run eslint && npm test -- --test-concurrency=1 && npm run build", @@ -65,7 +65,13 @@ "i18n:sync": "i18next-cli sync", "i18n:lint": "i18next-cli lint", "check:ui": "node scripts/check-ui-dependencies.mjs", - "vendor:icons": "node scripts/vendor-brand-icons.mjs" + "vendor:icons": "node scripts/vendor-brand-icons.mjs", + "test:e2e:headless": "node scripts/run-playwright.mjs headless", + "test:e2e:extended": "node scripts/run-playwright.mjs extended", + "test:e2e:dist": "node scripts/run-playwright.mjs dist", + "verify:build": "node scripts/verify-build.mjs", + "test:acceptance": "npm test -- --test-concurrency=1 && node scripts/run-acceptance.mjs", + "test:e2e:environment": "node scripts/test-playwright-environment.mjs" }, "browserslist": { "production": [ @@ -80,7 +86,7 @@ ] }, "devDependencies": { - "@playwright/test": "^1.64.1", + "@playwright/test": "1.64.1", "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.21", "esbuild": "0.21.5", diff --git a/playwright.config.js b/playwright.config.js index 3678bc20..df8970b6 100644 --- a/playwright.config.js +++ b/playwright.config.js @@ -17,107 +17,72 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { defineConfig, devices } from '@playwright/test'; +import { defineConfig } from '@playwright/test'; +import { + browserChannel, + contextOptions, + projectViewports, +} from './scripts/browser-environment.mjs'; +import { runtimeOptions } from './scripts/playwright-runtime.mjs'; -const target = process.env.PW_TARGET || 'local-dev'; -if (!['local-dist', 'local-dev', 'remote'].includes(target)) { - throw new Error('PW_TARGET must be local-dist, local-dev or remote'); -} -if (target === 'remote' && !process.env.PW_BASE_URL) { - throw new Error('PW_BASE_URL is required for remote tests'); -} -const baseURL = new URL(process.env.PW_BASE_URL || 'http://127.0.0.1:4175/'); +const runtime = runtimeOptions({ defaultPort: 4176, defaultWorkers: 1 }); +const { target, baseURL, isCI, headless, workers, outputDir, reportDir } = + runtime; if ( - !['http:', 'https:'].includes(baseURL.protocol) || - baseURL.username || - baseURL.password || - baseURL.search || - baseURL.hash -) { - throw new Error( - 'PW_BASE_URL must be an HTTP(S) URL without credentials, query or hash', - ); -} -if (!baseURL.pathname.endsWith('/')) - throw new Error('PW_BASE_URL directory path must end with /'); -if ( - target !== 'remote' && - (baseURL.hostname !== '127.0.0.1' || - baseURL.protocol !== 'http:' || - baseURL.pathname !== '/') -) { - throw new Error('Local targets require http://127.0.0.1:/'); -} -const isCI = Boolean(process.env.CI && process.env.CI !== 'false'); -const headless = - process.env.PW_HEADLESS === undefined - ? isCI - : process.env.PW_HEADLESS === '1'; -const viewports = [ - ['desktop', 1920, 1080], - ['mobile', 360, 800], -]; -if (process.env.PW_EXTENDED_LAYOUT === '1') { - viewports.push( - ['tablet', 768, 1024], - ['desktop-boundary', 1024, 768], - ['laptop-hd', 1366, 768], - ['laptop-wxga', 1440, 900], - ['qhd', 2560, 1440], - ['uhd', 3840, 2160], - ); -} + isCI && + process.argv.some((argument) => + ['--headed', '--debug', '--ui'].includes(argument), + ) +) + throw new Error('CI requires headless non-interactive tests'); +const viewports = runtime.extended + ? projectViewports + : projectViewports.slice(0, 2); + +// UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。 +// Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式 +// (或 UI_VISUAL_OFFSCREEN=1),避免弹出 UI 或依赖显示环境。 +// 离屏不能保证系统启动时不激活窗口;公共 fixture 探测到前台或状态不明时停止。 +const listOnly = process.argv.includes('--list'); export default defineConfig({ testDir: './e2e', testMatch: '**/*.spec.js', - outputDir: 'test-results', + outputDir, fullyParallel: false, - workers: 1, - forbidOnly: isCI || process.env.PW_REQUIRE_ALL === '1', + workers, + forbidOnly: isCI || runtime.requireAll, failOnFlakyTests: isCI, retries: isCI ? 1 : 0, timeout: 30000, expect: { timeout: 5000 }, - reporter: [ - ['list'], - ['html', { outputFolder: 'playwright-report', open: 'never' }], - ...(isCI ? [['junit', { outputFile: 'test-results/junit.xml' }]] : []), - ], + reporter: listOnly + ? [['list']] + : [ + ['list'], + ['html', { outputFolder: reportDir, open: 'never' }], + ...(isCI ? [['junit', { outputFile: `${outputDir}/junit.xml` }]] : []), + ['./scripts/playwright-reporter.mjs'], + ], metadata: { platform: process.platform, node: process.version, target, baseURL: baseURL.href, + runId: runtime.runId, }, use: { baseURL: baseURL.href, headless, - launchOptions: - process.env.UI_VISUAL_OFFSCREEN === '1' - ? { - args: [ - '--window-position=-32000,-32000', - '--disable-backgrounding-occluded-windows', - ], - } - : {}, - locale: 'zh-CN', - timezoneId: 'Asia/Shanghai', - deviceScaleFactor: 1, - colorScheme: 'light', - reducedMotion: 'reduce', + launchOptions: { args: runtime.launchArgs }, + ...contextOptions('desktop'), + screenshot: { mode: 'only-on-failure', scale: 'css' }, trace: 'retain-on-failure', - screenshot: 'only-on-failure', - video: process.env.PW_VIDEO === '1' ? 'retain-on-failure' : 'off', + video: runtime.video ? 'retain-on-failure' : 'off', }, - projects: viewports.map(([name, width, height]) => ({ + projects: viewports.map((name) => ({ name: `chrome-${name}`, - use: { - ...(name === 'mobile' ? devices['Pixel 5'] : devices['Desktop Chrome']), - channel: 'chrome', - viewport: { width, height }, - }, + use: { ...contextOptions(name), channel: browserChannel }, })), webServer: target === 'remote' @@ -125,7 +90,7 @@ export default defineConfig({ : { command: target === 'local-dist' - ? `npm run preview -- --host 127.0.0.1 --port ${baseURL.port || 80}` + ? `node scripts/preview-dist.mjs --port ${baseURL.port || 80}` : `npm run dev -- --host 127.0.0.1 --port ${baseURL.port || 80} --strictPort`, url: baseURL.href, reuseExistingServer: false, diff --git a/scripts/browser-capture.mjs b/scripts/browser-capture.mjs new file mode 100644 index 00000000..d1a25f52 --- /dev/null +++ b/scripts/browser-capture.mjs @@ -0,0 +1,59 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。 +// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。 + +// Use this for static review captures, not for interaction/animation tests. +export async function prepareStaticCapture(page) { + await page.evaluate(async () => { + await Promise.race([ + Promise.all([ + document.fonts.ready, + ...[...document.images] + .filter((image) => image.currentSrc && image.checkVisibility()) + .map((image) => image.decode().catch(() => {})), + ]), + new Promise((_, reject) => + setTimeout( + () => + reject( + new Error( + 'Static capture fonts/images did not settle within 10s', + ), + ), + 10000, + ), + ), + ]); + }); +} + +export const staticScreenshotOptions = { + scale: 'css', + animations: 'disabled', + caret: 'hide', + style: + '*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }', +}; + +export async function captureStatic(page, options = {}) { + await prepareStaticCapture(page); + return page.screenshot({ ...options, ...staticScreenshotOptions }); +} diff --git a/scripts/browser-environment.mjs b/scripts/browser-environment.mjs new file mode 100644 index 00000000..cdd9e94d --- /dev/null +++ b/scripts/browser-environment.mjs @@ -0,0 +1,81 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { devices } from '@playwright/test'; +import { browserStabilityArgs } from './playwright-runtime.mjs'; + +// The review JSON is also read by Python; keep dimensions and device choices there. +const config = JSON.parse( + readFileSync(new URL('./ui-review/config.json', import.meta.url), 'utf8'), +); +const aliases = { + 'desktop-boundary': 'laptop', + 'laptop-hd': 'hd', + 'laptop-wxga': 'wxga', +}; +export const browserChannel = config.browser.channel; +export const projectViewports = [ + 'desktop', + 'mobile', + 'tablet', + 'desktop-boundary', + 'laptop-hd', + 'laptop-wxga', + 'qhd', + 'uhd', +]; + +export function deviceOptions(name) { + const key = aliases[name] || name; + const size = config.viewports[key]; + if (!size) throw new Error(`Unknown viewport: ${name}`); + const descriptor = + devices[ + config.browser[key === 'mobile' ? 'mobileDevice' : 'desktopDevice'] + ]; + if (!descriptor) throw new Error(`Unknown device profile for ${name}`); + const { defaultBrowserType, ...context } = descriptor; + return { ...context, viewport: { width: size[0], height: size[1] } }; +} + +export function contextOptions(name, reducedMotion = 'reduce') { + return { + ...deviceOptions(name), + locale: config.browser.locale, + timezoneId: config.browser.timezone, + colorScheme: 'light', + reducedMotion, + }; +} + +export function environmentFingerprint(name, reducedMotion = 'reduce') { + return createHash('sha256') + .update( + JSON.stringify({ + version: 2, + channel: browserChannel, + options: contextOptions(name, reducedMotion), + launchArgs: browserStabilityArgs, + screenshotScale: 'css', + }), + ) + .digest('hex'); +} diff --git a/scripts/playwright-focus-guard.mjs b/scripts/playwright-focus-guard.mjs new file mode 100644 index 00000000..872d2d0b --- /dev/null +++ b/scripts/playwright-focus-guard.mjs @@ -0,0 +1,322 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。 +// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。 + +import { contextOptions as sharedContextOptions } from './browser-environment.mjs'; +import { prepareStaticCapture } from './browser-capture.mjs'; +import { browserRuntime, browserStabilityArgs } from './playwright-runtime.mjs'; + +import { execFile } from 'node:child_process'; +import { mkdtemp, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +export const FOCUS_SAFE_ARGS = Object.freeze([ + ...browserStabilityArgs, + '--window-position=-32000,-32000', +]); + +export const FOCUS_EVENTS = Object.freeze({ + STARTUP: '启动焦点激活事件', + STARTUP_PERSIST: '启动焦点仍保持', + REACTIVATED: '二次焦点激活', + UNKNOWN: '无法确认后台状态', + EXTRA_PAGE: '意外新页面', + FORBIDDEN: '禁止的焦点操作', + BACKGROUND_TARGET: '后台创建页面', +}); + +export class FocusGuardError extends Error { + constructor(message) { + super(message); + this.name = 'FocusGuardError'; + } +} + +export function createFocusLog(sink = console.log) { + const entries = []; + return { + entries, + record(type, detail = {}) { + const entry = { time: new Date().toISOString(), type, ...detail }; + entries.push(entry); + sink(`[focus] ${type} ${JSON.stringify(detail)}`); + return entry; + }, + }; +} + +// 在页面内拦截 window.open 与 target 非 _self 的链接,避免应用自行打开新标签页。 +export const BLOCK_POPUP_SCRIPT = `(() => { + if (window.__focusGuardBlockedOpens) return; + const blocked = []; + Object.defineProperty(window, '__focusGuardBlockedOpens', { value: blocked }); + window.open = function (url) { + blocked.push(String(url ?? '')); + return null; + }; + const intercept = (event) => { + const anchor = event.target && event.target.closest && event.target.closest('a[target]'); + if (!anchor) return; + const target = String(anchor.getAttribute('target') || '').toLowerCase(); + if (!target || target === '_self' || target === '_top' || target === '_parent') return; + event.preventDefault(); + blocked.push(anchor.href); + }; + document.addEventListener('click', intercept, true); + document.addEventListener('auxclick', intercept, true); +})();`; + +export function installFocusGuards(context, page, log) { + const browser = context.browser?.(); + const forbid = (api) => async () => { + log.record(FOCUS_EVENTS.FORBIDDEN, { api }); + throw new FocusGuardError( + `${api} 被焦点约束禁止:只能在唯一页面内用 goto 导航`, + ); + }; + const original = { + newPage: context.newPage, + bringToFront: page.bringToFront, + browserNewPage: browser?.newPage, + browserNewContext: browser?.newContext, + }; + context.newPage = forbid('context.newPage'); + page.bringToFront = forbid('page.bringToFront'); + if (browser) { + browser.newPage = forbid('browser.newPage'); + browser.newContext = forbid('browser.newContext'); + } + const onPage = async (extra) => { + if (extra === page) return; + log.record(FOCUS_EVENTS.EXTRA_PAGE, { url: extra.url() }); + await extra.close().catch(() => {}); + }; + context.on('page', onPage); + return () => { + context.off('page', onPage); + context.newPage = original.newPage; + page.bringToFront = original.bringToFront; + if (browser) { + browser.newPage = original.browserNewPage; + browser.newContext = original.browserNewContext; + } + }; +} + +// 状态迁移:启动阶段的激活只记录;之后仅“后台 → 前台”视为二次激活。 +export function classifyFocus({ phase, previous, current }) { + if (current === 'unknown') + return { event: FOCUS_EVENTS.UNKNOWN, fatal: true }; + if (current !== 'foreground') return { event: null, fatal: false }; + if (phase === 'startup') return { event: FOCUS_EVENTS.STARTUP, fatal: false }; + if (previous === 'foreground') + return { event: FOCUS_EVENTS.STARTUP_PERSIST, fatal: false }; + return { event: FOCUS_EVENTS.REACTIVATED, fatal: true }; +} + +const FOREGROUND_PS = `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8; +Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '[DllImport("user32.dll")] public static extern System.IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint p);' +$fg = 0; [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fg) +$dir = $env:FOCUS_GUARD_PROFILE +$ids = @() +if ($dir) { $ids = @(Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($dir) } | ForEach-Object { $_.ProcessId }) } +Write-Output ("$fg|" + ($ids -join ','))`; + +export function parseForegroundOutput(output) { + const match = /^(\d+)\|([\d,]*)$/.exec(String(output).trim()); + if (!match) return { state: 'unknown', reason: 'unparsable' }; + const pids = match[2] ? match[2].split(',').map(Number) : []; + if (!pids.length) return { state: 'unknown', reason: 'no-browser-process' }; + return { + state: pids.includes(Number(match[1])) ? 'foreground' : 'background', + foregroundPid: Number(match[1]), + browserPids: pids, + }; +} + +// 只读查询系统前台窗口所属进程,并与本次 profile 启动的 chrome.exe 比对;不调用任何激活 API。 +export function probeOsForeground(profileDir) { + if (process.platform !== 'win32') + return Promise.resolve({ + state: 'unknown', + reason: 'unsupported-platform', + }); + const encoded = Buffer.from(FOREGROUND_PS, 'utf16le').toString('base64'); + return new Promise((resolve) => { + execFile( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], + { + windowsHide: true, + timeout: 15000, + env: { ...process.env, FOCUS_GUARD_PROFILE: profileDir }, + }, + (error, stdout) => + resolve( + error + ? { state: 'unknown', reason: 'probe-failed' } + : parseForegroundOutput(stdout), + ), + ); + }); +} + +async function createBackgroundPage(context, log) { + const browser = context.browser(); + if (!browser) + throw new FocusGuardError('无法获取 Browser,不能用 CDP 后台创建页面'); + const session = await browser.newBrowserCDPSession(); + try { + const pagePromise = context.waitForEvent('page', { timeout: 10000 }); + await session.send('Target.createTarget', { + url: 'about:blank', + background: true, + newWindow: false, + }); + const page = await pagePromise; + log.record(FOCUS_EVENTS.BACKGROUND_TARGET, { via: 'Target.createTarget' }); + return page; + } finally { + await session.detach().catch(() => {}); + } +} + +/** + * 启动唯一页面的有头 Chrome。切换桌面 / 移动需关闭后重新启动(计为新的启动阶段)。 + * 返回 { context, page, log, checkpoint, resetSession, blockedPopups, close }。 + */ +export async function launchFocusSafe(options = {}) { + const runtime = browserRuntime({ + ...process.env, + ...(options.headless === undefined + ? {} + : { PW_HEADLESS: options.headless ? '1' : '0' }), + }); + const { + chromium = (await import('@playwright/test')).chromium, + device = 'desktop', + colorScheme = 'light', + headless = runtime.headless, + blockPopups = true, + extraArgs = [], + contextOptions = {}, + log = createFocusLog(), + } = options; + const deviceEnvironment = sharedContextOptions(device); + const profileDir = await mkdtemp(path.join(os.tmpdir(), 'monkey-pw-focus-')); + let context; + try { + context = await chromium.launchPersistentContext(profileDir, { + ...deviceEnvironment, + locale: 'zh-CN', + timezoneId: 'Asia/Shanghai', + colorScheme, + reducedMotion: 'reduce', + serviceWorkers: 'block', + ...contextOptions, + channel: 'chrome', + headless, + args: [...extraArgs, ...runtime.launchArgs], + }); + } catch (error) { + await rm(profileDir, { recursive: true, force: true, maxRetries: 5 }); + throw error; + } + if (blockPopups) await context.addInitScript(BLOCK_POPUP_SCRIPT); + const page = context.pages()[0] ?? (await createBackgroundPage(context, log)); + const removeGuards = installFocusGuards(context, page, log); + const screenshot = page.screenshot.bind(page); + page.screenshot = async (options = {}) => { + await prepareStaticCapture(page); + return screenshot({ scale: 'css', ...options }); + }; + + let previous = 'background'; + let phase = 'startup'; + async function checkpoint(label, { pauseOnUnknown = true } = {}) { + if ( + log.entries.some((entry) => + [FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.EXTRA_PAGE].includes(entry.type), + ) + ) { + throw new FocusGuardError( + `焦点守护发现禁止操作或意外新页面(${label}),已停止`, + ); + } + let state; + let detail = {}; + if (headless) state = 'background'; + else { + const osProbe = await probeOsForeground(profileDir); + // Playwright 默认开启焦点模拟,document.hasFocus() 恒为 true,只作记录;以系统前台进程为准。 + const pageFocus = await page + .evaluate(() => document.hasFocus()) + .catch(() => null); + detail = { + os: osProbe.state, + reason: osProbe.reason, + foregroundPid: osProbe.foregroundPid, + documentHasFocus: pageFocus, + }; + state = osProbe.state; + } + const verdict = classifyFocus({ phase, previous, current: state }); + if (verdict.event) log.record(verdict.event, { label, ...detail }); + phase = 'running'; + if (state !== 'unknown') previous = state; + if (verdict.fatal && (state !== 'unknown' || pauseOnUnknown)) + throw new FocusGuardError(`${verdict.event}(${label}),已暂停`); + return { state, ...detail }; + } + + async function resetSession(origins = []) { + await context.clearCookies(); + const session = await context.newCDPSession(page); + try { + for (const origin of origins) + await session.send('Storage.clearDataForOrigin', { + origin, + storageTypes: 'all', + }); + } finally { + await session.detach().catch(() => {}); + } + await page.goto('about:blank'); + } + + const blockedPopups = () => + page.evaluate(() => [...(window.__focusGuardBlockedOpens || [])]); + + async function close() { + removeGuards(); + await context.close().catch(() => {}); + await rm(profileDir, { recursive: true, force: true, maxRetries: 5 }); + } + + try { + await checkpoint('launch'); + } catch (error) { + await close(); + throw error; + } + return { context, page, log, checkpoint, resetSession, blockedPopups, close }; +} diff --git a/scripts/playwright-reporter.mjs b/scripts/playwright-reporter.mjs new file mode 100644 index 00000000..01558c6d --- /dev/null +++ b/scripts/playwright-reporter.mjs @@ -0,0 +1,75 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +const FOCUS_ANNOTATION = 'focus-guard'; + +export default class AcceptanceReporter { + onBegin(config, suite) { + this.suite = suite; + this.focusEvents = new Set(); + this.focusChecks = new Set(); + this.headed = config.projects.some( + (project) => project.use?.headless === false, + ); + } + + onTestEnd(test, result) { + for (const note of [...(result.annotations || []), ...test.annotations]) { + if (note.type === FOCUS_ANNOTATION) + this.focusEvents.add( + `${test.titlePath().slice(1).join(' > ')}:${note.description}`, + ); + if (note.type === 'focus-guard-checked') + this.focusChecks.add(`${test.id}:${note.description}`); + } + } + + onEnd(result) { + // 焦点守护汇总:有事件时如实列出,不能宣称已保证后台运行 + if (this.focusEvents.size) { + console.warn( + `\n[focus-guard] 记录到 ${this.focusEvents.size} 条焦点事件,本次运行不能宣称已保证后台运行:`, + ); + for (const entry of this.focusEvents) console.warn(`- ${entry}`); + } else if (this.headed && this.focusChecks.size) { + console.log( + '\n[focus-guard] 各采样点(页面创建后、用例结束后)未检测到 Playwright Chrome 处于前台;采样点之间的瞬时激活无法排除', + ); + } + if (process.env.PW_REQUIRE_ALL !== '1') return; + const incomplete = this.suite + .allTests() + .filter( + (test) => + test.expectedStatus !== 'passed' || + test.results.length === 0 || + test.results.some((run) => run.status === 'skipped') || + test.outcome() === 'flaky', + ); + if (incomplete.length) { + console.error( + 'Full acceptance requires every test to pass without skips, expected failures or flaky retries:', + ); + for (const test of incomplete) + console.error(`- ${test.titlePath().join(' > ')}`); + return { status: 'failed' }; + } + return { status: result.status }; + } +} diff --git a/scripts/playwright-runner-focus.mjs b/scripts/playwright-runner-focus.mjs new file mode 100644 index 00000000..b63af286 --- /dev/null +++ b/scripts/playwright-runner-focus.mjs @@ -0,0 +1,197 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +// 浏览器焦点守护:有头真实 Chrome 运行时尽最大可能不抢占用户桌面焦点。 +// - 唯一页面:每个用例只有一个页面,由 CDP Target.createTarget({ background: true }) 后台创建, +// 不走 context.newPage()(Playwright 内部创建时不带 background,会以前台方式打开窗口)。 +// - 禁止新建/切换标签页:context.newPage、browser.newPage、browser.newContext、page.bringToFront 调用即报错; +// 页面隐式打开的新标签页(target=_blank、window.open)立即关闭并判定用例失败。 +// - 焦点探测:页面创建后与用例结束后各查一次前台窗口,若属于本 worker 启动的 Chrome, +// 记录「启动焦点激活事件」/「运行中焦点激活事件」;探测失败记为「焦点状态未确认」。只记录,不做任何激活操作。 +// CI(无头)不创建窗口,跳过探测;页面仍按同样规程创建。 +import { spawn } from 'node:child_process'; +import { createInterface } from 'node:readline'; + +export const FOCUS_ANNOTATION = 'focus-guard'; + +const PROBE_SCRIPT = [ + '[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;', + "Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '", + '[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();', + '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);', + "';", + // 预热 CIM(首次查询需数秒),就绪后才应答查询 + '[void](Get-CimInstance Win32_Process -Filter "ProcessId=$PID")', + '[Console]::Out.WriteLine("ready"); [Console]::Out.Flush()', + 'while ($null -ne ($line = [Console]::In.ReadLine())) {', + ' try {', + ' $fgPid = [uint32]0', + ' [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fgPid)', + ' $parent = (Get-CimInstance Win32_Process -Filter "ProcessId=$fgPid").ParentProcessId', + ' [Console]::Out.WriteLine("$fgPid $parent")', + ' } catch { [Console]::Out.WriteLine("error") }', + ' [Console]::Out.Flush()', + '}', +].join('\n'); + +// 每个 worker 一个常驻 PowerShell 只读探测进程(Add-Type 编译只发生一次),按行应答「前台窗口进程号 父进程号」 +export function createFocusProbe() { + if (process.platform !== 'win32') return null; + const child = spawn( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-Command', PROBE_SCRIPT], + { + stdio: ['pipe', 'pipe', 'ignore'], + windowsHide: true, + }, + ); + child.on('error', () => {}); + const lines = createInterface({ input: child.stdout }); + const waiting = []; + let markReady; + const ready = new Promise((resolve) => { + markReady = resolve; + }); + lines.on('line', (line) => { + if (line.trim() === 'ready') markReady(true); + else waiting.shift()?.(line.trim()); + }); + child.on('exit', () => { + markReady(false); + while (waiting.length) waiting.shift()(null); + }); + return { + // 返回 { foregroundPid, parentPid };探测失败或超时返回 null + async query(timeout = 8000) { + const started = await Promise.race([ + ready, + new Promise((resolve) => { + setTimeout(resolve, 15000, false).unref(); + }), + ]); + if (!started || child.exitCode !== null || !child.stdin.writable) + return null; + const answer = await new Promise((resolve) => { + const timer = setTimeout(() => { + resolve(null); + }, timeout); + waiting.push((line) => { + clearTimeout(timer); + resolve(line); + }); + child.stdin.write('q\n'); + }); + const match = /^(\d+) (\d+)$/.exec(answer || ''); + return match + ? { foregroundPid: Number(match[1]), parentPid: Number(match[2]) } + : null; + }, + dispose() { + child.stdin.end(); + if (child.exitCode === null) + setTimeout(() => { + if (child.exitCode === null) child.kill(); + }, 2000).unref(); + }, + }; +} + +// 前台窗口是否属于本 worker 启动的 Chrome(Chrome 主进程由 worker 进程直接启动并持有窗口) +export async function checkFocus(probe, stage, testInfo) { + if (!probe) return; + const state = await probe.query(); + let description; + if (!state) { + description = `焦点状态未确认(${stage}):前台窗口探测失败,不能宣称已保证后台运行`; + } else if (state.parentPid === process.pid) { + description = `${stage === '页面创建后' ? '启动焦点激活事件' : '运行中焦点激活事件'}:${stage}前台窗口属于 Playwright Chrome(pid ${state.foregroundPid})`; + } else { + testInfo.annotations.push({ + type: 'focus-guard-checked', + description: stage, + }); + return; + } + testInfo.annotations.push({ type: FOCUS_ANNOTATION, description }); + console.warn( + `[${FOCUS_ANNOTATION}] ${new Date().toISOString()} ${testInfo.titlePath.join(' > ')}:${description}`, + ); + throw new Error(description); +} + +// 本用例上下文的 CDP browserContextId:每个 worker 独占一个浏览器且用例串行,同一时刻只应有一个上下文 +async function contextIdOf(cdp) { + const { browserContextIds } = await cdp.send('Target.getBrowserContexts'); + if (browserContextIds.length !== 1) { + throw new Error( + `焦点守护:无法唯一确定当前浏览器上下文(共 ${browserContextIds.length} 个),拒绝以前台方式创建页面`, + ); + } + return browserContextIds[0]; +} + +// 唯一页面:通过 CDP Target.createTarget({ background: true }) 后台创建,由 Playwright 自动接管为 context 的页面 +export async function openBackgroundPage(browser, context) { + const cdp = await browser.newBrowserCDPSession(); + try { + const browserContextId = await contextIdOf(cdp); + const pageEvent = context.waitForEvent('page', { timeout: 15000 }); + await cdp.send('Target.createTarget', { + url: 'about:blank', + browserContextId, + background: true, + }); + return await pageEvent; + } finally { + await cdp.detach().catch(() => {}); + } +} + +const forbid = (name, violations) => () => { + violations.push(`禁止调用 ${name}`); + throw new Error( + `焦点守护:禁止调用 ${name}(唯一页面原则,不得新建或切换标签页/窗口;访问新地址请在当前页 page.goto)`, + ); +}; + +// 安装禁止项,返回 { violations, restore };restore 在用例结束时调用,恢复 worker 共享的 browser 方法 +export function installGuards(browser, context, page) { + const violations = []; + const saved = { newPage: browser.newPage, newContext: browser.newContext }; + context.newPage = forbid('context.newPage()', violations); + page.bringToFront = forbid('page.bringToFront()', violations); + browser.newPage = forbid('browser.newPage()', violations); + browser.newContext = forbid('browser.newContext()', violations); + const onPage = (extra) => { + if (extra === page) return; + violations.push( + `页面隐式打开了新标签页/窗口:${extra.url() || 'about:blank'}(已立即关闭)`, + ); + extra.close().catch(() => {}); + }; + context.on('page', onPage); + return { + violations, + restore() { + context.off('page', onPage); + browser.newPage = saved.newPage; + browser.newContext = saved.newContext; + }, + }; +} diff --git a/scripts/playwright-runtime.mjs b/scripts/playwright-runtime.mjs new file mode 100644 index 00000000..4dba0cc5 --- /dev/null +++ b/scripts/playwright-runtime.mjs @@ -0,0 +1,149 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { randomUUID } from 'node:crypto'; + +export const browserStabilityArgs = Object.freeze([ + '--hide-scrollbars', + '--disable-backgrounding-occluded-windows', + '--disable-renderer-backgrounding', + '--disable-background-timer-throttling', + '--disable-features=CalculateNativeWinOcclusion', + '--no-first-run', + '--no-default-browser-check', +]); + +export function positiveInteger(value, name) { + const text = String(value); + if ( + !['number', 'string'].includes(typeof value) || + text !== text.trim() || + !/^[1-9]\d*$/.test(text) || + !Number.isSafeInteger(Number(value)) + ) { + throw new Error(`${name} must be a positive safe integer (1, 2, 3, ...)`); + } + return Number(value); +} + +function flag(env, name, fallback) { + if (env[name] === undefined) return fallback; + if (!['0', '1'].includes(env[name])) + throw new Error(`${name} must be 0 or 1`); + return env[name] === '1'; +} + +export function browserRuntime(env = process.env) { + const isCI = Boolean(env.CI && env.CI !== 'false' && env.CI !== '0'); + const headless = flag(env, 'PW_HEADLESS', isCI); + if (isCI && !headless) + throw new Error( + 'CI requires headless Chrome; PW_HEADLESS=0 is not allowed', + ); + // UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。 + // Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式 + // (或 UI_VISUAL_OFFSCREEN=1),避免弹出 UI 或依赖显示环境。 + const offscreen = flag(env, 'UI_VISUAL_OFFSCREEN', true); + const knownAgent = Boolean( + env.CODEX_THREAD_ID || env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT, + ); + if (!offscreen && (isCI || headless || knownAgent)) + throw new Error( + 'UI_VISUAL_OFFSCREEN=0 is only allowed for manual local headed debugging', + ); + return { + isCI, + headless, + offscreen, + launchArgs: [ + ...browserStabilityArgs, + ...(offscreen ? ['--window-position=-32000,-32000'] : []), + ], + }; +} + +export function runtimeOptions({ + defaultPort, + defaultWorkers, + env = process.env, +}) { + const target = env.PW_TARGET || 'local-dev'; + if (!['local-dev', 'local-dist', 'remote'].includes(target)) + throw new Error('PW_TARGET must be local-dist, local-dev or remote'); + if (target === 'remote' && !env.PW_BASE_URL) + throw new Error('PW_BASE_URL is required for remote tests'); + const baseURL = new URL( + env.PW_BASE_URL || `http://127.0.0.1:${defaultPort}/`, + ); + if ( + !['http:', 'https:'].includes(baseURL.protocol) || + baseURL.username || + baseURL.password || + baseURL.search || + baseURL.hash + ) { + throw new Error( + 'PW_BASE_URL must be an HTTP(S) URL without credentials, query or hash', + ); + } + if (!baseURL.pathname.endsWith('/')) + throw new Error('PW_BASE_URL directory path must end with /'); + if ( + target !== 'remote' && + (baseURL.hostname !== '127.0.0.1' || + baseURL.protocol !== 'http:' || + baseURL.pathname !== '/') + ) { + throw new Error('Local targets require http://127.0.0.1:/'); + } + const browser = browserRuntime(env); + const { isCI } = browser; + const workers = + env.PW_WORKERS === undefined + ? isCI + ? 1 + : positiveInteger(defaultWorkers, 'resources.concurrency') + : positiveInteger(env.PW_WORKERS, 'PW_WORKERS'); + const extended = flag(env, 'PW_EXTENDED_LAYOUT', false); + const video = flag(env, 'PW_VIDEO', false); + const requireAll = flag(env, 'PW_REQUIRE_ALL', false); + const runId = env.PW_RUN_ID ?? `${target}-${Date.now()}-${randomUUID()}`; + if ( + typeof runId !== 'string' || + runId !== runId.trim() || + !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}$/.test(runId) + ) + throw new Error( + 'PW_RUN_ID must be a safe directory name of 1-100 letters, digits, underscores or hyphens', + ); + // Workers inherit this ID; every run keeps its traces and reports together. + env.PW_RUN_ID = runId; + return { + target, + baseURL, + ...browser, + workers, + extended, + video, + requireAll, + runId, + outputDir: `test-results/${runId}`, + reportDir: `playwright-report/${runId}`, + }; +} diff --git a/scripts/playwright-test.mjs b/scripts/playwright-test.mjs new file mode 100644 index 00000000..985dc5b6 --- /dev/null +++ b/scripts/playwright-test.mjs @@ -0,0 +1,69 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { test as base, expect } from '@playwright/test'; +import { + checkFocus, + createFocusProbe, + installGuards, + openBackgroundPage, +} from './playwright-runner-focus.mjs'; +import { prepareStaticCapture } from './browser-capture.mjs'; + +export const test = base.extend({ + focusProbe: [ + async ({ headless }, use) => { + const probe = headless ? null : createFocusProbe(); + if (!headless && !probe) + throw new Error( + '焦点状态未确认:当前系统不支持前台窗口探测,请使用 PW_HEADLESS=1', + ); + try { + await use(probe); + } finally { + probe?.dispose(); + } + }, + { scope: 'worker' }, + ], + page: async ({ browser, context, focusProbe, headless }, use, testInfo) => { + if (!headless && process.env.CI && !['0', 'false'].includes(process.env.CI)) + throw new Error('CI requires headless Chrome'); + const page = await openBackgroundPage(browser, context); + const guards = installGuards(browser, context, page); + const screenshot = page.screenshot.bind(page); + page.screenshot = async (options = {}) => { + await prepareStaticCapture(page); + return screenshot({ scale: 'css', ...options }); + }; + try { + await checkFocus(focusProbe, '页面创建后', testInfo); + await use(page); + await checkFocus(focusProbe, '用例结束后', testInfo); + } finally { + guards.restore(); + expect( + guards.violations, + '焦点守护:用例不得新建或切换标签页/窗口', + ).toEqual([]); + } + }, +}); + +export { expect }; diff --git a/scripts/preview-dist.mjs b/scripts/preview-dist.mjs new file mode 100644 index 00000000..df9eb136 --- /dev/null +++ b/scripts/preview-dist.mjs @@ -0,0 +1,41 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { preview } from 'vite'; +import { fileURLToPath } from 'node:url'; +import { positiveInteger } from './playwright-runtime.mjs'; +import { verifyBuild } from './verify-build.mjs'; + +const directory = + process.env.PW_DIST_DIR || + fileURLToPath(new URL('../dist/', import.meta.url)); +const portIndex = process.argv.indexOf('--port'); +const port = positiveInteger( + portIndex === -1 ? 4176 : process.argv[portIndex + 1], + 'port', +); +if (port > 65535) throw new Error('port must be <= 65535'); +await verifyBuild(directory); +const server = await preview({ + build: { outDir: directory }, + preview: { host: '127.0.0.1', port, strictPort: true }, +}); +server.printUrls(); +for (const signal of ['SIGTERM', 'SIGINT']) + process.on(signal, () => server.httpServer.close()); diff --git a/scripts/run-acceptance.mjs b/scripts/run-acceptance.mjs new file mode 100644 index 00000000..8f4dd609 --- /dev/null +++ b/scripts/run-acceptance.mjs @@ -0,0 +1,65 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawn } from 'node:child_process'; +import { verifyBuild } from './verify-build.mjs'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-build-')); +const env = { + ...process.env, + PW_TARGET: 'local-dist', + PW_BASE_URL: 'http://127.0.0.1:4176/', + PW_REQUIRE_ALL: '1', + PW_DIST_DIR: directory, +}; +function run(script, args) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [script, ...args], { + cwd: root, + stdio: 'inherit', + env, + }); + child.on('error', reject); + child.on('exit', (code) => + code === 0 + ? resolve() + : reject(new Error(`${path.basename(script)} failed (${code})`)), + ); + }); +} +try { + await run(path.join(root, 'node_modules/vite/bin/vite.js'), [ + 'build', + '--outDir', + directory, + '--emptyOutDir', + ]); + await verifyBuild(directory); + await run(path.join(root, 'node_modules/@playwright/test/cli.js'), [ + 'test', + ...process.argv.slice(2), + ]); +} finally { + await rm(directory, { recursive: true, force: true }); +} diff --git a/scripts/run-playwright.mjs b/scripts/run-playwright.mjs new file mode 100644 index 00000000..e1ef765e --- /dev/null +++ b/scripts/run-playwright.mjs @@ -0,0 +1,91 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { spawn } from 'node:child_process'; +import { readdir, stat, access } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; + +export async function latestReport(directory) { + const reports = []; + try { + const legacy = await stat(path.join(directory, 'index.html')); + reports.push({ candidate: directory, modified: legacy.mtimeMs }); + } catch { + /* Older runners wrote index.html directly in this directory. */ + } + for (const entry of await readdir(directory, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const candidate = path.join(directory, entry.name); + try { + const info = await stat(path.join(candidate, 'index.html')); + reports.push({ candidate, modified: info.mtimeMs }); + } catch { + /* Incomplete runs have no report to open. */ + } + } + reports.sort((a, b) => b.modified - a.modified); + if (!reports.length) throw new Error('No completed HTML report found'); + return reports[0].candidate; +} + +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + const [mode, ...args] = process.argv.slice(2); + const env = { ...process.env }; + const cli = fileURLToPath( + new URL('../node_modules/@playwright/test/cli.js', import.meta.url), + ); + let command = ['test', ...args]; + if (mode === 'headless') env.PW_HEADLESS = '1'; + else if (mode === 'extended') env.PW_EXTENDED_LAYOUT = '1'; + else if (mode === 'dist') { + env.PW_TARGET = 'local-dist'; + env.PW_BASE_URL = 'http://127.0.0.1:4176/'; + const root = + env.PW_DIST_DIR || fileURLToPath(new URL('../dist/', import.meta.url)); + await access(path.join(root, 'index.html')); + } else if (mode === 'report') { + const explicitDirectory = args[0] && !args[0].startsWith('-'); + const directory = explicitDirectory + ? args[0] + : await latestReport( + fileURLToPath(new URL('../playwright-report/', import.meta.url)), + ); + command = [ + 'show-report', + directory, + ...(explicitDirectory ? args.slice(1) : args), + ]; + } else throw new Error('Expected headless, extended, dist or report'); + const child = spawn(process.execPath, [cli, ...command], { + cwd: fileURLToPath(new URL('../', import.meta.url)), + stdio: 'inherit', + env, + }); + child.on('error', (error) => { + console.error(error); + process.exitCode = 1; + }); + child.on('exit', (code) => { + process.exitCode = code ?? 1; + }); +} diff --git a/scripts/test-playwright-environment.mjs b/scripts/test-playwright-environment.mjs new file mode 100644 index 00000000..6c3cd2a1 --- /dev/null +++ b/scripts/test-playwright-environment.mjs @@ -0,0 +1,86 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { mkdtemp, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { spawn } from 'node:child_process'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const directory = await mkdtemp(path.join(tmpdir(), 'pw-environment-')); +const url = (name) => pathToFileURL(path.join(root, name)).href; +try { + await writeFile( + path.join(directory, 'playwright.config.mjs'), + ` +import config from ${JSON.stringify(url('playwright.config.js'))} +export default { ...config, testDir: ${JSON.stringify(directory)}, testMatch: '**/*.spec.mjs', fullyParallel: false, workers: 1, + outputDir: ${JSON.stringify(root)} + config.outputDir, + reporter: config.reporter.map(([name, options]) => [name.startsWith('.') ? ${JSON.stringify(root)} + name : name, name === 'html' ? { ...options, outputFolder: ${JSON.stringify(root)} + options.outputFolder } : options]), + webServer: config.webServer ? { ...config.webServer, cwd: ${JSON.stringify(root)} } : undefined } +`, + ); + await writeFile( + path.join(directory, 'environment.spec.mjs'), + ` +import { test, expect } from ${JSON.stringify(url('scripts/playwright-test.mjs'))} +import { contextOptions } from ${JSON.stringify(url('scripts/browser-environment.mjs'))} +import { captureStatic } from ${JSON.stringify(url('scripts/browser-capture.mjs'))} +test('设备上下文、触摸、DPR、CSS 截图与稳定字体', async ({ page, baseURL }, info) => { + const expected = contextOptions(info.project.name.replace('chrome-', '')) + await page.route('**/__pw_environment__', route => route.fulfill({ contentType: 'text/html', body: '
环境验证
' })) + await page.goto(new URL('__pw_environment__', baseURL).href) + const actual = await page.evaluate(() => ({ width: innerWidth, height: innerHeight, dpr: devicePixelRatio, ua: navigator.userAgent, touch: navigator.maxTouchPoints > 0, language: navigator.language, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, reduced: matchMedia('(prefers-reduced-motion: reduce)').matches })) + expect(actual).toMatchObject({ width: expected.viewport.width, height: expected.viewport.height, dpr: expected.deviceScaleFactor, touch: expected.hasTouch, language: expected.locale, timezone: expected.timezoneId, reduced: true }) + expect(actual.ua).toBe(expected.userAgent) + const image = await captureStatic(page) + expect(image.readUInt32BE(16)).toBe(expected.viewport.width) + expect(image.readUInt32BE(20)).toBe(expected.viewport.height) + expect((await captureStatic(page)).equals(image)).toBe(true) +}) +`, + ); + const env = { + ...process.env, + PW_HEADLESS: '1', + UI_VISUAL_OFFSCREEN: '1', + PW_EXTENDED_LAYOUT: '1', + PW_WORKERS: '1', + }; + delete env.PW_RUN_ID; + delete env.PLAYWRIGHT_HTML_OUTPUT_DIR; + const code = await new Promise((resolve, reject) => { + const child = spawn( + process.execPath, + [ + path.join(root, 'node_modules/@playwright/test/cli.js'), + 'test', + '--config', + path.join(directory, 'playwright.config.mjs'), + ], + { cwd: root, env, stdio: 'inherit' }, + ); + child.on('error', reject); + child.on('exit', (code) => resolve(code ?? 1)); + }); + process.exitCode = code; +} finally { + await rm(directory, { recursive: true, force: true }); +} diff --git a/scripts/ui-review/config.json b/scripts/ui-review/config.json new file mode 100644 index 00000000..9c81d148 --- /dev/null +++ b/scripts/ui-review/config.json @@ -0,0 +1,19 @@ +{ + "browser": { + "channel": "chrome", + "desktopDevice": "Desktop Chrome", + "mobileDevice": "Pixel 5", + "locale": "zh-CN", + "timezone": "Asia/Shanghai" + }, + "viewports": { + "desktop": [1920, 1080], + "mobile": [360, 800], + "tablet": [768, 1024], + "laptop": [1024, 768], + "hd": [1366, 768], + "wxga": [1440, 900], + "qhd": [2560, 1440], + "uhd": [3840, 2160] + } +} diff --git a/scripts/verify-build.mjs b/scripts/verify-build.mjs new file mode 100644 index 00000000..728d4380 --- /dev/null +++ b/scripts/verify-build.mjs @@ -0,0 +1,56 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { readFile, access } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export async function verifyBuild(directory) { + const root = path.resolve(directory); + const html = await readFile(path.join(root, 'index.html'), 'utf8'); + // Inspect actual resource tags, not URLs embedded in comments or inline scripts. + const markup = html + .replace(//g, '') + .replace(/(]*>)[\s\S]*?<\/script\s*>/gi, '$1'); + const tags = [ + ...markup.matchAll(/<(?:script|link|img|source)\b[^>]*>/gi), + ].map((match) => match[0]); + const assets = tags + .flatMap((tag) => [...tag.matchAll(/\s(?:src|href)\s*=["']([^"']+)["']/g)]) + .map((match) => match[1].split(/[?#]/)[0]) + // The inline brand bootstrap resolves this server placeholder to /logo.svg. + .map((value) => (value === '__WL_BRAND_FAVICON__' ? '/logo.svg' : value)) + .filter((value) => value && !/^(?:[a-z]+:|\/\/|#)/i.test(value)); + if (!assets.some((value) => /\.js$/.test(value))) + throw new Error('Build has no JavaScript entry'); + for (const asset of assets) { + const filename = path.resolve(root, asset.replace(/^\//, '')); + if (!filename.startsWith(root + path.sep)) + throw new Error(`Build asset escapes output directory: ${asset}`); + await access(filename); + } + return { root, assets: assets.length }; +} + +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + console.log(await verifyBuild(process.argv[2] || 'dist')); +} diff --git a/src/pages/Recharge/AmountCard.jsx b/src/pages/Recharge/AmountCard.jsx index dde39d6c..0dde53b9 100644 --- a/src/pages/Recharge/AmountCard.jsx +++ b/src/pages/Recharge/AmountCard.jsx @@ -85,7 +85,6 @@ const AmountCard = ({ {t('{{rate}}折', { rate: formatDiscountRate(discount), - percent: Math.round(100 - discount * 100), })} ) diff --git a/src/pages/Recharge/RechargeV2.jsx b/src/pages/Recharge/RechargeV2.jsx index 948784d7..6cc5a177 100644 --- a/src/pages/Recharge/RechargeV2.jsx +++ b/src/pages/Recharge/RechargeV2.jsx @@ -264,7 +264,6 @@ const RechargeV2 = () => { > {t('{{rate}}折优惠', { rate: (option.discount * 10).toFixed(1), - percent: Math.round(100 - option.discount * 100), })} )} @@ -296,7 +295,6 @@ const RechargeV2 = () => { {t('{{rate}}折', { rate: (payInfo.discount_rate * 10).toFixed(1), - percent: Math.round(100 - payInfo.discount_rate * 100), })} diff --git a/src/pages/Setting/AmountOptionsManager.jsx b/src/pages/Setting/AmountOptionsManager.jsx index a73b1843..71c00ffa 100644 --- a/src/pages/Setting/AmountOptionsManager.jsx +++ b/src/pages/Setting/AmountOptionsManager.jsx @@ -81,7 +81,6 @@ const AmountOptionsManager = ({ render: (v) => t('{{rate}}折', { rate: (v * 10).toFixed(1), - percent: Math.round(100 - v * 100), }), width: 80, }, diff --git a/test/unit/playwright-config.test.js b/test/unit/playwright-config.test.js new file mode 100644 index 00000000..9be5b768 --- /dev/null +++ b/test/unit/playwright-config.test.js @@ -0,0 +1,279 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + runtimeOptions, + positiveInteger, + browserRuntime, +} from '../../scripts/playwright-runtime.mjs'; +import { + contextOptions, + projectViewports, +} from '../../scripts/browser-environment.mjs'; +import { latestReport } from '../../scripts/run-playwright.mjs'; +import { + installGuards, + openBackgroundPage, + checkFocus, +} from '../../scripts/playwright-runner-focus.mjs'; +import { EventEmitter } from 'node:events'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const options = (env) => + runtimeOptions({ defaultPort: 4175, defaultWorkers: 4, env }); + +test('worker counts reject invalid input rather than silently using defaults', () => { + for (const value of [ + '', + '0', + '-1', + '1.5', + '2e2', + ' 2 ', + '1\n', + 'Infinity', + 'NaN', + '01', + '9007199254740992', + null, + false, + [2], + {}, + ]) { + assert.throws(() => options({ PW_WORKERS: value }), /PW_WORKERS.*positive/); + } + assert.equal(options({}).workers, 4); + assert.equal(options({ CI: '1' }).workers, 1); + assert.equal(options({ PW_WORKERS: '2' }).workers, 2); + assert.throws( + () => positiveInteger(undefined, 'resources.concurrency'), + /resources.concurrency/, + ); + assert.throws( + () => positiveInteger(-1, 'resources.concurrency'), + /resources.concurrency/, + ); +}); + +test('headless, offscreen and CI flags enforce the same contract', () => { + assert.equal(options({}).headless, false); + assert.equal(options({}).offscreen, true); + assert.equal(options({ PW_HEADLESS: '1' }).headless, true); + assert.equal(options({ CI: 'false' }).isCI, false); + assert.equal(options({ CI: '0' }).isCI, false); + assert.throws( + () => options({ CI: '1', PW_HEADLESS: '0' }), + /CI requires headless/, + ); + for (const extra of [ + { CI: '1' }, + { PW_HEADLESS: '1' }, + { CODEX_THREAD_ID: 'test-agent' }, + { CLAUDECODE: '1' }, + ]) { + assert.throws( + () => options({ UI_VISUAL_OFFSCREEN: '0', ...extra }), + /only allowed for manual/, + ); + } + for (const key of [ + 'PW_HEADLESS', + 'PW_EXTENDED_LAYOUT', + 'PW_VIDEO', + 'PW_REQUIRE_ALL', + 'UI_VISUAL_OFFSCREEN', + ]) { + assert.throws(() => options({ [key]: 'true' }), /must be 0 or 1/); + } +}); + +test('standalone capture policy does not inherit the runner target or worker strategy', () => { + const capture = browserRuntime({ + PW_TARGET: 'remote', + PW_WORKERS: 'not-a-runner-value', + PW_HEADLESS: '1', + }); + assert.equal(capture.headless, true); + assert.ok(capture.launchArgs.includes('--hide-scrollbars')); +}); + +test('targets and run directories reject ambiguous or unsafe values', () => { + for (const env of [ + { PW_TARGET: 'unknown' }, + { PW_TARGET: 'remote' }, + { PW_BASE_URL: 'https://127.0.0.1:4175/' }, + { PW_BASE_URL: 'http://localhost:4175/' }, + { PW_BASE_URL: 'http://user:pass@127.0.0.1:4175/' }, + { PW_BASE_URL: 'http://127.0.0.1:4175/?v=1' }, + { PW_RUN_ID: '../other' }, + { PW_RUN_ID: '' }, + { PW_RUN_ID: 'a/b' }, + { PW_RUN_ID: 'a\n' }, + ]) + assert.throws(() => options(env)); + const a = options({}), + b = options({}); + assert.notEqual(a.runId, b.runId); + assert.notEqual(a.reportDir, b.reportDir); + assert.equal(options({ PW_RUN_ID: a.runId }).outputDir, a.outputDir); + assert.equal( + options({ PW_TARGET: 'remote', PW_BASE_URL: 'https://example.test/sub/' }) + .baseURL.pathname, + '/sub/', + ); +}); + +test('mobile retains UA, touch and DPR while using the requested CSS viewport', () => { + assert.equal(projectViewports.length, 8); + const mobile = contextOptions('mobile'); + assert.deepEqual(mobile.viewport, { width: 360, height: 800 }); + assert.equal(mobile.deviceScaleFactor, 2.75); + assert.equal(mobile.hasTouch, true); + assert.equal(mobile.isMobile, true); + assert.match(mobile.userAgent, /Mobile/); + assert.equal(contextOptions('tablet').hasTouch, false); +}); + +test('config isolates HTML, JUnit and traces and supports extended projects', () => { + const env = { ...process.env }; + for (const key of Object.keys(env)) + if (/^(PW_|UI_VISUAL_OFFSCREEN$|CI$)/.test(key)) delete env[key]; + const script = `import c from './playwright.config.js'; console.log(JSON.stringify(c))`; + const read = (extra, args = []) => + JSON.parse( + execFileSync( + process.execPath, + ['--input-type=module', '-e', script, '--', ...args], + { + cwd: root, + env: { ...env, ...extra }, + encoding: 'utf8', + stdio: 'pipe', + }, + ), + ); + const base = read({}), + ci = read({ CI: '1', PW_EXTENDED_LAYOUT: '1', PW_WORKERS: '1' }); + assert.equal(base.projects.length, 2); + assert.equal(ci.projects.length, 8); + assert.equal(base.use.headless, false); + assert.equal(ci.use.headless, true); + assert.ok( + ci.reporter + .find(([kind]) => kind === 'junit')[1] + .outputFile.startsWith(ci.outputDir + '/'), + ); + assert.equal( + base.reporter.find(([kind]) => kind === 'html')[1].outputFolder, + `playwright-report/${base.metadata.runId}`, + ); + assert.ok(base.use.launchOptions.args.includes('--hide-scrollbars')); + assert.ok(base.webServer.command.includes('--strictPort')); + assert.deepEqual(read({}, ['--list']).reporter, [['list']]); + assert.throws( + () => read({ CI: '1' }, ['--headed']), + /CI requires headless non-interactive/, + ); +}); + +test('report command finds the latest complete report and ignores incomplete runs', async () => { + const directory = await mkdtemp(path.join(tmpdir(), 'pw-report-test-')); + try { + for (const name of ['older', 'newer', 'incomplete']) + await mkdir(path.join(directory, name)); + for (const name of ['older', 'newer']) + await writeFile(path.join(directory, name, 'index.html'), 'report'); + await utimes(path.join(directory, 'older', 'index.html'), 1, 1); + assert.equal(await latestReport(directory), path.join(directory, 'newer')); + await writeFile(path.join(directory, 'index.html'), 'legacy report'); + await utimes( + path.join(directory, 'index.html'), + Date.now() / 1000 + 10, + Date.now() / 1000 + 10, + ); + assert.equal(await latestReport(directory), directory); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test('focus guard records forbidden calls even if the caller catches the error', async () => { + const browser = { newPage() {}, newContext() {} }, + original = browser.newContext; + const context = new EventEmitter(); + const page = { bringToFront() {} }; + const guard = installGuards(browser, context, page); + for (const call of [ + () => browser.newContext(), + () => browser.newPage(), + () => context.newPage(), + () => page.bringToFront(), + ]) + assert.throws(call, /焦点守护/); + let closed = false; + context.emit('page', { + url: () => 'about:blank', + close: async () => { + closed = true; + }, + }); + assert.equal(closed, true); + assert.equal(guard.violations.length, 5); + guard.restore(); + assert.equal(browser.newContext, original); +}); + +test('background page uses the existing context and rejects ambiguous contexts', async () => { + let parameters; + const cdp = { + send: async (command, args) => + command === 'Target.getBrowserContexts' + ? { browserContextIds: ['one'] } + : (parameters = args), + detach: async () => {}, + }; + const browser = { newBrowserCDPSession: async () => cdp }; + const page = {}; + assert.equal( + await openBackgroundPage(browser, { waitForEvent: async () => page }), + page, + ); + assert.equal(parameters.background, true); + assert.equal(parameters.browserContextId, 'one'); + cdp.send = async () => ({ browserContextIds: ['one', 'two'] }); + await assert.rejects(openBackgroundPage(browser, {}), /无法唯一确定/); +}); + +test('foreground activation or an unknown probe stops the run after recording evidence', async () => { + for (const state of [null, { parentPid: process.pid }]) { + const info = { annotations: [], titlePath: ['guard test'] }; + await assert.rejects( + checkFocus({ query: async () => state }, '页面创建后', info), + /焦点/, + ); + assert.equal(info.annotations.length, 1); + } +}); diff --git a/test/unit/playwright-focus-guard.test.js b/test/unit/playwright-focus-guard.test.js new file mode 100644 index 00000000..07247bf9 --- /dev/null +++ b/test/unit/playwright-focus-guard.test.js @@ -0,0 +1,122 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import test from 'node:test'; +import { + FOCUS_EVENTS, + FOCUS_SAFE_ARGS, + FocusGuardError, + classifyFocus, + createFocusLog, + installFocusGuards, + parseForegroundOutput, +} from '../../scripts/playwright-focus-guard.mjs'; + +test('focus-safe args keep the window offscreen and unthrottled', () => { + for (const arg of [ + '--window-position=-32000,-32000', + '--disable-backgrounding-occluded-windows', + '--disable-renderer-backgrounding', + '--disable-background-timer-throttling', + ]) + assert.ok(FOCUS_SAFE_ARGS.includes(arg), arg); + assert.ok(Object.isFrozen(FOCUS_SAFE_ARGS)); +}); + +test('guards forbid newPage / bringToFront and close unexpected pages', async () => { + const context = new EventEmitter(); + context.newPage = async () => 'opened'; + const page = { bringToFront: async () => 'front' }; + const extra = { + closed: false, + url: () => 'https://example.test/popup', + close: async () => { + extra.closed = true; + }, + }; + const log = createFocusLog(() => {}); + const remove = installFocusGuards(context, page, log); + + await assert.rejects(context.newPage(), FocusGuardError); + await assert.rejects(page.bringToFront(), FocusGuardError); + context.emit('page', page); + context.emit('page', extra); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(extra.closed, true); + assert.deepEqual( + log.entries.map((entry) => entry.type), + [FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.EXTRA_PAGE], + ); + + remove(); + assert.equal(await context.newPage(), 'opened'); + assert.equal(context.listenerCount('page'), 0); +}); + +test('startup activation is logged; only a later background-to-foreground transition is fatal', () => { + assert.deepEqual( + classifyFocus({ + phase: 'startup', + previous: 'background', + current: 'foreground', + }), + { event: FOCUS_EVENTS.STARTUP, fatal: false }, + ); + assert.deepEqual( + classifyFocus({ + phase: 'running', + previous: 'foreground', + current: 'foreground', + }), + { event: FOCUS_EVENTS.STARTUP_PERSIST, fatal: false }, + ); + assert.deepEqual( + classifyFocus({ + phase: 'running', + previous: 'background', + current: 'foreground', + }), + { event: FOCUS_EVENTS.REACTIVATED, fatal: true }, + ); + assert.deepEqual( + classifyFocus({ + phase: 'running', + previous: 'background', + current: 'unknown', + }), + { event: FOCUS_EVENTS.UNKNOWN, fatal: true }, + ); + assert.deepEqual( + classifyFocus({ + phase: 'running', + previous: 'background', + current: 'background', + }), + { event: null, fatal: false }, + ); +}); + +test('foreground probe output maps to background, foreground or unknown', () => { + assert.equal(parseForegroundOutput('100|200,300\r\n').state, 'background'); + assert.equal(parseForegroundOutput('300|200,300').state, 'foreground'); + assert.equal(parseForegroundOutput('300|').state, 'unknown'); + assert.equal(parseForegroundOutput('garbled').state, 'unknown'); +}); diff --git a/test/unit/playwright-preview.test.js b/test/unit/playwright-preview.test.js new file mode 100644 index 00000000..53d2e4e9 --- /dev/null +++ b/test/unit/playwright-preview.test.js @@ -0,0 +1,103 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createServer } from 'node:net'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { verifyBuild } from '../../scripts/verify-build.mjs'; + +test('static build validation rejects missing entry resources', async () => { + const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-preview-')); + try { + await assert.rejects(verifyBuild(directory), /ENOENT/); + await writeFile( + path.join(directory, 'index.html'), + '', + ); + await assert.rejects(verifyBuild(directory), /ENOENT/); + await mkdir(path.join(directory, 'assets')); + await writeFile(path.join(directory, 'assets/app.js'), 'export {}'); + assert.equal((await verifyBuild(directory)).assets, 1); + await writeFile(path.join(directory, 'logo.svg'), ''); + await writeFile( + path.join(directory, 'index.html'), + '', + ); + assert.equal((await verifyBuild(directory)).assets, 2); + await writeFile( + path.join(directory, 'index.html'), + '', + ); + await assert.rejects(verifyBuild(directory), /escapes output/); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test('preview refuses an occupied port instead of silently choosing the next port', async () => { + const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-preview-')); + const blocker = createServer(); + try { + await writeFile( + path.join(directory, 'index.html'), + '', + ); + await writeFile(path.join(directory, 'app.js'), 'export {}'); + await new Promise((resolve) => blocker.listen(0, '127.0.0.1', resolve)); + const port = blocker.address().port; + const result = await new Promise((resolve, reject) => { + const child = spawn( + process.execPath, + [ + fileURLToPath( + new URL('../../scripts/preview-dist.mjs', import.meta.url), + ), + '--port', + String(port), + ], + { + cwd: fileURLToPath(new URL('../../', import.meta.url)), + env: { ...process.env, PW_DIST_DIR: directory }, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + timeout: 20000, + }, + ); + let output = ''; + child.stdout.on('data', (chunk) => { + output += chunk; + }); + child.stderr.on('data', (chunk) => { + output += chunk; + }); + child.on('error', reject); + child.on('close', (code) => resolve({ code, output })); + }); + assert.notEqual(result.code, 0); + assert.match(result.output, /already in use/); + } finally { + await new Promise((resolve) => blocker.close(resolve)); + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/tests/environment.test.js b/tests/environment.test.js index 22915a21..b65711a3 100644 --- a/tests/environment.test.js +++ b/tests/environment.test.js @@ -122,10 +122,15 @@ test('checked-in defaults preserve same-origin behavior and disable analytics', }); test('development server transforms the HTML and runtime configuration modules', async () => { + // Inline `watch: null` is dropped when merged with the config file, so pass the + // loaded config directly; otherwise chokidar keeps the test process alive. + const userConfig = await config(root, 'development'); const server = await createServer({ + ...userConfig, + configFile: false, root, cacheDir: path.join(root, '.cache/vite-environment-test'), - server: { middlewareMode: true }, + server: { ...userConfig.server, middlewareMode: true, watch: null }, optimizeDeps: { noDiscovery: true, include: [] }, }); try { @@ -166,6 +171,7 @@ test('Vite proxies API requests on Node 22 without DEP0060', async () => { server: { host: '127.0.0.1', port: 0, + watch: null, proxy: { '/api': { target: `http://127.0.0.1:${upstream.address().port}`,