Files
yun-xue-tang-assistant/runner/supervisor.mjs
T
void 65bf63ea6a 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(假时钟口径)
2026-10-26 21:49:13 +08:00

121 lines
5.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 进程层:日志开关、终端面板、启动横幅、崩溃重启循环、退出码。
//
// 一次会话(session.mjs)只管一个浏览器进程;这里管「崩了就重来」以及「什么情况该放弃」。
// 重试等待递增:15s → 30s → 45s …,上限 120s,避免持续失败时疯狂刷 CDP 端口。
import { sleep } from './cdp.mjs';
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;
/**
* @param {object} o
* @param {object} o.cfg
* @param {string} o.binary
* @param {string} o.scriptSrc
* @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) {
const { cfg, stop } = o;
const log = o.log, warn = o.warn, error = o.error;
// 自检不写文件日志:避免每次 --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,使用内置默认值)'));
log('浏览器 ' + o.binary);
log('profile ' + cfg.PROFILE_DIR + '(cookie / localStorage 持久化,删掉即重置登录态与进度缓存)');
if (cfg.WANT_VISIBLE && !cfg.VISIBLE) {
warn(noDisplayReason() + ',配置里的 headless: false 被忽略,强制无头运行。');
}
if (!cfg.CHECK_ONLY) {
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, 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;
cleanStaleSingleton(cfg.PROFILE_DIR);
} catch (e) {
if (stop.stopping) break;
// 会话抛错时内部的收尾代码已被跳过,这里补上:否则浏览器进程会残留、端口被占
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);
const secs = Math.round(waitMs / 1000);
warn('浏览器/连接异常,' + secs + ' 秒后重试(第 ' + attempt + ' 次)');
tui.set({ phase: '会话异常,' + secs + ' 秒后重试', tone: 'warn' });
await sleep(waitMs);
}
}
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'));
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 };
}