// 平台差异集中在这里,其它模块不再直接判断 process.platform。 // // 三个操作系统要处理的差异: // Linux 无 DISPLAY 必须无头;root 必须 --no-sandbox;容器 /dev/shm 小;SIGTERM 可优雅退出 // Windows 会话 0(服务 / 计划任务「不管用户是否登录」)没有交互桌面; // 关闭终端窗口发的是 SIGHUP、Ctrl+Break 发的是 SIGBREAK(SIGTERM 根本收不到); // 跨进程只能用 taskkill 强杀(process.kill 是 TerminateProcess,子进程来不及收尾); // 浏览器进程树要用 taskkill /T 收;spawn 要 windowsHide 避免弹黑框 // macOS 与 Linux 类似但没有 root 沙箱问题,SIGTERM 可用 import { spawnSync } from 'node:child_process'; export const isWindows = process.platform === 'win32'; export const isLinux = process.platform === 'linux'; export const isMac = process.platform === 'darwin'; /** 给人看的平台名(日志 / 提示里用) */ export const platformName = isWindows ? 'Windows' : isMac ? 'macOS' : 'Linux'; export function isRunningAsRoot() { return typeof process.getuid === 'function' && process.getuid() === 0; } /** * 有没有图形显示会话(决定能不能开有界面浏览器)。 * 拿不准时返回 true(宁可按有界面处理,免得把正常桌面环境误判成无头)。 * 可用 YUN_XUE_TANG_HAS_DISPLAY=0/1 强制覆盖。 */ export function hasDisplay() { const force = process.env.YUN_XUE_TANG_HAS_DISPLAY; if (force !== undefined && force !== '') return !/^(0|false|no|off)$/i.test(force); if (isLinux) { // 跑在 Xvfb / x11vnc 下时这两个变量会被设置 return !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY); } if (isWindows) { // SESSIONNAME=Services 表示当前在 Session 0(服务、计划任务勾了「不管用户是否登录」), // 那里没有交互式桌面,带界面的 Chrome 起不来。正常控制台是 Console,远程桌面是 RDP-Tcp#N。 const sess = process.env.SESSIONNAME || ''; if (/^Services$/i.test(sess)) return false; return true; } return true; // macOS:登录会话里默认有 WindowServer } /** 为什么判定没有图形显示(无图形时的日志用,有图形时返回 '') */ export function noDisplayReason() { if (isLinux) { return '当前环境没有图形显示(DISPLAY / WAYLAND_DISPLAY 都为空)'; } if (isWindows) { return '当前进程运行在 Session 0(SESSIONNAME=Services,服务或「不管用户是否登录」的计划任务),没有交互式桌面'; } return '当前环境没有图形显示'; } // 平台安全参数验证:Windows 不注入 --no-sandbox(沙箱能正常工作,关掉只会削弱安全) // 注意:不要在这里返回 --disable-features,因为 Chrome 对同名开关只认最后一个, // 会抵消 buildArgs 里已有的 --disable-features=Translate,MediaRouter,OptimizationHints。 export function safetyArgs() { if (isWindows) { // Windows 上不存在 /dev/shm 与 zygote;需要的是「别弹崩溃恢复气泡」, // 否则无人值守时会卡在一个等点击的窗口上。 return ['--disable-session-crashed-bubble', '--hide-crash-restore-bubble']; } if (isLinux) { const args = ['--disable-dev-shm-usage']; if (isRunningAsRoot()) args.push('--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'); return args; } return []; } /** * 按 --user-data-dir 找出属于本 profile 的残留浏览器进程并杀掉。 * * 很必要的自愈:Windows 上用户常用任务管理器「结束任务」(= TerminateProcess), * 信号收尾根本不会执行,浏览器就成了孤儿进程占着 CDP 端口,下次启动直接失败; * Linux 上 kill -9 同理。这里只杀命令行里带我们专属 profile 目录的进程, * 不碰用户自己的 Chrome。 * * @param {string} profileDir * @param {{ log?: Function, timeoutMs?: number }} [opts] * @returns {Promise} 杀掉的进程数 */ export async function killProfileOrphans(profileDir, opts = {}) { const log = opts.log || (() => {}); const timeoutMs = opts.timeoutMs || 5000; if (!profileDir) return 0; const self = process.pid; let pids = []; try { if (isWindows) { // 注意:PowerShell 的各条语句必须用 '; ' 分隔,不能用空格连—— // 否则 "$p -join ','" 会被当成上一条 Select-Object 的参数,变量永远为空。 const pattern = profileDir.replace(/'/g, "''"); const ps = [ "$p = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe' or Name='msedge.exe' or Name='chromium.exe'\"", ' | Where-Object { $_.CommandLine -like \'*' + pattern + '*\' }', ' | Select-Object -ExpandProperty ProcessId;', '$p -join \",\"', ].join(' '); const r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', ps], { encoding: 'utf8', windowsHide: true, timeout: timeoutMs, }); if (opts.debug) log('[浏览器] 排查命令输出:' + JSON.stringify(String(r.stdout || '').trim())); pids = String(r.stdout || '').trim().split(/[,\s]+/).filter(Boolean).map(Number); } else { const r = spawnSync('sh', ['-c', 'ps -eo pid=,args= 2>/dev/null || ps ax -o pid=,args='], { encoding: 'utf8', timeout: timeoutMs, }); pids = String(r.stdout || '').split('\n') .filter((line) => line.includes(profileDir) && /(chrome|chromium|msedge)/i.test(line)) .map((line) => Number(String(line).trim().split(/\s+/)[0])) .filter(Boolean); } } catch (e) { return 0; } pids = pids.filter((pid) => Number.isFinite(pid) && pid > 0 && pid !== self); if (!pids.length) return 0; log('[浏览器] 发现 ' + pids.length + ' 个占用本 profile 的残留进程(pid ' + pids.join(', ') + '),先收掉'); if (isWindows) { spawnSync('taskkill', ['/pid', String(pids[0]), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); for (const pid of pids) { spawnSync('taskkill', ['/pid', String(pid), '/F'], { windowsHide: true, stdio: 'ignore' }); } } else { for (const pid of pids) { try { process.kill(pid, 'SIGKILL'); } catch (e) { /* 已经没了 */ } } } await new Promise((r) => setTimeout(r, 600)); return pids.length; } /** * 收掉浏览器进程(含子进程)。跨平台差异都在这里。 * @param {import('node:child_process').ChildProcess} child * @param {{ log?: Function, timeoutMs?: number, profileDir?: string }} [opts] */ export async function killTree(child, opts = {}) { const log = opts.log || (() => {}); const timeoutMs = opts.timeoutMs || 8000; const pid = child && child.pid; if (!pid) return; const exited = () => child.exitCode !== null || child.signalCode !== null; const waitExit = async (ms) => { const t0 = Date.now(); while (!exited() && Date.now() - t0 < ms) await new Promise((r) => setTimeout(r, 150)); }; if (isWindows) { // Windows 上 child.kill() 就是 TerminateProcess:不优雅但立即生效。 // 主进程若被 updater / crashpad handler 之类接管没退掉,退回 taskkill /T /F 收整棵树。 try { child.kill(); } catch (e) { /* ignore */ } await waitExit(timeoutMs); if (!exited()) { log('[浏览器] 主进程未退出,用 taskkill /T /F 收整棵树(pid=' + pid + ')'); try { spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); } catch (e) { /* ignore */ } await waitExit(3000); } return; } // POSIX:先 SIGTERM 让它自己收拾(Chrome 会 flush profile),超时再 SIGKILL try { child.kill('SIGTERM'); } catch (e) { /* ignore */ } await waitExit(timeoutMs); if (!exited()) { try { child.kill('SIGKILL'); } catch (e) { /* ignore */ } } } /** * 端口被占用时给用户可以照抄的命令(按平台出)。 * @param {number} port */ export function portInUseHint(port) { if (isWindows) { return [ 'netstat -ano | findstr :' + port + ' (最后一列是 PID)', 'taskkill /PID <上一步的 PID> /T /F', ]; } if (isMac) { return ['lsof -nP -iTCP:' + port + ' -sTCP:LISTEN', 'kill ']; } return [ 'ss -lptn "sport = :' + port + '"', 'pkill -f "remote-debugging-port=' + port + '"', ]; } /** 启动前提示:本平台的浏览器装在哪 / 怎么装 */ export function browserInstallHint() { if (isWindows) { return [ '装一个 Chrome 或 Edge 即可(Edge 是 Chromium 内核,同样可用):', ' winget install --id Google.Chrome', ' 或 YUN_XUE_TANG_CHROME_BIN="C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"', ]; } if (isMac) { return ['安装 Chrome:brew install --cask google-chrome(或下载 .dmg)', '或 YUN_XUE_TANG_CHROME_BIN="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"']; } return [ '安装浏览器:sudo apt install -y chromium (或 google-chrome-stable)', '或指定路径:YUN_XUE_TANG_CHROME_BIN=/usr/bin/chromium', ]; } /** 常驻方式提示(README 里也有,这里给的是「照着敲」的命令) */ export function residentHint() { if (isWindows) { return [ '前台:npm run headless (Ctrl+C 结束)', '后台:Start-Process -WindowStyle Hidden node -ArgumentList "runner/headless.mjs"', '开机自启:把上面一行做成「登录时运行」的计划任务(勾「不管用户是否登录」也支持)', ]; } return [ '前台:npm run headless (Ctrl+C 结束)', '后台:tmux new -d -s yun-xue-tang "npm run headless"', '看日志:tail -f run-logs/headless.log', ]; }