Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: add wechat unbind

openJiuwen-bot6aa6c7d8f127
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index 411e6140a4..9be19aa6e8 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -411,6 +411,7 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
nonlocal _last_channels_conf
nonlocal feishu_enterprise_channels, feishu_enterprise_tasks
+ restart_pending = channel_manager.pop_channel_restart_pending()
changed_channels: list[str] = []
for channel_name in [
"feishu",
@@ -423,7 +424,14 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
"wecom",
"wechat",
]:
- if _should_restart_channel(channel_name, _last_channels_conf, conf):
+ if _should_restart_channel(channel_name, _last_channels_conf, conf) or channel_name in restart_pending:
+ if channel_name in restart_pending and not _should_restart_channel(
+ channel_name, _last_channels_conf, conf
+ ):
+ logger.info(
+ "[App] channels.%s 将强制重启(配置快照相对上次未变,例如解绑后需丢弃内存中的旧微信凭据)",
+ channel_name,
+ )
changed_channels.append(channel_name)
_last_channels_conf = dict(conf or {})
diff --git a/jiuwenclaw/app_web_handlers.py b/jiuwenclaw/app_web_handlers.py
index 0e7ede1a17..c955ee194b 100644
--- a/jiuwenclaw/app_web_handlers.py
+++ b/jiuwenclaw/app_web_handlers.py
@@ -1192,6 +1192,37 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
logger.exception("[channel.wechat.get_login_ui] %s", e)
await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+ async def _channel_wechat_unbind(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ from jiuwenclaw.channel.wechat_channel import clear_wechat_bound_session, reset_wechat_login_ui_state
+
+ conf = cm.get_conf("wechat")
+ new_conf = clear_wechat_bound_session(conf)
+ await reset_wechat_login_ui_state()
+ # 若 YAML 里 bot_token 本就为空,仅删凭据文件时 dict 与上次相同,_should_restart_channel 不会重启,扫码 UI 会一直停在 idle
+ cm.mark_channel_restart_pending("wechat")
+ await cm.set_conf("wechat", new_conf)
+ final = cm.get_conf("wechat")
+ try:
+ update_channel_in_config("wechat", final)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.wechat.unbind] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": final})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wechat.unbind] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
# ----- cron jobs -----
def _get_cron():
@@ -1387,6 +1418,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
channel.register_method("channel.wechat.get_conf", _channel_wechat_get_conf)
channel.register_method("channel.wechat.set_conf", _channel_wechat_set_conf)
channel.register_method("channel.wechat.get_login_ui", _channel_wechat_get_login_ui)
+ channel.register_method("channel.wechat.unbind", _channel_wechat_unbind)
channel.register_method("cron.job.list", _cron_job_list)
channel.register_method("cron.job.get", _cron_job_get)
channel.register_method("cron.job.create", _cron_job_create)
diff --git a/jiuwenclaw/channel/wechat_channel.py b/jiuwenclaw/channel/wechat_channel.py
index b15aef051c..eb53bab483 100644
--- a/jiuwenclaw/channel/wechat_channel.py
+++ b/jiuwenclaw/channel/wechat_channel.py
@@ -296,6 +296,26 @@ async def reset_wechat_login_ui_state() -> None:
)
+def clear_wechat_bound_session(conf: dict[str, Any]) -> dict[str, Any]:
+ """删除 credential_file 指向的本地 JSON(若存在),并返回去掉 bot_token / ilink 绑定字段后的配置副本,用于写回 ChannelManager 与 config.yaml。"""
+ out = dict(conf)
+ cred_default = "~/.wx-ai-bridge/credentials.json"
+ cred_path = str(out.get("credential_file") or "").strip() or cred_default
+ path = Path(cred_path).expanduser()
+ if path.is_file():
+ try:
+ path.unlink()
+ logger.info("WechatChannel 已删除本地凭据文件: %s", path)
+ main_logger.info("WechatChannel 已删除本地凭据文件: %s", path)
+ except OSError as e:
+ logger.warning("WechatChannel 删除凭据文件失败: %s: %s", path, e)
+ main_logger.warning("WechatChannel 删除凭据文件失败: %s: %s", path, e)
+ out["bot_token"] = ""
+ out["ilink_bot_id"] = ""
+ out["ilink_user_id"] = ""
+ return out
+
+
class WechatChannel(BaseChannel):
"""
个人微信通道(基于 iLink Bot API)。
diff --git a/jiuwenclaw/gateway/channel_manager.py b/jiuwenclaw/gateway/channel_manager.py
index 790ab5fa81..36bfc704a4 100644
--- a/jiuwenclaw/gateway/channel_manager.py
+++ b/jiuwenclaw/gateway/channel_manager.py
@@ -40,6 +40,19 @@ class ChannelManager(ABC):
# 默认仅在网关侧使用;其他简单用法可以忽略该字段。
self._config: dict[str, Any] = dict(config or {})
self._on_config_updated = on_config_updated
+ # 下一次 on_config_updated 时强制重启的 channel_id(例如微信解绑:YAML 中 bot_token 本就为空时配置 dict 对比不会变,但内存里仍有旧凭据)
+ self._pending_channel_restart: set[str] = set()
+
+ def mark_channel_restart_pending(self, channel_id: str) -> None:
+ """请求在下次 set_conf / set_config 触发配置应用时,无论配置快照是否变化都重启该 channel。"""
+ if channel_id:
+ self._pending_channel_restart.add(channel_id)
+
+ def pop_channel_restart_pending(self) -> set[str]:
+ """取出并重置待强制重启集合(由网关 _apply_channel_config 调用)。"""
+ out = set(self._pending_channel_restart)
+ self._pending_channel_restart.clear()
+ return out
def _on_channel_message(self, msg: "Message") -> None:
"""Channel 同步 on_message 回调:交给 MessageHandler 处理(入队并最终发往 AgentServer)."""
diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.py
index 7d5f69b28f..3c8f26a99b 100644
--- a/jiuwenclaw/schema/message.py
+++ b/jiuwenclaw/schema/message.py
@@ -78,6 +78,7 @@ class ReqMethod(Enum):
CHANNEL_WECHAT_GET_CONF = "channel.wechat.get_conf"
CHANNEL_WECHAT_SET_CONF = "channel.wechat.set_conf"
CHANNEL_WECHAT_GET_LOGIN_UI = "channel.wechat.get_login_ui"
+ CHANNEL_WECHAT_UNBIND = "channel.wechat.unbind"
UPDATER_GET_STATUS = "updater.get_status"
UPDATER_CHECK = "updater.check"
diff --git a/jiuwenclaw/web/src/components/ChannelsPanel/WechatQrModal.tsx b/jiuwenclaw/web/src/components/ChannelsPanel/WechatQrModal.tsx
index 30221f4283..3c52d8534f 100644
--- a/jiuwenclaw/web/src/components/ChannelsPanel/WechatQrModal.tsx
+++ b/jiuwenclaw/web/src/components/ChannelsPanel/WechatQrModal.tsx
@@ -47,6 +47,9 @@ export function WechatQrModal({ open, onClose, loginUi }: WechatQrModalProps) {
{loginUi.error}
</div>
) : null}
+ {loginUi.phase === 'fetching_qr' && !String(loginUi.message ?? '').trim() ? (
+ <p className="text-text-muted">{t('channels.wechatLogin.fetchingQrFallback')}</p>
+ ) : null}
{loginUi.phase === 'idle' &&
!loginUi.qr &&
!loginUi.error &&
diff --git a/jiuwenclaw/web/src/components/ChannelsPanel/WechatUnbindConfirmModal.tsx b/jiuwenclaw/web/src/components/ChannelsPanel/WechatUnbindConfirmModal.tsx
new file mode 100644
index 0000000000..c87e3a2edd
--- /dev/null
+++ b/jiuwenclaw/web/src/components/ChannelsPanel/WechatUnbindConfirmModal.tsx
@@ -0,0 +1,75 @@
+import { useTranslation } from 'react-i18next';
+
+type WechatUnbindConfirmModalProps = {
+ open: boolean;
+ onClose: () => void;
+ onConfirm: () => void;
+ confirming: boolean;
+};
+
+export function WechatUnbindConfirmModal({
+ open,
+ onClose,
+ onConfirm,
+ confirming,
+}: WechatUnbindConfirmModalProps) {
+ const { t } = useTranslation();
+
+ if (!open) {
+ return null;
+ }
+
+ return (
+ <div
+ className="channels-panel__modal-backdrop"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="wechat-unbind-confirm-title"
+ onClick={(e) => {
+ if (e.target === e.currentTarget && !confirming) {
+ onClose();
+ }
+ }}
+ >
+ <div
+ className="channels-panel__modal rounded-xl border border-border bg-card shadow-xl max-w-md w-full max-h-[90vh] overflow-auto flex flex-col"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="px-4 py-3 border-b border-border flex items-center justify-between gap-3">
+ <h3 id="wechat-unbind-confirm-title" className="text-sm font-semibold text-text">
+ {t('channels.wechatUnbind.confirmTitle')}
+ </h3>
+ <button
+ type="button"
+ className="btn !px-2.5 !py-1 text-xs"
+ onClick={onClose}
+ disabled={confirming}
+ >
+ {t('channels.wechatLogin.close')}
+ </button>
+ </div>
+ <div className="p-4 text-sm text-text space-y-4">
+ <p className="text-text leading-relaxed">{t('channels.wechatUnbind.confirm')}</p>
+ <div className="flex flex-wrap items-center justify-end gap-2 pt-1">
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
+ onClick={onClose}
+ disabled={confirming}
+ >
+ {t('common.cancel')}
+ </button>
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5 border border-[var(--destructive)] text-[var(--destructive)] hover:bg-[var(--destructive)]/10 disabled:opacity-50 disabled:cursor-not-allowed"
+ onClick={onConfirm}
+ disabled={confirming}
+ >
+ {confirming ? t('channels.wechatUnbind.unbinding') : t('channels.wechatUnbind.confirmAction')}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx
index f86708401d..428386932d 100644
--- a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { webRequest } from '../../services/webClient';
import { WechatQrModal } from './WechatQrModal';
+import { WechatUnbindConfirmModal } from './WechatUnbindConfirmModal';
import {
DEFAULT_WECHAT_CONF,
buildWechatPayload,
@@ -738,6 +739,8 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
const [wechatVisibleFields, setWechatVisibleFields] = useState<Record<string, boolean>>({});
const [wechatLoading, setWechatLoading] = useState(false);
const [wechatSaving, setWechatSaving] = useState(false);
+ const [wechatUnbinding, setWechatUnbinding] = useState(false);
+ const [wechatUnbindConfirmOpen, setWechatUnbindConfirmOpen] = useState(false);
const [wechatSaveError, setWechatSaveError] = useState<string | null>(null);
const [wechatSuccess, setWechatSuccess] = useState<string | null>(null);
const [wechatQrModalOpen, setWechatQrModalOpen] = useState(false);
@@ -1427,6 +1430,31 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
}
};
+ const runWechatUnbind = async () => {
+ if (!isConnected || wechatUnbinding) return;
+ setWechatUnbinding(true);
+ setWechatSaveError(null);
+ setWechatSuccess(null);
+ try {
+ const result = await webRequest<{ config?: unknown }>('channel.wechat.unbind', {});
+ const normalized = normalizeWechatConfig(result?.config);
+ setWechatConfig(normalized);
+ setWechatDraft(draftFromWechatConfig(normalized));
+ setWechatVisibleFields({});
+ setWechatSuccess(t('channels.wechatUnbind.success'));
+ wechatLoginPollAppliedAt.current = null;
+ setWechatUnbindConfirmOpen(false);
+ if (normalized.enabled && !normalized.bot_token.trim()) {
+ setWechatQrModalOpen(true);
+ }
+ } catch (err) {
+ setWechatSaveError(err instanceof Error ? err.message : t('channels.errors.unbindWechat'));
+ setWechatUnbindConfirmOpen(false);
+ } finally {
+ setWechatUnbinding(false);
+ }
+ };
+
const isConfigRefreshing =
feishuLoading ||
xiaoyiLoading ||
@@ -1488,6 +1516,16 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
onClose={() => setWechatQrModalOpen(false)}
loginUi={wechatLoginUi}
/>
+ <WechatUnbindConfirmModal
+ open={wechatUnbindConfirmOpen}
+ onClose={() => {
+ if (!wechatUnbinding) {
+ setWechatUnbindConfirmOpen(false);
+ }
+ }}
+ onConfirm={() => void runWechatUnbind()}
+ confirming={wechatUnbinding}
+ />
<div className="card w-full h-full flex flex-col">
{configErrorNotice ? (
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 z-20">
@@ -2459,15 +2497,26 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
<button
type="button"
onClick={() => void fetchWechatConfig()}
- disabled={wechatSaving || isConfigRefreshing}
+ disabled={wechatSaving || wechatUnbinding || isConfigRefreshing}
className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
>
{wechatLoading ? t('common.refreshing') : t('common.refresh')}
</button>
+ <button
+ type="button"
+ onClick={() => {
+ if (!isConnected || wechatSaving || wechatUnbinding || wechatLoading) return;
+ setWechatUnbindConfirmOpen(true);
+ }}
+ disabled={!isConnected || wechatSaving || wechatUnbinding || wechatLoading}
+ className="btn !px-3 !py-1.5 border border-[var(--destructive)] text-[var(--destructive)] hover:bg-[var(--destructive)]/10 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {wechatUnbinding ? t('channels.wechatUnbind.unbinding') : t('channels.wechatUnbind.button')}
+ </button>
<button
type="button"
onClick={handleCancelWechatConfig}
- disabled={!hasWechatConfigChanges || wechatSaving}
+ disabled={!hasWechatConfigChanges || wechatSaving || wechatUnbinding}
className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
>
{t('common.cancel')}
@@ -2475,7 +2524,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
<button
type="button"
onClick={() => void handleSaveWechatConfig()}
- disabled={!hasWechatConfigChanges || wechatSaving || !isConnected}
+ disabled={!hasWechatConfigChanges || wechatSaving || wechatUnbinding || !isConnected}
className="btn primary !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
>
{wechatSaving ? t('common.saving') : t('common.save')}
diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.json
index 026600a27d..1d5e84d08a 100644
--- a/jiuwenclaw/web/src/i18n/locales/en.json
+++ b/jiuwenclaw/web/src/i18n/locales/en.json
@@ -332,6 +332,7 @@
"hintAfterSave": "Settings saved; the channel is starting. A QR code will appear below—scan with WeChat and confirm on your phone.",
"close": "Close",
"waitBackend": "Waiting for the QR code… If this takes too long, check server logs or clear bot_token and Save again.",
+ "fetchingQrFallback": "Requesting QR code from server…",
"qrTextHint": "No image from API; only raw QR payload is available. Use WeChat to scan per vendor flow or check server logs.",
"qrHostedPageHint": "WeChat blocks embedding this page in other sites (no iframe). Scan the QR below with WeChat, or open the link—same as the official flow.",
"openQrInNewTab": "Open scan page in new tab",
@@ -339,6 +340,14 @@
"savePrompt": "Login succeeded. Fields are filled in—click Save to persist configuration.",
"savePromptFromFile": "Credentials were loaded from the local file (not QR). Click Save to write them into config; to scan again, delete or clear the credential file first, then Save."
},
+ "wechatUnbind": {
+ "button": "Unlink WeChat account",
+ "confirmTitle": "Unlink WeChat account",
+ "confirmAction": "Unlink",
+ "confirm": "This deletes the local credential file (credential_file) and clears bot_token, ilink_bot_id, and ilink_user_id in config. The WeChat channel will restart. If it stays enabled with an empty bot_token, you can scan again to sign in with another account.",
+ "unbinding": "Unlinking…",
+ "success": "WeChat account unlinked; credential file and tokens cleared from config"
+ },
"errors": {
"loadChannels": "Failed to load channels",
"loadFeishu": "Failed to load Lark settings",
@@ -349,6 +358,7 @@
"loadWhatsApp": "Failed to load WhatsApp settings",
"loadWecom": "Failed to load WeCom settings",
"loadWechat": "Failed to load WeChat settings",
+ "unbindWechat": "Failed to unlink WeChat",
"saveGeneric": "Save failed, please try again later"
}
},
diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.json
index b371497e00..0dbbd65a02 100644
--- a/jiuwenclaw/web/src/i18n/locales/zh.json
+++ b/jiuwenclaw/web/src/i18n/locales/zh.json
@@ -331,6 +331,7 @@
"hintAfterSave": "配置已保存,通道正在启动。请稍候,下方将出现二维码;请使用微信扫码,并在手机上确认登录。",
"close": "关闭",
"waitBackend": "正在等待后端返回二维码… 若长时间无响应,请查看后端日志或稍后清空 bot_token 再保存一次。",
+ "fetchingQrFallback": "正在向后端请求二维码…",
"qrTextHint": "接口未返回图片,仅提供二维码内容,请用手机微信按官方流程扫码(或查看后端日志)。",
"qrHostedPageHint": "微信不允许在其它站点内嵌该页,故无法用 iframe 展示。请用微信扫描下方二维码,或点击链接在浏览器中打开(与官方扫码页一致)。",
"openQrInNewTab": "在新窗口打开扫码页",
@@ -338,6 +339,14 @@
"savePrompt": "登录成功。凭据已填入表单,请点击「保存」写入配置(与后端持久化一致)。",
"savePromptFromFile": "已从本地凭据文件读取并填入表单(非扫码流程)。请点击「保存」将 token 写入配置;若需重新扫码,请先删除或清空凭据文件后再保存。"
},
+ "wechatUnbind": {
+ "button": "解绑微信账号",
+ "confirmTitle": "解绑微信账号",
+ "confirmAction": "确定解绑",
+ "confirm": "将删除本地凭据文件(credential_file),并清空配置中的 bot_token、ilink_bot_id、ilink_user_id。微信通道会按新配置重启;若通道仍启用且 bot_token 为空,可再次扫码登录其他账号。",
+ "unbinding": "解绑中…",
+ "success": "已解绑当前微信账号,凭据文件与配置中的 token 已清除"
+ },
"errors": {
"loadChannels": "获取 channels 失败",
"loadFeishu": "获取飞书配置失败",
@@ -348,6 +357,7 @@
"loadWhatsApp": "获取 WhatsApp 配置失败",
"loadWecom": "获取企业微信配置失败",
"loadWechat": "获取微信配置失败",
+ "unbindWechat": "微信解绑失败",
"saveGeneric": "保存失败,请稍后重试"
}
},