feat(server,web,desktop,shared,deploy,docs): Linux 一键安装与 classhelper 运维命令、更新检查、图表去 echarts,版本统一 1.1.0
Linux 交付链(新增)
- deploy/install.sh:一键安装器(CLASSHELPER 大字 TUI、native/docker 双形态、向导选安装目录/
端口/数据库/初始管理员密码);识别 apt/yum/dnf 只补缺的依赖、建独立系统用户、下载内置 Node
运行时(glibc < 2.28 的 CentOS 7 自动改用 unofficial-builds 的 glibc-217 构建)、幂等覆盖安装
(保留 config.env 与 data/,不重置密钥)、全程写 /var/log/classhelper/install.log;
`--check` 只体检(不需要 root)、`--yes` 无人值守、`--package` 支持内网离线分发。
- deploy/classhelper:运维命令 —— status / doctor / password / backup(list,restore,schedule) /
upgrade / rollback / start|stop|restart|reload / logs / config / port / key rotate / uninstall /
completion / help。特权操作一律校验 EUID,关键动作写 /var/log/classhelper/audit.log。
- deploy/tools/admin-cli.mjs:离线账号工具(改密、列账号、VACUUM INTO 一致性快照、哈希回滚),
直连数据库 —— 服务停机也能救急,不需要先有一个能登录的账号。
- deploy/{classhelper.service,profile.d,logrotate.d,systemd}/ 模板 + Dockerfile.linux-package。
- scripts/dist-server.mjs 增加 --platform linux(根脚本 `pnpm dist:server:linux`),产物
classhelper-server-linux-x64-<版本>.tar.gz + 同名 .sha256;新增 GitHub Actions workflow 在
ubuntu runner 上构建并挂 Release(@libsql/linux-* 这类平台相关依赖只能在 Linux 上装)。
- docs/linux-deploy.md:安装 / 运维命令 / 升级回滚 / 备份恢复 / 排障 / 安全清单 /
Ubuntu 22.04 与 Rocky 9 的验收清单。deploy/install-linux.sh 改为转发壳,不留两份实现。
三处必须知道的取舍(已写进 AGENTS.md §5 第 59 条)
- 配置真身在 /etc/classhelper/config.env,安装目录里的 .env 是指向它的软链:Web 端
「数据库管理 → 一键切换」改写的是 <安装目录>/.env,而 systemd 注入的是同一份配置 ——
两处不是同一个文件时,切换会「看起来成功、重启后又连回旧库」。classhelper doctor 有专门断言。
- 升级/回滚替换程序文件用「改名 + 就位」而不是 rm+cp:升级时正在运行的就是 bin/classhelper
自己,直接删掉同名文件会让 bash 读到半个脚本。
- 交叉构建(在非 Linux 机器上打 Linux 包)会在包内写 .cross-built 标记、doctor 据此提示:
已核对 @libsql/linux-x64-gnu 与 -musl 就位且无 win32 残留,但 prisma CLI 的原生 schema engine
是宿主平台的,Web 端「数据库一键切换」那一步存疑;正式产物一律走 CI。
更新检查(此前只在工作区,本次一并提交)
- 服务端 modules/update:由服务端转发 GitHub Releases(Web 端 CSP 不允许直连),离线/限流/超时
一律收敛成 ok:false + 一句人话,失败结果同样进缓存;?force=1 只对管理员生效(避免刷爆匿名限流)。
- 版本比较放 @classhelper/shared(compareVersions / isNewerVersion),三端共用;服务端版本号
改由 lib/version.ts 读 package.json,不再在 app.ts 里写字面量。
- Web 端顶栏「检查更新」弹窗、客户端「关于」页的检查更新与诊断信息。
Web 端 / 客户端
- 成绩图表改用自包含的轻量组件(ScoreBarChart / ScoreLineChart),不再全量引入 echarts
(原先 echarts 占桌面端渲染产物 1.12MB、Web 端 1.13MB);柱状图是纯 HTML/CSS,折线图是
viewBox SVG,均无 resize 监听。
- Element Plus 图标改为按需注册(两端各一份 icons.ts),新增 scripts/check-icons.mjs 静态门禁
并挂进两端 build —— 漏注册的后果是界面静默渲染空白,只在控制台一条 warning。
版本号统一 1.1.0
- 5 份 package.json、deploy/package.runtime.json、.env.example 的 APP_VERSION、
docker-compose 与两个 Dockerfile 的镜像标签、Linux 安装包名示例、README 首页版本;
- ClassIsland 插件 manifest.yml 与 BridgeService.PluginVersion 同步(verify:classisland-plugin
有 manifest ↔ code 的一致性断言);
- 刻意保持不变的是**历史性表述与举例**:docs/mysql.md 的「自 v1.0.0 起内置 MySQL 适配器」、
shared/utils.ts 讲版本比较用的 1.0.0 / 1.0.0-fix、README 验收表里的实测记录。
This commit is contained in:
1 parent
aad22df4fd
commit
9a38f86cd3
77 files changed
+8021
-899
No files matched your search
@@ -42,6 +42,8 @@ interface PersistedConfig {
|
||||
theme?: 'light' | 'dark';
|
||||
/** 主侧边栏是否折叠(向后兼容:旧配置没有该字段视为展开) */
|
||||
sidebarCollapsed?: boolean;
|
||||
/** 用户选择「忽略此版本」的版本号(向后兼容:旧配置没有该字段视为没忽略过任何版本) */
|
||||
ignoredUpdateVersion?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG: PersistedConfig = {
|
||||
@@ -56,6 +58,7 @@ const DEFAULT_CONFIG: PersistedConfig = {
|
||||
onboardingDone: false,
|
||||
theme: 'light',
|
||||
sidebarCollapsed: false,
|
||||
ignoredUpdateVersion: '',
|
||||
};
|
||||
|
||||
/** 主题白名单:非法值一律回落浅色 */
|
||||
@@ -179,7 +182,7 @@ function decryptToken(raw: PersistedConfig): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function readPersisted(): PersistedConfig {
|
||||
function readPersistedFromDisk(): PersistedConfig {
|
||||
try {
|
||||
const content = fs.readFileSync(configFilePath(), 'utf8');
|
||||
const parsed = JSON.parse(content) as Partial<PersistedConfig>;
|
||||
@@ -198,16 +201,125 @@ function readPersisted(): PersistedConfig {
|
||||
onboardingDone: parsed.onboardingDone === true,
|
||||
theme: normalizeTheme(parsed.theme),
|
||||
sidebarCollapsed: parsed.sidebarCollapsed === true,
|
||||
ignoredUpdateVersion:
|
||||
typeof parsed.ignoredUpdateVersion === 'string' ? parsed.ignoredUpdateVersion : '',
|
||||
};
|
||||
} catch {
|
||||
return { ...DEFAULT_CONFIG };
|
||||
}
|
||||
}
|
||||
|
||||
function writePersisted(config: PersistedConfig): void {
|
||||
const target = configFilePath();
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, JSON.stringify(config, null, 2), 'utf8');
|
||||
/* ------------------------------------------------------------ 内存缓存 + 异步合并写
|
||||
*
|
||||
* 为什么不能每次 saveConfig 都同步读写盘(原来的写法):
|
||||
* 侧栏折叠(`stores/ui.ts` 的 toggleSidebar)、主题切换、通知渠道、作业看板偏好、登录/登出
|
||||
* 全都走 `saveConfig`,而它一次调用要做「readFileSync + JSON.parse + 8 个 normalize」**两遍**
|
||||
* (开头读一遍、结尾 `getConfig()` 又读一遍)+ `writeFileSync` 一遍 + DPAPI 解密一遍,
|
||||
* **全部同步跑在主进程主线程上**。主进程是 Electron 的消息泵进程,被它摁住的那一拍
|
||||
* 渲染进程也跟着掉帧 —— 用户反馈的"点汉堡展开/收回侧栏时卡一下"就是这一拍。
|
||||
*
|
||||
* 现在:配置常驻内存(连已解密的 token 一起缓存),写盘改成**异步 + 合并** ——
|
||||
* 同一拍内的多次改动只落最后一次,写入串行不会互相覆盖;退出前由 `flushConfigSync()` 兜底。
|
||||
*
|
||||
* **语义变化(有意为之)**:`saveConfig()` 返回时数据可能还没落盘(延迟 CONFIG_WRITE_DEBOUNCE_MS)。
|
||||
* 正常退出(托盘 → 退出)会走 `flushConfigSync()`,不会丢最后一次改动;只有进程被强杀
|
||||
* 才可能丢这最后 120ms 内的改动。
|
||||
*/
|
||||
|
||||
/** 写入合并窗口:拖动同类控件(滑块/连续点击)时的连续改动只落最后一次 */
|
||||
const CONFIG_WRITE_DEBOUNCE_MS = 120;
|
||||
|
||||
interface ConfigCache {
|
||||
config: PersistedConfig;
|
||||
/** 已解密的登录令牌(null = 未登录 / 解密失败)。缓存它是为了不再每次都走一遍 DPAPI */
|
||||
token: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 内存配置。**必须懒初始化**:`main/index.ts` 会先 `app.setPath('userData', smokeProfile)`
|
||||
* 把配置目录指到冒烟专用 profile,之后才第一次读配置;在模块顶层立即读盘会读错文件。
|
||||
*/
|
||||
let cache: ConfigCache | null = null;
|
||||
|
||||
function loadCache(): ConfigCache {
|
||||
if (cache) return cache;
|
||||
const config = readPersistedFromDisk();
|
||||
cache = { config, token: decryptToken(config) };
|
||||
return cache;
|
||||
}
|
||||
|
||||
/** 待写入的配置快照(合并窗口内只保留最后一次) */
|
||||
let pendingWrite: PersistedConfig | null = null;
|
||||
let writeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
/** 是否有一次异步写入正在进行(用它把写入串行化,避免两次写互相覆盖) */
|
||||
let writing = false;
|
||||
|
||||
/** 排一次落盘。合并窗口内的多次调用只会写最后一次;`immediate` 用于不该被延迟的场景 */
|
||||
function scheduleWrite(config: PersistedConfig, immediate = false): void {
|
||||
pendingWrite = config;
|
||||
if (immediate) {
|
||||
if (writeTimer !== null) {
|
||||
clearTimeout(writeTimer);
|
||||
writeTimer = null;
|
||||
}
|
||||
void flushConfigAsync();
|
||||
return;
|
||||
}
|
||||
// 已有待写任务(定时器在跑或正在写):内容已经记在 pendingWrite 里,等它自己收尾即可。
|
||||
// 正在写的那次结束后会再检查一次 pendingWrite(见 flushConfigAsync 的 finally)。
|
||||
if (writeTimer !== null || writing) return;
|
||||
writeTimer = setTimeout(() => {
|
||||
writeTimer = null;
|
||||
void flushConfigAsync();
|
||||
}, CONFIG_WRITE_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/** 异步落盘(不阻塞主进程消息泵)。失败只记日志 —— 与 readPersistedFromDisk 的容错口径一致 */
|
||||
async function flushConfigAsync(): Promise<void> {
|
||||
if (writing) return;
|
||||
const target = pendingWrite;
|
||||
if (!target) return;
|
||||
pendingWrite = null;
|
||||
writing = true;
|
||||
// 先把内容序列化下来:写入期间的后续改动由 pendingWrite 负责补一次,
|
||||
// 不会出现"这一次写的是半新半旧的对象"
|
||||
const payload = JSON.stringify(target, null, 2);
|
||||
try {
|
||||
const file = configFilePath();
|
||||
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
||||
await fs.promises.writeFile(file, payload, 'utf8');
|
||||
} catch (error) {
|
||||
logger.warn(`写入配置失败(${configFilePath()}):${error instanceof Error ? error.message : error}`);
|
||||
} finally {
|
||||
writing = false;
|
||||
// 写入期间又有改动:再写一次(内容已被 pendingWrite 合并成最后一次)
|
||||
if (pendingWrite) void flushConfigAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出前同步落地一次(`main/index.ts` 的 shutdownResources 调用)。
|
||||
*
|
||||
* 即使没有待写内容也把内存里的配置重写一遍:那一时刻可能正有一次异步写在进行中,
|
||||
* 它未必来得及完成;退出时多写一次的代价可以忽略。
|
||||
*/
|
||||
export function flushConfigSync(): void {
|
||||
if (writeTimer !== null) {
|
||||
clearTimeout(writeTimer);
|
||||
writeTimer = null;
|
||||
}
|
||||
const target = pendingWrite ?? cache?.config ?? null;
|
||||
if (!target) return;
|
||||
pendingWrite = null;
|
||||
try {
|
||||
const file = configFilePath();
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, JSON.stringify(target, null, 2), 'utf8');
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`退出前写入配置失败(${configFilePath()}):${error instanceof Error ? error.message : error}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -229,13 +341,13 @@ function normalizeServerUrl(input: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取配置(token 已解密),供渲染进程使用 */
|
||||
export function getConfig(): DesktopStoredConfig {
|
||||
const persisted = readPersisted();
|
||||
/** 由内存缓存组装对渲染进程暴露的配置(不再读盘、不再解密) */
|
||||
function toDesktopConfig(state: ConfigCache): DesktopStoredConfig {
|
||||
const persisted = state.config;
|
||||
return {
|
||||
serverUrl: persisted.serverUrl,
|
||||
username: persisted.username,
|
||||
token: decryptToken(persisted),
|
||||
token: state.token,
|
||||
island: normalizeIslandAppearance(persisted.island),
|
||||
homeworkBoard: normalizeHomeworkBoard(persisted.homeworkBoard),
|
||||
notificationChannel: normalizeNotificationChannel(persisted.notificationChannel),
|
||||
@@ -243,12 +355,19 @@ export function getConfig(): DesktopStoredConfig {
|
||||
onboardingDone: persisted.onboardingDone === true,
|
||||
theme: normalizeTheme(persisted.theme),
|
||||
sidebarCollapsed: persisted.sidebarCollapsed === true,
|
||||
ignoredUpdateVersion: persisted.ignoredUpdateVersion ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/** 读取配置(token 已解密),供渲染进程使用 */
|
||||
export function getConfig(): DesktopStoredConfig {
|
||||
return toDesktopConfig(loadCache());
|
||||
}
|
||||
|
||||
/** 局部更新配置:只覆盖传入的字段 */
|
||||
export function saveConfig(patch: Partial<DesktopStoredConfig>): DesktopStoredConfig {
|
||||
const persisted = readPersisted();
|
||||
const state = loadCache();
|
||||
const persisted = state.config;
|
||||
|
||||
if (typeof patch.serverUrl === 'string' && patch.serverUrl.trim()) {
|
||||
const normalized = normalizeServerUrl(patch.serverUrl);
|
||||
@@ -284,20 +403,28 @@ export function saveConfig(patch: Partial<DesktopStoredConfig>): DesktopStoredCo
|
||||
if (patch.sidebarCollapsed !== undefined) {
|
||||
persisted.sidebarCollapsed = patch.sidebarCollapsed === true;
|
||||
}
|
||||
// 空串是合法值(= 没有忽略任何版本),因此这里只判类型不判空
|
||||
if (typeof patch.ignoredUpdateVersion === 'string') {
|
||||
persisted.ignoredUpdateVersion = patch.ignoredUpdateVersion;
|
||||
}
|
||||
if (patch.token !== undefined) {
|
||||
const encrypted = encryptToken(patch.token);
|
||||
persisted.token = encrypted.token;
|
||||
persisted.tokenEncrypted = encrypted.tokenEncrypted;
|
||||
// 明文一并进缓存:既省掉一次 DPAPI 解密,也保证紧接着的 getConfig() 读到的就是刚存的令牌
|
||||
state.token = patch.token;
|
||||
}
|
||||
|
||||
writePersisted(persisted);
|
||||
return getConfig();
|
||||
scheduleWrite(persisted);
|
||||
return toDesktopConfig(state);
|
||||
}
|
||||
|
||||
/** 清空为默认配置(退出登录 / 重置) */
|
||||
/** 清空为默认配置(退出登录 / 重置)。立即落盘:它对应退出登录,不该被合并窗口延迟 */
|
||||
export function clearConfig(): DesktopStoredConfig {
|
||||
writePersisted({ ...DEFAULT_CONFIG });
|
||||
return getConfig();
|
||||
const state: ConfigCache = { config: { ...DEFAULT_CONFIG }, token: null };
|
||||
cache = state;
|
||||
scheduleWrite(state.config, true);
|
||||
return toDesktopConfig(state);
|
||||
}
|
||||
|
||||
export function getConfigPath(): string {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { BrowserWindow, app, shell } from 'electron';
|
||||
import { getConfig } from './config.js';
|
||||
import { flushConfigSync, getConfig } from './config.js';
|
||||
import { registerIpcHandlers } from './ipc.js';
|
||||
import { island, registerIslandIpc } from './island.js';
|
||||
import { logger } from './logger.js';
|
||||
import { runSmokeTest } from './smoke.js';
|
||||
import { createTray, destroyTray, isTrayReady } from './tray.js';
|
||||
import { scheduleStartupUpdateCheck } from './update.js';
|
||||
|
||||
// 主进程由 esbuild 打包为 CommonJS,因此这里可以直接使用 __dirname
|
||||
// (dist/main/index.js -> dist/preload/index.js 与 dist/renderer/index.html)
|
||||
@@ -163,6 +164,9 @@ if (!gotLock) {
|
||||
logger.warn(`系统托盘初始化失败(不影响主功能):${error instanceof Error ? error.message : error}`);
|
||||
}
|
||||
|
||||
// 启动后自动查一次更新(延迟几秒,不跟首屏抢带宽);冒烟模式下自动跳过,见 main/update.ts
|
||||
scheduleStartupUpdateCheck(() => mainWindow);
|
||||
|
||||
if (isSmokeTest) {
|
||||
try {
|
||||
await runSmokeTest(mainWindow);
|
||||
@@ -190,6 +194,11 @@ if (!gotLock) {
|
||||
*/
|
||||
function shutdownResources(): string {
|
||||
const done: string[] = [];
|
||||
// 配置是**异步合并写**的(见 main/config.ts):退出前必须同步落地一次,
|
||||
// 否则"刚改完设置就退出"这一类操作会丢掉最后一次改动。
|
||||
// 放在最前面:后面会销毁窗口与灵动岛,先落盘不依赖任何窗口是否还在。
|
||||
flushConfigSync();
|
||||
done.push('配置已落盘');
|
||||
if (isTrayReady()) {
|
||||
destroyTray();
|
||||
done.push('托盘已销毁');
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { app, ipcMain, shell } from 'electron';
|
||||
import type { UpdateInfo } from '@classhelper/shared';
|
||||
import { clearConfig, getConfig, getConfigPath, saveConfig } from './config.js';
|
||||
import { checkForUpdates, ignoreUpdateVersion } from './update.js';
|
||||
import type { DesktopAppInfo, DesktopStoredConfig } from '../types/desktop.js';
|
||||
|
||||
/** IPC 通道名集中管理,preload 与主进程共用同一份字符串 */
|
||||
@@ -9,6 +11,8 @@ export const IPC_CHANNELS = {
|
||||
clearConfig: 'classhelper:config:clear',
|
||||
appInfo: 'classhelper:app:info',
|
||||
openExternal: 'classhelper:shell:open-external',
|
||||
updateCheck: 'classhelper:update:check',
|
||||
updateIgnore: 'classhelper:update:ignore',
|
||||
} as const;
|
||||
|
||||
export function registerIpcHandlers(): void {
|
||||
@@ -39,6 +43,21 @@ export function registerIpcHandlers(): void {
|
||||
await shell.openExternal(url);
|
||||
return true;
|
||||
});
|
||||
|
||||
/**
|
||||
* 检查更新(走主进程直连 GitHub,见 main/update.ts 的说明)。
|
||||
*
|
||||
* `force` 为 true 时绕过主进程缓存 —— 对应「关于」页里用户主动点的那次检查;
|
||||
* 启动自动检查一律用缓存(避免同一分钟内重复请求打满匿名限流)。
|
||||
*/
|
||||
ipcMain.handle(IPC_CHANNELS.updateCheck, (_event, force?: boolean): Promise<UpdateInfo> => {
|
||||
return checkForUpdates(force === true);
|
||||
});
|
||||
|
||||
/** 忽略某个版本的更新提示(记入 config.json,启动自动检查不再提示它) */
|
||||
ipcMain.handle(IPC_CHANNELS.updateIgnore, (_event, version: string): void => {
|
||||
if (typeof version === 'string') ignoreUpdateVersion(version);
|
||||
});
|
||||
}
|
||||
|
||||
export function getDiagnostics(): { configPath: string; config: DesktopStoredConfig } {
|
||||
|
||||
@@ -958,9 +958,9 @@ class IslandController {
|
||||
}
|
||||
|
||||
/** 当前应该把岛放在哪块屏上:跟随鼠标时用光标所在屏,否则用主屏 */
|
||||
private targetDisplay(): Electron.Display {
|
||||
private targetDisplay(cursor?: { x: number; y: number } | null): Electron.Display {
|
||||
return this.appearance.followCursorDisplay
|
||||
? screen.getDisplayNearestPoint(this.cursorOverride ?? screen.getCursorScreenPoint())
|
||||
? screen.getDisplayNearestPoint(cursor ?? this.cursorOverride ?? screen.getCursorScreenPoint())
|
||||
: screen.getPrimaryDisplay();
|
||||
}
|
||||
|
||||
@@ -970,10 +970,13 @@ class IslandController {
|
||||
* 原先锚点只在 `setAppearance()` 里算一次,于是"跟随鼠标屏幕"实际上**只在改设置的那一瞬间**
|
||||
* 生效:讲台从投影切回来之后,岛还留在原来那块屏上,直到用户再动一次外观设置。
|
||||
* 这里挂在已有的 60ms 命中轮询上(不新增定时器),并且只在目标屏幕真的变了、且窗口可见时才动窗口。
|
||||
*
|
||||
* 不需要额外监听 `screen` 的 display-* 事件:目标屏是由**当前光标位置**或主屏推出来的,
|
||||
* 插拔/切主屏之后下一轮 tick 自然会算出不同的 id,一样能触发重排。
|
||||
*/
|
||||
private syncAnchorDisplay(): void {
|
||||
private syncAnchorDisplay(cursor?: { x: number; y: number } | null): void {
|
||||
if (!this.win || this.win.isDestroyed()) return;
|
||||
const displayId = this.targetDisplay().id;
|
||||
const displayId = this.targetDisplay(cursor).id;
|
||||
if (this.anchorDisplayId === displayId) return;
|
||||
this.anchorDisplayId = displayId;
|
||||
// 换屏了:可用高度(工作区)也跟着换,列表"能放几行"要重算
|
||||
@@ -1409,11 +1412,14 @@ class IslandController {
|
||||
/**
|
||||
* 光标相对窗口左上角的本地坐标(CSS px / DIP,与渲染进程上报的岛体矩形同一坐标系)。
|
||||
* 冒烟里用 `setHitTestCursor` 注入,真实场景读系统光标。
|
||||
*
|
||||
* `cursor`:调用方在本轮 tick 里已经读过的光标位置(见 `startHitPoll`)。
|
||||
* 传进来就复用它,避免同一个 tick 里重复调 `screen.getCursorScreenPoint()`。
|
||||
*/
|
||||
private cursorLocal(): { x: number; y: number } | null {
|
||||
private cursorLocal(cursor?: { x: number; y: number } | null): { x: number; y: number } | null {
|
||||
if (!this.win || this.win.isDestroyed()) return null;
|
||||
const bounds = this.win.getBounds();
|
||||
const point = this.cursorOverride ?? screen.getCursorScreenPoint();
|
||||
const point = cursor ?? this.cursorOverride ?? screen.getCursorScreenPoint();
|
||||
return { x: point.x - bounds.x, y: point.y - bounds.y };
|
||||
}
|
||||
|
||||
@@ -1494,7 +1500,7 @@ class IslandController {
|
||||
}
|
||||
|
||||
/** 按光标位置校正命中(不依赖渲染进程是否收到 mousemove) */
|
||||
private syncHitFromCursor(): void {
|
||||
private syncHitFromCursor(cursor?: { x: number; y: number } | null): void {
|
||||
if (!this.win || this.win.isDestroyed() || !this.win.isVisible()) {
|
||||
this.setInteractive(false, '窗口不可见');
|
||||
return;
|
||||
@@ -1505,18 +1511,34 @@ class IslandController {
|
||||
this.setInteractive(false, '隐藏态');
|
||||
return;
|
||||
}
|
||||
this.setInteractive(this.isInsideHitRect(this.cursorLocal()), '光标轮询');
|
||||
this.setInteractive(this.isInsideHitRect(this.cursorLocal(cursor)), '光标轮询');
|
||||
}
|
||||
|
||||
private startHitPoll(): void {
|
||||
if (this.hitTimer) return;
|
||||
// 60ms:渲染进程的 mousemove 转发在 Windows 上并不可靠,这里是命中的**权威来源**,
|
||||
// 间隔必须足够小,否则"指针移上胶囊后立刻点击"会因窗口还没接收鼠标而点空(用户反馈过)。
|
||||
//
|
||||
// 每一跳的成本要压到最低(这个定时器从岛初始化一直跑到进程退出):
|
||||
// 1) 光标位置**每跳只读一次**,命中判定与"跟随鼠标屏幕"共用 —— 原先 cursorLocal() 与
|
||||
// targetDisplay() 各读一次,等于每跳两次 `screen.getCursorScreenPoint()`;
|
||||
// 2) 窗口不可见时直接返回:此时命中判定与心跳检查本来就各自早退(窗口不可见 ⇒ 无命中可言),
|
||||
// 留着那两次系统调用纯属白跑。
|
||||
this.hitTimer = setInterval(() => {
|
||||
if (!this.win || this.win.isDestroyed()) return;
|
||||
const visible = this.win.isVisible();
|
||||
// 不可见、且不跟随鼠标屏幕时,连读光标都可省掉(targetDisplay 会走主屏分支)
|
||||
const cursor =
|
||||
visible || this.appearance.followCursorDisplay
|
||||
? (this.cursorOverride ?? screen.getCursorScreenPoint())
|
||||
: null;
|
||||
|
||||
// 先按目标屏幕校正窗口位置(换屏/插拔显示器),再算命中与心跳:
|
||||
// 顺序不能反,否则命中判定会用上一块屏的窗口坐标
|
||||
this.syncAnchorDisplay();
|
||||
this.syncHitFromCursor();
|
||||
this.syncAnchorDisplay(cursor);
|
||||
if (!visible) return;
|
||||
|
||||
this.syncHitFromCursor(cursor);
|
||||
this.checkRendererAlive();
|
||||
}, 60);
|
||||
// 定时器不应拖住进程退出
|
||||
@@ -1748,12 +1770,12 @@ const MIN_CARD_HEIGHT = 120;
|
||||
|
||||
|
||||
/**
|
||||
* 渲染进程心跳(渲染进程每 5s 上报一次):超过这个时间没上报就认为它已经卡死/不响应。
|
||||
* 渲染进程心跳(渲染进程每 5s 上报一次,间隔写死在 `src/island/IslandApp.vue`):
|
||||
* 超过这个时间没上报就认为它已经卡死/不响应。
|
||||
* 岛是"无边框透明置顶窗口",渲染进程一旦挂掉,Windows 会把**最后一帧留在屏幕上**
|
||||
* 形成"幽灵胶囊":窗口还在、看着正常,但怎么点都没反应(实测复现:崩掉渲染进程后
|
||||
* 点击完全不产生任何动作)。所以必须有心跳 + 重建来兜底。
|
||||
*/
|
||||
const RENDERER_ALIVE_INTERVAL_MS = 5_000;
|
||||
const RENDERER_ALIVE_TIMEOUT_MS = 20_000;
|
||||
/** 窗口重建限流:一段时间内最多重建几次,避免持续崩坏时无限重建 */
|
||||
const RECOVER_MAX_TIMES = 3;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
ISLAND_URGENT_SIZE,
|
||||
} from './island.js';
|
||||
import { destroyTray, getTrayState, isTrayReady } from './tray.js';
|
||||
import { checkForUpdates, wasStartupCheckSkipped } from './update.js';
|
||||
|
||||
interface SmokeResult {
|
||||
name: string;
|
||||
@@ -555,11 +556,26 @@ async function diagnoseClosingFlash(label: string, withTouch: boolean): Promise<
|
||||
);
|
||||
if (buttonPoint) {
|
||||
const bounds = win.getBounds();
|
||||
island.setHitTestCursor({ x: Math.round(bounds.x + buttonPoint.x), y: Math.round(bounds.y + buttonPoint.y) });
|
||||
island.setHitTestCursor({
|
||||
x: Math.round(bounds.x + buttonPoint.x),
|
||||
y: Math.round(bounds.y + buttonPoint.y),
|
||||
});
|
||||
await sleep(160);
|
||||
win.webContents.sendInputEvent({ type: 'mouseDown', x: buttonPoint.x, y: buttonPoint.y, button: 'left', clickCount: 1 });
|
||||
win.webContents.sendInputEvent({
|
||||
type: 'mouseDown',
|
||||
x: buttonPoint.x,
|
||||
y: buttonPoint.y,
|
||||
button: 'left',
|
||||
clickCount: 1,
|
||||
});
|
||||
await sleep(40);
|
||||
win.webContents.sendInputEvent({ type: 'mouseUp', x: buttonPoint.x, y: buttonPoint.y, button: 'left', clickCount: 1 });
|
||||
win.webContents.sendInputEvent({
|
||||
type: 'mouseUp',
|
||||
x: buttonPoint.x,
|
||||
y: buttonPoint.y,
|
||||
button: 'left',
|
||||
clickCount: 1,
|
||||
});
|
||||
}
|
||||
const deadline = Date.now() + 1600;
|
||||
let index = 0;
|
||||
@@ -581,14 +597,8 @@ async function diagnoseClosingFlash(label: string, withTouch: boolean): Promise<
|
||||
const crop = image.crop({
|
||||
x: Math.max(0, Math.round((geometry.window.x - pad) * shotScale)),
|
||||
y: Math.max(0, Math.round((geometry.window.y - pad) * shotScale)),
|
||||
width: Math.min(
|
||||
image.getSize().width,
|
||||
Math.round((geometry.window.width + pad * 2) * shotScale),
|
||||
),
|
||||
height: Math.min(
|
||||
image.getSize().height,
|
||||
Math.round((geometry.window.height + pad * 2) * shotScale),
|
||||
),
|
||||
width: Math.min(image.getSize().width, Math.round((geometry.window.width + pad * 2) * shotScale)),
|
||||
height: Math.min(image.getSize().height, Math.round((geometry.window.height + pad * 2) * shotScale)),
|
||||
});
|
||||
fs.writeFileSync(path.join(dir, `${label}-${String(index).padStart(2, '0')}.png`), crop.toPNG());
|
||||
lines.push(
|
||||
@@ -2087,7 +2097,8 @@ async function runIslandChecks(
|
||||
let count = 0;
|
||||
for (let y = Math.max(0, fromY); y < Math.min(collapseShotSize.height, toY); y += 2) {
|
||||
for (let x = Math.max(0, fromX); x < Math.min(collapseShotSize.width, toX); x += 2) {
|
||||
if (x >= cardBox.x && x <= cardBox.x + cardBox.w && y >= cardBox.y && y <= cardBox.y + cardBox.h) continue;
|
||||
if (x >= cardBox.x && x <= cardBox.x + cardBox.w && y >= cardBox.y && y <= cardBox.y + cardBox.h)
|
||||
continue;
|
||||
const index = (y * collapseShotSize.width + x) * 4;
|
||||
if (index + 3 >= bitmap.length) continue;
|
||||
const b = bitmap[index];
|
||||
@@ -4349,6 +4360,46 @@ export async function runSmokeTest(win: BrowserWindow): Promise<void> {
|
||||
);
|
||||
record('关于页渲染(应用信息/诊断信息/鸣谢)', Boolean(aboutPage?.ok), String(aboutPage?.detail ?? ''));
|
||||
|
||||
// 更新检查(新功能回归):主进程直连 GitHub 取最新 Release。
|
||||
//
|
||||
// **刻意不断言"一定有新版本"**:那会把冒烟绑死在外网可达上,而教室机器常常没有外网
|
||||
// (`ok=false` 是设计内的降级结果,不是失败)。因此两种结果都算通过,验的是:
|
||||
// 结构完整、失败时有可读原因、以及缓存真的生效。
|
||||
const updateFirst = await checkForUpdates(true);
|
||||
const isVersionLike = (value: unknown): boolean => typeof value === 'string' && /^\d/.test(value);
|
||||
const updateShapeOk =
|
||||
isVersionLike(updateFirst.currentVersion) &&
|
||||
typeof updateFirst.ok === 'boolean' &&
|
||||
typeof updateFirst.hasUpdate === 'boolean' &&
|
||||
(updateFirst.ok
|
||||
? isVersionLike(updateFirst.latestVersion) &&
|
||||
Array.isArray(updateFirst.assets) &&
|
||||
/^https:\/\//.test(updateFirst.releaseUrl) &&
|
||||
updateFirst.error === null
|
||||
: typeof updateFirst.error === 'string' && updateFirst.error.length > 0);
|
||||
record(
|
||||
'更新检查返回结构正确(无外网时降级为 ok=false 且带原因)',
|
||||
updateShapeOk,
|
||||
`ok=${updateFirst.ok} 本机=${updateFirst.currentVersion} 最新=${updateFirst.latestVersion ?? '-'} ` +
|
||||
`有新版本=${updateFirst.hasUpdate} 附件=${updateFirst.assets.length}` +
|
||||
`${updateFirst.error ? ` 原因=${updateFirst.error}` : ''}`,
|
||||
);
|
||||
|
||||
// 缓存:紧接着再查一次(不传 force)应命中缓存 —— checkedAt 不变即说明没有二次请求
|
||||
const updateSecond = await checkForUpdates();
|
||||
record(
|
||||
'更新检查结果带缓存(不重复请求 GitHub)',
|
||||
updateSecond.checkedAt === updateFirst.checkedAt,
|
||||
`两次 checkedAt 相同=${updateSecond.checkedAt === updateFirst.checkedAt}`,
|
||||
);
|
||||
|
||||
// 启动自动检查在冒烟模式下必须被跳过,否则每次验证都会产生一次真实网络请求与提示条
|
||||
record(
|
||||
'冒烟模式下跳过启动自动检查(验证不依赖外网)',
|
||||
wasStartupCheckSkipped(),
|
||||
`skipped=${wasStartupCheckSkipped()}`,
|
||||
);
|
||||
|
||||
// 未读红点必须挂在"通知"图标右上方(用户反馈:原来挂在文字后面,位置不对)
|
||||
const readBadgeGeometry = async (): Promise<{
|
||||
ok: boolean;
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { app, type BrowserWindow } from 'electron';
|
||||
import {
|
||||
GITHUB_RELEASES_LATEST_API,
|
||||
GITHUB_RELEASES_PAGE,
|
||||
UPDATE_CHECK_CACHE_TTL_MS,
|
||||
UPDATE_CHECK_TIMEOUT_MS,
|
||||
UPDATE_CHECK_USER_AGENT,
|
||||
isNewerVersion,
|
||||
normalizeVersion,
|
||||
type UpdateAssetDto,
|
||||
type UpdateInfo,
|
||||
} from '@classhelper/shared';
|
||||
import { getConfig, saveConfig } from './config.js';
|
||||
import { logger } from './logger.js';
|
||||
|
||||
/**
|
||||
* 更新检查(桌面客户端)。
|
||||
*
|
||||
* **为什么在主进程做**:渲染进程通过 preload 能拿到 `getConfig()` 的明文 token(代表全班身份),
|
||||
* 它的 CSP 与导航防线是整个安全模型里最要紧的一层;让它额外去连一个外部域名、
|
||||
* 解析外部 JSON,等于把"外部数据"请进最有价值的那一侧。主进程本来就在做网络与文件,
|
||||
* 放这里也顺带复用 Node 的 fetch(无需额外依赖)。
|
||||
*
|
||||
* 与 Web 管理端的差别:Web 端受服务端 CSP 的 `connect-src` 限制,只能走 `/api/update/check` 转发;
|
||||
* 客户端没有这个限制,按用户选择**直连 GitHub**。两边归一化出的 `UpdateInfo` 结构一致。
|
||||
*/
|
||||
|
||||
/** 主进程 → 渲染进程:发现新版本(渲染进程据此弹一次性提示) */
|
||||
export const UPDATE_AVAILABLE_CHANNEL = 'classhelper:update:available';
|
||||
|
||||
/** 启动后多久自动查一次:等窗口与登录流程就绪,也不跟首屏请求抢带宽 */
|
||||
const STARTUP_DELAY_MS = 5_000;
|
||||
|
||||
interface GithubReleasePayload {
|
||||
tag_name?: unknown;
|
||||
name?: unknown;
|
||||
published_at?: unknown;
|
||||
body?: unknown;
|
||||
html_url?: unknown;
|
||||
assets?: unknown;
|
||||
}
|
||||
|
||||
let cache: { at: number; info: UpdateInfo } | null = null;
|
||||
let startupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
/** 冒烟断言用:启动自动检查是否被跳过(冒烟模式下必须是 true) */
|
||||
let startupCheckSkipped = false;
|
||||
|
||||
/** 失败的统一出口:结构完整,界面不必做 null 判断 */
|
||||
function failure(error: string): UpdateInfo {
|
||||
return {
|
||||
ok: false,
|
||||
error,
|
||||
currentVersion: app.getVersion(),
|
||||
latestVersion: null,
|
||||
hasUpdate: false,
|
||||
releaseUrl: GITHUB_RELEASES_PAGE,
|
||||
releaseName: null,
|
||||
publishedAt: null,
|
||||
notes: null,
|
||||
assets: [],
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function toAssets(raw: unknown): UpdateAssetDto[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.map((item) => item as { name?: unknown; browser_download_url?: unknown; size?: unknown })
|
||||
.filter(
|
||||
(item): item is { name: string; browser_download_url: string; size?: unknown } =>
|
||||
typeof item.name === 'string' && typeof item.browser_download_url === 'string',
|
||||
)
|
||||
.map((item) => ({
|
||||
name: item.name,
|
||||
downloadUrl: item.browser_download_url,
|
||||
size: typeof item.size === 'number' && Number.isFinite(item.size) ? item.size : 0,
|
||||
}));
|
||||
}
|
||||
|
||||
function toInfo(payload: GithubReleasePayload, currentVersion: string): UpdateInfo {
|
||||
const latestVersion = normalizeVersion(typeof payload.tag_name === 'string' ? payload.tag_name : '');
|
||||
if (!latestVersion) {
|
||||
logger.warn('更新检查:GitHub 返回的 Release 里没有可识别的 tag_name');
|
||||
return failure('GitHub 返回的版本号无法识别');
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
error: null,
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
hasUpdate: isNewerVersion(currentVersion, latestVersion),
|
||||
releaseUrl:
|
||||
typeof payload.html_url === 'string' && payload.html_url ? payload.html_url : GITHUB_RELEASES_PAGE,
|
||||
releaseName: typeof payload.name === 'string' ? payload.name : null,
|
||||
publishedAt: typeof payload.published_at === 'string' ? payload.published_at : null,
|
||||
notes: typeof payload.body === 'string' ? payload.body : null,
|
||||
assets: toAssets(payload.assets),
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** 把各种失败翻译成一句用户能看懂的话(教室里最常见的就是"这台机器没有外网") */
|
||||
function describeFailure(error: unknown): string {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (error instanceof Error && error.name === 'TimeoutError') {
|
||||
return `连接 GitHub 超时(${UPDATE_CHECK_TIMEOUT_MS / 1000} 秒),本机可能没有外网`;
|
||||
}
|
||||
if (/fetch failed|ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|certificate|net::/i.test(message)) {
|
||||
return '无法连接 GitHub,本机可能没有外网';
|
||||
}
|
||||
return `检查更新失败:${message}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 GitHub 上有没有比本机新的版本(结果带缓存)。
|
||||
*
|
||||
* 缓存的意义:匿名调用 GitHub API 的限流是 60 次/小时/IP,而「关于」页的按钮可以随便点。
|
||||
* 失败结果同样进缓存 —— 否则离线时每点一次都要白等一个超时。
|
||||
*/
|
||||
export async function checkForUpdates(force = false): Promise<UpdateInfo> {
|
||||
const currentVersion = app.getVersion();
|
||||
const now = Date.now();
|
||||
if (!force && cache && now - cache.at < UPDATE_CHECK_CACHE_TTL_MS) {
|
||||
return cache.info;
|
||||
}
|
||||
|
||||
let info: UpdateInfo;
|
||||
try {
|
||||
const response = await fetch(GITHUB_RELEASES_LATEST_API, {
|
||||
headers: {
|
||||
// GitHub API 强制要求 User-Agent,不带会直接 403
|
||||
'User-Agent': UPDATE_CHECK_USER_AGENT,
|
||||
Accept: 'application/vnd.github+json',
|
||||
},
|
||||
signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
info =
|
||||
response.status === 403 || response.status === 429
|
||||
? failure('GitHub 暂时拒绝了请求(匿名查询次数过多),请过一会儿再试')
|
||||
: failure(`GitHub 返回 HTTP ${response.status}`);
|
||||
logger.warn(`更新检查失败:HTTP ${response.status}(本机版本 ${currentVersion})`);
|
||||
} else {
|
||||
info = toInfo((await response.json()) as GithubReleasePayload, currentVersion);
|
||||
logger.info(
|
||||
`更新检查:本机 ${currentVersion} / 最新 ${info.latestVersion ?? '-'}` +
|
||||
`${info.hasUpdate ? '(有新版本)' : '(已是最新)'}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
info = failure(describeFailure(error));
|
||||
logger.warn(`更新检查失败:${info.error}(本机版本 ${currentVersion})`);
|
||||
}
|
||||
|
||||
cache = { at: now, info };
|
||||
return info;
|
||||
}
|
||||
|
||||
/** 「知道了 / 忽略此版本」:记到配置里,同一个版本不再重复弹提示 */
|
||||
export function ignoreUpdateVersion(version: string): void {
|
||||
const normalized = normalizeVersion(version);
|
||||
if (!normalized) return;
|
||||
saveConfig({ ignoredUpdateVersion: normalized });
|
||||
logger.info(`已忽略版本 ${normalized} 的更新提示`);
|
||||
}
|
||||
|
||||
/** 该版本是否已被用户忽略 */
|
||||
export function isUpdateIgnored(version: string): boolean {
|
||||
return normalizeVersion(getConfig().ignoredUpdateVersion) === normalizeVersion(version);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动后的自动检查:延迟 `STARTUP_DELAY_MS` 查一次,有新版本(且没被忽略)就通知渲染进程弹提示。
|
||||
*
|
||||
* **冒烟模式直接跳过**:自动化验证不该每次都发真实网络请求(既抖动又依赖外网),
|
||||
* 而且凭空多出来的提示条会撞坏既有 UI 断言。冒烟用例改为直接调 IPC 验证返回结构。
|
||||
*/
|
||||
export function scheduleStartupUpdateCheck(getWindow: () => BrowserWindow | null): void {
|
||||
if (process.env.ELECTRON_SMOKE_TEST === '1') {
|
||||
startupCheckSkipped = true;
|
||||
logger.info('更新检查:冒烟模式下跳过启动自动检查');
|
||||
return;
|
||||
}
|
||||
if (startupTimer) clearTimeout(startupTimer);
|
||||
|
||||
startupTimer = setTimeout(() => {
|
||||
startupTimer = null;
|
||||
void (async () => {
|
||||
try {
|
||||
const info = await checkForUpdates();
|
||||
if (!info.ok || !info.hasUpdate || !info.latestVersion) return;
|
||||
if (isUpdateIgnored(info.latestVersion)) {
|
||||
logger.info(`更新检查:${info.latestVersion} 已被用户忽略,本次不提示`);
|
||||
return;
|
||||
}
|
||||
const win = getWindow();
|
||||
if (!win || win.isDestroyed()) return;
|
||||
win.webContents.send(UPDATE_AVAILABLE_CHANNEL, info);
|
||||
logger.info(`更新检查:已提示新版本 ${info.latestVersion}`);
|
||||
} catch (error) {
|
||||
// 自动检查失败不该打扰用户(手动检查才需要看到原因)
|
||||
logger.warn(`启动自动检查更新失败:${error instanceof Error ? error.message : error}`);
|
||||
}
|
||||
})();
|
||||
}, STARTUP_DELAY_MS);
|
||||
// 不阻止进程退出:这个定时器只是"顺便查一下"
|
||||
startupTimer.unref?.();
|
||||
}
|
||||
|
||||
/** 冒烟断言用:启动自动检查是否被跳过(冒烟模式下应为 true —— 否则每次验证都会发真实网络请求) */
|
||||
export function wasStartupCheckSkipped(): boolean {
|
||||
return startupCheckSkipped;
|
||||
}
|
||||
Reference in new issue
Block a user