feat: 客户端灵动岛 + 上课时段紧急通知二次确认,并修复打包/校验脚本在 Electron 宿主下的多个缺陷
## 客户端灵动岛(动态岛)
- 新增独立透明置顶窗口:桌面中上方常驻、不占任务栏、不抢焦点(268x44 胶囊 / 404x316 详情 / 424x344 紧急)
- 三种形态与动画:隐藏 ↔ 胶囊 ↔ 详情,尺寸用 easeOutCubic 260ms 逐帧缓动、透明度单独淡入淡出
(尺寸与淡入使用各自动画令牌,避免互相打断导致窗口卡在胶囊尺寸)
- 行为:普通通知变「新消息 · 共 N 条」胶囊,点击展开详情;上课时段自动隐藏并进入待发队列,
下课后自动弹出;紧急通知无论是否上课立即展开(红色呼吸光晕 + 紧急角标,无需点击)
- 上课状态来自 GET /api/schedules/current(10s 心跳 + 下课时长定时器),
新增 src/main/island.ts(控制器/IPC)、src/preload/island.ts、src/island/IslandApp.vue、
src/renderer/island/bridge.ts、island.html 与多页 Vite 构建
## 上课时段发布紧急通知的二次确认
- 服务端:priority=URGENT 且当前处于上课时间段且未带 confirmDuringClass 时返回
409 URGENT_DURING_CLASS(携带 current/next/week/serverTime),绕过界面调接口同样被拦截
- 新增 GET /api/schedules/current(inClass/current/next,at 参数用于诊断与测试)
- Web 管理端:全屏警告遮罩(UrgentClassWarning.vue),显示正在上的课时段与待发布标题,
确认按钮带 3 秒倒计时(圆环进度,倒计时结束前禁用),取消即不发;并发命中 409 同样兜底弹窗
## 打包与验证脚本修复(Electron 宿主环境)
- scripts/lib/node-runtime.mjs:定位真正的 node.exe。此前经 pnpm 运行时 process.execPath 指向
Electron,dist:server 会把 Electron 复制成安装包内的 node.exe,dist:win 会让 electron-builder 报
Unknown argument: .../cli.js(改为显式使用真实 Node)
- scripts/lib/electron-env.mjs:启动 Electron 前清理继承的 ELECTRON_RUN_AS_NODE(否则 Electron 退化为
纯 Node,require('electron') 直接 MODULE_NOT_FOUND),并从 path.txt 定位 electron.exe
(process.versions.electron 存在时 import 'electron' 返回的是 API 对象而非路径)
- scripts/dist-server.mjs:新增构建产物新鲜度校验(曾出现 server 已重建但打进安装包的 shared/dist 是旧的,
安装后服务启动即报 does not provide an export named MAX_TERM_WEEK)
- scripts/ui-smoke:新增 live-probe.mjs 真实制造/清理上课时段,Electron 驱动真实点击断言全屏警告文案、
按钮禁用与 3 秒倒计时时长(实测 2966ms),测试后自动删除探针课表与测试通知
## 验证结果
- pnpm verify:e2e 62/62(新增上课时段拦截、二次确认后发布、普通通知不受限等 8 项)
- pnpm verify:web 8/8(新增上课时段紧急通知全屏警告 + 倒计时)
- pnpm verify:desktop 18/18(新增灵动岛窗口/上课隐藏/下课弹出/紧急立即展开/胶囊点击展开 + 截图)
- 打包后 EXE 冒烟 15/15(packaged: true,退出码 0)
- 服务端安装程序升级安装:.env 与数据库保持不变,/api/schedules/current 正常
- pnpm lint / format:check / typecheck 全部通过
This commit is contained in:
1 parent
5545ef6f55
commit
3a9f8812fc
40 files changed
+3062
-149
No files matched your search
+42
-5
@@ -17,6 +17,7 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveNodeRuntime } from './lib/node-runtime.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const serverDir = path.join(root, 'packages', 'server');
|
||||
@@ -47,13 +48,49 @@ const run = (command, args, options = {}) => {
|
||||
function ensureBuilds() {
|
||||
const serverEntry = path.join(serverDir, 'dist', 'index.js');
|
||||
const webEntry = path.join(webDir, 'dist', 'index.html');
|
||||
const sharedEntry = path.join(root, 'packages', 'shared', 'dist', 'index.js');
|
||||
const missing = [];
|
||||
if (!fs.existsSync(sharedEntry)) missing.push('packages/shared/dist(请先 pnpm build:shared)');
|
||||
if (!fs.existsSync(serverEntry))
|
||||
missing.push('packages/server/dist(请先 pnpm --filter @classhelper/server build)');
|
||||
if (!fs.existsSync(webEntry))
|
||||
missing.push('packages/web-admin/dist(请先 pnpm --filter @classhelper/web-admin build)');
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`缺少构建产物:\n - ${missing.join('\n - ')}`);
|
||||
throw new Error(`缺少构建产物:\n - ${missing.join('\n - ')}\n建议直接执行:pnpm dist:server`);
|
||||
}
|
||||
|
||||
// 新鲜度校验:曾出现过"改动只重新构建了 server,却把旧的 shared/dist 打进安装包",
|
||||
// 结果安装后服务启动即报 "does not provide an export named ..."。这里直接拦住。
|
||||
const newestSource = (dir) => {
|
||||
let newest = 0;
|
||||
const walk = (current) => {
|
||||
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
||||
const full = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(full);
|
||||
else newest = Math.max(newest, fs.statSync(full).mtimeMs);
|
||||
}
|
||||
};
|
||||
if (fs.existsSync(dir)) walk(dir);
|
||||
return newest;
|
||||
};
|
||||
|
||||
const stale = [];
|
||||
const sharedSourceTime = newestSource(path.join(root, 'packages', 'shared', 'src'));
|
||||
const sharedBuildTime = fs.statSync(path.join(root, 'packages', 'shared', 'dist', 'index.js')).mtimeMs;
|
||||
if (sharedSourceTime > sharedBuildTime) stale.push('packages/shared(src 比 dist 新)');
|
||||
|
||||
const serverSourceTime = newestSource(path.join(serverDir, 'src'));
|
||||
const serverBuildTime = fs.statSync(serverEntry).mtimeMs;
|
||||
if (serverSourceTime > serverBuildTime) stale.push('packages/server(src 比 dist 新)');
|
||||
|
||||
const webSourceTime = newestSource(path.join(webDir, 'src'));
|
||||
const webBuildTime = fs.statSync(webEntry).mtimeMs;
|
||||
if (webSourceTime > webBuildTime) stale.push('packages/web-admin(src 比 dist 新)');
|
||||
|
||||
if (stale.length > 0) {
|
||||
throw new Error(
|
||||
`构建产物已过期:\n - ${stale.join('\n - ')}\n请重新构建(推荐直接执行:pnpm dist:server)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,10 +181,10 @@ function buildRuntime() {
|
||||
// Web 管理端
|
||||
copyRecursive(path.join(webDir, 'dist'), path.join(staging, 'web'));
|
||||
|
||||
// Node 运行时
|
||||
const nodeExe = process.execPath;
|
||||
copyRecursive(nodeExe, path.join(staging, 'node.exe'));
|
||||
log(`内置 Node 运行时:${nodeExe}`);
|
||||
// Node 运行时(必须是真正的 node.exe,不能用宿主 Electron 可执行文件)
|
||||
const nodeRuntime = resolveNodeRuntime();
|
||||
copyRecursive(nodeRuntime.path, path.join(staging, 'node.exe'));
|
||||
log(`内置 Node 运行时:${nodeRuntime.path}(${nodeRuntime.version})`);
|
||||
|
||||
// 数据目录:强制清空,避免把打包机上测试用的数据库带进安装包
|
||||
fs.rmSync(path.join(staging, 'data'), { recursive: true, force: true });
|
||||
|
||||
@@ -6,6 +6,7 @@ import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveElectronEnv, resolveElectronExecutable } from './lib/electron-env.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const electronDir = path.join(root, 'packages', 'desktop-client', 'node_modules', 'electron');
|
||||
@@ -15,15 +16,12 @@ if (!fs.existsSync(electronDir)) {
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const pathFile = path.join(electronDir, 'path.txt');
|
||||
const executable = fs.existsSync(pathFile)
|
||||
? path.join(electronDir, 'dist', fs.readFileSync(pathFile, 'utf8').trim())
|
||||
: path.join(electronDir, 'dist', 'electron.exe');
|
||||
const executable = resolveElectronExecutable(electronDir);
|
||||
|
||||
const child = spawn(executable, [path.join(root, 'scripts', 'icons', 'render.cjs')], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
env: resolveElectronEnv(),
|
||||
});
|
||||
|
||||
child.on('exit', (code) => process.exit(code ?? 1));
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 启动 Electron 应用时的公共辅助:环境变量清理 + 可执行文件定位。
|
||||
*
|
||||
* 背景(本机真实踩过的两个坑,都发生在"宿主终端本身就是 Electron"的场景,
|
||||
* 例如 DSH 桌面端内置终端 / VS Code 扩展宿主):
|
||||
*
|
||||
* 1. 宿主会带着 `ELECTRON_RUN_AS_NODE=1` 运行子进程(本机的 `pnpm` 运行在
|
||||
* Electron 内置 Node 上,因此经过 `pnpm run` 的脚本都会带着它)。
|
||||
* 该变量会一路继承到我们用 `spawn` 拉起的 Electron 上,使其**退化成纯 Node**:
|
||||
* `process.versions.electron` 仍在,但 `require('electron')` 抛 MODULE_NOT_FOUND,
|
||||
* 表现为"冒烟测试/开发模式一启动就报 Cannot find module 'electron'"。
|
||||
* 2. 同样因为 `process.versions.electron` 存在,`require('electron')` / `import electronPath
|
||||
* from 'electron'` 返回的是 **API 对象而不是可执行文件路径**,直接 spawn 会报
|
||||
* `ERR_INVALID_ARG_TYPE: The "file" argument must be of type string`。
|
||||
*
|
||||
* 因此:启动 Electron 一律用 `resolveElectronEnv()` + `resolveElectronExecutable()`,
|
||||
* 不要直接 import 'electron'。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** 清掉会让 Electron 退化成纯 Node 的继承变量,可附加自定义变量 */
|
||||
export function resolveElectronEnv(extra = {}) {
|
||||
const env = { ...process.env, ...extra };
|
||||
delete env.ELECTRON_RUN_AS_NODE;
|
||||
delete env.ELECTRON_NO_ATTACH_CONSOLE;
|
||||
return env;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由 `node_modules/electron` 目录定位真正的 Electron 可执行文件。
|
||||
* @param {string} electronDir `node_modules/electron` 的绝对路径
|
||||
*/
|
||||
export function resolveElectronExecutable(electronDir) {
|
||||
const pathFile = path.join(electronDir, 'path.txt');
|
||||
const binaryName = fs.existsSync(pathFile)
|
||||
? fs.readFileSync(pathFile, 'utf8').trim()
|
||||
: process.platform === 'win32'
|
||||
? 'electron.exe'
|
||||
: 'electron';
|
||||
return path.join(electronDir, 'dist', binaryName);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 定位"真正的 Node 运行时"。
|
||||
*
|
||||
* 为什么需要它:本机的 `pnpm` 运行在 Electron 内置的 Node 上(宿主终端本身是 Electron 应用,
|
||||
* 例如 DSH 桌面端内置终端)。此时 `process.execPath` 指向 **Electron 可执行文件**,
|
||||
* 用它去跑 Node CLI 会得到两种典型故障:
|
||||
*
|
||||
* 1. 没有 `ELECTRON_RUN_AS_NODE=1` 时:Electron 把脚本当成"应用入口"启动,
|
||||
* `process.argv` 里多出一个位置参数 —— 例如 electron-builder 直接报
|
||||
* `Unknown argument: .../electron-builder/out/cli/cli.js`。
|
||||
* 2. 有该变量时虽然能跑,但会把 Electron 当成 Node 复制进安装包,
|
||||
* 目标机上 `node.exe` 其实是 Electron,服务根本起不来。
|
||||
*
|
||||
* 因此凡是"需要纯 Node 去执行脚本"的地方(打包 CLI、内置运行时分发),
|
||||
* 都用 `resolveNodeRuntime()` 拿一个真实的 node 可执行文件。
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** 判断候选可执行文件能否以"纯 Node 身份"运行 */
|
||||
function isNodeRuntime(candidate) {
|
||||
const probe = spawnSync(
|
||||
candidate,
|
||||
['-e', "process.stdout.write(process.versions.electron ? 'electron' : 'node')"],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
timeout: 20_000,
|
||||
// 若候选其实是 Electron,则让它以 Node 模式运行,避免真的弹出应用窗口
|
||||
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
||||
},
|
||||
);
|
||||
const kind = String(probe.stdout ?? '').trim();
|
||||
return { ok: probe.status === 0 && kind === 'node', kind: kind || probe.error?.message || '未知' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回 `{ path, version }`;找不到时抛错(附带尝试过的候选,便于排查)。
|
||||
* @param {{ extraCandidates?: string[] }} [options]
|
||||
*/
|
||||
export function resolveNodeRuntime(options = {}) {
|
||||
const candidates = [];
|
||||
const push = (value) => {
|
||||
if (value && !candidates.includes(value)) candidates.push(value);
|
||||
};
|
||||
|
||||
// 1) 显式覆盖(打包机/CI 容易配置)
|
||||
push(process.env.CLASSHELPER_NODE_EXE);
|
||||
push(process.env.NODE_EXE);
|
||||
|
||||
// 2) 当前进程本身就是 node.exe 时直接复用
|
||||
if (path.basename(process.execPath).toLowerCase() === 'node.exe') push(process.execPath);
|
||||
|
||||
for (const candidate of options.extraCandidates ?? []) push(candidate);
|
||||
|
||||
// 3) PATH 中的 node(where node / which node)
|
||||
try {
|
||||
const finder = process.platform === 'win32' ? 'where' : 'which';
|
||||
const found = spawnSync(finder, ['node'], { encoding: 'utf8' });
|
||||
if (found.status === 0) {
|
||||
for (const line of String(found.stdout ?? '').split(/\r?\n/)) push(line.trim());
|
||||
}
|
||||
} catch {
|
||||
/* 忽略:继续尝试常见安装路径 */
|
||||
}
|
||||
|
||||
// 4) 常见安装路径
|
||||
push(path.join(process.env.ProgramFiles ?? 'C:\\Program Files', 'nodejs', 'node.exe'));
|
||||
push(path.join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'nodejs', 'node.exe'));
|
||||
push(path.join(process.env.LOCALAPPDATA ?? '', 'Programs', 'nodejs', 'node.exe'));
|
||||
push(path.join(process.env.NVM_SYMLINK ?? '', 'node.exe'));
|
||||
push(path.join(process.env.APPDATA ?? '', 'nvm', 'current', 'node.exe'));
|
||||
push('D:\\node.js\\node.exe');
|
||||
push('/usr/local/bin/node');
|
||||
push('/usr/bin/node');
|
||||
|
||||
const rejected = [];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (!fs.statSync(candidate).isFile()) continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
const verdict = isNodeRuntime(candidate);
|
||||
if (verdict.ok) {
|
||||
const version = spawnSync(candidate, ['--version'], { encoding: 'utf8' }).stdout?.trim() ?? '';
|
||||
return { path: candidate, version };
|
||||
}
|
||||
rejected.push(`${candidate}(${verdict.kind})`);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
'未找到可用的 Node 运行时。\n' +
|
||||
` 已尝试:\n - ${rejected.join('\n - ') || '(无候选)'}\n` +
|
||||
' 请安装 Node.js,或用环境变量 CLASSHELPER_NODE_EXE 指定 node.exe 的完整路径。',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* UI 冒烟测试用「真实上课时段探针」。
|
||||
*
|
||||
* 为了验证「上课时段发布紧急通知 → 全屏警告 + 3 秒倒计时」这条链路,
|
||||
* 测试必须先让服务端真实认定"现在正在上课"。本模块直接用 HTTP 调后端接口:
|
||||
*
|
||||
* 1. 登录(拿到 token)
|
||||
* 2. 取该教师第一个班级 + 该班级第一门课程
|
||||
* 3. 新建一条"今天 00:00-23:59、第 1-30 教学周"的课表 —— 覆盖当前时刻
|
||||
* 4. 调 /api/schedules/current 确认服务端确实返回 inClass = true
|
||||
*
|
||||
* 测试结束后 cleanup 会删除这条探针课表,并删除本次测试发布的通知,
|
||||
* 保证不污染演示数据。
|
||||
*
|
||||
* 注意:这里只使用 Node 内置 fetch(Node 20+),不引入额外依赖。
|
||||
*/
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
|
||||
async function call(baseUrl, path, { method = 'GET', token, body } = {}) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
method,
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
...(body ? { 'content-type': 'application/json' } : {}),
|
||||
...(token ? { authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
const text = await response.text();
|
||||
let payload = null;
|
||||
try {
|
||||
payload = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
payload = { raw: text.slice(0, 200) };
|
||||
}
|
||||
return { status: response.status, payload };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** 今天对应的课表星期(1=周一 … 7=周日) */
|
||||
function todayDayOfWeek(now = new Date()) {
|
||||
const weekday = now.getDay();
|
||||
return weekday === 0 ? 7 : weekday;
|
||||
}
|
||||
|
||||
/**
|
||||
* 制造一次真实的上课时段。
|
||||
* @returns {Promise<{token: string, classId: string, className: string, courseId: string,
|
||||
* scheduleId: string, inClass: boolean, period: object|null}>}
|
||||
*/
|
||||
export async function setupInClassProbe({ baseUrl, username = 'teacher1', password = 'teacher123' } = {}) {
|
||||
const base = (baseUrl ?? 'http://127.0.0.1:4000').replace(/\/$/, '');
|
||||
|
||||
const login = await call(base, '/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: { username, password },
|
||||
});
|
||||
const token = login.payload?.data?.token;
|
||||
if (login.status !== 200 || !token) {
|
||||
throw new Error(`探针登录失败:HTTP ${login.status} ${JSON.stringify(login.payload)?.slice(0, 160)}`);
|
||||
}
|
||||
|
||||
const classes = await call(base, '/api/classes', { token });
|
||||
const targetClass = Array.isArray(classes.payload?.data) ? classes.payload.data[0] : null;
|
||||
if (!targetClass) throw new Error('探针失败:该教师名下没有班级,无法制造上课时段');
|
||||
|
||||
const courses = await call(base, `/api/courses?classId=${encodeURIComponent(targetClass.id)}`, {
|
||||
token,
|
||||
});
|
||||
const targetCourse = Array.isArray(courses.payload?.data) ? courses.payload.data[0] : null;
|
||||
if (!targetCourse) throw new Error(`探针失败:班级「${targetClass.name}」没有课程,无法制造上课时段`);
|
||||
|
||||
const schedule = await call(base, '/api/schedules', {
|
||||
method: 'POST',
|
||||
token,
|
||||
body: {
|
||||
classId: targetClass.id,
|
||||
courseId: targetCourse.id,
|
||||
dayOfWeek: todayDayOfWeek(),
|
||||
startTime: '00:00',
|
||||
endTime: '23:59',
|
||||
weekStart: 1,
|
||||
weekEnd: 30,
|
||||
location: 'UI 冒烟探针',
|
||||
},
|
||||
});
|
||||
const scheduleId = schedule.payload?.data?.id;
|
||||
if (schedule.status !== 201 || !scheduleId) {
|
||||
throw new Error(
|
||||
`探针失败:创建课表返回 HTTP ${schedule.status} ${JSON.stringify(schedule.payload)?.slice(0, 200)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const status = await call(base, `/api/schedules/current?classId=${encodeURIComponent(targetClass.id)}`, {
|
||||
token,
|
||||
});
|
||||
|
||||
return {
|
||||
baseUrl: base,
|
||||
token,
|
||||
classId: targetClass.id,
|
||||
className: targetClass.name,
|
||||
courseId: targetCourse.id,
|
||||
scheduleId,
|
||||
inClass: Boolean(status.payload?.data?.inClass),
|
||||
period: status.payload?.data?.current ?? null,
|
||||
statusCode: status.status,
|
||||
};
|
||||
}
|
||||
|
||||
/** 删除探针课表 + 本次测试发布的通知,恢复原始数据 */
|
||||
export async function cleanupInClassProbe(probe, { notificationTitle } = {}) {
|
||||
const removed = [];
|
||||
if (!probe?.baseUrl || !probe?.token) return removed;
|
||||
|
||||
if (notificationTitle) {
|
||||
const list = await call(
|
||||
probe.baseUrl,
|
||||
`/api/notifications?classId=${encodeURIComponent(probe.classId)}&keyword=${encodeURIComponent(notificationTitle)}`,
|
||||
{ token: probe.token },
|
||||
);
|
||||
const matched = Array.isArray(list.payload?.data)
|
||||
? list.payload.data.filter((item) => item.title === notificationTitle)
|
||||
: [];
|
||||
for (const item of matched) {
|
||||
const result = await call(probe.baseUrl, `/api/notifications/${item.id}`, {
|
||||
method: 'DELETE',
|
||||
token: probe.token,
|
||||
});
|
||||
if (result.status === 200) removed.push(`notification:${item.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (probe.scheduleId) {
|
||||
const result = await call(probe.baseUrl, `/api/schedules/${probe.scheduleId}`, {
|
||||
method: 'DELETE',
|
||||
token: probe.token,
|
||||
});
|
||||
if (result.status === 200) removed.push(`schedule:${probe.scheduleId}`);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
+132
-2
@@ -7,6 +7,10 @@
|
||||
* 3. 进入主布局
|
||||
* 4. **侧边栏 7 个菜单逐一点击**:断言路由路径变化 + 页面标题渲染
|
||||
* —— 这是"点击左侧边栏没反应"的回归测试
|
||||
* 5. **上课时段发布紧急通知**:全屏警告 + 3 秒倒计时 + 确认后才真正发布
|
||||
* —— 上课时段由 run.mjs 的探针(今天 00:00-23:59 的课表)真实制造
|
||||
* 6. 前端路由深链直接访问
|
||||
* 7. PWA manifest + Service Worker(浏览器可安装为应用)
|
||||
*
|
||||
* 用法(需要后端已启动,且 Web 管理端由其托管):
|
||||
* UI_SMOKE_URL=http://127.0.0.1:4000/ node scripts/ui-smoke/run.mjs
|
||||
@@ -169,7 +173,133 @@ async function main() {
|
||||
`visited=[${visited.join(' ')}]${failures.length > 0 ? ` failures=${failures.join(';')}` : ''}`,
|
||||
);
|
||||
|
||||
// 5. SPA 深链刷新(生产环境静态托管必须支持)
|
||||
// 5. 上课时段发布紧急通知:全屏警告 + 3 秒倒计时 + 教师确认后才真正发布
|
||||
// "上课时段"由 run.mjs 的探针提前用 HTTP 建好(今天 00:00-23:59 的课表)
|
||||
const urgentTitle = process.env.UI_SMOKE_URGENT_TITLE ?? 'UI 冒烟紧急通知';
|
||||
const inClass = process.env.UI_SMOKE_INCLASS === '1';
|
||||
if (!inClass) {
|
||||
record(
|
||||
'上课时段发布紧急通知(全屏警告 + 3 秒倒计时)',
|
||||
false,
|
||||
`未能制造上课时段:${process.env.UI_SMOKE_PROBE_DETAIL || '未知原因'}`,
|
||||
);
|
||||
} else {
|
||||
const urgent = await win.webContents.executeJavaScript(`(async () => {
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const waitFor = async (check, timeout = 8000) => {
|
||||
const deadline = Date.now() + timeout;
|
||||
while (Date.now() < deadline) {
|
||||
const value = check();
|
||||
if (value) return value;
|
||||
await sleep(80);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const byText = (nodes, text) =>
|
||||
Array.from(nodes).find((node) => (node.textContent ?? '').trim().includes(text));
|
||||
const setValue = (element, value) => {
|
||||
const proto = element.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(proto, 'value').set.call(element, value);
|
||||
element.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
element.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
};
|
||||
const formItem = (dialog, label) =>
|
||||
Array.from(dialog.querySelectorAll('.el-form-item')).find((item) =>
|
||||
(item.querySelector('.el-form-item__label')?.textContent ?? '').trim().startsWith(label),
|
||||
);
|
||||
|
||||
const menu = byText(document.querySelectorAll('.el-menu-item'), '通知发布');
|
||||
if (!menu) return { ok: false, detail: '侧边栏未找到"通知发布"菜单' };
|
||||
menu.click();
|
||||
if (!(await waitFor(() => location.pathname === '/notifications')))
|
||||
return { ok: false, detail: '未跳转到 /notifications' };
|
||||
|
||||
const openButton = await waitFor(() => byText(document.querySelectorAll('button'), '发布通知'));
|
||||
if (!openButton) return { ok: false, detail: '未找到"发布通知"按钮' };
|
||||
openButton.click();
|
||||
|
||||
const dialog = await waitFor(() => document.querySelector('.el-dialog'));
|
||||
if (!dialog) return { ok: false, detail: '发布通知弹窗未打开' };
|
||||
|
||||
const titleItem = formItem(dialog, '标题');
|
||||
const contentItem = formItem(dialog, '内容');
|
||||
if (!titleItem || !contentItem) return { ok: false, detail: '弹窗表单缺少标题/内容字段' };
|
||||
setValue(titleItem.querySelector('input'), ${JSON.stringify(urgentTitle)});
|
||||
setValue(contentItem.querySelector('textarea'), '自动化校验:本节课紧急通知二次确认流程');
|
||||
|
||||
const urgentRadio = byText(dialog.querySelectorAll('.el-radio-button'), '紧急');
|
||||
if (!urgentRadio) return { ok: false, detail: '未找到"紧急"优先级选项' };
|
||||
(urgentRadio.querySelector('.el-radio-button__inner') ?? urgentRadio).click();
|
||||
const radioActive = await waitFor(() => {
|
||||
const node = byText(dialog.querySelectorAll('.el-radio-button'), '紧急');
|
||||
return Boolean(node && node.classList.contains('is-active'));
|
||||
});
|
||||
if (!radioActive) return { ok: false, detail: '"紧急"优先级未选中' };
|
||||
|
||||
const publish = byText(dialog.querySelectorAll('.el-dialog__footer button'), '立即发布');
|
||||
if (!publish) return { ok: false, detail: '未找到"立即发布"按钮' };
|
||||
publish.click();
|
||||
|
||||
const mask = await waitFor(() => document.querySelector('.urgent-mask'), 10000);
|
||||
if (!mask) return { ok: false, detail: '上课时段发布紧急通知未弹出全屏警告' };
|
||||
|
||||
const maskText = (mask.textContent ?? '').replace(/\\s+/g, ' ').trim();
|
||||
const periodText = (mask.querySelector('.urgent-period .period-value')?.textContent ?? '').trim();
|
||||
const dangerButton = mask.querySelector('.urgent-actions button.el-button--danger');
|
||||
if (!dangerButton) return { ok: false, detail: '全屏警告缺少确认按钮' };
|
||||
const disabledAtStart = dangerButton.disabled === true;
|
||||
const startText = (dangerButton.textContent ?? '').trim();
|
||||
|
||||
const startedAt = Date.now();
|
||||
const enabled = await waitFor(() => {
|
||||
const node = document.querySelector('.urgent-mask .urgent-actions button.el-button--danger');
|
||||
return Boolean(node && node.disabled !== true);
|
||||
}, 9000);
|
||||
const countdownMs = Date.now() - startedAt;
|
||||
if (!enabled) return { ok: false, detail: '倒计时结束后确认按钮仍未可用' };
|
||||
|
||||
document.querySelector('.urgent-mask .urgent-actions button.el-button--danger').click();
|
||||
|
||||
const closed = await waitFor(() => !document.querySelector('.urgent-mask'), 6000);
|
||||
const listed = await waitFor(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('.el-table__body td')).some((cell) =>
|
||||
(cell.textContent ?? '').includes(${JSON.stringify(urgentTitle)}),
|
||||
),
|
||||
10000,
|
||||
);
|
||||
|
||||
return {
|
||||
ok: Boolean(closed && listed),
|
||||
detail: closed
|
||||
? listed
|
||||
? ''
|
||||
: '确认后警告已关闭,但通知列表未出现该通知'
|
||||
: '点击确认后全屏警告未关闭',
|
||||
maskText,
|
||||
periodText,
|
||||
disabledAtStart,
|
||||
startText,
|
||||
countdownMs,
|
||||
};
|
||||
})()`);
|
||||
|
||||
record(
|
||||
'上课时段发布紧急通知(全屏警告 + 3 秒倒计时)',
|
||||
Boolean(urgent?.ok) &&
|
||||
Boolean(urgent?.maskText?.includes('现在为上课时间段')) &&
|
||||
Boolean(urgent?.periodText) &&
|
||||
urgent?.disabledAtStart === true &&
|
||||
Number(urgent?.countdownMs) >= 1500,
|
||||
urgent
|
||||
? `警告文案="${urgent.maskText?.slice(0, 60)}…" 上课时段=${urgent.periodText} ` +
|
||||
`初始按钮="${urgent.startText}"(禁用=${urgent.disabledAtStart}) ` +
|
||||
`倒计时=${urgent.countdownMs}ms${urgent.detail ? ` 问题=${urgent.detail}` : ''}`
|
||||
: '未执行',
|
||||
);
|
||||
}
|
||||
|
||||
// 6. SPA 深链刷新(生产环境静态托管必须支持)
|
||||
await win.loadURL(`${TARGET_URL.replace(/\/$/, '')}/grades`);
|
||||
const deepLinkOk = await waitFor(
|
||||
win,
|
||||
@@ -182,7 +312,7 @@ async function main() {
|
||||
`path=${await win.webContents.executeJavaScript('location.pathname')}`,
|
||||
);
|
||||
|
||||
// 6. PWA 可安装性:manifest 可获取 + Service Worker 已注册
|
||||
// 7. PWA 可安装性:manifest 可获取 + Service Worker 已注册
|
||||
// 注意:注入代码里不要使用 ${} 插值,避免与宿主文件的模板字符串冲突
|
||||
const manifestInfo = await win.webContents.executeJavaScript(`(async () => {
|
||||
const link = document.querySelector('link[rel="manifest"]');
|
||||
|
||||
@@ -13,11 +13,14 @@
|
||||
* UI_SMOKE_USER 默认 teacher1
|
||||
* UI_SMOKE_PASS 默认 teacher123
|
||||
* UI_SMOKE_RESULT 结果 JSON 输出路径(可选)
|
||||
* UI_SMOKE_SKIP_PROBE=1 跳过"上课时段探针"(只跑基础 UI 校验)
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveElectronEnv, resolveElectronExecutable } from '../lib/electron-env.mjs';
|
||||
import { cleanupInClassProbe, setupInClassProbe } from './live-probe.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
const electronDir = path.join(root, 'packages', 'desktop-client', 'node_modules', 'electron');
|
||||
@@ -28,11 +31,7 @@ if (!fs.existsSync(electronDir)) {
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const pathFile = path.join(electronDir, 'path.txt');
|
||||
const executable = fs.existsSync(pathFile)
|
||||
? path.join(electronDir, 'dist', fs.readFileSync(pathFile, 'utf8').trim())
|
||||
: path.join(electronDir, 'dist', 'electron.exe');
|
||||
|
||||
const executable = resolveElectronExecutable(electronDir);
|
||||
if (!fs.existsSync(executable)) {
|
||||
console.error(`[ui-smoke] Electron 可执行文件不存在:${executable}`);
|
||||
console.error(' 请执行:node packages/desktop-client/node_modules/electron/install.js');
|
||||
@@ -50,18 +49,63 @@ fs.rmSync(profileDir, { recursive: true, force: true });
|
||||
console.log(`[ui-smoke] 目标:${target}`);
|
||||
console.log(`[ui-smoke] Electron:${executable}`);
|
||||
|
||||
/**
|
||||
* 上课时段探针:让服务端真实认定"现在正在上课",
|
||||
* 以便验证「上课时段发布紧急通知 → 全屏警告 + 3 秒倒计时」。
|
||||
*/
|
||||
const urgentTitle = `UI 冒烟紧急通知 ${Date.now()}`;
|
||||
let probe = null;
|
||||
let probeError = '';
|
||||
|
||||
if (process.env.UI_SMOKE_SKIP_PROBE === '1') {
|
||||
probeError = '已通过 UI_SMOKE_SKIP_PROBE=1 跳过探针';
|
||||
console.log(`[ui-smoke] ${probeError}`);
|
||||
} else {
|
||||
try {
|
||||
probe = await setupInClassProbe({
|
||||
baseUrl: new URL(target).origin,
|
||||
username: process.env.UI_SMOKE_USER ?? 'teacher1',
|
||||
password: process.env.UI_SMOKE_PASS ?? 'teacher123',
|
||||
});
|
||||
if (!probe.inClass) probeError = '探针课表已创建,但服务端仍未判定为上课时段';
|
||||
console.log(
|
||||
`[ui-smoke] 上课时段探针:班级=${probe.className} 上课中=${probe.inClass} ` +
|
||||
`时段=${probe.period ? `${probe.period.startTime}-${probe.period.endTime} · ${probe.period.courseName}` : '-'}`,
|
||||
);
|
||||
} catch (error) {
|
||||
probeError = String(error?.message ?? error);
|
||||
console.error(`[ui-smoke] 上课时段探针准备失败:${probeError}`);
|
||||
console.error(' "上课时段紧急通知二次确认"校验项将被记为失败。');
|
||||
}
|
||||
}
|
||||
|
||||
const child = spawn(executable, [entry], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
env: resolveElectronEnv({
|
||||
UI_SMOKE_URL: target,
|
||||
UI_SMOKE_RESULT: resultFile,
|
||||
UI_SMOKE_PROFILE: profileDir,
|
||||
},
|
||||
UI_SMOKE_URGENT_TITLE: urgentTitle,
|
||||
UI_SMOKE_INCLASS: probe?.inClass ? '1' : '0',
|
||||
UI_SMOKE_PROBE_DETAIL: probeError,
|
||||
}),
|
||||
});
|
||||
|
||||
child.on('exit', (code) => {
|
||||
child.on('exit', async (code) => {
|
||||
if (probe) {
|
||||
try {
|
||||
const removed = await cleanupInClassProbe(probe, { notificationTitle: urgentTitle });
|
||||
console.log(
|
||||
removed.length > 0
|
||||
? `[ui-smoke] 探针清理完成:${removed.join(', ')}`
|
||||
: '[ui-smoke] 探针清理完成(无残留数据)',
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`[ui-smoke] 探针清理失败(请手动检查演示数据):${error?.message ?? error}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (code === 0) {
|
||||
console.log(`[ui-smoke] 全部通过,结果文件:${resultFile}`);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user