diff --git a/.gitignore b/.gitignore index ea465ae..e15d7c9 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,5 @@ skills-lock.json findings.md progress.md task_plan.md + +*tm-wcdb-config-helper* diff --git a/resources/wcdb/macos/arm64/libwcdb_api.dylib b/resources/wcdb/macos/arm64/libwcdb_api.dylib index 3bab03e..eda2136 100755 Binary files a/resources/wcdb/macos/arm64/libwcdb_api.dylib and b/resources/wcdb/macos/arm64/libwcdb_api.dylib differ diff --git a/resources/wcdb/macos/x64/libwcdb_api.dylib b/resources/wcdb/macos/x64/libwcdb_api.dylib index d076466..fcdf6ba 100755 Binary files a/resources/wcdb/macos/x64/libwcdb_api.dylib and b/resources/wcdb/macos/x64/libwcdb_api.dylib differ diff --git a/resources/wcdb/win32/x64/wcdb_api.dll b/resources/wcdb/win32/x64/wcdb_api.dll index d57cc18..cd95106 100644 Binary files a/resources/wcdb/win32/x64/wcdb_api.dll and b/resources/wcdb/win32/x64/wcdb_api.dll differ diff --git a/src/main/index.ts b/src/main/index.ts index 8e92c1e..6d0ecac 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,3 +1,4 @@ +import path from 'node:path' import { isLegacyMigrationHelper, isUserDataIsolated, @@ -124,7 +125,110 @@ import { MessageListenerService } from './services/message-listener-service' import { automationRuleStore } from './services/automation-rule-store' import { automationExecutionLogService } from './services/automation-execution-log-service' import { initAutomationService, getAutomationService } from './services/automation-service' +import { + applyMsgInsertSwitch, + emptyMsgInsertStatus, + eventModeStatus, + readMsgInsertSwitches, + reconcileMsgInsertRules, + resolveHelperPath, + type MsgInsertScopeInput, + type MsgInsertSwitchName +} from './services/msg-insert-switch-service' import { GroupStatsService } from './services/group-stats-service' +import { + configureWechatLocalExitNotice, + wechatLocalExitNoticeService +} from './services/wechat-local-exit-notice-service' + +/** + * 微信消息插入开关的作用面输入。 + * + * 目标群列表**复用退群监控的配置**,不在这里另维护一份。 + * 数据库没连上时返回 null,调用方据此禁用写入而不是假装能改。 + */ +function monitoredRoomCount(): number { + return (groupExitMonitorService.getState().monitoredRoomIds || []).length +} + +function resolveMsgInsertScopeInput(): MsgInsertScopeInput | null { + const client = chat.getChatDb()?.getWcdb4Client() + if (!client) return null + return { + client, + monitoredRoomIds: groupExitMonitorService.getState().monitoredRoomIds || [] + } +} + +/** + * 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。 + * + * 触发点:连库完成后 / 退群监控群列表变化后 / 用户打开开关时(那条在 service 里)。 + * 不轮询。微信新建 message_4.db 并把目标群的新表放进去时,下一次触发就会补上。 + */ +let lastMsgInsertReconciledShards = '' + +/** + * 启动时补齐 —— 防撤回 reconciliation 的入口之一。 + * + * 只在**持久化的开关已经是开**的时候跑(说明用户上次明确打开过)。开关是关的 + * 就什么都不做,避免每次启动都扫一遍目标会话。 + * + * 顺带覆盖「已启用时检测到新 shard / 新表」:分片清单变了就重新补齐,并把新的 + * 清单记下来。渲染层读状态**不会**走到这里 —— GET 必须是纯读。 + */ +async function reconcileMsgInsertRulesOnStart(): Promise { + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (!scope || !client) return + + let enabled = false + try { + const shards = client.listMessageShardPaths() + const shardSignature = shards.map((item) => path.basename(item)).join(',') + if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) { + /* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */ + console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则') + } + lastMsgInsertReconciledShards = shardSignature + for (const shardPath of shards) { + const read = client.getMsgInsertSwitches(shardPath) + if (read.success && read.switches?.recall_notice) { + enabled = true + break + } + } + } catch (error) { + console.warn('[MsgInsert] 启动检查失败:', error) + return + } + if (!enabled) return + await reconcileMsgInsertRulesNow() +} + +async function reconcileMsgInsertRulesNow(): Promise { + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (!scope || !client) return false + try { + const result = await reconcileMsgInsertRules({ + ...scope, + myWxid: String(chat.getSelfAccountInfo()?.wxid || ''), + databaseKey: client.getKey() + }) + if (result.rooms === 0) { + // 群列表还没就绪(或用户本来就没选群)—— 不算跑过,让下一次触发重试。 + return false + } + if (!result.done) { + console.warn(`[MsgInsert] reconcile 未完成 errorCode=${result.errorCode || 'UNKNOWN'}`) + } + return true + } catch (error) { + console.warn('[MsgInsert] reconcile 失败:', error) + return true + } +} import { wechatActionLogService } from './services/wechat-action-log-service' import { toPersonalWechatSendResult, wechatActionGateway } from './services/wechat-action-gateway' import { personalWechatSendService } from './services/personal-wechat-send-service' @@ -1087,7 +1191,32 @@ app.whenReady().then(async () => { * `handleGroupExit` 自己吞掉异常,这里再兜一层 `.catch` 是防御性的 —— * 未捕获的 rejection 会污染监控循环,而退群事实早就已经记录成功了。 */ + /* 退群本地提示的运行时依赖:密钥 / wxid / 账号目录都由主进程提供, + * 服务自己不依赖 chat-service 的具体形态。 */ + configureWechatLocalExitNotice({ + resolveDatabaseKey: () => chat.getChatDb()?.getWcdb4Client()?.getKey() || '', + resolveMyWxid: () => String(chat.getSelfAccountInfo()?.wxid || ''), + resolveAccountRoot: () => { + const shards = chat.getChatDb()?.getWcdb4Client()?.listMessageShardPaths() || [] + if (shards.length > 0) return path.dirname(path.dirname(path.dirname(shards[0]))) + return String(chat.getCurrentAccountRoot() || '') + } + }) + + /* + * 防撤回 reconciliation 的启动入口:只有当持久化的开关已经是「开」时才会跑。 + * 渲染层读状态、群列表变化都不会触发 DDL。 + */ + void reconcileMsgInsertRulesOnStart() + groupExitMonitorService.setGroupExitHandler((event) => { + /* + * 微信内退群监控消息:一次性往群里插一条本地提示。 + * + * 与下面的自动化通知**完全独立**:自己不抛异常(handleExitEvent 内部兜底)、 + * 不 await、失败只记日志 —— 插入失败绝不能影响退群监控循环或自动化通知。 + */ + void wechatLocalExitNoticeService.handleExitEvent(event) try { return getAutomationService() .handleGroupExit(event) @@ -1693,6 +1822,8 @@ app.whenReady().then(async () => { * 只有一个参数:旧版第二个参数(通知群聊)已经迁到「自动化 → 退群通知」, * 退群监控不再持有任何通知配置。 */ + /* 监控范围变化不再触发任何规则补齐:防撤回的目标是「全部有消息表的会话」, + * 与退群监控选中的群无关;退群提示也已经改成事件驱动、不依赖 per-room 规则。 */ ipcMain.handle('group-exit-monitor:setGroups', (_, roomIds: string[]) => groupExitMonitorService.setMonitoredRoomIds(Array.isArray(roomIds) ? roomIds : []) ) @@ -1757,6 +1888,100 @@ app.whenReady().then(async () => { }) ipcMain.handle('automation:clearExecutions', () => automationExecutionLogService.clear()) ipcMain.handle('automation:listGroups', () => tryAutomationService()?.listGroups() ?? []) + /** + * 微信消息插入开关 —— 读取。 + * + * 只走本进程只读路径(分片目录 + 开关值),不持有任何写权限。 + * 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能 + * 真的生效(规则可能没装齐),渲染层不能只看前者。 + */ + ipcMain.handle('automation:getMsgInsertSwitches', () => { + /* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。 + * 规则补齐只发生在「用户打开开关」(helper 的 apply 内部先 ensure)与 + * 「应用启动且持久化开关为开」这两个时机。 */ + const scope = resolveMsgInsertScopeInput() + if (scope) { + const snapshot = readMsgInsertSwitches(scope) + /* 退群提示的开关状态来自本地设置(事件驱动,不装规则), + * 不是微信库里的 _tm_config。 */ + snapshot.switches.group_exit_notice = eventModeStatus( + 'group_exit_notice', + wechatLocalExitNoticeService.isEnabled(), + monitoredRoomCount() + ) + return snapshot + } + return { + success: false, + switches: { + recall_notice: emptyMsgInsertStatus('recall_notice'), + group_exit_notice: eventModeStatus( + 'group_exit_notice', + wechatLocalExitNoticeService.isEnabled() + ) + }, + helperAvailable: resolveHelperPath() !== null, + detail: '微信数据库尚未连接' + } + }) + /** + * 微信消息插入开关 —— 写入。 + * + * 绝不使用本进程的 WCDB 句柄写(只读池会把它钉死)。这里 spawn 一次性 helper: + * 先补齐目标会话的规则 → 再写开关值 → 读回校验 → 本进程只读复核。 + * 失败不伪装成功:partial 会带 failedShards / notReadyRooms 回渲染层。 + */ + ipcMain.handle('automation:setMsgInsertSwitch', async (_, input: unknown) => { + const payload = (input || {}) as { name?: unknown; enabled?: unknown } + const name = String(payload.name || '') as MsgInsertSwitchName + if (name !== 'recall_notice' && name !== 'group_exit_notice') { + return { + success: false, + status: emptyMsgInsertStatus('recall_notice'), + errorCode: 'UNSUPPORTED_SWITCH', + message: '未知的开关' + } + } + /* + * 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条), + * 不装任何 per-room 规则。所以它的开关只是本地设置: + * 既不 spawn helper,也不碰微信库。 + */ + if (name === 'group_exit_notice') { + const toggled = wechatLocalExitNoticeService.setEnabled(payload.enabled === true) + if (toggled.error) { + return { + success: false, + status: eventModeStatus(name, toggled.enabled, monitoredRoomCount()), + errorCode: 'UNKNOWN', + message: '保存开关状态失败' + } + } + return { + success: true, + status: eventModeStatus(name, toggled.enabled, monitoredRoomCount()) + } + } + + const scope = resolveMsgInsertScopeInput() + const client = chat.getChatDb()?.getWcdb4Client() + if (!scope || !client) { + return { + success: false, + status: emptyMsgInsertStatus(name), + errorCode: 'DATABASE_UNAVAILABLE', + message: '微信数据库尚未连接' + } + } + return applyMsgInsertSwitch({ + ...scope, + name, + enabled: payload.enabled === true, + myWxid: String(chat.getSelfAccountInfo()?.wxid || ''), + /* 密钥只在这里读一次,随后直接进 helper 的 stdin,绝不落盘 / 进 argv */ + databaseKey: client.getKey() + }) + }) /** * 保存「退群通知」规则(singleton upsert)。 * diff --git a/src/main/services/msg-insert-switch-service.ts b/src/main/services/msg-insert-switch-service.ts new file mode 100644 index 0000000..5064756 --- /dev/null +++ b/src/main/services/msg-insert-switch-service.ts @@ -0,0 +1,729 @@ +/** + * 微信消息插入开关 —— 主进程侧封装。 + * + * 为什么写操作不能在本进程做 + * -------------------------- + * WCDB 的 CommonCore 按**路径**池化底层库对象(CoreBridge.cpp: + * `getOrCreateDatabase` + 只在 readOnly 时 `setReadOnly()`),而只读标志一旦 + * 设上去就没有逆操作。TraceMemo 启动后会用只读方式打开 message 分片,于是同一 + * 进程里任何「可写打开」拿到的都是那个只读对象 —— 写入必然得到 + * `-3004 attempt to write a readonly database`。 + * + * 所以: + * **读** → 本进程只读路径(分片目录 + 开关值),零写权限 + * **写** → spawn 一次性子进程 `tm-wcdb-config-helper`,池随进程销毁 + * + * 子进程的密钥只从 stdin 进,绝不进 argv / env(否则会出现在 `ps` 与进程环境里)。 + * + * 状态语义(不要退回「开关值写成功 = 功能已生效」) + * ------------------------------------------------ + * 真正干活的是挂在 `Msg_` 表上的规则。一个分片完全可能 + * 「有 _tm_config 却没规则」,此时开关写成 1 也毫无效果。而且一个会话可能同时 + * 存在于 2~4 个分片,必须**所有命中分片都 ready** 才算这个会话 ready。 + * + * 判断「是否生效」始终按目标会话算,不按分片算。 + */ + +import { spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import path from 'node:path' + +import { findResource } from '../resource-paths' +import type { Wcdb4Client } from '../wcdb4-client' +import { + MSG_INSERT_SWITCHES, + type MsgInsertApplyResult, + type MsgInsertErrorCode, + type MsgInsertScope, + type MsgInsertSwitchName, + type MsgInsertSwitchStatus, + type MsgInsertSwitchesSnapshot +} from '../../shared/msg-insert-switch' + +export { + MSG_INSERT_SWITCHES, + type MsgInsertSwitchName, + type MsgInsertSwitchStatus, + type MsgInsertSwitchesSnapshot +} + +/* --------------------------------------------------------------- 常量 */ + +const HELPER_NAME = 'tm-wcdb-config-helper' +const HELPER_TIMEOUT_MS = 60_000 +/** 分片里规则的名字(与 native 侧一致) */ +const RULE_CAPTURE = '_tm_msg_insert_capture' +/* notice 规则只装在 winner 分片、且不参与就绪判据,读路径不需要它的名字。 + * 退群已改事件驱动,不再有 queue 规则(常量已退役)。 */ + +/** + * 规则名在 native 侧按会话加了后缀。 + * + * SQLite 的 trigger 名是**库级唯一**的:如果所有会话都用固定名字,给第二个会话装规则 + * 会直接覆盖第一个。所以真实名字形如 `_tm_msg_insert_capture_`。 + * + * ⚠️ 读路径必须用带后缀的名字去查目录,否则会得出「库里明明有规则、界面却显示 0」这种 + * 自相矛盾的结论。 + */ +function ruleName(base: string, roomId: string): string { + return `${base}_${md5Hex(roomId)}` +} + +const SWITCH_SCOPE: Record = { + // 防撤回:群聊和私聊都要覆盖,所以目标是「全部可定位会话」 + recall_notice: 'all_sessions', + // 退群监控:只作用于退群监控当前选中的群 + group_exit_notice: 'monitored_rooms' +} + +interface HelperRunResult { + ok: boolean + exitCode: number | null + json?: Record + errorCode?: MsgInsertErrorCode + message?: string + detail?: string +} + +function md5Hex(value: string): string { + return createHash('md5').update(value).digest('hex') +} + +function messageTableFor(roomId: string): string { + return `Msg_${md5Hex(roomId)}` +} + +export const SWITCH_MODE: Record = { + // 防撤回靠装规则 + recall_notice: 'rules', + // 退群提示靠事件驱动的一次性插入,不装规则 + group_exit_notice: 'event' +} + +/** + * 事件驱动型开关的状态。 + * + * 它没有 room / shard 维度(不装规则),所以 room 计数一律为 0 —— UI 据此不显示 + * 「N / M 已启用」。desired 与 effective 同值:这条路径没有「值写了对但规则没装」 + * 的中间态,插入失败会记在 service 的 recent 里,不影响开关本身。 + */ +export function eventModeStatus( + name: MsgInsertSwitchName, + enabled: boolean, + monitoredRoomCount = 0 +): MsgInsertSwitchStatus { + const status = emptyMsgInsertStatus(name) + status.mode = 'event' + status.desiredEnabled = enabled + status.effectiveEnabled = enabled + status.operationOk = true + /* 事件驱动型没有「预装规则覆盖率」。这里给的只是**监控范围**, + * 用来告诉用户「开了之后哪些群的退群会被插提示」,不是覆盖率。 */ + status.monitoredRoomCount = monitoredRoomCount + return status +} + +export function emptyMsgInsertStatus( + name: MsgInsertSwitchName, + errorCode?: MsgInsertErrorCode, + message?: string +): MsgInsertSwitchStatus { + return { + switch: name, + scope: SWITCH_SCOPE[name], + mode: SWITCH_MODE[name], + desiredEnabled: false, + effectiveEnabled: false, + operationOk: false, + totalInstallableRooms: 0, + readyInstallableRooms: 0, + roomsWithoutTable: 0, + totalShards: 0, + targetShards: 0, + configuredShards: 0, + readyShards: 0, + notReadyShards: 0, + failedShards: 0, + errorCode, + message + } +} + +/* ------------------------------------------------------- helper 定位与调用 */ + +/** + * helper 与 libwcdb_api.dylib 同目录部署(依赖 @loader_path 解析 dylib)。 + * 开发态与打包态都靠 findResource 解析,不依赖当前工作目录。 + */ +export function resolveHelperPath(): string | null { + /* + * 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows), + * 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null, + * 表现为「缺少写入组件」+ 开关永久置灰。 + * + * 同目录还有 wcdb_api.dll / WCDB.dll / SDL2.dll,MSVC 运行库在 resources/runtime/win32/, + * 两者都由 preload-env.ts 加进 DLL 搜索路径,所以 helper.exe 能直接加载。 + */ + const archDir = process.arch === 'x64' ? 'x64' : 'arm64' + const otherArchDir = archDir === 'arm64' ? 'x64' : 'arm64' + const platformDir = process.platform === 'win32' ? 'win32' : 'macos' + const suffix = process.platform === 'win32' ? '.exe' : '' + const candidates = [ + `wcdb/${platformDir}/${archDir}/${HELPER_NAME}${suffix}`, + `wcdb/${platformDir}/${otherArchDir}/${HELPER_NAME}${suffix}`, + `wcdb/${platformDir}/${HELPER_NAME}${suffix}` + ] + for (const candidate of candidates) { + const resolved = findResource(candidate) + if (resolved) return resolved + } + return null +} + +/** 从分片路径反推账号根目录(helper 需要它来枚举分片) */ +function accountRootFromShard(shardPath: string): string { + // /db_storage/message/message_N.db + return path.dirname(path.dirname(path.dirname(shardPath))) +} + +/** + * 跑一次 helper。**密钥只走 stdin**。 + * + * 请求体是一行 JSON:{"key":"","rooms":[...],"myWxid":"..."} + * 用 JSON 而不是 argv,是因为目标会话可能有上千个,argv 会被撑爆; + * 顺带保证密钥永远不进进程参数表。 + */ +function runHelper( + helperPath: string, + args: string[], + request: { key: string; rooms: string[]; myWxid: string }, + timeoutMs = HELPER_TIMEOUT_MS +): Promise { + return new Promise((resolve) => { + let child: ReturnType + try { + child = spawn(helperPath, args, { stdio: ['pipe', 'pipe', 'pipe'] }) + } catch (error) { + resolve({ + ok: false, + exitCode: null, + errorCode: 'HELPER_START_FAILED', + message: 'helper 启动失败', + detail: error instanceof Error ? error.message : String(error) + }) + return + } + + let stdout = '' + let stderr = '' + let settled = false + const finish = (result: HelperRunResult): void => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(result) + } + + const timer = setTimeout(() => { + try { + child.kill('SIGKILL') + } catch { + /* 已经退出了 */ + } + finish({ + ok: false, + exitCode: null, + errorCode: 'HELPER_TIMEOUT', + message: '写入超时,已中止', + detail: `timeout=${timeoutMs}ms stderr=${stderr.slice(-400)}` + }) + }, timeoutMs) + + child.stdout?.on('data', (chunk: Buffer) => { + stdout += chunk.toString() + }) + child.stderr?.on('data', (chunk: Buffer) => { + stderr = `${stderr}${chunk.toString()}`.slice(-4000) + }) + child.on('error', (error) => { + finish({ + ok: false, + exitCode: null, + errorCode: 'HELPER_START_FAILED', + message: 'helper 启动失败', + detail: error.message + }) + }) + child.on('close', (code) => { + const lines = stdout.trim().split('\n').filter(Boolean) + let json: Record | undefined + try { + json = JSON.parse(lines[lines.length - 1] || '') as Record + } catch { + finish({ + ok: false, + exitCode: code, + errorCode: 'HELPER_BAD_OUTPUT', + message: 'helper 返回了无法解析的结果', + detail: `exit=${code} stdout=${stdout.slice(-400)} stderr=${stderr.slice(-400)}` + }) + return + } + const success = json.success === true + finish({ + ok: code === 0 || (code === 1 && json.success === false), + exitCode: code, + json, + errorCode: success ? undefined : inferErrorCode(json), + message: success ? undefined : describeFailure(json), + detail: `exit=${code} ${stderr.slice(-400)}`.trim() + }) + }) + + /* 密钥与请求一起写进 stdin,然后立刻关闭 —— 不进 argv、不进 env、不落盘。 */ + try { + child.stdin?.write(`${JSON.stringify(request)}\n`) + child.stdin?.end() + } catch (error) { + finish({ + ok: false, + exitCode: null, + errorCode: 'HELPER_START_FAILED', + message: '无法把密钥交给 helper', + detail: error instanceof Error ? error.message : String(error) + }) + } + }) +} + +function inferErrorCode(json: Record): MsgInsertErrorCode { + const code = String(json.code || '') + if (code === 'HELPER_BAD_ARGS') return 'HELPER_BAD_OUTPUT' + if (code === 'UNSUPPORTED_SWITCH') return 'UNSUPPORTED_SWITCH' + if (code === 'HELPER_NO_SHARDS') return 'DATABASE_UNAVAILABLE' + if (code === 'RULE_MISSING') return 'RULE_MISSING' + const failed = Number(json.failedShards || 0) + if (failed > 0) return 'SHARD_WRITE_FAILED' + /* roomsWithoutTable 是中性 pending,不是失败 —— 只有当**一个可安装会话都没有** + * 的时候才算没有目标。 */ + if ( + Number(json.totalTargetRooms || 0) > 0 && + Number(json.totalTargetRooms || 0) === Number(json.roomsWithoutTable || 0) + ) { + return 'NO_TARGET_ROOMS' + } + return 'UNKNOWN' +} + +function describeFailure(json: Record): string { + const failed = Number(json.failedShards || 0) + if (failed > 0) return `${failed} 个消息库写入失败` + const without = Number(json.roomsWithoutTable || 0) + if (Number(json.totalTargetRooms || 0) > 0 && Number(json.totalTargetRooms) === without) { + return `${without} 个目标会话在微信库里都还没有消息表` + } + const code = String(json.code || '') + const detail = String(json.error || '') + return code ? `${code}${detail ? `:${detail}` : ''}` : '操作未完成' +} + +/* ----------------------------------------------------------- 目标会话解析 */ + +export interface MsgInsertScopeInput { + client: Wcdb4Client + /** 退群监控当前选中的群(来自 group-exit-monitor 服务,不在这里另维护一份) */ + monitoredRoomIds: string[] +} + +/** + * 解析某个开关的目标会话集合。 + * + * - group_exit_notice → 退群监控选中的群(复用现有配置,不重新维护第二份群列表) + * - recall_notice → 全部可定位会话(群聊 + 私聊) + */ +export function resolveTargetRooms( + input: MsgInsertScopeInput, + name: MsgInsertSwitchName +): { scope: MsgInsertScope; rooms: string[]; error?: string } { + const scope = SWITCH_SCOPE[name] + if (scope === 'monitored_rooms') { + const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean))) + return { scope, rooms } + } + try { + const rooms = Array.from( + new Set( + input.client + .getSessions() + .map((session) => String(session.username || '').trim()) + .filter(Boolean) + ) + ) + return { scope, rooms } + } catch (error) { + return { + scope, + rooms: [], + error: error instanceof Error ? error.message : String(error) + } + } +} + +/* --------------------------------------------------------------- 只读状态 */ + +interface CatalogShard { + shard: string + dbPath: string + configTable: boolean + tables: Set + ruleTables: Map +} + +function readCatalog(client: Wcdb4Client): { + shards: CatalogShard[] + rawCount: number + error?: string +} { + const result = client.listMsgInsertShardCatalog() + if (!result.success || !result.catalog) { + return { shards: [], rawCount: 0, error: result.error || '分片目录读取失败' } + } + const shards = result.catalog.shards.map((entry) => ({ + shard: entry.shard, + dbPath: entry.dbPath, + configTable: entry.configTable, + tables: new Set(entry.tables || []), + ruleTables: new Map((entry.rules || []).map((rule) => [rule.name, rule.table])) + })) + return { shards, rawCount: shards.length } +} + +function roomReadiness( + shards: CatalogShard[], + roomId: string, + name: MsgInsertSwitchName +): { matched: string[]; ready: boolean; notReady: string[] } { + const table = messageTableFor(roomId) + const matched: string[] = [] + const notReady: string[] = [] + const captureName = ruleName(RULE_CAPTURE, roomId) + /* notice 规则只装在 winner 分片,就绪判据不看它(见下),所以这里不需要它的名字。 */ + for (const shard of shards) { + if (!shard.tables.has(table)) continue + matched.push(shard.shard) + /* 同时接受历史遗留的无后缀规则(只要它挂在同一张表上)—— 与 native 侧判据一致, + * 否则用旧脚本装过的那一个会话会被误判成未就绪。 */ + const attachedTo = (...names: string[]): boolean => + names.some((candidate) => shard.ruleTables.get(candidate) === table) + const capture = attachedTo(captureName, RULE_CAPTURE) + /* + * ⚠️ 只要求 capture。 + * + * notice 规则**只装在 winner 分片**上(分片之间是独立数据库文件、没有共享状态, + * 每个分片各生成一条会重复插提示)。所以这里不能再要求每个分片都有 notice —— + * 否则所有跨分片会话都会显示成「未就绪」。 + * 这条必须与 native 侧 `msgInsertEvaluateRoomShard` 的 `recallReady = capture` 一致。 + */ + const ready = name === 'recall_notice' ? capture : true + if (!ready) notReady.push(shard.shard) + } + return { matched, ready: matched.length > 0 && notReady.length === 0, notReady } +} + +/** + * 本进程只读地聚合两个开关的状态。 + * + * 只用「分片目录 + 开关值」:目录一次拿全,之后在本地用 md5(roomId) 匹配, + * 所以哪怕目标会话很多也不会有额外的查库开销。 + */ +export function readMsgInsertSwitches(input: MsgInsertScopeInput): MsgInsertSwitchesSnapshot { + const catalog = readCatalog(input.client) + const shardCount = catalog.rawCount + const switches = {} as Record + + if (catalog.error || shardCount === 0) { + for (const name of MSG_INSERT_SWITCHES) { + switches[name] = emptyMsgInsertStatus( + name, + 'DATABASE_UNAVAILABLE', + catalog.error || '找不到消息分片(数据库可能尚未连接)' + ) + } + return { success: false, switches, helperAvailable: resolveHelperPath() !== null } + } + + /* 每个分片读一次开关值,后面既用来算 desired,也用来算分片级 ready */ + const valuesByShard = new Map>() + for (const shard of catalog.shards) { + const read = input.client.getMsgInsertSwitches(shard.dbPath) + valuesByShard.set( + shard.shard, + read.success && read.switches + ? read.switches + : { recall_notice: false, group_exit_notice: false } + ) + } + + for (const name of MSG_INSERT_SWITCHES) { + const resolved = resolveTargetRooms(input, name) + const status = emptyMsgInsertStatus( + name, + resolved.error ? 'DATABASE_UNAVAILABLE' : undefined, + resolved.error + ) + status.scope = resolved.scope + status.totalShards = shardCount + + const targetShardNames = new Set() + const notReadyRooms: MsgInsertSwitchStatus['notReadyRooms'] = [] + let readyRooms = 0 + let roomsWithoutTable = 0 + + for (const room of resolved.rooms) { + const readiness = roomReadiness(catalog.shards, room, name) + if (readiness.matched.length === 0) { + /* 公众号 / 服务号 / 系统会话没有 Msg_ 表,装不了规则 —— **中性 pending**, + * 既不算失败,也不进 notReadyRooms,更不能拖累 effectiveEnabled。 */ + roomsWithoutTable += 1 + continue + } + for (const shard of readiness.matched) targetShardNames.add(shard) + if (readiness.ready) { + readyRooms += 1 + } else { + notReadyRooms.push({ + roomId: room, + reason: 'rules-missing', + matchedShards: readiness.matched, + notReadyShards: readiness.notReady + }) + } + } + + status.targetShards = targetShardNames.size + /* 分母是「有消息表、可安装」的会话数,不是全部会话数。 + * 否则总会有一部分会话装不了规则,界面会一直显示「部分成功」。 */ + status.totalInstallableRooms = readyRooms + notReadyRooms.length + status.readyInstallableRooms = readyRooms + status.roomsWithoutTable = roomsWithoutTable + + let configured = 0 + let readyShards = 0 + let notReadyShards = 0 + for (const shard of catalog.shards) { + const values = valuesByShard.get(shard.shard) + const on = Boolean(values?.[name]) + if (on) configured += 1 + if (!targetShardNames.has(shard.shard)) continue + const recallOk = roomShardsReady(catalog.shards, shard.shard, resolved.rooms, name) + if (on && recallOk) readyShards += 1 + else if (on) notReadyShards += 1 + } + status.configuredShards = configured + status.readyShards = readyShards + status.notReadyShards = notReadyShards + status.failedShards = 0 + status.desiredEnabled = configured > 0 + status.operationOk = true + /* 生效判定只看可安装会话:roomsWithoutTable 不能阻止 effectiveEnabled。 */ + status.effectiveEnabled = + status.desiredEnabled && + status.totalInstallableRooms > 0 && + readyRooms === status.totalInstallableRooms + status.notReadyRooms = notReadyRooms.slice(0, 20) + + if (resolved.rooms.length === 0) { + status.message = '没有可作用的目标会话' + } + switches[name] = status + } + + return { success: true, switches, helperAvailable: resolveHelperPath() !== null } +} + +/** 某分片上「所有目标会话」的规则是否都齐 */ +function roomShardsReady( + shards: CatalogShard[], + shardName: string, + rooms: string[], + name: MsgInsertSwitchName +): boolean { + const shard = shards.find((entry) => entry.shard === shardName) + if (!shard) return false + let any = false + for (const room of rooms) { + const table = messageTableFor(room) + if (!shard.tables.has(table)) continue + any = true + const attachedTo = (...names: string[]): boolean => + names.some((candidate) => shard.ruleTables.get(candidate) === table) + const capture = attachedTo(ruleName(RULE_CAPTURE, room), RULE_CAPTURE) + /* 与 roomReadiness、以及 native 侧 `msgInsertEvaluateRoomShard` 用同一判据: + * notice 只装在 winner 分片,就绪只看 capture。 */ + const ready = name === 'recall_notice' ? capture : true + if (!ready) return false + } + return any +} + +/* --------------------------------------------------------------- 写入动作 */ + +export interface MsgInsertApplyInput extends MsgInsertScopeInput { + name: MsgInsertSwitchName + enabled: boolean + myWxid: string + databaseKey: string +} + +/** + * 打开 / 关闭一个开关。 + * + * 顺序是**先规则、后开关**:开的时候必须先把目标会话的规则补齐并确认 ready, + * 才写开关值;关的时候只写值(规则体自己读 _tm_config,值为 0 时一行都不执行, + * 所以关闭不需要昂贵 DDL,下次打开直接恢复)。 + */ +export async function applyMsgInsertSwitch( + input: MsgInsertApplyInput +): Promise { + /* + * 防御:事件驱动型开关(退群提示)**不允许**走规则路径。 + * + * 它没有 per-room 规则,走 apply 只会把 `_tm_config.group_exit_notice` 写成 1 —— + * 一个写了也没人读的脏值,界面还会显示成关闭。 + */ + if (SWITCH_MODE[input.name] !== 'rules') { + return { + success: false, + status: eventModeStatus(input.name, false), + errorCode: 'UNSUPPORTED_SWITCH', + message: '这个开关不走规则路径' + } + } + + const resolved = resolveTargetRooms(input, input.name) + if (resolved.rooms.length === 0) { + return { + success: false, + status: emptyMsgInsertStatus(input.name, 'NO_TARGET_ROOMS', '没有可作用的目标会话'), + errorCode: 'NO_TARGET_ROOMS', + message: '没有可作用的目标会话' + } + } + if (!input.databaseKey) { + return { + success: false, + status: emptyMsgInsertStatus(input.name, 'DATABASE_UNAVAILABLE', '数据库密钥不可用'), + errorCode: 'DATABASE_UNAVAILABLE', + message: '数据库密钥不可用,请先连接微信数据库' + } + } + + const helperPath = resolveHelperPath() + if (!helperPath) { + return { + success: false, + status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '暂无法使用'), + errorCode: 'HELPER_NOT_FOUND', + /* 面向用户是能力语义;errorCode 仍是 HELPER_NOT_FOUND,门禁/授权层照旧能判。 */ + message: '暂无法使用:当前安装不包含微信内消息写入组件' + } + } + + const shards = input.client.listMessageShardPaths() + const accountRoot = shards.length > 0 ? accountRootFromShard(shards[0]) : '' + if (!accountRoot) { + return { + success: false, + status: emptyMsgInsertStatus(input.name, 'DATABASE_UNAVAILABLE', '找不到账号目录'), + errorCode: 'DATABASE_UNAVAILABLE', + message: '找不到微信账号目录' + } + } + + const run = await runHelper( + helperPath, + [ + '--account-root', + accountRoot, + '--action', + 'apply', + '--switch', + input.name === 'recall_notice' ? 'recall' : 'group_exit', + '--value', + input.enabled ? '1' : '0' + ], + { key: input.databaseKey, rooms: resolved.rooms, myWxid: input.myWxid } + ) + + /* 无论 helper 成功与否,都用本进程只读路径复核一遍,不拿 helper 的自述当结论 */ + const snapshot = readMsgInsertSwitches(input) + const status = snapshot.switches[input.name] + + if (!run.json) { + return { + success: false, + status, + errorCode: run.errorCode || 'UNKNOWN', + message: run.message || '操作失败', + detail: run.detail + } + } + + const success = run.json.success === true + /* 用 helper 的权威计数覆盖本地只读快照里的 room 分母,避免两边口径漂移。 */ + status.totalInstallableRooms = Number( + run.json.installableTargetRooms ?? status.totalInstallableRooms + ) + status.readyInstallableRooms = Number(run.json.readyTargetRooms ?? status.readyInstallableRooms) + status.roomsWithoutTable = Number(run.json.roomsWithoutTable ?? status.roomsWithoutTable) + return { + success, + status, + errorCode: success ? undefined : run.errorCode || 'PARTIAL_SUCCESS', + message: success ? undefined : run.message, + detail: run.detail + } +} + +/** + * 轻量 reconciliation:把目标会话缺失的规则补齐,**不动开关值**。 + * + * 触发时机:启动连库后 / 退群监控群列表变化后 / 用户打开开关时。 + * 微信新建 message_4.db 并把某个目标群的新表放进去时,下一次触发就会自动补上。 + */ +export async function reconcileMsgInsertRules( + input: MsgInsertScopeInput & { myWxid: string; databaseKey: string } +): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> { + const helperPath = resolveHelperPath() + if (!helperPath || !input.databaseKey) { + return { + done: false, + rooms: 0, + written: 0, + errorCode: helperPath ? 'DATABASE_UNAVAILABLE' : 'HELPER_NOT_FOUND' + } + } + const shards = input.client.listMessageShardPaths() + if (shards.length === 0) { + return { done: false, rooms: 0, written: 0, errorCode: 'DATABASE_UNAVAILABLE' } + } + /* 只补退群监控选中的群 —— 防撤回的作用面由「打开开关」那一刻决定, + * 启动时不做全量扫描,避免每次启动都摸一遍全部会话。 */ + const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean))) + if (rooms.length === 0) return { done: true, rooms: 0, written: 0 } + + const run = await runHelper( + helperPath, + ['--account-root', accountRootFromShard(shards[0]), '--action', 'ensure-rules'], + { key: input.databaseKey, rooms, myWxid: input.myWxid } + ) + if (!run.json) { + return { done: false, rooms: rooms.length, written: 0, errorCode: run.errorCode || 'UNKNOWN' } + } + return { + done: run.json.success === true, + rooms: rooms.length, + written: Number(run.json.rulesWritten || 0), + errorCode: run.json.success === true ? undefined : 'RULE_MISSING' + } +} diff --git a/src/main/services/wechat-local-exit-notice-service.ts b/src/main/services/wechat-local-exit-notice-service.ts new file mode 100644 index 0000000..0480d8f --- /dev/null +++ b/src/main/services/wechat-local-exit-notice-service.ts @@ -0,0 +1,322 @@ +/** + * 微信内退群监控消息 —— 事件驱动的一次性插入。 + * + * 为什么不再用 persistent trigger + * ------------------------------ + * 退群提示以前是给每个监控群装一条 `_tm_msg_insert_queue` 规则,靠微信自己插消息时 + * 触发。问题:粒度是「群 × 分片」,监控群一多就要铺成百上千条规则;而退群这个事实 + * TraceMemo 本来就已经知道了(GroupExitMonitorService 是**唯一**退群事实源)。 + * 让数据库再算一遍,等于维护两套退群判断,迟早不一致。 + * + * 现在改成: + * GroupExitMonitorService → GroupMemberExitedEvent → 本服务 → one-shot helper 插一条 + * + * 三条硬约束(都不能违反) + * ------------------------ + * 1. **不产生第二套退群事实**:本服务只消费事件、只插消息,从不自己判断谁退群。 + * 2. **失败不回滚、不阻塞**:插入失败绝不能让退群事件回滚、不能影响监控循环、 + * 不能影响自动化通知。所以 handleExitEvent **永不抛异常**,调用方也不必 await。 + * 3. **幂等**:以 eventId 为幂等键,同一事件最多插一次。幂等日志写在微信库里 + * (不是内存),所以跨进程、跨重启都有效。 + * + * 只插一个目标消息存储:写入分片由 native 侧按 MAX(sort_seq) 选出,不在历史分片 + * 重复插入。没有可插入的消息表时返回 NO_MESSAGE_STORE,TraceMemo 内部的退群记录 + * 照常保留。 + */ + +import { spawn } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' + +import { app } from 'electron' + +import type { GroupMemberExitedEvent } from '../../shared/group-exit-event' +import { renderLeaveNotificationText } from '../../shared/group-exit-event' +import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor' +import { findResource } from '../resource-paths' + +export type LocalExitNoticeOutcome = + | 'inserted' + | 'duplicate' + | 'disabled' + | 'no_message_store' + | 'failed' + | 'helper_unavailable' + +export interface LocalExitNoticeResult { + outcome: LocalExitNoticeOutcome + eventId: string + conversationId: string + shard?: string + localId?: number + /** 机器可读的原因,只进日志 */ + code?: string +} + +interface StoredState { + enabled?: boolean +} + +const HELPER_NAME = 'tm-wcdb-config-helper' +const HELPER_TIMEOUT_MS = 20_000 +/** 最近若干次插入结果,只用于诊断展示,不参与判定 */ +const RECENT_LIMIT = 50 + +function helperPath(): string | null { + /* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致: + * Windows 走 wcdb/win32// 且文件名带 .exe。 */ + const arch = process.arch === 'x64' ? 'x64' : 'arm64' + const other = arch === 'arm64' ? 'x64' : 'arm64' + const platformDir = process.platform === 'win32' ? 'win32' : 'macos' + const suffix = process.platform === 'win32' ? '.exe' : '' + for (const candidate of [ + `wcdb/${platformDir}/${arch}/${HELPER_NAME}${suffix}`, + `wcdb/${platformDir}/${other}/${HELPER_NAME}${suffix}`, + `wcdb/${platformDir}/${HELPER_NAME}${suffix}` + ]) { + const resolved = findResource(candidate) + if (resolved) return resolved + } + return null +} + +/** + * 退群本地提示服务。 + * + * 与 GroupExitMonitorService 是**消费**关系:它发事件,这里负责往微信里插一条。 + * 这里不持有任何群列表,也不判断退群 —— 避免第二套事实源。 + */ +export class WechatLocalExitNoticeService { + private enabled = false + private loaded = false + private recent: LocalExitNoticeResult[] = [] + + private statePath(): string { + return path.join(app.getPath('userData'), 'wechat-local-exit-notice.json') + } + + private ensureLoaded(): void { + if (this.loaded) return + this.loaded = true + try { + const raw = fs.readFileSync(this.statePath(), 'utf8') + const stored = JSON.parse(raw) as StoredState + this.enabled = stored.enabled === true + } catch { + this.enabled = false + } + } + + isEnabled(): boolean { + this.ensureLoaded() + return this.enabled + } + + setEnabled(enabled: boolean): { enabled: boolean; error?: string } { + this.ensureLoaded() + this.enabled = enabled === true + try { + fs.mkdirSync(path.dirname(this.statePath()), { recursive: true }) + fs.writeFileSync(this.statePath(), JSON.stringify({ enabled: this.enabled }, null, 2), 'utf8') + return { enabled: this.enabled } + } catch (error) { + return { + enabled: this.enabled, + error: error instanceof Error ? error.message : String(error) + } + } + } + + getRecent(): LocalExitNoticeResult[] { + return [...this.recent] + } + + private remember(result: LocalExitNoticeResult): void { + this.recent = [result, ...this.recent].slice(0, RECENT_LIMIT) + } + + /** + * 处理一次退群事件。 + * + * ⚠️ 本方法**永不抛异常**:它挂在退群监控的事件回调上,抛出去会污染监控循环。 + * 返回值只用于日志与诊断,调用方不需要(也不应该)等它。 + */ + async handleExitEvent(event: GroupMemberExitedEvent): Promise { + const base: LocalExitNoticeResult = { + outcome: 'failed', + eventId: event.eventId, + conversationId: event.conversationId + } + try { + this.ensureLoaded() + if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' }) + if (!event.eventId || !event.conversationId) { + return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' }) + } + + const resolved = helperPath() + if (!resolved) { + return this.finish({ ...base, outcome: 'helper_unavailable', code: 'HELPER_NOT_FOUND' }) + } + + const key = resolveDatabaseKey() + const myWxid = resolveMyWxid() + if (!key || !myWxid) { + return this.finish({ ...base, outcome: 'failed', code: 'DATABASE_UNAVAILABLE' }) + } + + const accountRoot = resolveAccountRoot() + if (!accountRoot) { + return this.finish({ ...base, outcome: 'failed', code: 'ACCOUNT_ROOT_UNRESOLVED' }) + } + + const text = renderLeaveNotificationText(event, GROUP_EXIT_NOTIFICATION_TEMPLATE) + const payload = JSON.stringify({ + key, + myWxid, + roomId: event.conversationId, + text, + dedupeKey: event.eventId + }) + + const parsed = await runInsertHelper(resolved, accountRoot, payload) + if (!parsed) { + return this.finish({ ...base, outcome: 'failed', code: 'HELPER_BAD_OUTPUT' }) + } + + const code = String(parsed.code || '') + const shard = typeof parsed.shard === 'string' && parsed.shard ? parsed.shard : undefined + const localId = Number(parsed.localId) || undefined + if (parsed.ok === true) { + return this.finish({ + ...base, + outcome: code === 'ALREADY_INSERTED' ? 'duplicate' : 'inserted', + shard, + localId, + code + }) + } + if (code === 'NO_MESSAGE_STORE') { + return this.finish({ ...base, outcome: 'no_message_store', code }) + } + return this.finish({ ...base, outcome: 'failed', shard, localId, code }) + } catch (error) { + /* 兜底:任何意外都不许冒到监控循环里去。 */ + return this.finish({ + ...base, + outcome: 'failed', + code: error instanceof Error ? error.message : String(error) + }) + } + } + + private finish(result: LocalExitNoticeResult): LocalExitNoticeResult { + this.remember(result) + if (result.outcome === 'failed' || result.outcome === 'helper_unavailable') { + console.warn( + `[LocalExitNotice] 插入未成功 outcome=${result.outcome} code=${result.code || 'UNKNOWN'}` + ) + } + return result + } +} + +export const wechatLocalExitNoticeService = new WechatLocalExitNoticeService() + +/* --------------------------------------------------------------- 依赖注入 */ + +interface LocalExitRuntime { + resolveDatabaseKey: () => string + resolveMyWxid: () => string + resolveAccountRoot: () => string +} + +let runtime: LocalExitRuntime | null = null + +/** 由主进程在启动时注入;这样服务本身不依赖 chat-service 的具体形态。 */ +export function configureWechatLocalExitNotice(next: LocalExitRuntime): void { + runtime = next +} + +function resolveDatabaseKey(): string { + try { + return runtime?.resolveDatabaseKey() || '' + } catch { + return '' + } +} + +function resolveMyWxid(): string { + try { + return runtime?.resolveMyWxid() || '' + } catch { + return '' + } +} + +function resolveAccountRoot(): string { + try { + return runtime?.resolveAccountRoot() || '' + } catch { + return '' + } +} + +/* ------------------------------------------------------------------ 执行 */ + +function runInsertHelper( + executable: string, + accountRoot: string, + payload: string +): Promise | null> { + return new Promise((resolve) => { + let child: ReturnType + try { + child = spawn(executable, ['--account-root', accountRoot, '--action', 'insert-notice'], { + stdio: ['pipe', 'pipe', 'pipe'] + }) + } catch { + resolve(null) + return + } + + let stdout = '' + let settled = false + const finish = (value: Record | null): void => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(value) + } + const timer = setTimeout(() => { + try { + child.kill('SIGKILL') + } catch { + /* 已退出 */ + } + finish(null) + }, HELPER_TIMEOUT_MS) + + child.stdout?.on('data', (chunk: Buffer) => { + stdout += chunk.toString() + }) + child.stderr?.on('data', () => { + /* 人类日志直接丢弃:里面不该有密钥,也没必要留 */ + }) + child.on('error', () => finish(null)) + child.on('close', () => { + try { + const lines = stdout.trim().split('\n').filter(Boolean) + finish(JSON.parse(lines[lines.length - 1] || '') as Record) + } catch { + finish(null) + } + }) + try { + child.stdin?.write(`${payload}\n`) + child.stdin?.end() + } catch { + finish(null) + } + }) +} diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index 2f33b89..2c49d30 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -526,6 +526,16 @@ export class Wcdb4Client { private wcdbGetGroupMembersBatch: | ((handle: number, chatroomIdsJson: string, outJson: WcdbVoidOut) => number) | null = null + // 微信消息插入开关(native extension,不属于最初 27 个绑定) + private wcdbMsgInsertSetSwitch: + | ((handle: number, dbPath: string, name: string, enabled: number) => number) + | null = null + private wcdbMsgInsertGetSwitches: + | ((handle: number, dbPath: string, outJson: WcdbVoidOut) => number) + | null = null + private wcdbMsgInsertListShardCatalog: + | ((handle: number, outJson: WcdbVoidOut) => number) + | null = null private wcdbGetGroupNicknames: | ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number) | null = null @@ -1804,6 +1814,113 @@ export class Wcdb4Client { return result } + /** + * 列出账号目录下所有消息分片路径(message_.db)。 + * + * 供「微信消息插入开关」这类**按分片存放**的状态遍历使用。 + * 只认 message_<数字>.db,不包含 biz_message_* / media_*。 + */ + listMessageShardPaths(): string[] { + const messageRoot = path.join(this.dbStoragePath, 'message') + if (!fs.existsSync(messageRoot)) return [] + return fs + .readdirSync(messageRoot) + .filter((name) => /^message_\d+\.db$/.test(name)) + .sort() + .map((name) => path.join(messageRoot, name)) + } + + /** + * 读取某个消息分片上的「微信消息插入开关」。 + * + * 开关按消息分片存放(native 侧的 _tm_config 表),所以调用方要先把分片路径定下来。 + * 返回形如 { recall_notice: boolean, group_exit_notice: boolean }。 + */ + getMsgInsertSwitches(dbPath: string): { + success: boolean + switches?: Record + error?: string + } { + if (!this.wcdbMsgInsertGetSwitches) { + return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' } + } + try { + const switches = this.callJson>((handle, outJson) => + this.wcdbMsgInsertGetSwitches!(handle, dbPath, outJson) + ) + return { success: true, switches } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : String(error) } + } + } + + /** + * 设置某个消息分片上的「微信消息插入开关」。 + * + * name 只接受 recall_notice / group_exit_notice(native 侧白名单)。 + * 写入走 native 单独维护的可写连接,只读查询链路不受影响。 + */ + setMsgInsertSwitch( + dbPath: string, + name: string, + enabled: boolean + ): { success: boolean; error?: string } { + if (!this.wcdbMsgInsertSetSwitch) { + return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' } + } + try { + const handle = this.ensureHandle() + const rc = this.wcdbMsgInsertSetSwitch(handle, dbPath, name, enabled ? 1 : 0) + if (rc !== 0) return { success: false, error: `返回码 ${rc}` } + return { success: true } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : String(error) } + } + } + + /** + * 读取「微信消息插入规则」的分片目录(只读)。 + * + * 每个分片只跑两条查询(表清单 + 规则清单),拿回来之后调用方可以在本地用 + * md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多, + * 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。 + */ + listMsgInsertShardCatalog(): { + success: boolean + catalog?: { + shardCount: number + shards: Array<{ + shard: string + dbPath: string + configTable: boolean + storeTables: { capture: boolean; names: boolean; queue: boolean } + tables: string[] + rules: Array<{ name: string; table: string }> + }> + } + error?: string + } { + if (!this.wcdbMsgInsertListShardCatalog) { + return { success: false, error: '当前 WCDB 服务不支持消息插入规则目录' } + } + try { + const catalog = this.callJson<{ + shardCount: number + shards: Array<{ + shard: string + dbPath: string + configTable: boolean + storeTables: { capture: boolean; names: boolean; queue: boolean } + tables: string[] + rules: Array<{ name: string; table: string }> + }> + }>((handle, outJson) => this.wcdbMsgInsertListShardCatalog!(handle, outJson)) + return { success: true, catalog } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : String(error) } + } + } + installRecallJournal(usernames: string[]): { installed: number; failed: number } { const stores = new Map() for (const username of this.uniq(usernames)) { @@ -3011,6 +3128,30 @@ export class Wcdb4Client { this.wcdbGetGroupMembersBatch = null } + try { + this.wcdbMsgInsertSetSwitch = lib.func( + 'int32 wcdb_msg_insert_set_switch(int64 handle, const char* dbPath, const char* name, int32 enabled)' + ) as (handle: number, dbPath: string, name: string, enabled: number) => number + } catch { + this.wcdbMsgInsertSetSwitch = null + } + + try { + this.wcdbMsgInsertGetSwitches = lib.func( + 'int32 wcdb_msg_insert_get_switches(int64 handle, const char* dbPath, _Out_ void** outJson)' + ) as (handle: number, dbPath: string, outJson: WcdbVoidOut) => number + } catch { + this.wcdbMsgInsertGetSwitches = null + } + + try { + this.wcdbMsgInsertListShardCatalog = lib.func( + 'int32 wcdb_msg_insert_list_shard_catalog(int64 handle, _Out_ void** outJson)' + ) as (handle: number, outJson: WcdbVoidOut) => number + } catch { + this.wcdbMsgInsertListShardCatalog = null + } + try { this.wcdbGetGroupNicknames = lib.func( 'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)' diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 9cfda07..6428963 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -105,6 +105,11 @@ import type { ScheduledRuleRunOutcome } from '../shared/automation' import type { ActionLogEntry } from '../shared/action-log' +import type { + MsgInsertApplyResult, + MsgInsertSwitchName, + MsgInsertSwitchesSnapshot +} from '../shared/msg-insert-switch' import type { AppUpdateCheckResult, AppUpdateInstallResult, @@ -326,6 +331,23 @@ declare global { saveLeaveNotificationRule: (draft: AutomationRuleDraft) => Promise /** 「指定好友」的可选项;已在 main 侧过滤掉群聊 / 公众号 / 文件传输助手 / 自己。 */ listSendableContacts: () => Promise> + /** + * 微信消息插入开关:读取当前状态。 + * + * 逐目标会话返回 desiredEnabled / effectiveEnabled —— 开关值写成功不等于 + * 功能真的生效(规则可能没装齐),界面不能只看前者。 + */ + getMsgInsertSwitches: () => Promise + /** + * 微信消息插入开关:打开 / 关闭。 + * + * 开的时候先补规则再写值;写入由一次性 helper 子进程完成, + * 失败会带 failedShards / notReadyRooms 回来,不伪装成功。 + */ + setMsgInsertSwitch: ( + name: MsgInsertSwitchName, + enabled: boolean + ) => Promise onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => () => void search: (keyword: string) => Promise searchKnowledge: (request: KnowledgeSearchIpcRequest) => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index bd6e74a..0ca592f 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -75,6 +75,11 @@ import type { } from '../shared/automation' import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats' import type { ActionLogEntry } from '../shared/action-log' +import type { + MsgInsertApplyResult, + MsgInsertSwitchName, + MsgInsertSwitchesSnapshot +} from '../shared/msg-insert-switch' import type { CacheClearScope, CacheSummary } from '../shared/cache' import type { ExportRequest, ExportJobProgress } from '../shared/export' import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption' @@ -222,6 +227,27 @@ const api = { */ listSendableContacts: (): Promise> => ipcRenderer.invoke('automation:listSendableContacts'), + /** + * 微信消息插入开关 —— 读取当前状态。 + * + * 返回的是**逐目标会话**的状态:desiredEnabled(开关值)与 effectiveEnabled + * (真的会生效)是两个概念,界面不能只看前者。数据库未连接时 `success=false`。 + */ + getMsgInsertSwitches: (): Promise => + ipcRenderer.invoke('automation:getMsgInsertSwitches'), + /** + * 微信消息插入开关 —— 打开 / 关闭。 + * + * 开的时候会先把目标会话的规则补齐、确认 ready 才写开关值;写不进本进程, + * 由一次性 helper 子进程完成。失败不伪装成功:`status.failedShards > 0` + * 表示真的有分片写失败,`status.readyTargetRooms < status.totalTargetRooms` + * 表示只是规则没装齐。 + */ + setMsgInsertSwitch: ( + name: MsgInsertSwitchName, + enabled: boolean + ): Promise => + ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }), onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => { const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void => callback(state) diff --git a/src/renderer/src/features/automation/AutomationWorkspace.tsx b/src/renderer/src/features/automation/AutomationWorkspace.tsx index bd4fc40..aa1c3c5 100644 --- a/src/renderer/src/features/automation/AutomationWorkspace.tsx +++ b/src/renderer/src/features/automation/AutomationWorkspace.tsx @@ -24,6 +24,7 @@ import { AutomationRuleTypeTabs, type AutomationRuleTabType } from './AutomationRuleTypeTabs' +import { MessageInsertSwitches } from './MessageInsertSwitches' import { ScheduledReportEditor } from './ScheduledReportEditor' import { ScheduledReportRuleList } from './ScheduledReportRuleList' import { ScheduledReportNotificationPanel } from './ScheduledReportNotificationPanel' @@ -483,16 +484,20 @@ export function AutomationWorkspace({

自动化

当群里出现符合条件的消息时,TraceMemo 会自动执行你配置的动作。

- {tab === 'rules' && !showEditor ? ( - - ) : null} +
+ {/* 微信消息插入开关:控制 TraceMemo 能在微信会话里插入哪些消息 */} + + {tab === 'rules' && !showEditor ? ( + + ) : null} +
{!apiAvailable ? ( diff --git a/src/renderer/src/features/automation/MessageInsertSwitches.tsx b/src/renderer/src/features/automation/MessageInsertSwitches.tsx new file mode 100644 index 0000000..7d14946 --- /dev/null +++ b/src/renderer/src/features/automation/MessageInsertSwitches.tsx @@ -0,0 +1,221 @@ +import * as React from 'react' +import { + MSG_INSERT_SWITCH_LABELS, + type MsgInsertApplyResult, + type MsgInsertSwitchName, + type MsgInsertSwitchStatus, + type MsgInsertSwitchesSnapshot +} from '../../../../shared/msg-insert-switch' +import { Switch, Spinner, useToast } from '../../components/ui' + +/** + * 「微信消息插入开关」—— 自动化页右上角的两个开关。 + * + * 分工: + * 开关值存在 native 侧(每个消息分片 `_tm_config` 表),真正干活的是挂在 + * `Msg_` 表上的规则;写入由主进程 spawn 一次性 helper 完成。 + * 这里只负责展示与触发,不做任何平台判断。 + * + * 三个状态都要如实展示,不能只画一个 boolean: + * desiredEnabled 用户意图(开关值) + * effectiveEnabled 是否真的生效(目标会话规则齐 + 开关值落到相关分片) + * ready / total 目标会话的覆盖情况 + * + * 打开时先 loading、成功才 ON、失败回滚;写失败与「规则没装齐」是两种不同的 + * 提示,不混成一句「设置失败」。 + */ +/* 首次拉取失败时的有界重试:2s 一次,最多 20 次(约 40s)。连上即停。 */ +const BLOCKED_RETRY_LIMIT = 20 +const BLOCKED_RETRY_INTERVAL_MS = 2000 + +export function MessageInsertSwitches(): React.JSX.Element { + const { toast } = useToast() + const [snapshot, setSnapshot] = React.useState(null) + const [pending, setPending] = React.useState(null) + const [blockedReason, setBlockedReason] = React.useState(null) + const [loading, setLoading] = React.useState(true) + + /** + * 拉一次状态。返回是否成功 —— 调用方据此决定要不要重试。 + */ + const refresh = React.useCallback(async (): Promise => { + const api = window.api + if (!api?.getMsgInsertSwitches) { + setBlockedReason('当前版本不支持微信消息插入开关') + setLoading(false) + return false + } + try { + const result = await api.getMsgInsertSwitches() + setSnapshot(result) + /* 数据库没连上时不能假装能改;但已经有数据时不要把界面打回禁用态。 */ + setBlockedReason(result.success ? null : result.detail || '微信数据库尚未连接') + return result.success + } catch (error) { + setBlockedReason(error instanceof Error ? error.message : String(error)) + return false + } finally { + setLoading(false) + } + }, []) + + /* + * 首次拉取失败要**有界重试**。 + * + * 自动化页常常在微信库还没连上的时候就被打开(冷启动、刚切库、微信还没起来), + * 这时只拉一次就会把开关永久置灰 —— 用户看到的是「灰的」,但真实原因只是「还没连上」, + * 而且切走再回来才会恢复。所以这里连上就停、连不上退避重试,最多 20 次(约 40s)。 + * + * 不轮询:一旦拿到 success=true 就彻底停,不会有常驻定时器。 + */ + React.useEffect(() => { + let cancelled = false + let timer: ReturnType | undefined + let attempt = 0 + const run = async (): Promise => { + const ok = await refresh() + if (cancelled || ok || attempt >= BLOCKED_RETRY_LIMIT) return + attempt += 1 + timer = setTimeout(() => void run(), BLOCKED_RETRY_INTERVAL_MS) + } + void run() + return () => { + cancelled = true + if (timer) clearTimeout(timer) + } + }, [refresh]) + + /** 把结果里的失败原因翻成人话;native code 只进日志。 */ + const humanize = React.useCallback((result: MsgInsertApplyResult): string => { + const status = result.status + if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少写入组件,请重新安装或更新 TraceMemo' + if (result.errorCode === 'DATABASE_UNAVAILABLE') return '微信数据库未连接' + if (result.errorCode === 'NO_TARGET_ROOMS') return '没有可作用的目标会话' + if (status && status.failedShards > 0) { + return `设置失败:${status.failedShards} 个消息库写入失败` + } + if ( + status && + status.totalInstallableRooms > 0 && + status.readyInstallableRooms < status.totalInstallableRooms + ) { + return `开启失败:${ + status.totalInstallableRooms - status.readyInstallableRooms + } 个会话的消息规则安装失败` + } + return result.message || '设置失败,请稍后重试' + }, []) + + const handleToggle = React.useCallback( + async (name: MsgInsertSwitchName, next: boolean): Promise => { + const api = window.api + if (!api?.setMsgInsertSwitch || pending) return + setPending(name) + try { + const result = await api.setMsgInsertSwitch(name, next) + /* 不乐观更新:写的是微信库里的规则 + 开关,失败必须回滚到真实状态。 + * 先拿主进程只读复核的结果,再决定开关画成什么。 */ + setSnapshot((prev) => + prev ? { ...prev, switches: { ...prev.switches, [name]: result.status } } : prev + ) + if (!result.success) { + toast({ description: humanize(result), variant: 'destructive', duration: 4000 }) + /* 复核一次,确保界面与库里真实状态一致(而不是停在乐观值上)。 */ + await refresh() + return + } + if (result.detail) console.warn('[MsgInsert]', result.detail) + await refresh() + } catch (error) { + toast({ + description: error instanceof Error ? error.message : '设置失败', + variant: 'destructive', + duration: 4000 + }) + await refresh() + } finally { + setPending(null) + } + }, + [humanize, pending, refresh, toast] + ) + + /* + * helper 缺失时**提前**禁用,而不是等用户点了再弹「缺少写入组件」。 + * 写开关必须靠那个一次性子进程,缺了它这个开关根本没法工作 —— + * 让人点了才失败是最差的一种交互。 + */ + /* + * 写入组件缺失 = **能力不可用**,不是安装坏了。 + * + * 主进程对微信库只有只读连接,任何写入都要 spawn 那个一次性组件;没有它, + * 「微信内防撤回提示」和「微信内退群监控消息」都做不了。所以这里按能力置灰 + + * 一句话说明,而不是弹「请重新安装」—— 后者会让人以为装坏了。 + * (machine-readable 的原因仍然是 snapshot.helperAvailable,付费/授权层可以据此判断。) + */ + const helperMissing = snapshot?.helperAvailable === false + const blocked = + blockedReason ?? (helperMissing ? '暂无法使用:当前安装不包含微信内消息写入组件' : null) + const disabled = blocked !== null + + return ( +
+ {loading ? : null} + {MSG_INSERT_SWITCH_LABELS.map(({ name, label, hint }) => { + const status: MsgInsertSwitchStatus | undefined = snapshot?.switches?.[name] + const busy = pending === name + /* rules 型:显示「已就绪 / 可安装」;事件驱动型没有覆盖率这个概念。 */ + const showCoverage = status?.mode === 'rules' && status.totalInstallableRooms > 0 + const partial = + status?.desiredEnabled === true && + status.totalInstallableRooms > 0 && + status.readyInstallableRooms < status.totalInstallableRooms + /* 内部口径(roomsWithoutTable 之类的「暂无消息表」计数)不面向普通用户, + * 只留在诊断/tooltip 里,不上主界面。 */ + const scopeHint = + status?.mode === 'event' && (status.monitoredRoomCount || 0) > 0 + ? `当前监控 ${status.monitoredRoomCount} 个群聊` + : null + return ( + /* 刻意用 span 而不是 label:
+ ) +} diff --git a/src/renderer/src/styles/automation.scss b/src/renderer/src/styles/automation.scss index 16089bc..c29d7f1 100644 --- a/src/renderer/src/styles/automation.scss +++ b/src/renderer/src/styles/automation.scss @@ -42,6 +42,74 @@ } } +/* 右上角操作区:微信消息插入开关 + 新建自动化 */ +.automation-page-header-actions { + display: flex; + align-items: center; + gap: 18px; + flex-wrap: wrap; + padding-top: 6px; +} + +.automation-msg-insert-switches { + display: flex; + align-items: center; + gap: 16px; + flex-wrap: wrap; +} + +.automation-msg-insert-switch { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 12px; + line-height: 20px; + color: var(--wxex-text-secondary); + /* 容器本身不可点(点了不切换),所以不要给 pointer 光标误导用户。 */ + cursor: default; + user-select: none; + + &.is-disabled { + opacity: 0.5; + cursor: not-allowed; + } +} + +.automation-msg-insert-switch-label { + white-space: nowrap; +} + +/* 处理中:把「正在写微信库」这件事显式说出来,避免用户以为界面卡死。 + 宽度不锁死会带着开关一起抖,所以这里只用固定行高、不加弹性布局。 */ +.automation-msg-insert-switch-busy { + display: inline-flex; + align-items: center; + gap: 4px; + white-space: nowrap; + color: var(--wxex-accent, var(--wxex-text-secondary)); +} + +/* 中性提示:既不表示失败,也不参与「是否生效」判定 → 不用警告色。 */ +.automation-msg-insert-switch-scope { + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--wxex-text-tertiary, var(--wxex-text-secondary)); + opacity: 0.7; +} + +/* 覆盖情况(已就绪 / 可安装)。规则没装齐时给出可读的警示,而不是只留一个 ON。 */ +.automation-msg-insert-switch-count { + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--wxex-text-tertiary, var(--wxex-text-secondary)); + opacity: 0.85; + + &.is-warning { + color: var(--wxex-warning, #d97706); + opacity: 1; + } +} + .automation-notice { margin: 0; padding: 10px 14px; diff --git a/src/shared/msg-insert-switch.ts b/src/shared/msg-insert-switch.ts new file mode 100644 index 0000000..4c88775 --- /dev/null +++ b/src/shared/msg-insert-switch.ts @@ -0,0 +1,166 @@ +/** + * 微信消息插入开关 —— 跨进程共享的类型与常量。 + * + * 开关本体存在 native 侧(每个消息分片 `_tm_config` 表),但**开关值写成功不等于 + * 功能真的生效**:真正干活的是挂在 `Msg_` 表上的规则,而某个分片 + * 完全可能「有 _tm_config 却没规则」。所以对外状态一律区分三件事: + * + * desiredEnabled 用户意图(开关值有没有写下去) + * effectiveEnabled 是否真的生效(目标会话的规则全齐 + 开关值落到相关分片) + * operationOk 写入层面有没有失败 + * + * 判断「生效」按**目标会话**算,不按分片算 —— 一个会话可能横跨 2~4 个分片, + * 只有当它命中的**每一个**分片都 ready,这个会话才算 ready。 + */ + +/** native 侧白名单里的开关名 */ +export const MSG_INSERT_SWITCHES = ['recall_notice', 'group_exit_notice'] as const + +export type MsgInsertSwitchName = (typeof MSG_INSERT_SWITCHES)[number] + +/** 目标会话的集合口径 */ +export const MSG_INSERT_SCOPES = ['monitored_rooms', 'all_sessions'] as const +export type MsgInsertScope = (typeof MSG_INSERT_SCOPES)[number] + +export interface MsgInsertRoomIssue { + roomId: string + reason: 'rules-missing' | 'table-not-found' + matchedShards: string[] + notReadyShards: string[] +} + +export interface MsgInsertShardIssue { + shard: string + errorCode: number + error: string +} + +/** 开关的实现形态 */ +export type MsgInsertSwitchMode = + /** 靠微信库里的 persistent 规则实现:需要按会话装规则 → 有 room / shard 维度 */ + | 'rules' + /** 靠事件驱动的一次性插入实现:没有 room / shard 维度 */ + | 'event' + +/** 单个开关的完整状态 */ +export interface MsgInsertSwitchStatus { + switch: MsgInsertSwitchName + scope: MsgInsertScope + /** rules = 装规则(防撤回);event = 事件驱动一次性插入(退群提示) */ + mode: MsgInsertSwitchMode + + /** 用户意图:开关值当前是否处于「开」 */ + desiredEnabled: boolean + /** 是否真的生效 */ + effectiveEnabled: boolean + /** 写入层面是否全部成功 */ + operationOk: boolean + + /** + * 目标会话总数(**分母**)。 + * + * ⚠️ 这是「**有消息表、可安装规则**的会话数」,不是全部会话数。 + * 公众号 / 服务号 / 系统会话根本没有 `Msg_` 表,装不了规则,它们是中性 pending, + * 拿它们当分母只会让开关永远显示「部分成功」。 + */ + totalInstallableRooms: number + /** 规则已就绪的可安装会话数(分子) */ + readyInstallableRooms: number + /** + * 微信库里找不到消息表的会话数。 + * + * **中性 pending,不是失败**:这类会话通常还没收发过消息。它们不会进 + * notReadyRooms,也不会阻止 effectiveEnabled。UI 单独显示为「暂无消息表」。 + */ + roomsWithoutTable: number + /** 事件驱动型开关用:当前监控范围里的群聊数(只是范围,不是覆盖率) */ + monitoredRoomCount?: number + + totalShards: number + /** 目标会话实际落在的分片数 */ + targetShards: number + /** 开关值已落到「开」的分片数 */ + configuredShards: number + /** 开关值对且目标规则齐的分片数 */ + readyShards: number + /** 值对了但目标规则不齐的分片数(不是失败) */ + notReadyShards: number + /** 写不进去 / 读回校验不过的分片数(真失败) */ + failedShards: number + + notReadyRooms?: MsgInsertRoomIssue[] + failures?: MsgInsertShardIssue[] + + /** 机器可读的错误分类,见 MsgInsertErrorCode */ + errorCode?: MsgInsertErrorCode + /** 给人看的一句话;UI 直接展示这个 */ + message?: string +} + +export interface MsgInsertSwitchesSnapshot { + success: boolean + switches: Record + /** helper 是否可用(不可用时只能读不能写) */ + /** + * **能力标志**:本机是否存在「微信内消息写入组件」(那个一次性 helper)。 + * + * 这是「微信内防撤回提示」和「微信内退群监控消息」的**唯一硬门槛**: + * 主进程对微信库只持只读连接,任何写入都必须 spawn 那个组件,没有它两个功能都做不了。 + * + * 语义上它是 **capability(能力)**,不是 error(错误)—— + * 缺失时 UI 显示「暂无法使用」,而不是「请重新安装」。 + * + * ⚠️ 它是**唯一**的能力判据,不要再新增第二份(曾经因为 native 与 TS 各存一份判据 + * 而出现 946 里莫名少 323 的假象)。将来的授权/付费门禁应当**并列**加在它旁边 + * (capability && entitlement),而不是替换它。 + */ + helperAvailable: boolean + /** native code 只放这里,不往 UI 上抛 */ + detail?: string +} + +/** 打开/关闭一个开关的结果 */ +export interface MsgInsertApplyResult { + success: boolean + status: MsgInsertSwitchStatus + errorCode?: MsgInsertErrorCode + message?: string + detail?: string +} + +/** + * 错误分类。底层码(-2002 / -3004 / exit code)一律进 detail, + * 不给普通用户看。 + */ +export type MsgInsertErrorCode = + | 'HELPER_NOT_FOUND' + | 'HELPER_START_FAILED' + | 'HELPER_TIMEOUT' + | 'HELPER_BAD_OUTPUT' + | 'HELPER_EXIT_NONZERO' + | 'SHARD_WRITE_FAILED' + | 'SHARD_VERIFY_FAILED' + | 'RULE_MISSING' + | 'PARTIAL_SUCCESS' + | 'UNSUPPORTED_SWITCH' + | 'NO_TARGET_ROOMS' + | 'DATABASE_UNAVAILABLE' + | 'UNKNOWN' + +/** 界面上要展示的两个开关(顺序即展示顺序) */ +export const MSG_INSERT_SWITCH_LABELS: Array<{ + name: MsgInsertSwitchName + label: string + hint: string +}> = [ + { + name: 'recall_notice', + label: '微信内防撤回提示', + hint: '别人撤回消息时,在微信会话里保留原消息并提示你撤回了什么' + }, + { + name: 'group_exit_notice', + label: '微信内退群监控消息', + hint: '检测到有人退群时,在微信会话里插入一条退出提示' + } +] diff --git a/tests/component/leave-notification-ui.test.tsx b/tests/component/leave-notification-ui.test.tsx index 8c9c59a..c1379e5 100644 --- a/tests/component/leave-notification-ui.test.tsx +++ b/tests/component/leave-notification-ui.test.tsx @@ -240,8 +240,13 @@ describe('退群通知 · 真实数据', () => { it('规则级启停只有一个开关,没有第二个「发送退群通知」', async () => { await openLeaveNotificationEditor() - expect(screen.getAllByRole('switch')).toHaveLength(1) - expect(screen.getByRole('switch', { name: '启用这条自动化' })).toBeVisible() + /* 作用域收敛到规则编辑器本体(.automation-editor)。页面右上角的 + * 「微信消息插入开关」是页面级控件,不属于这条规则的编辑器, + * 不该被本断言计入 —— 否则页面级功能一增加,这里就会假失败。 */ + const editor = document.querySelector('.automation-editor') as HTMLElement + expect(editor).not.toBeNull() + expect(within(editor).getAllByRole('switch')).toHaveLength(1) + expect(within(editor).getByRole('switch', { name: '启用这条自动化' })).toBeVisible() expect(screen.queryByText('发送退群通知')).toBeNull() }) })