diff --git a/micUploadRoutes.js b/micUploadRoutes.js index 4301f64..d0a1373 100644 --- a/micUploadRoutes.js +++ b/micUploadRoutes.js @@ -153,9 +153,22 @@ function registerMicUpload(app, server, ctx) { }); // ---- 会话生命周期 ---- + // 改成单例:全局只有一个会话,固定id='default'。前端每次挂载都调这个接口, + // 如果浏览器已经在跑,直接复用(不重启、不影响登录态),只有没有会话时才 + // 真正启动一个新的。这样避免"刷新页面=开一个新浏览器"导致旧进程占着 + // profile目录的锁、登录态传不过去的问题——只要不主动点"关闭会话", + // 浏览器和登录态就一直在。 app.post('/api/mic-upload/sessions', requireAuth, async (req, res) => { - const id = crypto.randomBytes(8).toString('hex'); + const id = 'default'; + const existing = sessions.get(id); + if (existing && existing.session && !existing.session.closed) { + // 已经有一个活着的会话,直接复用——不new浏览器,登录态原样保留。 + // token重新发一个(简单起见每次连接都发新的,旧token自然失效)。 + existing.token = crypto.randomBytes(24).toString('hex'); + return res.json({ sessionId: id, wsToken: existing.token, phase: existing.phase, reused: true }); + } + const token = crypto.randomBytes(24).toString('hex'); const entry = { session: null, token, wsClients: new Set(), createdAt: Date.now(), phase: 'browsing' }; sessions.set(id, entry); @@ -168,7 +181,7 @@ function registerMicUpload(app, server, ctx) { try { await session.start(); - res.json({ sessionId: id, wsToken: token }); + res.json({ sessionId: id, wsToken: token, phase: entry.phase, reused: false }); } catch (e) { sessions.delete(id); res.status(500).json({ error: `浏览器启动失败: ${e.message}` }); @@ -334,16 +347,13 @@ function registerMicUpload(app, server, ctx) { }); }); - // 空会话超时清理(比如浏览器标签页被直接关掉,没走DELETE接口) - setInterval(() => { - const now = Date.now(); - for (const [id, entry] of sessions.entries()) { - if (entry.wsClients.size === 0 && now - entry.createdAt > 30 * 60 * 1000) { - entry.session.close(); - sessions.delete(id); - } - } - }, 5 * 60 * 1000); + // 之前这里有个"30分钟无连接自动清理"的定时器,但既然目标是长期保持登录、 + // 单例复用,这个自动清理反而会在你没开着网页的时候把浏览器关掉、白白丢失 + // 登录态——所以去掉了,改成完全手动:只有点"关闭会话"才会真正关闭浏览器。 + // 代价是如果你长期不用也不点关闭,这个无头Chromium进程会一直占着内存 + // (几十MB量级,对单人使用的VPS影响不大);真要回收就SSH上去手动 + // `systemctl restart customer-crm` 即可,重启后浏览器会重新launch, + // 登录态因为是持久化profile,还在磁盘上,大概率还是已登录状态。 } module.exports = { registerMicUpload };