feat: v2.9.0 终端实时面板,学习时长与学分统计

新增 runner/tui.mjs(~470 行):前台运行时自动开一块实时面板,
框线布局显示状态 / 课程 / 学时 / 课时 / 视频进度条 / 进度 / 最近日志。

- 学习统计 runner/study.mjs:只累计视频真在播的时长(暂停、重试退避、
  页面加载都不计),学分按课程去重(重试 / 刷新不重复计)
- 页面侧新增 credit 快照:平台只把本门学分写在倒计时文案里,
  学完文案就消失,所以边播边记
- log.mjs 增加 setConsoleSink:面板接管终端那一路,日志文件仍是纯文本
- 面板里按 q 等价 Ctrl+C,走 stop.request 同一条优雅收尾路径
- 尺寸自适应:宽度跟随终端(不封顶 120 列),无 resize 事件的平台
  靠定时刷新发现尺寸变化;变窄时按旧帧在新宽度下的折行数回退光标,
  折完超过窗口高就整屏重置;宽度 / 高度不足按重要性丢字段
- 非 TTY(重定向 / 管道 / 计划任务 / --check)自动降级为逐行日志,
  不写 ANSI 控制字符;--no-tui / YUN_XUE_TANG_TUI=0 可手动关闭,
  --no-color / NO_COLOR 关颜色
- 监控轮询从 2000ms 调到 1000ms,与面板刷新对齐
- supervisor 收尾时先收面板再逐行打退出日志,并汇总本次学习时长 / 学分
- check.mjs 增加裸 CR 检查:脚本里的 config\runner 曾被写成裸 CR,
  变成 config<CR>unner 导致找不到配置文件

自测:npm run test:tui(渲染 / 列宽 / 极端尺寸)、npm run test:study(假时钟口径)
This commit is contained in:
void committed 2026-10-26 21:49:13 +08:00
1 parent c1e883d67f
commit 65bf63ea6a
17 files changed
+1607 -27

No files matched your search

