Files
yun-xue-tang-assistant/runner/tui.mjs
T
voidandClaude Sonnet 4.6 6b508a0b1a feat: Bark 增加开始运行与获得学分提醒
收尾通知去掉重复的积分台账与完成门数;学习统计在无 TTY 时照常累计,保证 Docker 里也能推送学分提醒。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-11-02 22:30:11 +08:00

567 lines
24 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.
// 终端面板(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,
doneCount: 0,
retryCount: 0,
retryWait: 0,
lessons: 0,
video: null,
// 学习统计(只在本次运行内累计,退出清零,不落盘)
studySeconds: 0, // 学习时长:只累加视频真正在播的时间
creditEarned: 0, // 获得学分:只算本次运行里完成(刷完)的课程
credit: null, // 当前课程可得多少学分(平台只在播放期间写在倒计时文案里)
points: null, // 每日积分:{ enabled, total, max, progress, text }
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.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.points && state.points.enabled) {
const p = '积分 ' + state.points.total + '/' + state.points.max;
if (used() + 3 + textWidth(p) <= width) parts.push(C.cyan(p));
}
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)。
* 面板关闭时也照常统计:学分明细要拿来发 Bark 通知,不能只在 TTY 下有。
* @returns {object|null} study.update() 的结果,含本次新增的学分事件
*/
snap(s) {
if (!s || s.noApi) return null;
const pick = (v, d) => (v === undefined ? d : v);
const st = study.update(s);
if (!enabled) return st;
state.studySeconds = st.studySeconds;
state.creditEarned = st.creditEarned;
state.credit = st.credit;
state.points = s.points || null;
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;
return st;
},
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(); },
};
}