微信绑定体验修复:并入账户页内联卡(去子页);绑定/刷新/解绑全 fire-and-forget 点击秒回;QR 就绪(has_qr)才取码内联渲染;轮询签名比对增量更新防闪烁;overview 双向自愈+启动对账清孤儿实例
This commit is contained in:
@@ -834,6 +834,11 @@ footer { flex: none; padding: 8px 12px calc(10px + env(safe-area-inset-bottom, 0
|
||||
.status-pill.queued { background: #e9edff; color: var(--active); }
|
||||
.status-pill.cancelled { background: #fdecea; color: #b3382c; }
|
||||
@keyframes pill-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
|
||||
/* 微信绑定内联卡(账户页):登录码用服务端 SVG 内联渲染(非 <img>,无坏图帧);未就绪时占位不跳高 */
|
||||
.wx-qr { display: flex; justify-content: center; align-items: center; margin: 10px 0 4px; min-height: 236px; }
|
||||
.wx-qr svg { width: 220px; height: 220px; background: #fff; padding: 8px; border-radius: 10px; box-shadow: 0 1px 4px rgba(0,0,0,.08); }
|
||||
.wx-qr-wait { color: var(--gray-light); font-size: 13px; }
|
||||
.wx-id { float: right; font-weight: 400; font-size: 11px; color: var(--gray-light); margin-top: 5px; }
|
||||
.stop-link {
|
||||
background: none; border: none; cursor: pointer; flex: none;
|
||||
color: #c33; font-size: 12px; padding: 4px 6px;
|
||||
|
||||
@@ -250,7 +250,6 @@
|
||||
const ctx = () => tok === setTok && setTop() === p; // 异步回包时页面可能已切走
|
||||
if (p === 'home') return setPageHome(ctx);
|
||||
if (p === 'account') return setPageAccount(ctx);
|
||||
if (p === 'wechat') return setPageWechat(ctx);
|
||||
if (p === 'service') return setPageService(ctx);
|
||||
if (p === 'cfg-editor') return setPageCfgEditor(ctx);
|
||||
if (p === 'skills') return setPageSkills(ctx);
|
||||
@@ -345,18 +344,16 @@
|
||||
try { const r = await req('GET', '/api/me'); if (r && r.user) me = r; } catch (_) { /* 404 等一律按无账户信息处理 */ }
|
||||
let p = null, pErr = '';
|
||||
try { p = await req('GET', '/api/profile'); } catch (e) { pErr = String((e && e.message) || e); }
|
||||
// 微信入口:未配置(wxbot.url 空)或「未配 wxbot 容器」时整卡隐藏,普通用户零打扰;
|
||||
// 已有绑定时即使 wxbot 没起也要展示(否则用户看不到自己的绑定状态)。
|
||||
let wx = null;
|
||||
try { const r = await req('GET', '/api/wechat'); if (r && r.enabled && (r.alive || (r.bindings || []).length)) wx = r; } catch (_) { /* 旧后端/异常隐藏 */ }
|
||||
if (!ctx()) return;
|
||||
let html = '<div class="set-scroll">';
|
||||
if (me) html += userCardHtml(me.user);
|
||||
html += pErr
|
||||
? '<div class="settings-card"><h4>用户画像</h4><div class="empty-tip">加载失败:' + esc(pErr) + '</div></div>'
|
||||
: profileCardHtml(p);
|
||||
if (wx) html += wechatCardHtml(wx);
|
||||
// 微信内联卡:占位隐藏,wxInitZone 拉到状态才显形(未配置/未连且无绑定 → 始终隐藏,零打扰)
|
||||
html += '<div class="settings-card" id="wx-zone" style="display:none"></div>';
|
||||
setBody(html + '</div>');
|
||||
wxInitZone(ctx);
|
||||
}
|
||||
async function changePassword() {
|
||||
try {
|
||||
@@ -394,86 +391,97 @@
|
||||
catch (e) { toast('保存失败:' + e.message); }
|
||||
}
|
||||
|
||||
// ---------- 页:微信绑定(后端 wechat.js + wxbot iLink;一人一绑,扫码后仅本人可与 bot 单线对话) ----------
|
||||
// ---------- 微信绑定(账户页内联卡 #wx-zone;一人一绑无子页,签名比对增量更新防闪烁) ----------
|
||||
// 体验约定:后端绑定/刷新/解绑全 fire-and-forget,点击秒回;QR 只在 has_qr(wxbot 实例快照里码已就绪)
|
||||
// 后才 fetch 内联 SVG——不再有无码必坏的 <img> 首帧;轮询只在渲染串真的变了才动 DOM,pending 之外停表。
|
||||
const WX_STATUS = { pending: ['待扫码', 'held'], online: ['已连接', 'active'], expired: ['二维码过期', 'held'], error: ['异常', 'cancelled'] };
|
||||
let wxTimer = null;
|
||||
function stopWxPoll() { if (wxTimer) { clearInterval(wxTimer); wxTimer = null; } }
|
||||
let wxTimer = null, wxLast = null, wxCtx = null;
|
||||
function wxStopTick() { if (wxTimer) { clearInterval(wxTimer); wxTimer = null; } }
|
||||
|
||||
function wechatCardHtml(w) {
|
||||
const n = (w.bindings || []).length;
|
||||
const sum = n ? ('已绑定 ' + n + ' 个 · ' + (w.alive ? '服务在线' : '服务未连接')) : (w.alive ? '未绑定' : '服务未连接');
|
||||
return '<div class="settings-card"><h4>微信绑定 <span class="badge ' + (w.alive && n ? 'active' : 'held') + '">' + esc(sum) + '</span></h4>' +
|
||||
'<button class="ghost-btn" onclick="setPush(\'wechat\')">管理</button>' +
|
||||
'<div class="cfg-note">微信里给 bot 好友发文字即与 Agent 对话;发送 /help 查看全部命令。会话与网页端同源。</div></div>';
|
||||
async function wxFetch() {
|
||||
const w = await req('GET', '/api/wechat'); // {enabled, alive, bindings:[行+has_qr]}
|
||||
const b = (w && w.bindings && w.bindings[0]) || null;
|
||||
let svg = '';
|
||||
if (b && b.status === 'pending' && b.has_qr) {
|
||||
try {
|
||||
const r = await fetch('/api/wechat/' + encodeURIComponent(b.id) + '/qr?ts=' + Date.now());
|
||||
if (r.ok) svg = await r.text();
|
||||
} catch (_) { /* 抖动:本轮无码,下轮再取 */ }
|
||||
}
|
||||
return { w, b, svg };
|
||||
}
|
||||
|
||||
async function setPageWechat(ctx) {
|
||||
setTitle('微信绑定');
|
||||
setActions('');
|
||||
setBody('<div class="set-scroll"><div class="empty-tip">加载中…</div></div>');
|
||||
await renderWechatPage(ctx);
|
||||
function wxCardInnerHtml(w, b, svg) {
|
||||
if (!w || !w.enabled) return '';
|
||||
if (!b) {
|
||||
if (!w.alive) return ''; // 未部署 wxbot 的新用户:整卡隐藏,零打扰
|
||||
return '<h4>微信绑定</h4>' +
|
||||
'<button class="primary-btn" onclick="sUI.wxBind()">生成登录二维码</button>' +
|
||||
'<div class="cfg-note">一人一绑(换号先解绑)。扫码登录后微信里会出现 bot 好友,发给它的消息即进入你的 Agent 会话,回复实时推回。</div>';
|
||||
}
|
||||
if (!w.alive) {
|
||||
return '<h4>微信绑定 <span class="badge cancelled">服务未连接</span></h4>' +
|
||||
'<div class="cfg-note">wxbot 未启动或网络不通。绑定与登录凭证都在,服务恢复后自动重连。</div>' +
|
||||
'<div style="margin-top:10px"><button class="ghost-btn" onclick="sUI.wxUnbind(\'' + esc(b.id) + '\')">解绑</button></div>';
|
||||
}
|
||||
const st = WX_STATUS[b.status] || [b.status || '-', 'held'];
|
||||
let html = '<h4>微信绑定 <span class="badge ' + esc(st[1]) + '">' + esc(st[0]) + '</span><span class="wx-id">' + esc(b.id) + '</span></h4>';
|
||||
if (b.note) html += '<div class="cfg-note">' + esc(b.note) + '</div>';
|
||||
if (b.bot_account_id) html += '<div class="cfg-kv"><label>微信账号</label><b>' + esc(b.bot_account_id) + '</b></div>';
|
||||
if (b.status === 'pending') {
|
||||
html += svg
|
||||
? '<div class="wx-qr">' + svg + '</div><div class="cfg-note" style="text-align:center">微信扫码 → 手机确认;二维码会过期,也可随时点刷新。</div>'
|
||||
: '<div class="wx-qr wx-qr-wait">正在获取二维码…</div>';
|
||||
html += '<button class="ghost-btn" onclick="sUI.wxRefresh(\'' + esc(b.id) + '\')">刷新二维码</button>';
|
||||
} else if (b.status === 'expired' || b.status === 'error') {
|
||||
html += '<button class="primary-btn" onclick="sUI.wxRefresh(\'' + esc(b.id) + '\')">重新获取二维码</button>';
|
||||
} else if (b.status === 'online') {
|
||||
html += '<div class="cfg-note">已在线:给 bot 好友发消息即对话(/help 看命令)。网页端可实时看到同一个会话。</div>';
|
||||
}
|
||||
html += '<div style="margin-top:10px"><button class="ghost-btn" onclick="sUI.wxUnbind(\'' + esc(b.id) + '\')">解绑</button></div>';
|
||||
return html;
|
||||
}
|
||||
|
||||
async function renderWechatPage(ctx) {
|
||||
stopWxPoll();
|
||||
let w = null, err = '';
|
||||
try { w = await req('GET', '/api/wechat'); } catch (e) { err = String(e && e.message || e); }
|
||||
function wxPaint(st) {
|
||||
const el = $('wx-zone');
|
||||
if (!el) return;
|
||||
const inner = wxCardInnerHtml(st.w, st.b, st.svg);
|
||||
if (inner === wxLast) return; // 内容没变绝不动 DOM——轮询不闪的根治点
|
||||
wxLast = inner;
|
||||
el.innerHTML = inner;
|
||||
el.style.display = inner ? '' : 'none';
|
||||
}
|
||||
|
||||
async function wxInitZone(ctx) {
|
||||
wxCtx = ctx;
|
||||
wxStopTick();
|
||||
wxLast = null; // 重新挂载 = 新元素,上一帧比对作废
|
||||
let st;
|
||||
try { st = await wxFetch(); } catch (_) { return; }
|
||||
if (!ctx()) return;
|
||||
if (!w) { setBody('<div class="set-scroll"><div class="empty-tip">读取失败:' + esc(err) + '</div></div>'); return; }
|
||||
if (!w.enabled) { setBody('<div class="set-scroll"><div class="empty-tip">微信接入未配置(config.yml wxbot.url 或环境变量 WXBOT_URL)。</div></div>'); return; }
|
||||
const bindings = w.bindings || [];
|
||||
let html = '<div class="set-scroll">';
|
||||
if (!w.alive && !bindings.length) {
|
||||
html += '<div class="settings-card"><h4>微信服务未连接 <span class="badge cancelled">离线</span></h4>' +
|
||||
'<div class="cfg-note">wxbot 容器未启动或网络不通;启动后重进本页即可。</div></div>';
|
||||
}
|
||||
if (!bindings.length) {
|
||||
html += '<div class="settings-card"><h4>绑定微信</h4>' +
|
||||
'<button class="primary-btn"' + (w.alive ? '' : ' disabled') + ' onclick="sUI.wxBind()">生成登录二维码</button>' +
|
||||
'<div class="cfg-note">' + (w.alive
|
||||
? '一人一绑(换号先解绑)。用你自己的微信扫码登录一个 bot 账号,登录后该微信里会出现 bot 好友,发给它的消息即进入你的 Agent 会话,回复实时推回。'
|
||||
: '微信服务当前未连接,无法发起绑定。') + '</div></div>';
|
||||
setBody(html + '</div>');
|
||||
return;
|
||||
}
|
||||
for (const b of bindings) {
|
||||
const st = WX_STATUS[b.status] || [b.status || '-', 'held'];
|
||||
html += '<div class="settings-card"><h4>' + esc(b.id) + ' <span class="badge ' + esc(st[1]) + '">' + esc(st[0]) + '</span></h4>';
|
||||
if (b.note) html += '<div class="cfg-kv"><label>说明</label><b>' + esc(b.note) + '</b></div>';
|
||||
if (b.bot_account_id) html += '<div class="cfg-kv"><label>微信账号</label><b>' + esc(b.bot_account_id) + '</b></div>';
|
||||
if (b.status === 'pending') {
|
||||
// ts 参数防缓存;二维码过期时 wxbot 侧无码 → 404,img 加载失败不致命,轮询到状态变 expired 后换成刷新按钮
|
||||
html += '<div style="text-align:center;padding:6px"><img alt="登录二维码" src="/api/wechat/' + encodeURIComponent(b.id) + '/qr?ts=' + Date.now() + '" style="width:220px;height:220px;background:#fff;border-radius:8px"></div>' +
|
||||
'<div class="cfg-note" style="text-align:center">微信「扫一扫」扫码并在手机上确认;没反应就点下方刷新。</div>';
|
||||
} else if (b.status === 'expired' || b.status === 'error') {
|
||||
html += '<button class="primary-btn" onclick="sUI.wxRefresh(\'' + esc(b.id) + '\')">重新获取二维码</button>';
|
||||
} else if (b.status === 'online') {
|
||||
html += '<div class="cfg-note">已在线:直接给微信里的 bot 好友发消息开始对话(/help 看命令)。在网页端也能看到同一个会话。</div>';
|
||||
}
|
||||
html += '<div style="margin-top:10px"><button class="ghost-btn" onclick="sUI.wxUnbind(\'' + esc(b.id) + '\')">解绑</button></div></div>';
|
||||
}
|
||||
setBody(html + '</div>');
|
||||
// 待扫码时轮询状态(上线/过期都要即时换画面);页面切走后 ctx 失效自停
|
||||
if (bindings.some(b => b.status === 'pending')) {
|
||||
wxTimer = setInterval(() => {
|
||||
if (!ctx()) { stopWxPoll(); return; }
|
||||
renderWechatPage(ctx);
|
||||
}, 2500);
|
||||
wxPaint(st);
|
||||
if (st.b && st.b.status === 'pending') {
|
||||
wxTimer = setInterval(async () => {
|
||||
if (!ctx()) { wxStopTick(); return; }
|
||||
let s2;
|
||||
try { s2 = await wxFetch(); } catch (_) { return; }
|
||||
if (!ctx()) return;
|
||||
wxPaint(s2);
|
||||
if (!(s2.b && s2.b.status === 'pending')) wxStopTick(); // 出结果即停表
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
async function wxBind() {
|
||||
try { await req('POST', '/api/wechat'); toast('已生成,请微信扫码'); renderWechatPage(() => true); }
|
||||
catch (e) { toast('绑定失败:' + e.message); }
|
||||
}
|
||||
async function wxRefresh(id) {
|
||||
try { await req('POST', '/api/wechat/' + encodeURIComponent(id) + '/refresh'); renderWechatPage(() => true); }
|
||||
catch (e) { toast('刷新失败:' + e.message); }
|
||||
// 动作统一流:请求(秒回)→ 重绘内联卡(按新状态决定要不要重启轮询)
|
||||
async function wxAct(fn, okToast) {
|
||||
try { await fn(); if (okToast) toast(okToast); } catch (e) { toast(e.message); return; }
|
||||
if (wxCtx) wxInitZone(wxCtx);
|
||||
}
|
||||
function wxBind() { return wxAct(() => req('POST', '/api/wechat'), '已发起登录,二维码就绪后自动显示'); }
|
||||
function wxRefresh(id) { return wxAct(() => req('POST', '/api/wechat/' + encodeURIComponent(id) + '/refresh')); }
|
||||
async function wxUnbind(id) {
|
||||
if (!await confirmModal('解绑微信', '解绑后该微信 bot 实例与登录凭证将被销毁,需重新扫码才能恢复;会话记录保留。', '解绑', true)) return;
|
||||
try { await req('DELETE', '/api/wechat/' + encodeURIComponent(id)); toast('已解绑'); renderWechatPage(() => true); }
|
||||
catch (e) { toast('解绑失败:' + e.message); }
|
||||
await wxAct(() => req('DELETE', '/api/wechat/' + encodeURIComponent(id)), '已解绑');
|
||||
}
|
||||
|
||||
// ---------- 页:服务(服务状态 + 系统配置;搬自 settings.js) ----------
|
||||
|
||||
@@ -66,11 +66,10 @@ function rowFor(req) {
|
||||
return b;
|
||||
}
|
||||
|
||||
// 面板总览:enabled=false(wxbot.url 未配)时前端整卡隐藏——没配置就当功能不存在。
|
||||
// 面板总览:enabled=false(wxbot.url 未配)时前端整卡隐藏——没配置就当功能不存在;
|
||||
// alive/has_qr 与状态自愈全在 wechat.overview()(hook 丢事件也能从实例快照纠回来)。
|
||||
router.get('/', wrap(async (req, res) => {
|
||||
const user = String(req.user || '');
|
||||
const alive = await wechat.wxbotAlive();
|
||||
res.json({ enabled: wechat.enabled(), alive, bindings: wechat.listBindings(user) });
|
||||
res.json(await wechat.overview(String(req.user || '')));
|
||||
}));
|
||||
|
||||
router.post('/', wrap(async (req, res) => {
|
||||
|
||||
+92
-34
@@ -54,18 +54,23 @@ async function wxbotApi(method, path, body, timeoutMs) {
|
||||
try { return JSON.parse(text); } catch (_) { return text; }
|
||||
}
|
||||
|
||||
// 存活探测(GET /wxbot 面板用):带 5s 缓存,wxbot 挂掉只表现为 false,绝不外抛。
|
||||
let aliveCache = { at: 0, ok: false };
|
||||
async function wxbotAlive() {
|
||||
if (!enabled()) return false;
|
||||
if (now() - aliveCache.at < 5000) return aliveCache.ok;
|
||||
let ok = false;
|
||||
// 实例快照探测(GET /api/wechat 面板数据 + 探活二合一):2s 缓存,一次拿齐「活没活 +
|
||||
// 每个绑定的实例状态/有无二维码」;wxbot 挂掉只表现为 alive:false,绝不外抛。
|
||||
let instCache = { at: 0, alive: false, map: new Map() }; // map: id -> {state, accountId, hasQr}
|
||||
async function wxbotInstances(timeoutMs) {
|
||||
if (!enabled()) return instCache;
|
||||
if (now() - instCache.at < 2000) return instCache;
|
||||
const map = new Map();
|
||||
let alive = false;
|
||||
try {
|
||||
const r = await fetch(wxUrl() + '/health', { signal: AbortSignal.timeout(2500) });
|
||||
ok = r.ok;
|
||||
const res = await fetch(wxUrl() + '/api/instances', {
|
||||
headers: { Authorization: 'Bearer ' + wxToken() },
|
||||
signal: AbortSignal.timeout(timeoutMs || 2500),
|
||||
});
|
||||
if (res.ok) { for (const r of (await res.json()) || []) map.set(String(r.id), r); alive = true; }
|
||||
} catch (_) { /* 不在线 */ }
|
||||
aliveCache = { at: now(), ok };
|
||||
return ok;
|
||||
instCache = { at: now(), alive, map };
|
||||
return instCache;
|
||||
}
|
||||
|
||||
// ---------- 绑定表 ----------
|
||||
@@ -92,29 +97,34 @@ async function createBinding(user) {
|
||||
db.prepare(
|
||||
"INSERT INTO wechat_bindings (id, user, status, last_msg_id, created_at, updated_at) VALUES (?,?,'pending',0,?,?)"
|
||||
).run(id, user, now(), now());
|
||||
try {
|
||||
await wxbotApi('POST', '/api/instances', { id });
|
||||
} catch (e) {
|
||||
touchBinding(id, { status: 'error', note: msg(e) });
|
||||
log.warn('wechat', id + ' 创建绑定成功但 wxbot 实例启动失败:' + msg(e));
|
||||
}
|
||||
// fire-and-forget 建实例:点击秒回——不拿 wxbot 的网络往返卡住按钮(实测 SDK 取码瞬时超时过,
|
||||
// 同步 await 会毁掉整个绑定 UX)。成功由 QR 出现体现;失败落 note,轮询可见、刷新按钮可恢复。
|
||||
wxbotApi('POST', '/api/instances', { id }, 15000).catch(e => {
|
||||
touchBinding(id, { status: 'error', note: '实例启动失败:' + msg(e) });
|
||||
log.warn('wechat', id + ' wxbot 实例启动失败:' + msg(e));
|
||||
});
|
||||
log.info('wechat', (user || '-') + ' 新建微信绑定 ' + id);
|
||||
return getBinding(id);
|
||||
}
|
||||
|
||||
// 重发登录(二维码过期/失败后用):清状态 → wxbot 重起登录流程。
|
||||
// 重发登录(二维码过期/失败后用):本地先置 pending(界面立刻变「正在获取二维码」),
|
||||
// wxbot 后台 destroy+recreate(路由幂等,实例不存在时等效新建);失败落 note 由轮询呈现。
|
||||
async function refreshBinding(id) {
|
||||
const b = mustBinding(id);
|
||||
await wxbotApi('POST', '/api/instances/' + encodeURIComponent(b.id) + '/refresh');
|
||||
wxbotApi('POST', '/api/instances/' + encodeURIComponent(b.id) + '/refresh', null, 15000).catch(e => {
|
||||
touchBinding(b.id, { status: 'error', note: 'wxbot 刷新失败:' + msg(e) });
|
||||
log.warn('wechat', b.id + ' 刷新失败:' + msg(e));
|
||||
});
|
||||
touchBinding(b.id, { status: 'pending', note: null });
|
||||
return getBinding(b.id);
|
||||
}
|
||||
|
||||
// 解绑:wxbot 停实例并删凭证(尽力而为,网络断了本地也必须删干净)。
|
||||
// 解绑:本地行秒删(channel 绑定一并清);通知 wxbot 销毁 fire-and-forget,
|
||||
// 通知丢了有两层兑底:inbox 404 → wxbot 自毁孤儿实例;core 启动 restore 双向对账清理。
|
||||
async function deleteBinding(id) {
|
||||
const b = mustBinding(id);
|
||||
try { await wxbotApi('DELETE', '/api/instances/' + encodeURIComponent(b.id)); }
|
||||
catch (e) { log.warn('wechat', b.id + ' 通知 wxbot 销毁实例失败(本地继续解绑):' + msg(e)); }
|
||||
wxbotApi('DELETE', '/api/instances/' + encodeURIComponent(b.id), null, 10000)
|
||||
.catch(e => log.warn('wechat', b.id + ' 通知 wxbot 销毁失败(对账/自毁兑底):' + msg(e)));
|
||||
db.prepare('DELETE FROM wechat_bindings WHERE id = ?').run(b.id);
|
||||
db.prepare("DELETE FROM channel_sessions WHERE channel = ?").run('wx:' + b.id);
|
||||
log.info('wechat', (b.user || '-') + ' 解绑微信 ' + b.id);
|
||||
@@ -131,33 +141,81 @@ function listBindings(user) {
|
||||
return db.prepare('SELECT ' + BIND_COLS + ' FROM wechat_bindings WHERE user = ? ORDER BY created_at DESC').all(user);
|
||||
}
|
||||
|
||||
// QR 代理:wxbot 的 SVG 原样透传给 core 前端 <img>(cookie 鉴权在路由层,wxbot token 只在内网)。
|
||||
// wxbot 404(无待扫二维码)翻译成 {none:true},前端按状态渲染,避免 img 报错红叉。
|
||||
// 面板总览(GET /api/wechat 唯一实现):{enabled, alive, bindings:[行+has_qr]},
|
||||
// 并向实例快照「静默自愈」——hook 只是尽力而为(core 重启窗口/wxbot 瞬时抖动都会丢事件),
|
||||
// 每轮页面访问/轮询顺带纠偏:
|
||||
// - 实例 online 而行未 online → 纠正(不等 inbox 兑底);
|
||||
// - 实例回退到 qr/scanned 而行还挂着 online(登录态掉了)→ 打回 pending 提示重扫;
|
||||
// - 实例 expired 而行 pending → 标过期(出刷新按钮);
|
||||
// - 行该有实例而快照没有(wxbot 重启前 core 先起等)→ 后台补建(幂等)。
|
||||
async function overview(user) {
|
||||
if (!enabled()) return { enabled: false, alive: false, bindings: [] };
|
||||
const snap = await wxbotInstances();
|
||||
const rows = listBindings(user);
|
||||
for (const b of rows) {
|
||||
const ins = snap.map.get(b.id);
|
||||
b.has_qr = !!(ins && ins.hasQr);
|
||||
if (!snap.alive) continue;
|
||||
if (!ins) {
|
||||
if (b.status === 'pending' || b.status === 'online') {
|
||||
wxbotApi('POST', '/api/instances', { id: b.id }, 15000)
|
||||
.catch(e => log.warn('wechat', b.id + ' 实例补建失败:' + msg(e)));
|
||||
}
|
||||
} else if (ins.state === 'online' && b.status !== 'online') {
|
||||
touchBinding(b.id, { status: 'online', bot_account_id: ins.accountId || b.bot_account_id, note: null });
|
||||
b.status = 'online';
|
||||
if (ins.accountId) b.bot_account_id = ins.accountId;
|
||||
} else if ((ins.state === 'qr' || ins.state === 'scanned') && b.status === 'online') {
|
||||
touchBinding(b.id, { status: 'pending', note: '登录态失效,需重新扫码' });
|
||||
b.status = 'pending';
|
||||
} else if (ins.state === 'expired' && b.status === 'pending') {
|
||||
touchBinding(b.id, { status: 'expired', note: '二维码已过期,点刷新重新获取' });
|
||||
b.status = 'expired';
|
||||
}
|
||||
}
|
||||
return { enabled: true, alive: snap.alive, bindings: rows };
|
||||
}
|
||||
|
||||
// QR 代理:wxbot 的 SVG 原样透传给账户页内联渲染(cookie 鉴权在路由层,wxbot token 只在内网)。
|
||||
// wxbot 404(无待扫二维码)翻译成 {none:true};前端只在 has_qr 就绪后才拉这个接口,这里短超时即可。
|
||||
async function qrSvg(b) {
|
||||
if (!enabled()) return { none: true };
|
||||
try {
|
||||
const res = await fetch(wxUrl() + '/api/instances/' + encodeURIComponent(b.id) + '/qr.svg', {
|
||||
headers: { Authorization: 'Bearer ' + wxToken() },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
signal: AbortSignal.timeout(4000),
|
||||
});
|
||||
if (!res.ok) return { none: true };
|
||||
return { svg: await res.text() };
|
||||
} catch (_) { return { none: true }; }
|
||||
}
|
||||
|
||||
// 启动恢复:把表里的 binding 逐个 POST 到 wxbot(幂等,wxbot 端 Map 去重)。
|
||||
// wxbot 不在线只留一行 info(它起来后用户点一次「刷新」或重新绑定即可自愈,不追着重试)。
|
||||
// 启动双向对账(fire-and-forget,不阻塞 listen):core 有行而 wxbot 缺实例 → 补建;
|
||||
// wxbot 有实例而 core 无行(解绑通知丢失的孤儿)→ 销毁。wxbot 不可达只留一行 info,
|
||||
// 之后 overview() 每轮访问还会自愈补建,这里不求一次成功。
|
||||
async function restore() {
|
||||
if (!enabled()) return;
|
||||
const rows = db.prepare('SELECT id FROM wechat_bindings').all();
|
||||
if (!rows.length) return;
|
||||
let ok = 0, fail = 0;
|
||||
for (const r of rows) {
|
||||
try { await wxbotApi('POST', '/api/instances', { id: r.id }, 4000); ok++; }
|
||||
catch (_) { fail++; }
|
||||
const snap = await wxbotInstances(5000);
|
||||
if (!snap.alive) {
|
||||
if (rows.length) log.info('wechat', '启动对账:wxbot 不可达,跳过(设置页访问时会自动补建实例)');
|
||||
return;
|
||||
}
|
||||
if (fail) log.info('wechat', '启动恢复:' + ok + '/' + rows.length + ' 个实例已确保存在,' + fail + ' 个失败(wxbot 未启动?可在设置页刷新重试)');
|
||||
else log.info('wechat', '启动恢复:' + ok + ' 个微信实例已确保存在');
|
||||
const want = new Set(rows.map(r => r.id));
|
||||
let built = 0;
|
||||
for (const r of rows) {
|
||||
if (snap.map.has(r.id)) continue;
|
||||
built++;
|
||||
wxbotApi('POST', '/api/instances', { id: r.id }, 15000).catch(e => log.warn('wechat', r.id + ' 补建失败:' + msg(e)));
|
||||
}
|
||||
let orphan = 0;
|
||||
for (const id of snap.map.keys()) {
|
||||
if (want.has(id)) continue;
|
||||
orphan++;
|
||||
log.info('wechat', '对账清理孤儿微信实例 ' + id);
|
||||
wxbotApi('DELETE', '/api/instances/' + encodeURIComponent(id), null, 10000).catch(() => {});
|
||||
}
|
||||
log.info('wechat', '启动对账:绑定 ' + rows.length + ' / 实例 ' + snap.map.size + ',补建 ' + built + ',清理孤儿 ' + orphan);
|
||||
}
|
||||
|
||||
// ---------- wxbot → core 回调(/wxhook,Bearer 服务 token,auth.middleware 之前挂载) ----------
|
||||
@@ -260,7 +318,7 @@ module.exports = {
|
||||
init,
|
||||
restore,
|
||||
enabled,
|
||||
wxbotAlive,
|
||||
overview,
|
||||
getBinding,
|
||||
listBindings,
|
||||
createBinding,
|
||||
|
||||
@@ -427,9 +427,9 @@ AI 通过 `schedule` 工具为所在会话建周期性任务(`scheduled_tasks`
|
||||
背景:仓库内 `wxbot/`(已入库,作为根 compose 的 `wxbot` 服务)是基于官方 iLink 协议 SDK 的微信「调制解调器」,只挂 `agent-mcp-net` 内网、不暴露公网;身份权威与全部会话逻辑在 core,引擎不感知微信。
|
||||
|
||||
- **模型**:一条 `wechat_bindings` = 一个 core 用户 = 一个 bot 实例(一人一绑,换号先解绑)。binding id 三用:实例控制/投递的寻址键、wxbot 凭证目录名、channel 键(`channel='wx:'+id`,因此命令层、会话自动新建、投递游标查询全部白借 §5.4 的 channel 机制,零新逻辑)。iLink 协议保证扫码登录后仅本人可与 bot 单线对话,无陌生人入口,故无联系人授权面。
|
||||
- **方向三条线**:① Web(设置页→账户→微信绑定)→ `/api/wechat` → wxbot `/api/instances*`(实例控制,QR SVG 代理给页面 `<img>`,服务 token 不出内网);② wxbot 收信 → `POST core:/wxhook/inbox` → 直调 `channel.handleSend()`(命令回执同步回文本;普通消息不回执,等异步投递);③ core 总线监听 assistant_message → 分段(~1800 字/段,行优先聚合)→ `POST wxbot:/api/deliver` → `bot.send`。
|
||||
- **方向三条线**:① Web(设置页→账户→微信内联卡)→ `/api/wechat` → wxbot `/api/instances*`(实例控制;QR SVG 代理内联渲染,只在 has_qr 就绪后取码,服务 token 不出内网);② wxbot 收信 → `POST core:/wxhook/inbox` → 直调 `channel.handleSend()`(命令回执同步回文本;普通消息不回执,等异步投递);③ core 总线监听 assistant_message → 分段(~1800 字/段,行优先聚合)→ `POST wxbot:/api/deliver` → `bot.send`。
|
||||
- **投递游标** `last_msg_id` 落库 + 每绑定串行队列:重启不重发旧回复,wxbot 短暂不可达不丢(下一条连带补齐);errAck/纯工具轮(空文本)不进微信,`__blocks__` 图消息降级为占位文案。
|
||||
- **降级承诺**:`wxbot.url` 未配 = 功能整体静默关闭(启动零日志噪声、设置页入口隐藏);配了但 wxbot 没起 = restore 只留一行 info,面板显示未连接,所有外呼失败只 warn,绝不阻塞/抛出未捕获异常影响 Web 主流程(鉴权/探活失败同样只降级)。
|
||||
- **降级承诺**:`wxbot.url` 未配 = 功能整体静默关闭(启动零日志噪声、设置页入口隐藏);配了但 wxbot 没起 = restore 只留一行 info,面板显示未连接,所有外呼失败只 warn,绝不阻塞/抛出未捕获异常影响 Web 主流程(鉴权/探活失败同样只降级)。绑定/刷新/解绑对 wxbot 均 **fire-and-forget**(点击秒回,不拿 wxbot 网络往返卡按钮;失败落 note 由轮询/刷新按钮恢复);`overview()` 每轮访问拿实例快照双向纠偏(补建缺失实例/纠正丢的 hook),`restore()` 启动对账兼清孤儿实例;前端内联卡按渲染串比对增量更新,QR 只在 has_qr 就绪后才取码,无闪烁无坏图帧。
|
||||
- 鉴权:双向共用一个服务 token(根 .env `WXBOT_TOKEN`,init.sh 生成/复用)——core→wxbot 时 wxbot 把该 env 自动并入 /api 白名单;wxbot→core 走 `/wxhook`(挂 auth.middleware 之前,Bearer 哈希后定长比较,token 未配一律 503 fail-closed)。wxbot 零配置文件(同 executor 模式),接线全靠 env,config.yml 仅作可选覆盖。
|
||||
|
||||
---
|
||||
|
||||
Reference in New Issue
Block a user