+53 -3
View File
@@ -143,6 +143,42 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
但如果是在任务管理器里「结束任务」或 `taskkill /F`,进程会被直接终止、收尾代码不会执行;
这种情况下次启动时会自动清理残留的浏览器进程与 `lockfile`,不需要手工处理。
### 终端面板
在终端里前台运行时(`npm run headless`、`tmux`、SSH 会话),运行器会自动开一块实时面板:
```text
╭ 云学堂助手 · 无头运行器 ─────────────────────────────────────────────────────────╮
│ 状态 刷课中 已运行 1:12:01 │
│ 课程 2025年安全生产月专题培训课程(第三期) │
│ 学时 已学 1:23:45 · 学分 12.75 · 本门 6.52 │
│ 课时 第三章 事故应急处置与自救互救 已学 62% │
│ 视频 ████████████████████░░░░░░░░░░░░ 62% 13:32/22:00 │
│ 进度 本次 3/10 · 累计 17 · 课时数 8 · 等待重试 12s · 倒计时 42s │
│ 日志 ./run-logs/headless.log · 已注入 4 次 │
├ 最近日志 ────────────────────────────────────────────────────────────────────────┤
│ [2024-05-21 09:12:03] [信息] 浏览器就绪:HeadlessChrome/124.0.6367.91 │
│ [2024-05-21 09:12:07] [信息] 已注入脚本(第 1 次):…/course/play/xxx │
╰──────────────────────────────────────────────────────────────────────────────────╯
q 退出(等价 Ctrl+C:暂停视频、停批量、关浏览器)· 完整日志照常写入日志文件
```
- **学习统计**:`学时` 那行给出两个数字——
- `已学`:**视频真正在播**的累计时长(排队、重试退避、页面加载都不计;暂停时右侧会标「暂停中,不计时」,好确认面板是活的而不是卡住了);
- `学分`:**本次运行里真正刷完**的课程累计能拿到的学分,按课程去重,重试/刷新页面不会重复计。
- `本门 6.52` 是当前在刷这门课学完能拿多少分——平台只把这个数字写在倒计时文案里(「还需 2小时 8分钟 可完成本课程学习并获得6.52学分」),学完后文案元素就消失了,所以运行器是边播边记。
- 两个数字都只统计本次运行(不落盘、不加 `stats.json`),退出即清零;退出时日志里会多一行「本次学习:视频累计播放 1:23:45,获得 12.75 学分」。
- 注意学分口径是「运行器亲眼看到刷完的课」,如果中途 `Ctrl+C` 退出,正在刷的那门课即使已经学了 90% 也不会算进学分(平台只在课程真正完成时才给分)。
- **只读**:面板不接收命令,唯一的按键是 `q`(等价 `Ctrl+C`,走同一套优雅退出:暂停视频 → 停批量 → 关浏览器)。`Ctrl+L` 可强制重绘。
- **自动降级**:stdout 不是 TTY(重定向到文件、计划任务、`nohup cmd > out.txt`)时自动关闭,回到原来的逐行日志,不会往日志里写 ANSI 控制字符。
- **不想用面板**:`--no-tui`(或配置文件 `tui: false`、环境变量 `YUN_XUE_TANG_TUI=0`)。
- **不想用颜色**:`--no-color`、配置文件 `color: false` 或 `NO_COLOR=1`;关闭后只剩框线与符号,排版不变。
- **完整日志不受影响**:面板只是终端的另一种显示方式,`run-logs/headless.log` 还是纯文本、按时间递增,`tail -f` 照常可看。
- **跟随窗口**:面板宽度直接取终端宽度,多宽就画多宽(不再封顶 120 列),每秒重画一次。拖拽窗口或用 `tmux` 分屏时,能收到 `resize` 事件的终端(Linux / macOS / Windows Terminal)去抖 60ms 后立即重排;收到不到的(Windows 传统控制台 `conhost` 拖窗口、最大化,Node 不会发任何事件)由每秒的定时刷新发现尺寸变了、自动重画,最多晚 1 秒。
- **变窄 / 还原**时要额外处理一件事:终端会把之前那些更宽的行重新折成多行,旧面板实际占的屏幕行数会比记录的逻辑行数多。运行器按「旧帧在新宽度下会折成几行」来回退光标,而不是数逻辑行;如果折完比整个窗口还高(最大化后还原就是这样),光标退不到块首,只能整屏重置(`Esc[H` + `Esc[2J`)后在顶部重画——代价是上方已经滚出去的历史日志不在屏幕上(但 `run-logs/*.log` 里一直都有一份)。小幅变窄(折完仍装得下窗口)走精确回退,不丢历史。
- **宽度不够**时按重要性丢字段,而不是一律打省略号:「进度」先丢倒计时、课时数,「视频」先缩进度条、再丢 `13:32/22:00` 这种时间标——剩下的始终是百分比和「本次/累计」骨架。
- **高度不够**时先降级成紧凑模式(不足 15 行省掉课时、日志两行,但**学时行一定保留**),再矮(不足 10 行)连 `q` 提示也省掉,更矮时连日志区一起省。任何时候帧高都不超过窗口,否则会把回滚区里的历史顶掉。
运行器做的事:
| 能力 | 说明 |
@@ -152,7 +188,7 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
| 掉登录自动重登 | cookie 失效或被踢回登录页时,用 `YUN_XUE_TANG_USR` / `YUN_XUE_TANG_PWD` 自动登录并接着刷课 |
| 崩溃自愈 | CDP 断线、浏览器崩溃、90 秒读不到脚本状态都会重启浏览器,并由看护循环在新会话里显式重新开跑(浏览器重启后 sessionStorage 清空,进度里的「完成书目」会重新从平台接口取) |
| 无进展保护 | 连续 30 分钟没有任何进展(`YUN_XUE_TANG_IDLE_RESTART_MINUTES`)时退出,避免无意义挂机 |
| 优雅退出 | `Ctrl+C` / `SIGTERM` 时先 `pauseAllMedia`、停批量、再关浏览器,不留脏状态(Windows 上监听 `SIGINT` / `SIGBREAK` / `SIGHUP`) |
| 优雅退出 | `Ctrl+C` / `q`(面板里)/ `SIGTERM` 时先 `pauseAllMedia`、停批量、再关浏览器,不留脏状态(Windows 上监听 `SIGINT` / `SIGBREAK` / `SIGHUP`) |
| 残留自愈 | 上次被强杀(`kill -9` / 任务管理器「结束任务」)留下的浏览器进程与锁文件,启动时按 profile 目录自动清理,端口不会一直被占 |
| 平台适配 | 平台差异集中在 `runner/platform.mjs`:有无图形会话、沙箱参数、进程树收尾、端口排查命令都按系统出 |
| 日志 | 同时写终端和 `./run-logs/headless.log`(`YUN_XUE_TANG_LOG_MAX_BYTES` 默认 5MB,超出轮转成 `.1`) |
@@ -172,14 +208,19 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
| `runner/stop.mjs` | ~60 | 终止信号优雅退出(Windows 走 SIGINT/SIGBREAK/SIGHUP) |
| `runner/browser.mjs` | ~230 | 浏览器探测、启动参数、陈旧锁与孤儿进程清理 |
| `runner/cdp.mjs` | ~90 | 极简 CDP 客户端(Node 22+ 原生 WebSocket,无第三方依赖) |
| `runner/page.mjs` | ~150 | 注入后要调用的页面 JS 表达式 + `page.evalJS/json/tryEval` 封装 |
| `runner/page.mjs` | ~155 | 注入后要调用的页面 JS 表达式 + `page.evalJS/json/tryEval` 封装 |
| `runner/session.mjs` | ~310 | 单次会话:起浏览器 → 注入 → 自动重登 → 刷课 → 监控 → 收尾 |
| `runner/selfcheck.mjs` | ~60 | `--check` 的只读环境自检 |
| `runner/supervisor.mjs` | ~75 | 崩溃重启循环与退出码 |
| `runner/tui.mjs` | ~470 | 终端面板:框线布局、进度条、ANSI 宽度对齐、`q` 退出、尺寸自适应、非 TTY 自动关闭 |
| `runner/study.mjs` | ~110 | 学习统计:本次跑了多久(只算视频真在播)、拿到多少学分(按课程去重) |
| `runner/supervisor.mjs` | ~85 | 崩溃重启循环、退出码与本次学习统计汇总 |
模块之间是单向依赖(`headless` → `supervisor` → `session` → `page`/`selfcheck` → `cdp`),
平台相关的判断全部下沉到 `platform.mjs`(`browser.mjs` 转发它的导出,老代码不用改),
没有循环引用,也没有需要打包的步骤:`node runner/headless.mjs` 直接跑多文件 ESM。
`tui.mjs` 只单向依赖 `log.mjs`(接管终端输出)与 `study.mjs`(学时/学分累计),
所以对它来说 `session.mjs`、`supervisor.mjs` 都是「可选调用方」——面板关了也不会影响它们任何逻辑。
`study.mjs` 不读终端也不读浏览器(只吃快照 + 一个可替换的时钟),所以能脱离两者直接用假时钟测。
改脚本内部 API(`window.__yunXueTangAuto` 上的方法)只需要动 `runner/page.mjs`。
命令行参数(**日常改配置文件就行**;这里的开关只是临时覆盖,适合写进 `tmux` 命令或 `~/.bashrc`):
@@ -203,6 +244,8 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
| `--extra-args "…"` | `YUN_XUE_TANG_EXTRA_ARGS` | `extraArgs` | 空 | 追加给浏览器的命令行参数(空格分隔) |
| `--log-file PATH`(旧名 `--log`) | `YUN_XUE_TANG_LOG_FILE` | `logFile` | `./run-logs/headless.log` | 日志文件路径 |
| `--log-max-bytes N`(旧名 `--log-max`) | `YUN_XUE_TANG_LOG_MAX_BYTES` | `logMaxBytes` | `5242880` | 单文件上限,超出轮转 |
| `--no-tui` | `YUN_XUE_TANG_TUI` | `tui` | 开 | `1`/`0`,是否在终端显示实时面板;stdout 不是 TTY 时自动关闭 |
| `--no-color` | `YUN_XUE_TANG_COLOR` | `color` | 开 | `1`/`0`,面板是否带 ANSI 颜色(也认 `NO_COLOR`) |
| `--config PATH` | `YUN_XUE_TANG_CONFIG` | — | `./config/runner.config.mjs` | 指定另一个配置文件 |
| `--help` / `-h` | — | — | — | 打印完整参数表(含配置文件字段、环境变量、当前生效值) |
| — | `YUN_XUE_TANG_HAS_DISPLAY` | — | 自动判断 | `1`/`0` 强制认定「有无图形会话」(Linux 看 `DISPLAY`,Windows 看 `SESSIONNAME`;判断不准时用) |
@@ -226,6 +269,8 @@ export default {
port: 9336,
profile: './.run-profile',
logFile: './run-logs/headless.log',
tui: true, // 终端面板;false = 逐行日志
color: true, // 面板颜色;false 或不设 NO_COLOR 都可
};
```
@@ -251,6 +296,7 @@ export default {
| 端口被占 | 全平台 | 运行器会先清理「命令行带本 profile」的残留浏览器(自愈);仍被别的程序占用时按提示换 `--port`。提示命令按平台出:Linux `pkill -f "remote-debugging-port=9336"`,Windows `netstat -ano \| findstr :9336` + `taskkill /PID <PID> /T /F` |
| `"无法创建数据目录"` / `配置文件正在使用中` | Windows | 上次浏览器被强杀后 profile 还锁着。运行器启动时会自动清理;也可手动删掉 `.run-profile`(会丢失登录态) |
| `Ctrl+C` 后浏览器没关 | Windows | 用了任务管理器「结束任务」/ `taskkill /F` 时收尾代码不执行(TerminateProcess)。下次启动会自动清理残留进程 |
| 面板显示错行 / 有残留字符 | 全平台 | 终端被非运行器输出(后台脚本、`echo`、另一个进程)插话会打乱面板,按 `Ctrl+L` 重绘一次即可;或用 `--no-tui` 退回逐行日志 |
| 计划任务里一起床就退出 | Windows | 运行在 Session 0 没有桌面。运行器检测 `SESSIONNAME=Services` 后强制无头,正常;若仍失败看 `run-logs/headless.log` |
| `'鍏?npm' 不是内部或外部命令` / `'01' 不是内部或外部命令` / `'rofile' 不是内部或外部命令` | Windows | 批处理文件里出现了**中文(非 ASCII)字符**或**裸 LF 行尾**。cmd.exe 按当前代码页逐字节读批处理,多字节字符和 LF 都会让行偏移错位,于是把一行拆成几段当命令执行。修法:`.cmd` 只用 ASCII 且必须 CRLF。`npm run check` 会直接拦下这类文件 |
@@ -310,6 +356,8 @@ runner/ 无头运行器(Linux / Windows,无图形
page.mjs 页面求值封装与注入后调用的表达式
session.mjs 单次会话:起浏览器 / 注入 / 自动重登 / 崩溃自愈
selfcheck.mjs --check 只读环境自检
tui.mjs 终端面板(框线 + 进度条,q 退出,非 TTY 自动关闭)
study.mjs 学习统计(本次播放时长 / 获得学分)
supervisor.mjs 崩溃重启循环与退出码
config/
runner.config.mjs 无头运行器配置(日常调参改这里,不用 build)
@@ -321,6 +369,8 @@ dev/ 本地热加载开发工具(HTTP 服务 + 薄
real-test.mjs 面板渲染 / 路由 / 热替换断言(只读)
real-e2e.mjs 真实账号登录 → 列表 → 进课 → 播放
real-run.mjs 持续跑:跨章节 / 跨课程 / 断线重启
tui-test.mjs 终端面板自测(不用浏览器:列宽 / 截断 / 极端尺寸)
study-test.mjs 学习统计自测(假时钟:暂停不计时 / 防重复计分)
docs/
reports/ 历史实跑报告
run-report-v203.md 2026-10-19 实跑报告(v2.0.3)
+7 -1
View File
@@ -15,7 +15,7 @@
export default {
// ---------- 选课 / 刷课策略 ----------
/** 本次最多完成多少门课;0 = 不限(一直刷到没有未学完的课) */
maxCourses: 10,
maxCourses: 100,
/** 运行多少分钟后收尾退出;0 = 不限(适合 cron 定长跑时设成 60) */
budgetMinutes: 0,
/** 优先总时长最短的课程(正序);false = 按列表原顺序 */
@@ -46,4 +46,10 @@ export default {
logFile: './run-logs/headless.log',
/** 单个日志文件上限(字节),超出后轮转成 .1 */
logMaxBytes: 5 * 1024 * 1024,
// ---------- 终端面板 ----------
/** 终端里显示实时面板(框线 + 进度条);false = 回到逐行日志。非 TTY(重定向/计划任务)时自动关闭 */
tui: true,
/** 面板是否带 ANSI 颜色;false = 只用框线和符号。也认 NO_COLOR 环境变量 */
color: true,
};
+28 -1
View File
@@ -15,7 +15,7 @@
| `../yun-xue-tang-assistant.user.js` | **构建产物**(不要手改,改 `src/` 后 `npm run build`) |
| `serve.mjs` | 本地 HTTP 服务,向浏览器提供源码与版本哈希(127.0.0.1:8899) |
| `dev-loader.user.js` | Tampermonkey 里的薄加载器,轮询版本、释放旧实例、注入新实例 |
| `tests/` | 真机测试脚本(真实 Chrome + 真实站点,见下方「真机测试」) |
| `tests/` | 测试脚本(真机测试 + 终端面板纯函数测试,见下方「真机测试」) |
| `../scripts/start-dev.cmd` | 双击启动服务 |
| `../scripts/check.mjs` | `npm run check` 的实现:自动遍历 `runner/`、`dev/`、`scripts/`、`config/` 跑 `node --check`,同时检查 `.cmd` 必须是纯 ASCII + CRLF(cmd.exe 逐字节按代码页读批处理,中文和裸 LF 会让行偏移错位);新增模块不用再手改命令 |
@@ -52,6 +52,33 @@ npm run test:real:headless # 无头模式(CI / 无人值守)
node dev/tests/real-test.mjs --keep # 跑完不关浏览器,便于人工复核
```
### 终端面板自测(不用浏览器)
`runner/tui.mjs` 有个不联网、不开浏览器的纯函数测试;`runner/study.mjs` 的学时/学分累计也有一份(带假时钟):
```bash
npm run test:tui # 面板渲染 / 列宽 / 尺寸自适应
npm run test:study # 学习时长与学分累计口径
```
它用假 stdout 渲染真实帧,逐行量列宽,重点盯五件容易错的事:
- 中文/全角/emoji 占 2 列,ANSI 转义序列占 0 列(算错边框就歪、中文被劈成半个);
- 截断到指定列宽时要补 `\x1b[0m`,否则颜色会溢出到下几行;
- 尺寸自适应:宽度直接跟终端(240 列终端框线就是 240),从 40 行到 8 行的每种高度都不超出窗口,矮到 15 行时自动省掉课时/日志行但仍保留学时与视频进度;
- 没有 `resize` 事件的平台(Windows 传统控制台):完全不发事件也能在定时刷新里发现尺寸变化,最大化后框线跟着变宽、缩小后自动清整块重画(不会把旧帧的尾巴留在屏上),尺寸没变时不多做一次清屏;
- 折行感知的回退:终端变窄时会把宽行重排成多行,所以按「旧帧在新宽度下的可视行数」算回退步数;如果折完比窗口还高(最大化后还原)就整屏重置(`Esc[H` + `Esc[2J`),否则旧面板的上半截会永远留在屏幕上;小幅变窄(折完仍装得下)走精确回退,不丢上方历史;
- 36 列窄终端 / 8 行矮终端下不崩、不超界;缩窗(100×24 → 60×12)后硬重绘的回退步数受新窗口高限制,不会把上面历史顶出屏幕;
- 学时/学分累计:暂停时不计时、播放中按两帧间隔累加、倒计时元素消失后沿用学分缓存、完成数没变不重复计分、换课后重新读分。
`study-test.mjs` 用假时钟(不依赖真实时间)把口径钉死:
- 暂停 30 秒一点都不计、
- 两帧间隔超过 60 秒(浏览器重启 / 进程挂起)直接丢弃不补计、
- 同一门课重复完成不重复计分、没读到学分的课完成后不瞎加分、
- `0.1 + 0.2` 这种浮点累加输出成 `0.3` 而不是 `0.30000000000000004`。
另外还断言了「禁用时是空操作」(上层可以无条件调 `tui.set()`)和
「`finish()` 只生效一次且会恢复光标」。改面板布局后先跑这个,比真机跑一轮快得多。
三个真机脚本(`dev/tests/real-test.mjs` / `real-e2e.mjs` / `real-run.mjs`)会自动适配当前平台:
没有图形会话时强制 `--headless=new`(即使没传 `--headless`),并补上该平台需要的参数
(Linux:`--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage`;Windows:不弹崩溃恢复气泡),
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env node
/**
* 学习统计(runner/study.mjs)自测:纯数据逻辑,假时钟,不需要浏览器也不碰终端。
*
* 为什么单独测:这段逻辑的口径一旦错,面板上的「已学 1:23:45 / 学分 12.75」就是假的,
* 而这种错在日志里完全看不出来(日志只有收尾那一行)。用假时钟把
* 「暂停不计时」「间隔过大不补计」「重复完成不重复计分」这些边界钉死。
*
* 用法:
* node dev/tests/study-test.mjs
* npm run test:study
*/
import { createStudyTracker } from '../../runner/study.mjs';
let failed = 0;
function ok(cond, name, extra) {
if (cond) console.log(' ✔ ' + name);
else { failed++; console.log(' ✘ ' + name + (extra ? ' → ' + extra : '')); }
}
function eq(actual, expect, name) {
ok(actual === expect, name, '期望 ' + JSON.stringify(expect) + ',实际 ' + JSON.stringify(actual));
}
/** 假时钟:手动推进,不依赖真实时间 */
function clock(start = 1700000000000) {
let t = start;
return { now: () => t, tick(sec) { t += sec * 1000; } };
}
const video = (paused) => ({ t: 10, d: 100, paused, err: 0, src: 1 });
// ---------------------------------------------------------------------------
// 1. 学习时长:只在视频真的在播时累加
// ---------------------------------------------------------------------------
console.log('学习时长');
{
const c = clock();
const s = createStudyTracker({ now: c.now });
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 0, '首帧没有上一帧可比,不计时');
c.tick(2);
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 2, '连续两帧都在播,累加 2 秒');
c.tick(2);
s.update({ course: 'A', video: video(true) });
eq(s.get().studySeconds, 2, '这一帧已暂停:上一段播到暂停前就停了,不再补');
c.tick(30);
s.update({ course: 'A', video: video(true) });
eq(s.get().studySeconds, 2, '暂停 30 秒一点都不计(排队/挂机不算学习)');
c.tick(2);
s.update({ course: 'A', video: video(false) });
c.tick(3);
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 5, '恢复播放后从 2 秒接着累加');
// 没有 video(列表页 / 加载中)等于没在播
c.tick(10);
s.update({ course: 'A', video: null });
c.tick(2);
s.update({ course: 'A', video: null });
eq(s.get().studySeconds, 5, 'video 为 null 时不计时(列表页/加载中的时间不算学习)');
c.tick(2);
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 5, '从 null 回到播放:这一帧不算(上一帧没在播)');
}
// ---------------------------------------------------------------------------
// 2. 学习时长:间隔异常(浏览器重启 / 进程挂起)不补计
// ---------------------------------------------------------------------------
console.log('异常间隔');
{
const c = clock();
const s = createStudyTracker({ now: c.now });
s.update({ course: 'A', video: video(false) });
c.tick(600); // 10 分钟没有任何快照:中间肯定断过
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 0, '间隔 600 秒视为断线,不补计(上限 60 秒)');
c.tick(59);
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 59, '间隔 59 秒仍在容忍范围内');
c.tick(61);
s.update({ course: 'A', video: video(false) });
eq(s.get().studySeconds, 59, '间隔 61 秒丢弃');
}
// ---------------------------------------------------------------------------
// 3. 学分:边播边记,倒计时消失后沿用缓存
// ---------------------------------------------------------------------------
console.log('学分读取');
{
const c = clock();
const s = createStudyTracker({ now: c.now });
s.update({ course: 'A', credit: 2.5, video: video(false) });
eq(s.get().credit, 2.5, '播放期间读到本门可得学分');
// 学完后倒计时元素消失(credit=null),本门学分仍要显示
s.update({ course: 'A', credit: null, completed: 1, video: video(false) });
eq(s.get().credit, 2.5, '倒计时消失后沿用缓存(否则面板会突然变 —)');
eq(s.get().creditEarned, 2.5, '课程完成后计入获得学分');
// 换到新课,还没读到学分
s.update({ course: 'B', credit: null, completed: 1, video: video(false) });
eq(s.get().credit, null, '换课后本门学分先清空(还没读到新课的分)');
s.update({ course: 'B', credit: 1.25, completed: 1, video: video(false) });
eq(s.get().credit, 1.25, '读到新课学分');
s.update({ course: 'B', credit: null, completed: 2, video: video(false) });
eq(s.get().creditEarned, 3.75, '第二门学完累加(2.5 + 1.25)');
}
// ---------------------------------------------------------------------------
// 4. 学分:不重复计数
// ---------------------------------------------------------------------------
console.log('防重复计数');
{
const c = clock();
const s = createStudyTracker({ now: c.now });
s.update({ course: 'A', credit: 2.5, completed: 0, video: video(false) });
s.update({ course: 'A', credit: 2.5, completed: 1, video: video(false) });
eq(s.get().creditEarned, 2.5, '第一次完成计 2.5');
// completed 没变(页面刷新 / 重试后重复上报)
for (let i = 0; i < 5; i++) s.update({ course: 'A', credit: 2.5, completed: 1, video: video(false) });
eq(s.get().creditEarned, 2.5, '完成数没变不重复加');
// completed 涨到 2 但课程名还是 A(重试同一门又完成了一遍)——按课程去重,仍不加
s.update({ course: 'A', credit: 2.5, completed: 2, video: video(false) });
eq(s.get().creditEarned, 2.5, '同一门课重复完成不重复计分');
// 没读到过学分的课,完成后也不瞎加
s.update({ course: 'C', credit: null, completed: 3, video: video(false) });
eq(s.get().creditEarned, 2.5, '没读到学分的课完成后不加分');
}
// ---------------------------------------------------------------------------
// 5. 学分文本:浮点累加不出现 3.7499999
// ---------------------------------------------------------------------------
console.log('学分文本');
{
const s = createStudyTracker({ now: clock().now });
eq(s.creditText(3.75), '3.75', '3.75 原样输出');
eq(s.creditText(1), '1', '整数不带小数点');
eq(s.creditText(0.1 + 0.2), '0.3', '浮点误差被抹平(0.1+0.2)');
eq(s.creditText(6.5), '6.5', '一位小数不带尾随 0');
eq(s.creditText(12.75), '12.75', '两位小数');
}
// ---------------------------------------------------------------------------
// 6. 摘要 / 空状态
// ---------------------------------------------------------------------------
console.log('摘要与空状态');
{
const s = createStudyTracker({ now: clock().now });
eq(s.summary(), '', '什么都没学时摘要为空(收尾不该打一行 0 学时的废话)');
eq(s.get().studySeconds, 0, '初始时长为 0');
eq(s.get().creditEarned, 0, '初始学分为 0');
eq(s.get().credit, null, '初始本门学分为 null');
const c = clock();
const s2 = createStudyTracker({ now: c.now });
s2.update({ course: 'A', credit: 2.5, video: video(false) });
c.tick(3600);
s2.update({ course: 'A', credit: null, completed: 1, video: video(false) });
// 间隔 3600 秒 > 60 被丢弃,所以时长仍是 0;这里主要是验证摘要格式
eq(s2.summary(), '视频累计播放 00:00,获得 2.5 学分', '摘要把时长和学分写在一句里');
const c3 = clock();
const s3 = createStudyTracker({ now: c3.now });
s3.update({ course: 'A', video: video(false) });
c3.tick(2);
s3.update({ course: 'A', video: video(false) });
eq(s3.summary(), '视频累计播放 00:02,获得 0 学分', '只有时长没有学分时也照常输出');
}
// ---------------------------------------------------------------------------
// 7. reset:重开一轮(supervisor 重启的会话之间)要能清零
// ---------------------------------------------------------------------------
console.log('重置');
{
const c = clock();
const s = createStudyTracker({ now: c.now });
s.update({ course: 'A', credit: 2.5, video: video(false) });
c.tick(2);
s.update({ course: 'A', credit: null, completed: 1, video: video(false) });
ok(s.get().studySeconds > 0 && s.get().creditEarned > 0, '重置前有数据');
s.reset();
eq(s.get().studySeconds, 0, 'reset 清空时长');
eq(s.get().creditEarned, 0, 'reset 清空学分');
eq(s.get().credit, null, 'reset 清空本门学分');
eq(s.summary(), '', 'reset 后摘要为空');
// 重置后再来一门同名的课,应该能重新计分(去重表也清了)
s.update({ course: 'A', credit: 2.5, completed: 1, video: video(false) });
eq(s.get().creditEarned, 2.5, 'reset 后同名课程能重新计分');
}
console.log('');
if (failed) {
console.log('学习统计自测:' + failed + ' 项失败');
process.exit(1);
}
console.log('学习统计自测:全部通过');
+449
View File
@@ -0,0 +1,449 @@
#!/usr/bin/env node
/**
* 终端面板(runner/tui.mjs)自测:纯函数 + 假终端渲染,不需要浏览器、不联网。
*
* 为什么需要它:面板的正确性全在「列宽」上——中文占 2 列、ANSI 转义不占列、
* 截断后要补 reset。这三处一旦算错,边框就会歪或者把中文劈成半个,
* 而这类问题是肉眼看日志发现不了的(日志文件里根本没有面板)。
*
* 用法:
* node dev/tests/tui-test.mjs # 断言全部通过则退出码 0
* npm run test:tui
*/
import { textWidth, stripAnsi, formatDuration, progressBar, visualRows, createTui } from '../../runner/tui.mjs';
let failed = 0;
function ok(cond, name, extra) {
if (cond) {
console.log(' ✔ ' + name);
} else {
failed++;
console.log(' ✘ ' + name + (extra ? ' → ' + extra : ''));
}
}
function eq(actual, expect, name) {
ok(actual === expect, name, '期望 ' + JSON.stringify(expect) + ',实际 ' + JSON.stringify(actual));
}
// ---------------------------------------------------------------------------
// 1. 列宽:中文 2 列、emoji 2 列、组合/控制字符 0 列
// ---------------------------------------------------------------------------
console.log('列宽计算');
eq(textWidth('abc'), 3, 'ASCII 每字符 1 列');
eq(textWidth('课程'), 4, '中文每字 2 列');
eq(textWidth('课'), 2, '单字中文');
eq(textWidth('(三)'), 6, '全角标点 2 列');
eq(textWidth('a课b'), 4, '中英混排');
eq(textWidth(''), 0, '空串 0 列');
eq(textWidth('\x1b[32m课\x1b[0m'), 2, 'ANSI 序列不占列');
eq(textWidth(stripAnsi('\x1b[1m\x1b[31mabc\x1b[0m')), 3, 'stripAnsi 后再量');
eq(textWidth('😀'), 2, 'emoji 2 列');
eq(textWidth('█░'), 2, '进度条字符 1 列(非全角)');
// ---------------------------------------------------------------------------
// 2. 时长 / 进度条
// ---------------------------------------------------------------------------
console.log('时长与进度条');
eq(formatDuration(0), '00:00', '0 秒');
eq(formatDuration(72), '01:12', '72 秒');
eq(formatDuration(3600), '1:00:00', '整小时');
eq(formatDuration(3661), '1:01:01', '超一小时');
eq(formatDuration(-5), '00:00', '负数按 0');
eq(progressBar(0, 4), '░░░░', '0% 全空');
eq(progressBar(1, 4), '████', '100% 全满');
eq(progressBar(0.5, 4), '██░░', '50% 一半');
eq(progressBar(2, 4), '████', '大于 1 截到 1');
eq(progressBar(0.5, 4).length, 4, '进度条宽度准确');
// ---------------------------------------------------------------------------
// 3. 帧渲染:假 stdout 捕获一帧,逐行量宽度
// ---------------------------------------------------------------------------
console.log('帧渲染');
function makeFrame(opts) {
const chunks = [];
const out = {
columns: opts.columns || 80,
rows: opts.rows || 24,
isTTY: true,
write(s) { chunks.push(s); },
on() {},
removeListener() {},
};
const tui = createTui({
enabled: true,
out,
stdin: null,
color: opts.color !== false,
logFile: './run-logs/headless.log',
title: '面板测试',
});
if (opts.setup) opts.setup(tui, out);
// 强制重画一帧(createTui 建的时候已经画过一帧,这里要最后一帧)
tui.render();
const frame = chunks[chunks.length - 1] || '';
// 一帧内用 \r\n 分隔;最后一行后面紧跟 \x1b[0J
const lines = frame.split('\r\n').map((l) => l.replace(/\x1b\[0J$/, '').replace(/\x1b\[K/g, ''));
tui.finish();
return { lines, chunks, frame, out, tui };
}
const plain = makeFrame({ columns: 80, color: false });
ok(plain.lines.length >= 12, '帧有足够行数(' + plain.lines.length + ' 行)');
for (const line of plain.lines) {
const w = textWidth(stripAnsi(line));
ok(w <= 80, '行宽不超过 80 列', w + ' 列:' + JSON.stringify(stripAnsi(line)));
}
// 边框的三行必须等宽,否则右边框会锯齿
const boxLines = plain.lines.filter((l) => /^[╭├╰│]/.test(stripAnsi(l)));
const widths = [...new Set(boxLines.map((l) => textWidth(stripAnsi(l))))];
eq(widths.length, 1, '所有框线行等宽(实际宽度集合:' + widths.join(',') + ')');
ok(widths[0] === 80, '框线正好占满终端宽度', String(widths[0]));
// ---------------------------------------------------------------------------
// 4. 彩色帧:ANSI 序列混在中文里也不能顶歪边框
// ---------------------------------------------------------------------------
console.log('彩色帧');
const colored = makeFrame({
columns: 84,
color: true,
setup(tui) {
tui.snap({
course: '2025年安全生产月专题培训课程(第三期)',
lesson: '第三章 事故应急处置与自救互救',
summary: { text: '已学 62%' },
countdown: 42,
completed: 3,
doneCount: 17,
retryCount: 1,
retryWait: 12,
lessons: 8,
video: { t: 812, d: 1320, paused: false, err: 0, src: 1 },
});
tui.set({ phase: '刷课中', tone: 'ok', injected: 4, maxCourses: 10 });
},
});
ok(colored.frame.includes('\x1b['), '彩色帧里确实有 ANSI 序列');
for (const line of colored.lines) {
const w = textWidth(stripAnsi(line));
ok(w <= 84, '彩色帧行宽不超过 84 列', w + ' 列');
}
const coloredBox = colored.lines.filter((l) => /^[╭├╰│]/.test(stripAnsi(l)));
const cw = [...new Set(coloredBox.map((l) => textWidth(stripAnsi(l))))];
eq(cw.length, 1, '彩色帧里框线仍等宽(' + cw.join(',') + ')');
ok(cw[0] === 84, '彩色帧框线占满宽度', String(cw[0]));
// 状态行不该出现「多余的省略号」(上一版把带色的状态行误判成超宽)
const statusLine = colored.lines.find((l) => stripAnsi(l).includes('状态'));
ok(statusLine && !stripAnsi(statusLine).includes('刷课中…'), '状态行没有被误截断');
// ---------------------------------------------------------------------------
// 5. 窗口尺寸自适应:宽度跟随终端(不再封顶 120 列)+ 矮终端降级
// ---------------------------------------------------------------------------
console.log('窗口尺寸自适应');
{
// 宽终端(240 列):框线也得撑满 240,不能停在 120
const wide = makeFrame({ columns: 240, rows: 30, color: false });
const wideBox = wide.lines.filter((l) => /^[╭├╰│]/.test(stripAnsi(l)));
const ww = [...new Set(wideBox.map((l) => textWidth(stripAnsi(l))))];
eq(ww.length, 1, '240 列终端:框线仍等宽(' + ww.join(',') + ')');
eq(ww[0], 240, '240 列终端:框线跟随终端宽度(不再封顶 120)');
// 每种高度下,帧的行数都不能超过窗口,否则会把回滚区里的历史顶掉
for (const rows of [40, 30, 24, 20, 16, 14, 12, 10, 8]) {
const f = makeFrame({ columns: 100, rows, color: false });
ok(f.lines.length <= rows, rows + ' 行窗口:帧高 ' + f.lines.length + ' 不超过窗口');
}
// 24 行:正常模式(有课时 / 日志行)
const full = makeFrame({ columns: 100, rows: 24, color: false });
ok(stripAnsi(full.lines.join('\n')).includes('课时'), '24 行窗口:显示课时行');
ok(stripAnsi(full.lines.join('\n')).includes('已注入'), '24 行窗口:显示日志行');
ok(stripAnsi(full.lines.join('\n')).includes('q 退出'), '24 行窗口:显示 q 提示');
// 12 行:紧凑模式,先丢课时/日志,保住视频进度与 q 提示
const tight = makeFrame({ columns: 100, rows: 12, color: false });
const tightText = stripAnsi(tight.lines.join('\n'));
ok(!tightText.includes('课时'), '12 行窗口:省掉课时行');
ok(tightText.includes('视频'), '12 行窗口:保留视频进度行');
ok(tightText.includes('进度'), '12 行窗口:保留完成数行');
ok(tightText.includes('q 退出'), '12 行窗口:仍显示 q 提示');
ok(tightText.includes('最近日志'), '12 行窗口:保留日志区(只是变矮)');
// 8 行:极端矮,连 q 提示都省掉,也绝不能有半截框
const tiny = makeFrame({ columns: 100, rows: 8, color: false });
ok(tiny.lines.length <= 8, '8 行窗口:帧高不超过 8(实际 ' + tiny.lines.length + ')');
ok(!tiny.lines[0].includes('\n'), '8 行窗口:标题行完整');
}
// ---------------------------------------------------------------------------
// 6. 尺寸变化时重画不错位:上帧 24 行 → 窗口缩到 12 行
// ---------------------------------------------------------------------------
console.log('尺寸变化重绘');
{
const chunks = [];
const ESC = String.fromCharCode(27);
const CRLF = String.fromCharCode(13, 10);
const ANSI_ALL = new RegExp(ESC + '\\\[[0-9;]*[A-Za-z]', 'g');
const foldMarker = ESC + '[H';
const out = {
columns: 100, rows: 24, isTTY: true,
write(s) { chunks.push(s); },
on() {}, removeListener() {},
};
const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' });
tui.render();
// 窗口缩小到 60×12:上帧每行 100 列,在 60 列下要折成 2 行,
// 整块折完远超新窗口高度 —— 光标退不到块首,只能整屏重置
out.rows = 12;
out.columns = 60;
chunks.length = 0;
tui.redraw();
const after = chunks.join('');
ok(after.includes(foldMarker), '旧帧折行后比窗口还高时走整屏重置(ESC[H)');
const lines = after.split(CRLF).map((l) => l.replace(ANSI_ALL, ''));
const box = lines.filter((l) => /^[╭├╰│]/.test(l));
const bw = [...new Set(box.map((l) => textWidth(l)))];
eq(bw.length, 1, '缩窗后框线仍等宽(' + bw.join(',') + ')');
eq(bw[0], 60, '缩窗后框线跟新宽度 60');
ok(box.length <= 12, '缩窗后帧高不超过 12(实际 ' + box.length + ')');
tui.finish();
}
// ---------------------------------------------------------------------------
// 6b. 尺寸小幅变窄:折行后仍装得下窗口 → 精确回退,不整屏重置(保住可视历史)
// ---------------------------------------------------------------------------
console.log('小幅变窄');
{
const chunks = [];
const ESC = String.fromCharCode(27);
const out = { columns: 120, rows: 48, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} };
const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' });
tui.render();
// 120 列的行在 110 列下折成 2 行,整块约 42 行但仍装得进 48 行的窗口
out.columns = 110;
chunks.length = 0;
tui.redraw();
const frame = chunks.join('');
ok(!frame.includes(ESC + '[2J'), '装得下时不整屏重置(不白白丢掉上方历史日志)');
ok(/\x1b\[\d+A\x1b\[0J/.test(frame), '改用精确回退(向上退到旧帧首行)');
tui.finish();
}
// ---------------------------------------------------------------------------
// 7. 没有 resize 事件的平台(Windows 传统控制台):靠定时刷新自己发现尺寸变化
// ---------------------------------------------------------------------------
console.log('无 resize 事件的尺寸变化');
{
const chunks = [];
const CRLF = String.fromCharCode(13, 10);
const ESC = String.fromCharCode(27);
// 注意:on/removeListener 是空实现,模拟「平台根本不发 resize 事件」
const out = {
columns: 100, rows: 24, isTTY: true,
write(s) { chunks.push(s); },
on() {}, removeListener() {},
};
const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' });
tui.render();
ok(chunks.length > 0, '首帧已画');
const boxWidths = (text) => [...new Set(text.split(CRLF).map(stripAnsi).filter((l) => /^[╭├╰│]/.test(l)).map(textWidth))];
const boxHeight = (text) => text.split(CRLF).map(stripAnsi).filter((l) => /^[╭├╰│]/.test(l)).length;
const clears = (text) => text.split(ESC + '[0J').length - 1;
// 最大化:100×24 → 180×40,全程不触发任何事件
out.columns = 180;
out.rows = 40;
chunks.length = 0;
tui.render();
eq(boxWidths(chunks.join('')).join(','), '180', '最大化后框线跟到 180 列(不靠 resize 事件)');
// 缩回去:同样没有事件,必须自己发现并清旧帧
out.columns = 80;
out.rows = 20;
chunks.length = 0;
tui.render();
const shrunk = chunks.join('');
ok(shrunk.includes(ESC + '[2J'), '缩窗时整屏重置(旧帧折行后比窗口还高)');
eq(boxWidths(shrunk).join(','), '80', '缩窗后框线跟到 80 列');
ok(boxHeight(shrunk) <= 20, '缩窗后帧高不超 20 行');
// 尺寸没变时不该多清屏(每帧都清屏会闪)
chunks.length = 0;
tui.render();
eq(clears(chunks.join('')), 1, '尺寸未变时不多做清屏(只留帧尾那一次)');
tui.finish();
}
// ---------------------------------------------------------------------------
// 7b. 最大化后还原:终端会把宽行折成多行,回退行数必须按折行后的可视行算
// ---------------------------------------------------------------------------
console.log('最大化后还原');
{
const chunks = [];
const ESC = String.fromCharCode(27);
const CRLF = String.fromCharCode(13, 10);
const out = { columns: 180, rows: 40, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} };
const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' });
chunks.length = 0;
tui.render();
// 上一帧是 180 列宽的一整块面板(帧内用 CRLF 分隔,首行前面还有回退控制符);
// 只看框线行,它们才是真正撑满宽度的内容行
const wideWidths = chunks.join('').split(CRLF)
.map((l) => stripAnsi(l))
.filter((l) => /^[╭├╰│]/.test(l))
.map(textWidth);
ok(wideWidths.length > 0 && wideWidths.every((w) => w > 80), '上一帧那些框线行都比 80 列宽(还原后必然折行)');
const folded = visualRows(wideWidths, 80);
ok(folded > wideWidths.length, '按 80 列重排后行数变多(' + wideWidths.length + ' → ' + folded + ' 行)');
ok(folded > 24, '折行后(' + folded + ' 行)比新窗口 24 行还高,光标退不到块首');
// 还原到 80 列:不发 resize 事件,靠定时刷新发现
out.columns = 80;
out.rows = 24;
chunks.length = 0;
tui.render();
const back = chunks.join('');
ok(back.includes(ESC + '[H') && back.includes(ESC + '[2J'), '还原时整屏重置,旧帧上半截不会残留');
ok(!/\x1b\[\d+A\x1b\[0J/.test(back), '不再用「向上退 N 行」那条路径(退不到块首)');
const box = back.split(CRLF).map(stripAnsi).filter((l) => /^[╭├╰│]/.test(l));
eq([...new Set(box.map(textWidth))].join(','), '80', '重置后框线是 80 列');
ok(box.length <= 24, '重置后帧高不超 24(实际 ' + box.length + ')');
tui.finish();
}
// ---------------------------------------------------------------------------
// 7c. visualRows 纯函数
// ---------------------------------------------------------------------------
console.log('可视行换算');
{
eq(visualRows([80, 80, 80], 80), 3, '不折行时等于行数');
eq(visualRows([160, 160], 80), 4, '两行 160 列在 80 列终端下折成 4 行');
eq(visualRows([181], 80), 3, '181 列折成 3 行(向上取整)');
eq(visualRows([], 80), 0, '空数组 0 行');
eq(visualRows([0, 0], 80), 2, '空白行也占一行');
eq(visualRows([40], 0), 1, '宽度非法时按 1 行算,不会崩');
}
// ---------------------------------------------------------------------------
// 8. 窄终端:不超界、不硬截断(字段按重要性递降)
// ---------------------------------------------------------------------------
console.log('极端尺寸');
const narrow = makeFrame({ columns: 36, rows: 12, color: true, setup(tui) {
tui.snap({ course: '课程', completed: 3, doneCount: 17, lessons: 8, retryCount: 1, countdown: 812, video: { t: 812, d: 1320, paused: false, err: 0, src: 1 } });
tui.set({ maxCourses: 10 });
}});
for (const line of narrow.lines) {
ok(textWidth(stripAnsi(line)) <= 36, '36 列终端:行宽不超界', String(textWidth(stripAnsi(line))));
}
ok(narrow.lines.length <= 12, '矮终端帧行数不超过 12', String(narrow.lines.length));
const narrowText = narrow.lines.map((l) => stripAnsi(l));
const progressLine = narrowText.find((l) => l.includes('进度'));
ok(progressLine.includes('本次') && progressLine.includes('累计'), '36 列:进度行保住本次/累计两个骨架字段');
ok(!progressLine.includes('倒计时'), '36 列:进度行主动丢掉倒计时字段(而不是截断成省略号)');
const videoLine = narrowText.find((l) => l.includes('视频'));
ok(videoLine.includes('%'), '36 列:视频行保住百分比');
// ---------------------------------------------------------------------------
// 9. 学习时长与学分:只算视频真在播的时间,学分只算刷完的课
// ---------------------------------------------------------------------------
console.log('学习时长与学分');
{
const chunks = [];
const out = { columns: 100, rows: 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} };
const tui = createTui({ enabled: true, out, stdin: null, color: false });
const snap = (o) => tui.snap({ course: 'A课', lessons: 3, video: { t: 10, d: 100, paused: false, err: 0, src: 1 }, ...o });
// 视频在播:靠真实的 Date.now 差累计,这里直接用间隔验证(把时钟往前拨太脏,改断言区间)
snap({ credit: 2.5 });
eq(tui.state.credit, 2.5, '学分:在播时从倒计时文案读到的本门学分');
eq(tui.state.studySeconds, 0, '首帧没有上一帧可比,不计时');
// 暂停期间不累加:间隔再长也不计入
tui.snap({ course: 'A课', video: { t: 10, d: 100, paused: true, err: 0, src: 1 } });
const pausedAt = tui.state.studySeconds;
tui.snap({ course: 'A课', video: { t: 10, d: 100, paused: true, err: 0, src: 1 } });
eq(tui.state.studySeconds, pausedAt, '视频暂停时不计学习时长');
// 播放中才有增量(正常应 < 1 秒,断言「大于 0 且不超 30 秒封顶」)
snap({ video: { t: 20, d: 100, paused: false, err: 0, src: 1 } });
const t1 = tui.state.studySeconds;
snap({ video: { t: 21, d: 100, paused: false, err: 0, src: 1 } });
const t2 = tui.state.studySeconds;
ok(t2 >= t1 && t2 - t1 < 30, '两帧之间按真实间隔累计', t1 + ' → ' + t2);
// 倒计时消失(学完)后沿用缓存,不会变回 —
snap({ credit: undefined });
eq(tui.state.credit, 2.5, '倒计时消失后沿用本门学分缓存');
// 真的完成了才发分;重复上报不重复计数
snap({ completed: 1 });
eq(tui.state.creditEarned, 2.5, '课程完成后计入获得学分');
snap({ completed: 1 });
eq(tui.state.creditEarned, 2.5, '完成数没变不重复加学分');
// 换课:学分清零待读,学完再累加
snap({ course: 'B课', completed: 1, credit: 1.25 });
eq(tui.state.credit, 1.25, '换课后读到新课的学分');
snap({ course: 'B课', completed: 2, credit: null });
eq(tui.state.creditEarned, 3.75, '第二门学完后累加(2.5 + 1.25)');
// 面板上真的画出来了吗
tui.render();
const frame = (chunks[chunks.length - 1] || '').split('\r\n').map(stripAnsi).join('\n');
ok(frame.includes('学时'), '面板有「学时」行');
ok(frame.includes('已学 '), '「学时」行显示学习时长');
ok(frame.includes('学分 3.75'), '「学时」行显示累计学分', frame.match(/学分[^·│]*/)?.[0]);
tui.finish();
// 暂停时提示「不计时」,避免用户以为面板死了
const f2 = makeFrame({ columns: 100, rows: 24, color: false, setup(t2ui) {
t2ui.snap({ course: 'A课', video: { t: 10, d: 100, paused: true, err: 0, src: 1 } });
} });
ok(f2.lines.map(stripAnsi).some((l) => l.includes('暂停中,不计时')), '暂停时明确提示不计时');
}
// ---------------------------------------------------------------------------
// 10. 禁用时是空操作(上层可以无条件调用)
// ---------------------------------------------------------------------------
console.log('禁用即空操作');
{
const chunks = [];
const out = { columns: 80, rows: 24, isTTY: false, write(s) { chunks.push(s); }, on() {}, removeListener() {} };
let quitCalled = 0;
const tui = createTui({ enabled: false, out, stdin: null, onQuit: () => quitCalled++ });
tui.set({ phase: '不该出现' });
tui.snap({ course: '不该出现', video: { t: 1, d: 2 } });
tui.render();
tui.finish();
eq(chunks.length, 0, '禁用时不写任何字节');
eq(tui.state.phase, '启动中', '禁用时 set 不改状态');
eq(tui.logLines.length, 0, '禁用时不缓存日志');
eq(quitCalled, 0, '禁用时不会触发退出回调');
}
// ---------------------------------------------------------------------------
// 11. 收尾:finish 只生效一次,且恢复光标 / 换行
// ---------------------------------------------------------------------------
console.log('收尾');
{
const chunks = [];
const out = { columns: 80, rows: 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} };
const tui = createTui({ enabled: true, out, stdin: null, color: false });
chunks.length = 0;
tui.finish();
const after = chunks.join('');
ok(after.includes('\x1b[?25h'), 'finish 恢复了光标(?25h)');
ok(after.startsWith('\n'), 'finish 先换行,收尾日志不会盖在面板上');
chunks.length = 0;
tui.finish();
eq(chunks.length, 0, '重复 finish 不重复输出');
}
console.log('');
if (failed) {
console.log('TUI 自测:' + failed + ' 项失败');
process.exit(1);
}
console.log('TUI 自测:全部通过');
+2
View File
@@ -12,6 +12,8 @@
"test:real:headless": "node dev/tests/real-test.mjs --headless",
"test:e2e": "node dev/tests/real-e2e.mjs",
"test:e2e:play": "node dev/tests/real-e2e.mjs --play",
"test:tui": "node dev/tests/tui-test.mjs",
"test:study": "node dev/tests/study-test.mjs",
"headless": "node runner/headless.mjs",
"headless:check": "node runner/headless.mjs --check"
},
+33 -1
View File
@@ -37,6 +37,8 @@ const DEFAULTS = {
profile: '', // 留空 = ./.run-profile
logFile: '', // 留空 = ./run-logs/headless.log
logMaxBytes: 5 * 1024 * 1024,
tui: true, // true = 交互式终端里启用面板;非 TTY 自动退化为逐行日志
color: true, // false = 面板不用 ANSI 颜色(也认 NO_COLOR 环境变量)
};
const argv = process.argv.slice(2);
@@ -100,7 +102,7 @@ if (CONFIG_FILE) {
// ---------------------------------------------------------------------------
// 命令行解析:--key value / --key=value / --flag
// ---------------------------------------------------------------------------
const BOOL_KEYS = ['preferShort', 'headless', 'check'];
const BOOL_KEYS = ['preferShort', 'headless', 'check', 'tui', 'color'];
const NUM_KEYS = ['maxCourses', 'budgetMinutes', 'restartMinutes', 'idleRestartMinutes', 'port', 'logMaxBytes'];
const STR_KEYS = ['origin', 'url', 'profile', 'logFile', 'chrome', 'extraArgs', 'config'];
@@ -140,6 +142,8 @@ for (let i = 0; i < argv.length; i++) {
let key = toCamel(name);
if (ALIASES[name]) key = ALIASES[name];
if (name === '--visible') key = 'headless'; // --visible = headless false
if (name === '--no-tui') key = 'tui'; // --no-tui = tui false
if (name === '--no-color') key = 'color'; // --no-color = color false
if (name === '--help' || name === '-h') key = 'help';
if (name === '--check') key = 'check';
const known = CONFIG_KNOWN.has(key) || key === 'help' || key === 'config';
@@ -164,6 +168,7 @@ for (let i = 0; i < argv.length; i++) {
continue;
}
if (name === '--visible') val = String(parseBool(val, name) ? 0 : 1); // --visible 0 → headless 1
if (name === '--no-tui' || name === '--no-color') val = String(parseBool(val, name) ? 0 : 1);
cliRaw[key] = val;
}
@@ -209,6 +214,8 @@ merged.logFile = envStr('YUN_XUE_TANG_LOG_FILE', merged.logFile);
merged.profile = envStr('YUN_XUE_TANG_PROFILE_DIR', merged.profile);
merged.chrome = envStr('YUN_XUE_TANG_CHROME_BIN', merged.chrome);
merged.extraArgs = envStr('YUN_XUE_TANG_EXTRA_ARGS', merged.extraArgs);
merged.tui = envBool('YUN_XUE_TANG_TUI', merged.tui);
merged.color = envBool('YUN_XUE_TANG_COLOR', merged.color);
// 命令行最后覆盖
const numBad = [];
@@ -291,6 +298,26 @@ export const EXTRA_ARGS = String(merged.extraArgs || '').split(/\s+/).filter(Boo
export const CHROME_BIN = merged.chrome || '';
export const WARNINGS = configWarnings;
/** 面板是否带颜色:配置 / 环境变量 / 行业惯例的 NO_COLOR 都生效 */
export const COLOR = merged.color && !process.env.NO_COLOR;
/**
* 是否启用终端面板(TUI)。
* 三个条件都满足才开:配置没关 + stdout 是交互式终端 + 不是自检模式。
* 自检要打印 PASS/FAIL 清单,塞进面板的日志区会看不到,所以强制逐行输出。
* 重定向到文件、管道、CI、计划任务里 stdout 不是 TTY,会自然退化。
*/
export const TUI = !!merged.tui && !CHECK_ONLY && !!process.stdout.isTTY;
/** 面板没开时,给一句人能看懂的原因(日志里只打一次) */
export function tuiDisabledReason() {
if (TUI) return '';
if (CHECK_ONLY) return '自检模式不启用面板(要逐行看 PASS/FAIL)';
if (!merged.tui) return '已按配置 / --no-tui 关闭面板';
if (!process.stdout.isTTY) return 'stdout 不是交互式终端(重定向 / 管道 / 服务),改用逐行日志';
return '环境不支持终端面板,改用逐行日志';
}
/** 一条便于粘贴到 issue / 日志的自述 */
export function describeRun() {
return {
@@ -306,6 +333,8 @@ export function describeRun() {
idleRestartMinutes: IDLE_RESTART_MINUTES,
profileDir: PROFILE_DIR,
logFile: LOG_FILE,
tui: TUI,
color: COLOR,
};
}
@@ -325,6 +354,8 @@ export function helpText() {
['chrome', '--chrome', 'YUN_XUE_TANG_CHROME_BIN', CHROME_BIN || '(自动探测)', '浏览器可执行文件'],
['extraArgs', '--extra-args', 'YUN_XUE_TANG_EXTRA_ARGS', EXTRA_ARGS.join(' ') || '(无)', '追加给浏览器的参数'],
['profile', '--profile', 'YUN_XUE_TANG_PROFILE_DIR', PROFILE_DIR, '持久化 profile 目录'],
['tui', '--no-tui', 'YUN_XUE_TANG_TUI', TUI ? '开' : '关', '交互式终端里的进度面板;非 TTY 自动关闭'],
['color', '--no-color', 'YUN_XUE_TANG_COLOR', COLOR ? '开' : '关', '面板是否用 ANSI 颜色(也认 NO_COLOR)'],
['logFile', '--log-file', 'YUN_XUE_TANG_LOG_FILE', LOG_FILE, '日志文件'],
['logMaxBytes', '--log-max-bytes', 'YUN_XUE_TANG_LOG_MAX_BYTES', LOG_MAX_BYTES, '单文件上限,超出轮转'],
['(字段 check)', '--check', '', CHECK_ONLY, '只做环境自检,不动进度'],
@@ -349,6 +380,7 @@ export function helpText() {
lines.push(' node runner/headless.mjs --check # 只做环境自检');
lines.push(' node runner/headless.mjs --max-courses 3 # 本次最多 3 门');
lines.push(' node runner/headless.mjs --headless 0 # 开有界面浏览器调试');
lines.push(' node runner/headless.mjs --no-tui # 不用面板,回到逐行日志');
lines.push(' node runner/headless.mjs --config ./config/runner.config.mjs # 显式指定配置文件');
lines.push('');
lines.push('旧参数名(仍然兼容):--max / --budget / --restart / --idle / --log / --log-max / --visible');
+26 -3
View File
@@ -18,6 +18,7 @@
* session.mjs 单次会话:起浏览器 → 注入 → 自动登录 → 刷课 → 监控 → 收尾
* selfcheck.mjs --check 的只读环境自检
* supervisor.mjs 崩溃重启循环与退出码
* tui.mjs 交互式终端面板(框线 + 进度条,q 退出;非 TTY 自动关闭)
*
* 用法(详见 README「无头运行」):
* npm run build # 先出构建产物
@@ -35,6 +36,8 @@
* --profile DIR 持久化 profile 目录(默认 ./.run-profile)
* --port N CDP 调试端口(默认 9336)
* --visible 不无头(无图形环境里会被忽略;本机调试用)
* --no-tui 不用终端面板,回到逐行日志(stdout 非 TTY 时自动如此)
* --no-color 面板不用 ANSI 颜色(也认 NO_COLOR 环境变量)
* --url URL 起始页面(默认 https://kfmic.yunxuetang.cn/login.html)
* YUN_XUE_TANG_CHROME_BIN Chrome/Chromium 可执行文件路径(默认自动探测)
* YUN_XUE_TANG_EXTRA_ARGS 追加给浏览器的命令行参数(空格分隔)
@@ -44,6 +47,8 @@
* YUN_XUE_TANG_LOG_FILE 日志文件路径(默认 ./run-logs/headless.log)
* YUN_XUE_TANG_LOG_MAX_BYTES 单个日志文件上限,超过就轮转成 .1(默认 5MB)
* YUN_XUE_TANG_HAS_DISPLAY 0/1,强制认定「有没有图形显示会话」(自动判断不准时用)
* YUN_XUE_TANG_TUI 0/1,是否启用终端面板(默认 1,非 TTY 时无效)
* YUN_XUE_TANG_COLOR 0/1,面板是否带颜色(也认 NO_COLOR)
*
* 退出码:0 正常收尾 / 1 无进展卡死 / 2 环境或参数问题 / 3 连续登录失败
*/
@@ -52,6 +57,7 @@ import { log, warn, error, closeLog } from './log.mjs';
import { createStopHandler } from './stop.mjs';
import { runPreflight, PreflightError } from './preflight.mjs';
import { runSupervisor } from './supervisor.mjs';
import { createTui } from './tui.mjs';
async function main() {
// --help:打印完整参数表(含配置文件字段、环境变量、当前生效值)后直接退出
@@ -59,11 +65,22 @@ async function main() {
console.log(cfg.helpText());
process.exit(0);
}
// 配置文件里有未知字段 / 废弃参数 / 被忽略的凭据:起来先提醒一句,不阻断
for (const w of cfg.WARNINGS || []) warn('配置:' + w);
const stop = createStopHandler({ log });
// 面板在预检之前就建好:预检的提示也进面板日志区,不会出现「先刷屏再盖住」
const tui = createTui({
enabled: cfg.TUI,
title: '云学堂助手 · 无头运行器' + (cfg.CHECK_ONLY ? '(自检)' : ''),
logFile: cfg.CHECK_ONLY ? '' : cfg.LOG_FILE,
color: cfg.COLOR,
onQuit: (reason) => stop.request(reason),
});
tui.set({ phase: '环境预检', tone: 'info' });
// 配置文件里有未知字段 / 废弃参数 / 被忽略的凭据:起来先提醒一句,不阻断
for (const w of cfg.WARNINGS || []) warn('配置:' + w);
let pre;
try {
pre = await runPreflight({
@@ -77,11 +94,16 @@ async function main() {
log,
});
} catch (e) {
closeLog();
if (e instanceof PreflightError) {
tui.set({ phase: '环境预检失败', tone: 'error' });
tui.finish();
for (const l of e.lines) error(l);
warn('修好上面问题后重跑;参数用 --help 查看。');
closeLog();
process.exit(e.exitCode);
}
tui.finish();
closeLog();
throw e;
}
@@ -90,6 +112,7 @@ async function main() {
binary: pre.browser,
scriptSrc: pre.scriptSrc,
stop,
tui,
log,
warn,
error,
+18
View File
@@ -5,11 +5,25 @@
// openLog(file, maxBytes); // 不调用就只打终端
// log('信息A', { x: 1 }); // → [2026-01-01 00:00:00] [信息] 信息A {"x":1}
//
// 终端面板(tui.mjs)启用时会把「终端」这一路改道到面板的日志区(setConsoleSink),
// 文件那一路始终是纯文本逐行 —— 面板不会污染日志文件,grep / 采集不受影响。
//
// 注意:openLog 必须在任何写文件之前调用;closeLog 在进程退出路径上兜底调用。
import fs from 'node:fs';
import path from 'node:path';
let stream = null;
/** 终端输出目标;null = 直接 console.log(未启用面板时的默认行为) */
let consoleSink = null;
/**
* 接管 / 归还终端输出。传 null 恢复逐行 console.log。
* sink(level, text) 收到的是完整的一行(不含换行)。
* @param {null | ((level: string, text: string) => void)} fn
*/
export function setConsoleSink(fn) {
consoleSink = typeof fn === 'function' ? fn : null;
}
/** 打开日志文件;maxBytes 为单文件上限,超出时把现有文件改名成 .1 */
export function openLog(file, maxBytes) {
@@ -42,7 +56,11 @@ function line(level, args) {
if (typeof a === 'string') return a;
try { return JSON.stringify(a); } catch (e) { return String(a); }
}).join(' ');
if (consoleSink) {
try { consoleSink(level, text); } catch (e) { /* 面板异常不影响日志文件 */ }
} else {
console.log(text);
}
if (stream) { try { stream.write(text + '\n'); } catch (e) { /* ignore */ } }
}
+10
View File
@@ -93,6 +93,16 @@ export const EXPR_SNAPSHOT = `JSON.stringify((function () {
lessons: items.length,
summary: a.readSummary(),
countdown: a.readCountdown(),
// 本课程可获得多少学分:平台只把它写在倒计时文案里
// 「还需 2小时 7分钟 可完成本课程学习并获得6.52学分,加油!」
// 学完后倒计时会消失,所以必须在播放期间就读出来(运行器靠它累计到手学分)
credit: (function () {
var el = document.querySelector('.yxtulcdsdk-course-player__countdown');
if (!el) return null;
var t = String(el.innerText || el.textContent || '').replace(/\\s+/g, '');
var m = t.match(/获得([0-9]+(?:\\.[0-9]+)?)学分/);
return m ? Number(m[1]) : null;
})(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
doneCount: Object.keys(a.S.completedTitles || {}).length,
retryCount: Object.keys(a.S.courseRetries || {}).length,
+29 -4
View File
@@ -13,6 +13,8 @@ import { runSelfCheck } from './selfcheck.mjs';
/** 看护循环间隔:既不能太密(CDP 往返),也要能及时补注入 */
export const WATCHDOG_MS = 1500;
/** 主监控轮询间隔:与面板的 1 秒刷新对齐,画面才不会一帧新一帧旧 */
export const MONITOR_MS = 1000;
/** 状态读不到多久后判定浏览器不可用 */
const STATE_TIMEOUT_MS = 90000;
/** 连续多少次登录失败判定为凭据/验证码问题(退出码 3) */
@@ -37,11 +39,14 @@ const LOGIN_COOLDOWN_MS = 20000;
* @param {string} o.binary 浏览器可执行文件
* @param {string} o.scriptSrc 构建产物源码(注入用)
* @param {object} o.stop stop.mjs 的 stop 句柄
* @param {object} [o.tui] tui.mjs 的面板(不传 / 未启用时所有调用都是空操作)
* @param {Function} o.log / o.warn / o.error 日志函数
*/
export async function runSession(o) {
const { cfg, binary, scriptSrc, stop } = o;
const log = o.log, warn = o.warn, error = o.error;
// 面板是可选件:未启用时 set/snap 都是空操作,这里不需要分支判断
const tui = o.tui || { set: () => {}, snap: () => {}, finish: () => {}, enabled: false };
let browser = null;
let cdp = null;
@@ -79,6 +84,8 @@ export async function runSession(o) {
activeCleanup = async () => { await disposeSession(); unregister(); };
// ---- 起浏览器 + 建标签页 + 连 CDP ----
// 注意:attempt 由 supervisor 管,这里不要传(传 undefined 会把它抹掉)
tui.set({ phase: '启动浏览器', tone: 'info' });
browser = await launchBrowser({
binary,
profileDir: cfg.PROFILE_DIR,
@@ -88,6 +95,7 @@ export async function runSession(o) {
log,
});
log('浏览器就绪:' + browser.version.Browser + ' profile=' + cfg.PROFILE_DIR);
tui.set({ phase: '打开页面', tone: 'info' });
const target = await httpJson('http://127.0.0.1:' + cfg.PORT + '/json/new?' + encodeURIComponent(cfg.START_URL), 'PUT');
const wsUrl = target && target.webSocketDebuggerUrl;
@@ -138,6 +146,7 @@ export async function runSession(o) {
const t = await page.evalJS('typeof window.__yunXueTangAuto');
if (t === 'object') {
injected++;
tui.set({ injected, phase: '已注入脚本' });
log('已注入脚本(第 ' + injected + ' 次):' + String(s.href).slice(0, 90));
} else {
warn('注入后未生成 window.__yunXueTangAuto(typeof=' + t + ')');
@@ -163,6 +172,7 @@ export async function runSession(o) {
if (Date.now() - loginLastAt < LOGIN_COOLDOWN_MS) return;
loginLastAt = Date.now();
loginAttempts++;
tui.set({ phase: '自动登录(第 ' + loginAttempts + ' 次)', tone: 'warn' });
log('登录页:自动登录(第 ' + loginAttempts + ' 次尝试)');
try {
const r = await page.evalJS(exprAutoLogin(cfg.USR, cfg.PWD));
@@ -175,6 +185,7 @@ export async function runSession(o) {
if (loginAttempts) {
loginAttempts = 0;
tui.set({ phase: '已登录,准备刷课', tone: 'ok' });
log('已离开登录页,登录成功');
}
@@ -202,12 +213,16 @@ export async function runSession(o) {
}
if (!st.batchRunning && st.route !== 'other') {
const ok = await page.tryEval(exprStartBatch(cfg.PREFER_SHORT));
if (ok) log('已启动列表刷课' + (cfg.PREFER_SHORT ? '(优先短课程)' : ''));
if (ok) {
tui.set({ phase: '刷课中', tone: 'ok' });
log('已启动列表刷课' + (cfg.PREFER_SHORT ? '(优先短课程)' : ''));
}
}
};
// ---------------- 自检模式 ----------------
if (cfg.CHECK_ONLY) {
tui.set({ phase: '环境自检中', tone: 'info' });
const result = await runSelfCheck({
page,
tickWatchdog,
@@ -260,7 +275,7 @@ export async function runSession(o) {
if (Date.now() - lastStateAt > STATE_TIMEOUT_MS) {
throw new Error('超过 ' + Math.round(STATE_TIMEOUT_MS / 1000) + ' 秒读不到脚本状态,重启浏览器');
}
await sleep(2000);
await sleep(MONITOR_MS);
continue;
}
const snap = JSON.parse(raw);
@@ -268,10 +283,19 @@ export async function runSession(o) {
if (Date.now() - lastStateAt > STATE_TIMEOUT_MS) {
throw new Error('超过 ' + Math.round(STATE_TIMEOUT_MS / 1000) + ' 秒读不到脚本状态,重启浏览器');
}
await sleep(2000);
await sleep(MONITOR_MS);
continue;
}
lastStateAt = Date.now();
// 面板每一轮都刷(快照本身就是最新状态,不需要另算);未启用时是空操作
tui.snap(snap);
if (!finishReason) {
if (snap.runFinished) tui.set({ phase: '脚本已停止', tone: 'ok' });
else if (snap.retryWait > 0) tui.set({ phase: '等待重试', tone: 'warn' });
else if (snap.video && !snap.video.paused) tui.set({ phase: '刷课中', tone: 'ok' });
else if (snap.route === 'list') tui.set({ phase: '列表页排队中', tone: 'info' });
else tui.set({ phase: '运行中', tone: 'info' });
}
// 编解码器缺失:视频元素有源但解码错误(MEDIA_ERR_DECODE / SRC_NOT_SUPPORTED)
if (!codecWarned && snap.video && snap.video.src && snap.video.err >= 3) {
@@ -321,12 +345,13 @@ export async function runSession(o) {
break;
}
await sleep(2000);
await sleep(MONITOR_MS);
}
// ---------------- 收尾 ----------------
const elapsed = Math.round((Date.now() - startedAt) / 1000);
const final = await page.tryEval(EXPR_FINAL_STATS).then((v) => (v ? JSON.parse(v) : {})).catch(() => ({}));
tui.set({ phase: '本次会话结束,收尾中', tone: 'ok', completed: final.completed || 0 });
log('本次会话结束:' + (finishReason || '收到退出信号') +
' 用时 ' + Math.floor(elapsed / 60) + ' 分 ' + (elapsed % 60) + ' 秒' +
' 本次完成 ' + (final.completed || 0) + ' 门,累计 ' + (final.doneCount || 0) + ' 门');
+8
View File
@@ -4,6 +4,7 @@
// const stop = createStopHandler({ log });
// const unregister = stop.add(() => browser.kill());
// if (stop.stopping) return; // 主循环里轮询这个开关
// stop.request('q'); // 面板里按 q 也走同一条收尾路径
//
// 收尾完成后会 closeLog() 并以 0 退出,所以主循环不用自己处理信号。
//
@@ -56,6 +57,13 @@ export function createStopHandler(opts = {}) {
if (i >= 0) cleaners.splice(i, 1);
};
},
/**
* 主动请求收尾(终端面板里按 q / Ctrl+C 走这里),
* 与收到信号完全同一条路径:并行收尾 → closeLog → exit(0)。
*/
request(reason) {
run(reason || '面板退出');
},
get stopping() { return stopping; },
get signal() { return triggered; },
/** 本平台实际监听的信号列表(自检 / 日志里用) */
+111
View File
@@ -0,0 +1,111 @@
// 学习统计:本次运行学了多久、拿到多少学分。
//
// 两个口径都是用户能直接验证的,所以规则要写死在这里、别散到面板里:
// · 学习时长 = 视频真正在播的累计时间(暂停 / 排队 / 重试退避 / 页面加载都不算)
// · 获得学分 = 本次运行里真正刷完的课程能拿到的学分之和(按课程去重)
//
// 数据都来自 page.mjs 的 EXPR_SNAPSHOT:视频状态来自 <video> 元素,
// 学分来自倒计时文案「…可完成本课程学习并获得6.52学分,加油!」。
// 学完之后那个倒计时元素就消失了,所以学分必须边播边记进 creditOf。
//
// 这里不读时钟以外的任何东西,也不太碰终端——所以能脱离浏览器和 TTY 直接测。
/** 两次快照间隔超过这个秒数就认为中间断过(浏览器重启 / 进程被挂起),不补计 */
const MAX_GAP_SECONDS = 60;
/**
* @param {object} [opts]
* @param {Function} [opts.now] 取当前时间(毫秒),测试里可换成假时钟
*/
export function createStudyTracker(opts = {}) {
const now = opts.now || (() => Date.now());
let studySeconds = 0; // 本次运行累计播放时长(秒)
let creditEarned = 0; // 本次运行累计获得学分
let credit = null; // 当前这门课学完能拿多少学分(平台只在播放期间写出来)
let lastAt = 0; // 上一条快照的时间,用来算两次之间播了多少秒
let lastPlaying = false;
let lastCompleted = 0;
let lastCourse = '';
const creditOf = new Map(); // 课程名 → 可得学分(学完后元素消失,只能靠缓存)
const credited = new Set(); // 已计入的课程,防止重试 / 刷新页面重复累加
/**
* 吃一条主监控快照,返回最新的统计值。
* 传进来的快照字段可能缺失(页面刚跳转时就是半空的),所以全部按可选处理。
*/
function update(snap) {
if (!snap || snap.noApi) return get();
const at = now();
const course = snap.course || '';
// ---- 学习时长:只算视频真的在播的时间 ----
// 用「两次快照的真实间隔」而不是写死的轮询周期:CDP 往返偶尔会慢,
// 写死一个常数会让长跑下来明显偏少或偏多。间隔过大说明中间断过,直接丢弃不补计。
// 只有「上一帧在播、这一帧也在播」才计:宁可少算一秒,不能把
// 暂停后挂机的时间 算成学习时长(挂机好几分钟才是常态)。
const playing = !!(snap.video && !snap.video.paused);
if (lastPlaying && playing && lastAt > 0) {
const gap = (at - lastAt) / 1000;
if (gap > 0 && gap <= MAX_GAP_SECONDS) studySeconds += gap;
}
lastPlaying = playing;
lastAt = at;
// ---- 学分:边播边记「这门课值多少分」----
const read = typeof snap.credit === 'number' && snap.credit > 0 ? snap.credit : null;
if (read != null) {
credit = read;
if (course) creditOf.set(course, read);
} else if (course && creditOf.has(course)) {
credit = creditOf.get(course); // 倒计时消失(学完了)后沿用缓存值
} else if (course && course !== lastCourse) {
credit = null; // 换课了,新课的学分还没读出来
}
// ---- 学分:只给真正刷完的课发分 ----
const completed = Number(snap.completed) || 0;
if (completed > lastCompleted) {
// 完成数涨了:刚刷完的那门课此刻可能已经从快照里切走,所以用上一次记的课程名
const justDone = lastCourse || course;
if (justDone && creditOf.has(justDone) && !credited.has(justDone)) {
credited.add(justDone);
creditEarned += creditOf.get(justDone);
}
lastCompleted = completed;
}
if (course) lastCourse = course;
return get();
}
/** 当前统计值(不会被外部改到内部状态) */
function get() {
// 学分保留两位小数:平台给的本来就是 0.23 / 6.52 这种,浮点累加会出现 3.7499999
return { studySeconds, credit, creditEarned };
}
/** 日志 / 收尾用的一句话(没有数据时返回空串,调用方直接跳过) */
function summary() {
if (studySeconds <= 0 && creditEarned <= 0) return '';
return '视频累计播放 ' + fmt(studySeconds) + ',获得 ' + creditText() + ' 学分';
}
/** 学分文本:整数不带小数点,小数保留最多两位并去掉尾随 0 */
function creditText(value) {
const v = value === undefined ? creditEarned : value;
return String(Number(v.toFixed(2)));
}
return { update, get, summary, creditText, reset() { studySeconds = 0; creditEarned = 0; credit = null; lastAt = 0; lastPlaying = false; lastCompleted = 0; lastCourse = ''; creditOf.clear(); credited.clear(); } };
}
/** 秒 → 1:23:45 / 23:45(与面板显示保持一致,面板自己那份在 tui.mjs) */
function fmt(sec) {
const s = Math.max(0, Math.round(Number(sec) || 0));
const h = Math.floor(s / 3600);
const two = (n) => String(n).padStart(2, '0');
const m = Math.floor((s % 3600) / 60);
const r = s % 60;
return h > 0 ? h + ':' + two(m) + ':' + two(r) : two(m) + ':' + two(r);
}
+50 -10
View File
@@ -1,4 +1,4 @@
// 进程层:日志开关、启动横幅、崩溃重启循环、退出码。
// 进程层:日志开关、终端面板、启动横幅、崩溃重启循环、退出码。
//
// 一次会话(session.mjs)只管一个浏览器进程;这里管「崩了就重来」以及「什么情况该放弃」。
// 重试等待递增:15s → 30s → 45s …,上限 120s,避免持续失败时疯狂刷 CDP 端口。
@@ -7,6 +7,7 @@ import { cleanStaleSingleton } from './browser.mjs';
import { runSession, disposeActiveSession } from './session.mjs';
import { openLog } from './log.mjs';
import { noDisplayReason, platformName } from './platform.mjs';
import { createTui } from './tui.mjs';
const RETRY_BASE_MS = 15000;
const RETRY_MAX_MS = 120000;
@@ -16,7 +17,9 @@ const RETRY_MAX_MS = 120000;
* @param {object} o.cfg
* @param {string} o.binary
* @param {string} o.scriptSrc
* @param {object} o.stop
* @param {object} o.stop stop.mjs 的句柄
* @param {object} [o.tui] 已创建的面板(不传就按 cfg.TUI 自己建)
* @param {Function} [o.onQuitRequest] 面板按 q 时的回调(默认接到 stop 上)
* @param {Function} o.log / o.warn / o.error
*/
export async function runSupervisor(o) {
@@ -26,6 +29,19 @@ export async function runSupervisor(o) {
// 自检不写文件日志:避免每次 --check 都改仓库内容
if (!cfg.CHECK_ONLY) openLog(cfg.LOG_FILE, cfg.LOG_MAX_BYTES);
// 面板要先于启动横幅建好:横幅和后续日志都会进面板的日志区
const tui = o.tui || createTui({
enabled: cfg.TUI,
title: '云学堂助手 · 无头运行器' + (cfg.CHECK_ONLY ? '(自检)' : ''),
logFile: cfg.CHECK_ONLY ? '' : cfg.LOG_FILE,
color: cfg.COLOR,
onQuit: (reason) => {
if (o.onQuitRequest) o.onQuitRequest(reason);
else if (typeof stop.request === 'function') stop.request(reason);
},
});
tui.set({ maxCourses: cfg.MAX_COURSES });
log('=== 云学堂助手 · 无头运行器' + (cfg.CHECK_ONLY ? '(自检)' : '') + ' 启动 ===');
log('Node ' + process.version + ' ' + platformName + '/' + process.arch);
log('配置 ' + (cfg.CONFIG_FILE || '(未找到 config/runner.config.mjs,使用内置默认值)'));
@@ -35,23 +51,33 @@ export async function runSupervisor(o) {
warn(noDisplayReason() + ',配置里的 headless: false 被忽略,强制无头运行。');
}
if (!cfg.CHECK_ONLY) {
log('日志 ' + cfg.LOG_FILE + '(' + (process.platform === 'win32' ? 'Ctrl+C 结束' : 'Ctrl+C 结束') + ')');
log('日志 ' + cfg.LOG_FILE + '(Ctrl+C 或面板里按 q 结束)');
}
if (!cfg.TUI && cfg.tuiDisabledReason) log('面板:' + cfg.tuiDisabledReason());
tui.set({ phase: '启动中' });
let attempt = 0;
let last = null;
/** 收尾时先把面板收掉,退出日志和退出码提示才会逐行打印出来 */
const finishTui = (phase, tone) => {
tui.set({ phase, tone });
tui.finish();
};
while (!stop.stopping) {
attempt++;
if (attempt > 1) log('--- 第 ' + attempt + ' 次尝试 ---');
tui.set({ attempt, phase: attempt > 1 ? '重启浏览器' : '启动浏览器', tone: 'info' });
try {
last = await runSession({ ...o, cfg });
last = await runSession({ ...o, cfg, tui });
if (stop.stopping) break;
if (cfg.CHECK_ONLY) break;
// 正常结束:只有「脚本自己停了 / 无进展」且配了重启间隔才再来一轮
const restartable = !last.limitReached && cfg.RESTART_MINUTES > 0;
if (!restartable) break;
log('按 YUN_XUE_TANG_RESTART_MINUTES=' + cfg.RESTART_MINUTES + ' 等待后重新开始…');
tui.set({ phase: '等待 ' + cfg.RESTART_MINUTES + ' 分钟后重开', tone: 'ok' });
const until = Date.now() + cfg.RESTART_MINUTES * 60000;
while (!stop.stopping && Date.now() < until) await sleep(2000);
if (stop.stopping) break;
@@ -61,20 +87,34 @@ export async function runSupervisor(o) {
// 会话抛错时内部的收尾代码已被跳过,这里补上:否则浏览器进程会残留、端口被占
await disposeActiveSession();
error('会话异常:' + (e && e.message ? e.message : e));
tui.set({ phase: '会话异常,准备重试', tone: 'error' });
// 连登 5 次失败基本都是密码错 / 要验证码,重试没意义,直接用专门的退出码结束
if (e && e.message && /连续 \d+ 次登录失败/.test(e.message)) {
finishTui('登录失败,检查账号密码 / 验证码', 'error');
return { exitCode: 3, last };
}
const waitMs = Math.min(RETRY_BASE_MS * attempt, RETRY_MAX_MS);
warn('浏览器/连接异常,' + Math.round(waitMs / 1000) + ' 秒后重试(第 ' + attempt + ' 次)');
const secs = Math.round(waitMs / 1000);
warn('浏览器/连接异常,' + secs + ' 秒后重试(第 ' + attempt + ' 次)');
tui.set({ phase: '会话异常,' + secs + ' 秒后重试', tone: 'warn' });
await sleep(waitMs);
}
}
log('=== 运行器退出 ===');
const stalled = !!(last && /没有任何进展/.test(last.finishReason || ''));
const exitCode = cfg.CHECK_ONLY ? (last && last.ok ? 0 : 1) : (stalled ? 1 : 0);
// 0 = 正常收尾(达到上限 / 预算 / 无更多课程);1 = 无进展卡死;3 = 连续登录失败
const phase = cfg.CHECK_ONLY
? (exitCode === 0 ? '自检通过' : '自检失败')
: stalled ? '退出:长时间无进展' : '正常收尾';
finishTui(phase, exitCode === 0 ? 'ok' : (stalled ? 'warn' : 'error'));
if (cfg.CHECK_ONLY) return { exitCode: last && last.ok ? 0 : 1, last };
// 0 = 正常收尾(达到上限 / 预算 / 无更多课程);1 = 无进展卡死
if (last && /没有任何进展/.test(last.finishReason || '')) return { exitCode: 1, last };
return { exitCode: 0, last };
log('=== 运行器退出 ===');
if (last && last.finishReason) log('结束原因:' + last.finishReason);
if (cfg.CHECK_ONLY && last) log('自检结果:' + (last.ok ? '通过' : '失败 —— ' + last.reason));
// 学习统计只在本次运行内有效(不落盘),退出时在日志里留一行,方便事后回看
const studyLine = typeof tui.studySummary === 'function' ? tui.studySummary() : '';
if (!cfg.CHECK_ONLY && studyLine) log('本次学习:' + studyLine);
return { exitCode, last, tui };
}
+558
View File
@@ -0,0 +1,558 @@
// 终端面板(TUI):把无头运行器的状态画成一个会自己刷新的框,代替刷屏的逐行日志。
//
// 设计约束(都很重要,改之前先看一遍):
// 1. 只读:面板不提供暂停 / 改配置之类的操作,唯一按键是 q(或 Ctrl+C)优雅退出。
// 「改行为」仍然走配置文件 / 环境变量 / 命令行,面板不制造第二套控制入口。
// 2. 不碰日志文件:面板只接管「终端」输出(log.mjs 的控制台 sink),
// run-logs/*.log 仍然是纯文本逐行,grep / 采集都不受影响。
// 3. 自动降级:stdout 不是交互式终端(重定向到文件、CI、计划任务)时完全不启用,
// 行为与旧版逐行日志一模一样(见 config.mjs 的 TUI 判断)。
//
// 重绘方式:不整屏清空,而是「回到本帧首行重画」——面板上方的启动横幅等历史输出
// 仍留在回滚区里。技巧是最后一帧不留结尾换行,光标停在帧尾;下次从帧尾向上移动
// (行数-1) 行即回到首行,因此永远不会触发终端滚动、也不会闪烁。
import { setConsoleSink } from './log.mjs';
import { createStudyTracker } from './study.mjs';
const ESC = '\x1b[';
const RESET = ESC + '0m';
/** 保留多少行历史日志(终端再高也只显示其中一部分) */
const BUFFER_MAX = 200;
/** 标签列宽(「倒计时」这类三字标签也放得下) */
const LABEL_W = 7;
// ---------------------------------------------------------------------------
// 中文对齐:全角字符占 2 列,直接用 String.length 补空格会把边框顶歪
// ---------------------------------------------------------------------------
function charWidth(ch) {
const cp = ch.codePointAt(0);
if (cp === 0 || cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0;
if (cp === 0x2329 || cp === 0x232a) return 2;
if (cp >= 0x1100 && cp <= 0x115f) return 2;
if (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) return 2;
if (cp >= 0xac00 && cp <= 0xd7a3) return 2;
if (cp >= 0xf900 && cp <= 0xfaff) return 2;
if (cp >= 0xfe30 && cp <= 0xfe6f) return 2;
if (cp >= 0xff00 && cp <= 0xff60) return 2;
if (cp >= 0xffe0 && cp <= 0xffe6) return 2;
if (cp >= 0x1f300 && cp <= 0x1f64f) return 2;
if (cp >= 0x1f900 && cp <= 0x1f9ff) return 2;
if (cp >= 0x20000 && cp <= 0x3fffd) return 2;
return 1;
}
/** 字符串在终端里占几列(ANSI 转义序列不计数) */
export function textWidth(s) {
let w = 0;
for (const ch of stripAnsi(s)) w += charWidth(ch);
return w;
}
/** 去掉 ANSI 序列(算可见宽度用) */
export function stripAnsi(s) {
return String(s).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
}
const ANSI_RE = /\x1b\[[0-9;]*[A-Za-z]/g;
/**
* 按可见列宽遍历:回调拿到 (token, width),ANSI 转义序列 width=0。
* cut / padEnd 都靠它,否则带颜色的字符串会被当成超宽而错误截断。
*/
function walkWidth(s, fn) {
s = String(s);
let i = 0;
ANSI_RE.lastIndex = 0;
let m;
while ((m = ANSI_RE.exec(s))) {
for (const ch of s.slice(i, m.index)) fn(ch, charWidth(ch));
fn(m[0], 0);
i = m.index + m[0].length;
}
for (const ch of s.slice(i)) fn(ch, charWidth(ch));
}
/** 右侧补空格到指定列宽(ANSI 序列不计数) */
function padEnd(s, width) {
const gap = width - textWidth(s);
return gap > 0 ? String(s) + ' '.repeat(gap) : String(s);
}
/** 截断到指定列宽,被截断时末尾用 … 占位(ANSI 序列不计数,截断后补 reset) */
function cut(s, width) {
s = String(s);
if (width <= 0) return '';
const plain = stripAnsi(s);
if (textWidth(plain) <= width) return s;
let out = '';
let w = 0;
let truncated = false;
walkWidth(s, (tok, cw) => {
if (truncated) return;
if (cw === 0) { out += tok; return; } // ANSI 序列照常透传
if (w + cw > width - 1) { truncated = true; return; }
out += tok;
w += cw;
});
return out + '…' + (s.includes('\x1b[') ? '\x1b[0m' : '');
}
/** 秒数 → 01:12:45 / 12:45 */
export function formatDuration(sec) {
const s = Math.max(0, Math.round(Number(sec) || 0));
const h = Math.floor(s / 3600);
const two = (n) => String(n).padStart(2, '0');
const m = Math.floor((s % 3600) / 60);
const r = s % 60;
return h > 0 ? h + ':' + two(m) + ':' + two(r) : two(m) + ':' + two(r);
}
/** 进度条:█ / ░ 各占 1 列 */
export function progressBar(ratio, width) {
const r = Math.max(0, Math.min(1, Number(ratio) || 0));
const filled = Math.round(r * width);
return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled));
}
/**
* 一组行在宽度 cols 下实际占的屏幕行数。
* 终端在窗口变窄时会把超宽的行自己折成多行,所以「逻辑行数」≠「屏幕行数」;
* 回退光标、决定清屏起点都得用这个函数,否则窗口一变就会留下半截面板。
* 行宽为 0 时算一行(空白行不折)。
*/
export function visualRows(widths, cols) {
const w = Math.max(1, Number(cols) || 80);
let total = 0;
for (const raw of widths || []) {
const width = Number(raw) || 0;
total += Math.max(1, Math.ceil(width / w));
}
return total;
}
/** ANSI 颜色;关闭时全部退化为恒等函数(NO_COLOR / --no-color) */
function makeColors(on) {
const wrap = (code) => (s) => (on ? ESC + code + 'm' + s + RESET : String(s));
return {
bold: wrap('1'), dim: wrap('2'), gray: wrap('90'),
red: wrap('31'), green: wrap('32'), yellow: wrap('33'),
blue: wrap('34'), magenta: wrap('35'), cyan: wrap('36'),
};
}
/**
* 创建面板实例。enabled 为 false 时所有方法都是空操作,
* 所以上层(supervisor / session)可以无条件调用 tui.set() / tui.snap()。
*
* @param {object} opts
* @param {boolean} opts.enabled 是否启用(由 config.mjs 按 TTY 判断)
* @param {Function} [opts.onQuit] 用户按 q / Ctrl+C 时的回调(接到 stop.mjs 上)
* @param {string} [opts.title] 标题
* @param {string} [opts.logFile] 日志文件路径(面板里显示)
* @param {boolean} [opts.color] 是否用 ANSI 颜色(默认看 NO_COLOR)
* @param {object} [opts.out] 输出流(测试用,默认 process.stdout)
* @param {object} [opts.stdin] 输入流(测试用,默认 process.stdin)
*/
export function createTui(opts = {}) {
const enabled = !!opts.enabled;
const out = opts.out || process.stdout;
const stdin = opts.stdin || process.stdin;
const onQuit = opts.onQuit || (() => {});
const colorOn = enabled && opts.color !== false && !process.env.NO_COLOR;
const C = makeColors(colorOn);
const state = {
title: opts.title || '云学堂助手 · 无头运行器',
phase: '启动中',
tone: 'info', // info / ok / warn / error
attempt: 1,
course: '',
lesson: '',
summary: '',
countdown: null,
completed: 0,
maxCourses: 0,
doneCount: 0,
retryCount: 0,
retryWait: 0,
lessons: 0,
video: null,
// 学习统计(只在本次运行内累计,退出清零,不落盘)
studySeconds: 0, // 学习时长:只累加视频真正在播的时间
creditEarned: 0, // 获得学分:只算本次运行里完成(刷完)的课程
credit: null, // 当前课程可得多少学分(平台只在播放期间写在倒计时文案里)
injected: 0,
logFile: opts.logFile || '',
startedAt: Date.now(),
};
const buffer = [];
// 学时 / 学分累计逻辑在 study.mjs(纯数据,可脱离终端与浏览器单测)
const study = createStudyTracker(opts.studyOpts);
let timer = null;
let resizeTimer = null;
let lastLines = 0;
// 上一帧每行的「可见列宽」。终端变窄时它会把自己重排(把宽行折成多行),
// 所以回退光标时不能只数逻辑行数,得按新宽度算出旧帧实际占了几行。
let lastWidths = [];
let finished = false;
let rawAttached = false;
// ---------------- 布局 ----------------
// 窗口大小每画一帧都重新读:拖动终端、tmux 分屏、浏览器式面板都会改 out.columns / out.rows,
// 不做缓存,resize 之后第一帧就是对的。宽度跟终端走(只保留最小 36 列防止破版)。
const columns = () => Math.max(36, Number(out.columns) || 80);
const rowsOf = () => Math.max(8, Number(out.rows) || 24);
// 记住上一次实际用过的尺寸。Windows 的 Node 不会在最大化 / 拉伸控制台时发 resize 事件
// (libuv 拿不到那边的控制台尺寸变更通知),所以不能只靠事件,必须每次画之前自己比一次。
let lastCols = columns();
let lastRows = rowsOf();
/** 终端尺寸真的变了就记录并报告;缩小需要先清整块(否则旧帧的尾巴会露在框外) */
function syncSize() {
const cols = columns();
const rows = rowsOf();
if (cols === lastCols && rows === lastRows) return false;
const shrank = cols < lastCols || rows < lastRows;
lastCols = cols;
lastRows = rows;
return shrank;
}
/**
* 当前窗口下的行分配。
* 矮窗口(<15 行)进紧凑模式:省掉「课时」「日志」两行,先保住视频进度和学时;
* 更矮时连日志区和底部 q 提示也省掉——绝不让面板超出窗口,超出会把回滚区里的历史顶掉。
*/
function layout() {
const rows = rowsOf();
const compact = rows < 15;
const hint = rows >= 10 ? 1 : 0;
const infoRows = compact ? 5 : 7; // 状态 / 课程 / 学时 / 视频 / 进度(+ 课时 / 日志)
// 1 标题行 + infoRows + 1 分隔行 + room 日志行 + 1 底边框 + hint
const slack = rows - (infoRows + 3 + hint);
const showLogs = slack >= 1;
const room = showLogs ? Math.min(10, slack) : 0;
return { rows, compact, hint, showLogs, room };
}
function toneWrap(text) {
if (state.tone === 'ok') return C.green(text);
if (state.tone === 'warn') return C.yellow(text);
if (state.tone === 'error') return C.red(text);
return C.cyan(text);
}
function videoValue(width) {
const v = state.video;
if (!v || !v.d) {
if (state.countdown != null) return C.gray('等待视频(倒计时 ' + state.countdown + 's)');
return C.gray('—');
}
const ratio = v.d > 0 ? v.t / v.d : 0;
// 窄终端里进度条先缩,仍有地方就按实宽决定加不加时光与状态(不硬截断)
const times = formatDuration(v.t) + '/' + formatDuration(v.d);
const barW = Math.max(10, Math.min(40, width - 30));
const parts = [progressBar(ratio, barW), String(Math.round(ratio * 100)).padStart(3) + '%'];
const used = () => textWidth(parts.join(' '));
if (used() + 2 + textWidth(times) <= width) parts.push(times);
const tail = v.err >= 3 ? C.red('解码失败 error.code=' + v.err) : (v.paused ? C.yellow('暂停') : '');
if (tail && used() + 2 + textWidth(tail) <= width) parts.push(tail);
return parts.join(' ');
}
function countValue(width) {
// 字段按重要性递降:本次/累计是骨架,其余在窄终端里从右往左丢,不硬截断
const parts = ['本次 ' + state.completed + (state.maxCourses > 0 ? '/' + state.maxCourses : ''),
'累计 ' + state.doneCount];
const extra = [];
if (state.lessons) extra.push('课时数 ' + state.lessons);
if (state.retryWait > 0) extra.push(C.yellow('等待重试 ' + state.retryWait + 's'));
else if (state.retryCount > 0) extra.push(C.yellow('待重试 ' + state.retryCount));
if (state.countdown != null) extra.push('倒计时 ' + state.countdown + 's');
const used = () => textWidth(parts.join(' · '));
for (const item of extra) {
if (used() + 3 + textWidth(item) > width) break; // +3 = ' · '
parts.push(item);
}
return parts.join(' · ');
}
function statusValue(valueW) {
const plain = state.phase + (state.attempt > 1 ? ' · 第 ' + state.attempt + ' 次尝试' : '');
const colored = toneWrap(plain);
const elapsed = '已运行 ' + formatDuration((Date.now() - state.startedAt) / 1000);
const gap = valueW - textWidth(plain) - textWidth(elapsed);
if (gap < 2) return cut(colored + (gap > 0 ? ' '.repeat(gap) : '') + ' ' + elapsed, valueW);
return colored + ' '.repeat(gap) + C.gray(elapsed);
}
/**
* 「学时」行:本次已学时长 + 本次获得学分。
* 时长按视频实际播放累计(排队 / 重试 / 加载不算);
* 学分只算真正刷完的课程,且按课程去重。窄终端先丢「本门」再截断。
*/
function studyValue(width) {
const parts = [C.cyan('已学 ' + formatDuration(state.studySeconds))];
parts.push(C.green('学分 ' + study.creditText(state.creditEarned)));
const used = () => textWidth(parts.join(' · '));
if (state.credit != null) {
const now = '本门 ' + study.creditText(state.credit);
if (used() + 3 + textWidth(now) <= width) parts.push(now);
}
const tail = state.video && state.video.paused ? C.gray('暂停中,不计时') : '';
if (tail && used() + 3 + textWidth(tail) <= width) parts.push(tail);
return parts.join(' · ');
}
/** 组装一帧的所有行(含 ANSI 色,宽度已按列算好) */
function buildFrame() {
const cols = columns();
const inner = cols - 4; // "│ " + 内容 + " │"
const valueW = inner - LABEL_W;
const row = (label, value) => {
const text = padEnd(cut(value, valueW), valueW);
return '│ ' + C.dim(padEnd(label, LABEL_W)) + text + ' │';
};
const { compact, hint, showLogs, room } = layout();
const lines = [];
const title = ' ' + cut(state.title, cols - 8) + ' ';
lines.push('╭' + title + '─'.repeat(Math.max(0, cols - 2 - textWidth(title))) + '╮');
lines.push(row('状态', statusValue(valueW)));
lines.push(row('课程', state.course || (state.phase === '启动中' ? '—' : '列表页 / 未识别')));
// 学时紧跟在课程后面:挂机时最关心「学了多久、赚了多少」
lines.push(row('学时', studyValue(valueW)));
// 紧凑模式先丢「课时」「日志」:视频进度和学时才是挂机时真想看的
if (!compact) lines.push(row('课时', [state.lesson || '—', state.summary].filter(Boolean).join(' ')));
lines.push(row('视频', videoValue(valueW)));
lines.push(row('进度', countValue(valueW)));
if (!compact) {
lines.push(row('日志', [state.logFile || '(未写日志文件)', '已注入 ' + state.injected + ' 次'].join(' · ')));
}
if (showLogs) {
const sec = ' 最近日志 ';
lines.push('├' + C.dim(sec) + '─'.repeat(Math.max(0, cols - 2 - textWidth(sec))) + '┤');
const recent = buffer.slice(-room);
const blank = '│' + ' '.repeat(cols - 2) + '│';
for (let i = recent.length; i < room; i++) lines.push(blank);
for (const line of recent) {
lines.push('│ ' + C.dim(padEnd(cut(line, inner), inner)) + ' │');
}
}
lines.push('╰' + '─'.repeat(Math.max(0, cols - 2)) + '╯');
if (hint) lines.push(C.gray(cut(' q 退出(等价 Ctrl+C:暂停视频、停批量、关浏览器)· 完整日志照常写入日志文件', cols)));
return lines;
}
/**
* 画一帧。尺寸变了就改跑 redraw():终端变窄 / 变矮时,上一帧更宽或更高的字符
* 会露在新框外面,必须先整块清掉;变大时旧帧完全被盖住,直接重画就行。
*/
function render() {
if (!enabled || finished) return;
// Windows 控制台最大化 / 拖动时不会发 resize 事件,只能在这里发现变化
if (syncSize()) redraw();
else paint();
}
function paint() {
if (!enabled || finished) return;
let lines;
try {
lines = buildFrame();
} catch (e) {
return; // 面板自身出错绝不能影响刷课
}
const cols = columns();
const maxRows = rowsOf();
if (lines.length > maxRows) lines = lines.slice(0, maxRows);
// 上一帧在当前宽度下实际占的可视行数(窗口没变时它就等于上帧的逻辑行数)
const prevRows = visualRows(lastWidths, cols);
let buf = '';
// 上一帧光标停在帧尾;向上移动 (可视行数-1) 行即回到本帧首行
if (prevRows > 0) {
const up = Math.max(0, Math.min(prevRows - 1, maxRows - 1));
buf += ESC + up + 'A\r';
}
for (let i = 0; i < lines.length; i++) {
// 行尾清到行末(\x1b[K):终端变窄或日志变短时,上一帧的尾巴不会残留
buf += lines[i] + ESC + 'K';
if (i < lines.length - 1) buf += '\r\n';
}
buf += ESC + '0J'; // 本帧下方的内容一并清掉(终端变矮时防残留)
try { out.write(buf); } catch (e) { /* ignore */ }
lastLines = lines.length;
lastWidths = lines.map((l) => textWidth(stripAnsi(l)));
}
/**
* 硬重绘:终端尺寸变了之后,上次记的帧行数已经不可信(终端可能还自己重排过),
* 所以先把光标拉回块首、清掉整块,再按新尺寸画一帧。
* 向上移动的步数取 min(上帧行数-1, 当前行数-1):窗口缩到比上帧还矮时不会被顶出屏幕。
*/
function redraw() {
if (!enabled || finished) return;
if (lastWidths.length > 0 || lastLines > 0) {
const cols = columns();
const maxRows = rowsOf();
// 关键:用「旧帧在新宽度下会被折成几行」来回退,而不是旧的逻辑行数。
// 最大化后再还原(170 列 → 80 列)时,旧帧每行都被折成两行,
// 按逻辑行数退会落在旧面板中间,上半截就永远留在屏幕上了。
const folded = visualRows(lastWidths, cols);
if (folded - 1 > maxRows - 1) {
// 旧帧折行后比整个窗口还高:它的起点已经滚到屏幕上方去了,
// 光标最多只能退到第一行,退不到块首。这种情况只能整屏重置——
// 先把光标匀回左上角再清掉全屏,然后在顶部重画。
// (屏幕上方的历史会没,但那些日志本来就在 run-logs/*.log 里)
try { out.write(ESC + 'H' + ESC + '2J'); } catch (e) { /* ignore */ }
} else {
const up = Math.max(0, folded - 1);
try { out.write('\r' + (up > 0 ? ESC + up + 'A' : '') + ESC + '0J'); } catch (e) { /* ignore */ }
}
lastLines = 0; // 光标已经回到块首,paint 不必再回退
lastWidths = [];
}
paint();
}
// ---------------- 键盘:只认 q / Q / Ctrl+C ----------------
function onKey(chunk) {
for (const ch of String(chunk)) {
if (ch === 'q' || ch === 'Q' || ch === '\u0003') {
// 先收面板再走退出流程,退出日志才能正常打在面板下面
const reason = ch === '\u0003' ? 'Ctrl+C' : 'q';
finish();
onQuit(reason);
return;
}
if (ch === '\u000c') redraw(); // Ctrl+L 强制重画(终端被外部输出打乱时用)
}
}
function attachInput() {
if (!enabled || rawAttached) return;
if (!stdin || !stdin.isTTY || typeof stdin.setRawMode !== 'function') return;
try {
stdin.setRawMode(true);
stdin.setEncoding('utf8');
stdin.on('data', onKey);
stdin.resume();
rawAttached = true;
} catch (e) {
rawAttached = false;
}
}
function restoreInput() {
if (!rawAttached) return;
rawAttached = false;
try {
stdin.off('data', onKey);
stdin.setRawMode(false);
stdin.pause();
} catch (e) { /* ignore */ }
}
// ---------------- 生命周期 ----------------
function finish() {
if (!enabled || finished) return;
finished = true;
if (timer) { clearInterval(timer); timer = null; }
if (resizeTimer) { clearTimeout(resizeTimer); resizeTimer = null; }
if (typeof out.removeListener === 'function') {
out.removeListener('resize', onResize);
}
restoreInput();
setConsoleSink(null); // 终端输出恢复逐行,收尾日志才看得见
// 摘掉 exit 监听:supervisor 重试用例里同一进程会建多次面板,不摘会触发 MaxListeners 警告
try { process.removeListener('exit', finish); } catch (e) { /* ignore */ }
try { out.write('\n' + ESC + '?25h'); } catch (e) { /* ignore */ } // 换行 + 显示光标
}
/**
* 窗口尺寸变化:拖拽终端时 resize 事件会连发几十次,去抖后再硬重绘。
* 注意这条路径只在支持该事件的平台生效(Linux / macOS / Windows Terminal);
* Windows 传统控制台(conhost)拖窗口 / 最大化不会发事件,那种情况靠
* render() 里的 syncSize() 在 1 秒内发现。两者取其一即可,都碰到也只是多一次重绘。
*/
function onResize() {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
resizeTimer = null;
lastCols = columns(); // 事件已经告诉我们尺寸变了,直接记录,避免 syncSize 再判一次
lastRows = rowsOf();
redraw();
}, 60);
if (typeof resizeTimer.unref === 'function') resizeTimer.unref();
}
function install() {
if (!enabled || finished) return;
attachInput();
try { out.write(ESC + '?25l'); } catch (e) { /* ignore */ } // 隐藏光标
// 终端输出改道到面板日志区;文件日志不受影响(log.mjs 里两路分开写)
setConsoleSink((level, text) => {
buffer.push(text);
if (buffer.length > BUFFER_MAX) buffer.splice(0, buffer.length - BUFFER_MAX);
// 警告 / 错误立即重绘,普通信息等下一次定时刷新,避免频繁重绘
if (level !== '信息') render();
});
if (typeof out.on === 'function') out.on('resize', onResize);
render();
timer = setInterval(render, 1000);
if (typeof timer.unref === 'function') timer.unref();
if (typeof process.on === 'function') process.on('exit', finish);
}
if (enabled) install();
return {
enabled,
/** 合并更新面板状态(enabled=false 时是空操作) */
set(patch) {
if (enabled && patch) Object.assign(state, patch);
},
/**
* 用 session 的主监控快照刷新面板,顺便累计学习时长与学分(详细规则见 study.mjs)。
*/
snap(s) {
if (!enabled || !s || s.noApi) return;
const pick = (v, d) => (v === undefined ? d : v);
const st = study.update(s);
state.studySeconds = st.studySeconds;
state.creditEarned = st.creditEarned;
state.credit = st.credit;
state.course = pick(s.course, '');
state.lesson = pick(s.lesson, '');
state.summary = (s.summary && s.summary.text) || '';
state.countdown = s.countdown == null ? null : s.countdown;
state.completed = Number(s.completed) || 0;
state.doneCount = pick(s.doneCount, 0);
state.retryCount = pick(s.retryCount, 0);
state.retryWait = pick(s.retryWait, 0);
state.lessons = pick(s.lessons, 0);
state.video = s.video || null;
},
render,
redraw,
finish,
/** 学习统计(收尾日志用,与面板显示同一份数据) */
get study() { return study.get(); },
/** 学习统计的一句话摘要(没有数据时是空串) */
studySummary() { return study.summary(); },
/** 当前布局分配(自测里断言矮终端降级用) */
get layout() { return layout(); },
/** 当前状态快照(自检 / 测试用) */
get state() { return { ...state }; },
/** 已缓存的终端日志行(测试用) */
get logLines() { return buffer.slice(); },
};
}
+9
View File
@@ -83,12 +83,21 @@ for (const file of cmdTargets.sort()) {
let lf = 0;
let crlf = 0;
let loneCr = 0;
for (let i = 0; i < buf.length; i++) {
if (buf[i] === 0x0a) {
lf++;
if (i > 0 && buf[i - 1] === 0x0d) crlf++;
} else if (buf[i] === 0x0d && buf[i + 1] !== 0x0a) {
loneCr++;
}
}
// 裸 CR(不是 CRLF 的一部分)会把下一个字符吃掉:'config\runner' 里的反斜杠
// 曾经变成 CR,报“configunner.config.mjs not found”
if (loneCr) {
bad.push('有 ' + loneCr + ' 处裸 CR(不是 CRLF 的 CR);'
+ '它会吞掉后面的字符,例如 config\\runner 变成 config<CR>unner');
}
if (lf !== crlf) {
bad.push('有 ' + (lf - crlf) + ' 处裸 LF 行尾(共 ' + lf + ' 个 LF / ' + crlf + ' 个 CRLF);'
+ 'cmd.exe 会把上一行尾部当成命令的一部分');
+4 -4
View File
@@ -7,7 +7,7 @@ rem it report nonsense like "'npm' is not recognized".
rem All Chinese messages come from the Node runner output instead.
rem
rem Usage:
rem scripts\start-headless.cmd use config␍unner.config.mjs
rem scripts\start-headless.cmd use config\runner.config.mjs
rem scripts\start-headless.cmd --help print all options
rem scripts\start-headless.cmd --max 3 command line overrides config file
rem ---------------------------------------------------------------
@@ -25,12 +25,12 @@ call npm run build
if errorlevel 1 goto build_fail
:have_build
if not exist "config␍unner.config.mjs" goto no_config
echo [config] config␍unner.config.mjs found, editing it is enough (no rebuild needed)
if not exist "config\runner.config.mjs" goto no_config
echo [config] config\runner.config.mjs found, editing it is enough (no rebuild needed)
goto run
:no_config
echo [warn] config␍unner.config.mjs not found, built-in defaults will be used
echo [warn] config\runner.config.mjs not found, built-in defaults will be used
:run
echo [run] headless runner starting, press Ctrl+C to stop