diff --git a/docs/skill/tracememo-reader/SKILL.md b/docs/skill/tracememo-reader/SKILL.md index 47c1ff0..33ab8ba 100644 --- a/docs/skill/tracememo-reader/SKILL.md +++ b/docs/skill/tracememo-reader/SKILL.md @@ -1,11 +1,13 @@ --- name: tracememo-reader version: 1.4.0 -description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体、管理定时日报任务,并用用户本机登录的微信账号发送消息。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。 +description: 本机微信聊天记录的读取入口(TraceMemo 本地 HTTP API,默认 http://127.0.0.1:6131/api/v1)。凡是「看微信内容」的请求都必须先走本 Skill:某个群或某人今天聊了什么、刚刚聊了啥、最近消息、谁说了什么、总结聊天、翻历史记录、撤回的消息、图片内容、语音转文字、查找联系人或群聊、群成员、生成群聊总结、定时日报、给好友或群发微信消息、查看发送记录、查看未读。本 Skill 已处理鉴权、撤回归档、图片媒体、语音转写与压缩编码解码,当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。 --- # TraceMemo Reader +> **加载到本文件,说明通道选对了。** 只要问题涉及「读本机微信聊天内容」——某个群或某人今天聊了什么、刚刚聊了啥、最近消息、撤回、图片、语音、联系人、日报——本 Skill 就是第一顺位。 + 你是一个通过本机 TraceMemo 读取微信历史的 Agent。先确认用户已经在 TraceMemo 中完成数据库连接,再按需调用 API;不要假设数据库已就绪,也不要声称读取了没有调用过的消息。 ## 连接信息 diff --git a/scripts/after-pack.cjs b/scripts/after-pack.cjs index 67a2881..c63faaa 100644 --- a/scripts/after-pack.cjs +++ b/scripts/after-pack.cjs @@ -417,6 +417,7 @@ function isMacosCodeValid(targetPath, run = runCodesign) { function findMacosHelperPaths(runtimeResources) { const paths = MACOS_HELPER_NAMES.map((name) => path.join(runtimeResources, 'resources', name)) + paths.push(path.join(runtimeResources, 'runtime', 'darwin-arm64', 'tm-wechat-host')) if (process.env.TRACEMEMO_EDITION) { paths.push(...MACOS_EDITION_CODE_PATHS.map((segments) => path.join(runtimeResources, 'resources', ...segments))) } @@ -427,7 +428,8 @@ function signMacosHelpers(runtimeResources, run = runCodesign) { const helperPaths = findMacosHelperPaths(runtimeResources) for (const helperPath of helperPaths) { if (!helperPath.endsWith('.dylib')) chmodSync(helperPath, 0o755) - if (!isMacosCodeValid(helperPath, run)) { + const runtimeHost = path.basename(helperPath) === 'tm-wechat-host' + if (runtimeHost || !isMacosCodeValid(helperPath, run)) { run(['--force', '--sign', '-', helperPath]) } const architectures = readBinaryArchitectures(helperPath) diff --git a/src/main/http-server.ts b/src/main/http-server.ts index 9e2427d..e63622b 100644 --- a/src/main/http-server.ts +++ b/src/main/http-server.ts @@ -690,7 +690,21 @@ function parseWechatSendPayload(payload: unknown): ParsedWechatSend { message: `text 长度 ${text.length} 超过上限 ${WECHAT_SEND_MAX_TEXT_LENGTH} 字符` } } - content = { type: 'text', text } + let at: Record | undefined + if (body.at !== undefined) { + if (!body.at || typeof body.at !== 'object' || Array.isArray(body.at)) { + return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'at 必须是 wxid 到显示名称的对象' } + } + const entries = Object.entries(body.at as Record) + if (entries.length > 50 || entries.some(([wxid, name]) => !wxid.trim() || typeof name !== 'string')) { + return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'at 最多支持 50 个有效成员' } + } + if (recipient.type !== 'group') { + return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'at 只能用于群聊' } + } + at = Object.fromEntries(entries.map(([wxid, name]) => [wxid.trim(), String(name).trim()])) + } + content = { type: 'text', text, ...(at ? { at } : {}) } } else { const filePath = readSendString(body.filePath) if (!filePath) { diff --git a/src/main/index.ts b/src/main/index.ts index 034b839..efe1dfc 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1917,7 +1917,11 @@ app.whenReady().then(async () => { recipient, content: request.type === 'text' - ? { type: 'text', text: String(request.text || '') } + ? { + type: 'text', + text: String(request.text || ''), + ...(request.at ? { at: request.at } : {}) + } : { type: 'image', path: String(request.filePath || '') } }) // 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。 @@ -3517,8 +3521,12 @@ app.whenReady().then(async () => { undefined, (targets) => { if ( - macWechatRuntimeManager.getPort() === 4290 && - targets.some((target) => target.targets.includes('port_4290')) + targets.some( + (target) => + target.targets.includes('host') || + (macWechatRuntimeManager.getPort() === 4290 && + target.targets.includes('port_4290')) + ) ) { macWechatRuntimeManager.prepareForResidualCleanup() runtimeStopped = true diff --git a/src/main/services/automation-action-runner.ts b/src/main/services/automation-action-runner.ts index ad1ff2e..d570bc0 100644 --- a/src/main/services/automation-action-runner.ts +++ b/src/main/services/automation-action-runner.ts @@ -1,5 +1,6 @@ import { AUTOMATION_STEP_LABELS, + BUILTIN_DAILY_REPORT_RULE_ID, AUTOMATION_SEND_ORIGIN, AUTOMATION_SEND_PURPOSE, DEFAULT_REPLY_TEXT, @@ -99,6 +100,8 @@ export interface AutomationRunInput { isGroup: boolean /** 用户可读的来源名(群名 / 昵称)。**不是** id。 */ sourceDisplayName: string + /** 群消息触发者;仅内置日报确认回复会使用它构造 @。 */ + triggerSender?: { wxid: string; displayName: string } } export interface AutomationRunResult { @@ -302,9 +305,19 @@ export class AutomationActionRunner { const replyStep = stepAt('reply') replyStep.status = 'running' replyStep.startedAt = this.now() + const triggerWxid = input.triggerSender?.wxid.trim() + const triggerDisplayName = input.triggerSender?.displayName.trim() + const confirmationAt = + input.rule.id === BUILTIN_DAILY_REPORT_RULE_ID && + input.isGroup && + triggerWxid && + triggerDisplayName + ? { [triggerWxid]: triggerDisplayName } + : undefined const sent = await this.sendThroughGateway(input, 'reply', { type: 'text', - text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT + text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT, + ...(confirmationAt ? { at: confirmationAt } : {}) }) if (!sent.ok) { markFailed(replyStep, this.now(), sent.error || '回复确认失败') diff --git a/src/main/services/automation-service.ts b/src/main/services/automation-service.ts index 3128119..4c14ab7 100644 --- a/src/main/services/automation-service.ts +++ b/src/main/services/automation-service.ts @@ -719,7 +719,15 @@ export class AutomationService { rule, conversationId: message.sessionId, isGroup, - sourceDisplayName + sourceDisplayName, + ...(message.senderId && message.senderNickname + ? { + triggerSender: { + wxid: message.senderId, + displayName: message.senderNickname + } + } + : {}) }) } catch (error) { result = { diff --git a/src/main/services/mac-wechat-residual-cleanup.ts b/src/main/services/mac-wechat-residual-cleanup.ts index 1d1a1a6..bb87ce6 100644 --- a/src/main/services/mac-wechat-residual-cleanup.ts +++ b/src/main/services/mac-wechat-residual-cleanup.ts @@ -13,6 +13,7 @@ type PidCommandRunner = ( export interface MacWechatResidualCleanupDependencies { platform: NodeJS.Platform listWechatPids: () => Promise + listHostPids: () => Promise listPortPids: () => Promise processName: (pid: number) => Promise processIdentity: (pid: number) => Promise @@ -49,6 +50,7 @@ const defaultDependencies: MacWechatResidualCleanupDependencies = { return [...new Set(results.flat())] }, listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']), + listHostPids: () => readPids('/usr/bin/pgrep', ['-x', 'tm-wechat-host']), processName: async (pid) => { try { const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], { @@ -81,20 +83,27 @@ interface ObservedTarget extends MacWechatResidualProcess { function mergeTargets( wechatPids: number[], + hostPids: number[], portPids: number[], processNames: Map, processIdentities: Map ): ObservedTarget[] { - const targets = new Map>() + const targets = new Map>() for (const pid of wechatPids) { if (!Number.isSafeInteger(pid) || pid <= 0) continue - const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>() + const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>() reasons.add('wechat') targets.set(pid, reasons) } + for (const pid of hostPids) { + if (!Number.isSafeInteger(pid) || pid <= 0) continue + const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>() + reasons.add('host') + targets.set(pid, reasons) + } for (const pid of portPids) { if (!Number.isSafeInteger(pid) || pid <= 0) continue - const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>() + const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>() reasons.add('port_4290') targets.set(pid, reasons) } @@ -112,20 +121,25 @@ async function inspectObservedTargets( dependencies: MacWechatResidualCleanupDependencies ): Promise { if (dependencies.platform !== 'darwin') return [] - const [rawWechatPids, rawPortPids] = await Promise.all([ + const [rawWechatPids, rawHostPids, rawPortPids] = await Promise.all([ dependencies.listWechatPids(), + dependencies.listHostPids(), dependencies.listPortPids() ]) const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid) + const hostPids = rawHostPids.filter((pid) => pid !== process.pid) const portPids = rawPortPids.filter((pid) => pid !== process.pid) const pids = [...new Set([...wechatPids, ...portPids])].filter( (pid) => Number.isSafeInteger(pid) && pid > 0 ) + for (const pid of hostPids) { + if (Number.isSafeInteger(pid) && pid > 0 && !pids.includes(pid)) pids.push(pid) + } const [names, identities] = await Promise.all([ Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)), Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const)) ]) - return mergeTargets(wechatPids, portPids, new Map(names), new Map(identities)) + return mergeTargets(wechatPids, hostPids, portPids, new Map(names), new Map(identities)) } export async function inspectMacWechatResidualProcesses( @@ -170,15 +184,18 @@ export async function cleanupMacWechatResidualProcesses( ): Promise => { const identity = await dependencies.processIdentity(target.pid) if (!expectedIdentity || identity !== expectedIdentity) return + if ( + (target.targets.includes('host') || target.targets.includes('port_4290')) && + !cleanupTargetsNotified + ) { + cleanupTargetsNotified = true + onTargetsConfirmed?.([target]) + } try { dependencies.signal(target.pid, signal) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error } - if (target.targets.includes('port_4290') && !cleanupTargetsNotified) { - cleanupTargetsNotified = true - onTargetsConfirmed?.([target]) - } } for (const target of selected.filter((item) => item.targets.includes('wechat'))) { diff --git a/src/main/services/mac-wechat-runtime-artifact.ts b/src/main/services/mac-wechat-runtime-artifact.ts index 9e7f2be..9fd650e 100644 --- a/src/main/services/mac-wechat-runtime-artifact.ts +++ b/src/main/services/mac-wechat-runtime-artifact.ts @@ -11,8 +11,7 @@ function assertFile(path: string, label: string): void { } } -function assertMachOArm64(path: string, label: string): void { - const binary = readFileSync(path) +function assertMachOArm64(binary: Buffer, label: string): void { if (binary.length < 8 || binary.readUInt32LE(0) !== 0xfeedfacf) { throw new Error(`${label} is not a 64-bit Mach-O binary`) } @@ -71,17 +70,74 @@ export function readMacWechatRuntimeManifest( throw new Error(`runtime manifest capability missing: ${capability}`) } } - assertMachOArm64(hostPath, 'runtime host') - assertMachOArm64(dylibPath, 'runtime dylib') - if (!readFileSync(dylibPath).includes(Buffer.from(manifest.tmSendSourceSha256, 'utf8'))) { + assertMachOArm64(readFileSync(hostPath), 'runtime host') + const dylib = readFileSync(dylibPath) + assertMachOArm64(dylib, 'runtime dylib') + if (!dylib.includes(Buffer.from(manifest.tmSendSourceSha256, 'utf8'))) { throw new Error('runtime dylib embedded agent hash does not match manifest') } - if (!readFileSync(dylibPath).includes(Buffer.from(manifest.addressProfileSha256, 'utf8'))) { + if (!dylib.includes(Buffer.from(manifest.addressProfileSha256, 'utf8'))) { throw new Error('runtime dylib embedded address profile hash does not match manifest') } return manifest } +type RuntimeFileSignature = readonly [ + path: string, + device: string, + inode: string, + size: string, + modifiedNs: string, + changedNs: string +] + +function getRuntimeFileSignatures(runtimeDir: string): RuntimeFileSignature[] { + return ['runtime-manifest.json', 'tm-wechat-host', 'libtmwechat.dylib'].map((name) => { + const filePath = join(runtimeDir, name) + assertFile(filePath, name) + const stats = statSync(filePath, { bigint: true }) + if (!stats.isFile()) throw new Error(`runtime artifact is not a file: ${filePath}`) + return [ + filePath, + stats.dev.toString(), + stats.ino.toString(), + stats.size.toString(), + stats.mtimeNs.toString(), + stats.ctimeNs.toString() + ] + }) +} + +export class MacWechatRuntimeManifestCache { + private entry: { + runtimeDir: string + architecture: string + signatures: RuntimeFileSignature[] + manifest: MacWechatRuntimeManifest + } | null = null + + read(runtimeDir: string, architecture = process.arch): MacWechatRuntimeManifest { + const signatures = getRuntimeFileSignatures(runtimeDir) + if ( + this.entry?.runtimeDir === runtimeDir && + this.entry.architecture === architecture && + signatures.every((signature, index) => + signature.every((value, part) => value === this.entry?.signatures[index]?.[part]) + ) + ) { + return this.entry.manifest + } + + const manifest = readMacWechatRuntimeManifest(runtimeDir, architecture) + this.entry = { runtimeDir, architecture, signatures, manifest } + return manifest + } + + clear(): void { + this.entry = null + } +} + export function bindingMatchesRuntimeManifest( binding: { hostPid?: number diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index aad5bb1..94619b7 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -1,4 +1,4 @@ -import { spawn, type ChildProcess } from 'child_process' +import { execFileSync, spawn, type ChildProcess } from 'child_process' import { chmodSync, existsSync } from 'fs' import { get, request as httpRequest } from 'http' import { join } from 'path' @@ -27,7 +27,7 @@ import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat' import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action' import { bindingMatchesRuntimeManifest, - readMacWechatRuntimeManifest + MacWechatRuntimeManifestCache } from './mac-wechat-runtime-artifact' /* @@ -75,6 +75,16 @@ export function shouldClearWechatRestartRequired( return orphanWechatPid > 0 && currentWechatPid > 0 && orphanWechatPid !== currentWechatPid } +export function resolveMacWechatSendMechanism( + binding: MacWechatBindingStatus | null, + manifest: MacWechatRuntimeManifest | null +): string | undefined { + if (!binding || !manifest || !bindingMatchesRuntimeManifest(binding, manifest)) return undefined + return binding.wechatVersion + ? manifest.capabilitiesByVersion?.[binding.wechatVersion]?.textMechanism + : undefined +} + export function deriveMacWechatSenderStatus({ snapshot, binding, @@ -86,10 +96,12 @@ export function deriveMacWechatSenderStatus({ const versionCapabilities = binding?.wechatVersion ? manifest.capabilitiesByVersion?.[binding.wechatVersion] : undefined - const nativeMechanism = versionCapabilities?.textMechanism === 'native-msg-object' + const contextIndependentMechanism = + versionCapabilities?.textMechanism === 'native-msg-object' || + versionCapabilities?.textMechanism === 'tm-message-source-send' const nativeBindingReady = identityMatches && - nativeMechanism && + contextIndependentMechanism && binding?.runtimeState === 'ready' && binding.sessionAttached && binding.scriptLoaded @@ -99,6 +111,12 @@ export function deriveMacWechatSenderStatus({ if (snapshot.wechatRestartRequired) { state = 'error' message = '微信发送组件异常退出。由于当前微信进程中可能残留上一发送会话,请重启微信后重新绑定。' + } else if (snapshot.lifecycle === 'crashed_unbound') { + state = 'error' + message = snapshot.error || '微信发送运行时启动失败,请重新启动发送组件。' + } else if (snapshot.lifecycle === 'stopped' && snapshot.error) { + state = 'error' + message = snapshot.error } else if (binding && !identityMatches) { state = 'error' message = '运行中的微信发送 host 与当前 Native Runtime 不一致,请退出旧 host 后重启 TraceMemo。' @@ -115,7 +133,9 @@ export function deriveMacWechatSenderStatus({ message = '个人微信已准备好发送日报' } else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') { state = 'hook_not_ready' - message = nativeMechanism ? '已绑定,等待原生发送 hook 就绪' : '已绑定,等待捕获微信发送上下文' + message = contextIndependentMechanism + ? '已绑定,等待原生发送 hook 就绪' + : '已绑定,等待捕获微信发送上下文' } else if (stale) { state = 'stopped' message = '检测到微信已重启,请重新绑定' @@ -190,8 +210,9 @@ export function resolveLicenseRefreshFailure( return offlineMacLicenseStatus('server_unavailable', diagnostic) } -class MacWechatRuntimeManager { +export class MacWechatRuntimeManager { private child: ChildProcess | null = null + private startInFlight: Promise | null = null private lifecycle: MacWechatRuntimeLifecycle = 'stopped' private wechatRestartRequired = false /* The WeChat pid that was bound when the host died / bind hit the orphan @@ -200,6 +221,8 @@ class MacWechatRuntimeManager { private orphanWechatPid = 0 private lastBinding: MacWechatBindingStatus | null = null private manifest: MacWechatRuntimeManifest | null = null + private readonly manifestCache = new MacWechatRuntimeManifestCache() + private senderStatusInFlight: Promise | null = null private lastError: string | null = null private restartTimer: NodeJS.Timeout | null = null private manuallyStopped = false @@ -254,7 +277,7 @@ class MacWechatRuntimeManager { try { const runtimeDir = this.resolveRuntimeDir() if (!runtimeDir) return false - this.manifest = readMacWechatRuntimeManifest(runtimeDir) + this.manifest = this.manifestCache.read(runtimeDir) return true } catch { return false @@ -268,7 +291,7 @@ class MacWechatRuntimeManager { try { const runtimeDir = this.resolveRuntimeDir() if (!runtimeDir) throw new Error('发送 Runtime 目录缺失') - this.manifest = readMacWechatRuntimeManifest(runtimeDir) + this.manifest = this.manifestCache.read(runtimeDir) return { state: 'available', message: '微信发送组件可用' } } catch (error) { const detail = error instanceof Error ? error.message : String(error) @@ -281,8 +304,26 @@ class MacWechatRuntimeManager { * comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime * online" and "WeChat bound" stay two independent states. */ - async ensureStarted( + ensureStarted( options: { allowManualRestart?: boolean } = {} + ): Promise { + if (this.startInFlight) return this.startInFlight + + const startPromise = this.ensureStartedOnce(options) + this.startInFlight = startPromise + void startPromise.then( + () => { + if (this.startInFlight === startPromise) this.startInFlight = null + }, + () => { + if (this.startInFlight === startPromise) this.startInFlight = null + } + ) + return startPromise + } + + protected async ensureStartedOnce( + options: { allowManualRestart?: boolean } ): Promise { if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot() if (options.allowManualRestart) this.manuallyStopped = false @@ -303,7 +344,7 @@ class MacWechatRuntimeManager { return this.getSnapshot() } try { - this.manifest = readMacWechatRuntimeManifest(runtimeDir) + this.manifest = this.manifestCache.read(runtimeDir) appLogger.write({ level: 'info', scope: 'mac-wechat-runtime', @@ -393,6 +434,29 @@ class MacWechatRuntimeManager { } catch { /* best effort — dev checkouts usually keep the exec bit */ } + try { + if (!app.isPackaged) { + execFileSync('/usr/bin/codesign', [ + '--force', + '--sign', + '-', + '--timestamp=none', + hostPath + ]) + } + execFileSync('/usr/bin/codesign', ['--verify', '--strict', hostPath]) + } catch (error) { + this.lifecycle = 'stopped' + this.lastError = '无法验证发送 Host 签名:' + + (error instanceof Error ? error.message : String(error)) + appLogger.write({ + level: 'error', + scope: 'mac-wechat-runtime', + message: 'host_signature_invalid', + details: { detail: this.lastError } + }) + return this.getSnapshot() + } this.lifecycle = 'starting' this.lastError = null @@ -427,6 +491,7 @@ class MacWechatRuntimeManager { } this.child.on('exit', (code) => { + const exitedDuringStartup = this.lifecycle === 'starting' && this.startInFlight !== null const wasBound = this.lastBinding?.bound === true || this.lastBinding?.sessionAttached === true || @@ -448,18 +513,38 @@ class MacWechatRuntimeManager { }) } else { this.lifecycle = 'crashed_unbound' + if (exitedDuringStartup) { + this.lastError = + code === null + ? '发送运行时在启动过程中退出' + : `发送运行时启动失败(进程退出码 ${code})` + } appLogger.write({ level: 'warn', scope: 'mac-wechat-runtime', message: 'host_died_while_unbound_auto_restart', details: { code: code ?? null } }) - if (this.restartTimer) clearTimeout(this.restartTimer) - this.restartTimer = setTimeout(() => { - void this.ensureStarted() - }, CRASH_RESTART_DELAY_MS) + if (!exitedDuringStartup) { + if (this.restartTimer) clearTimeout(this.restartTimer) + this.restartTimer = setTimeout(() => { + void this.ensureStarted() + }, CRASH_RESTART_DELAY_MS) + } } }) + this.child.on('error', (error) => { + if (this.lifecycle === 'stopped') return + this.child = null + this.lifecycle = 'crashed_unbound' + this.lastError = '无法启动发送 Host:' + error.message + appLogger.write({ + level: 'error', + scope: 'mac-wechat-runtime', + message: 'host_spawn_failed', + details: { detail: error.message } + }) + }) // Wait for /healthz const deadline = Date.now() + START_TIMEOUT_MS @@ -614,6 +699,10 @@ class MacWechatRuntimeManager { return this.lastBinding } + async getSendMechanism(): Promise { + return resolveMacWechatSendMechanism(await this.getBindingStatus(), this.manifest) + } + // GET reads the local snapshot; POST runs one real online check. // Neither touches the WeChat binding. @@ -723,7 +812,22 @@ class MacWechatRuntimeManager { * capability mapping and the send path report the same facts without a * circular import. */ - async buildSenderStatus(): Promise { + buildSenderStatus(): Promise { + if (this.senderStatusInFlight) return this.senderStatusInFlight + const statusPromise = this.buildSenderStatusOnce() + this.senderStatusInFlight = statusPromise + void statusPromise.then( + () => { + if (this.senderStatusInFlight === statusPromise) this.senderStatusInFlight = null + }, + () => { + if (this.senderStatusInFlight === statusPromise) this.senderStatusInFlight = null + } + ) + return statusPromise + } + + private async buildSenderStatusOnce(): Promise { if (isMacNativeRuntimeUnavailable()) { const message = '当前环境不包含微信发送能力' return { @@ -769,7 +873,7 @@ class MacWechatRuntimeManager { try { const runtimeDir = this.resolveRuntimeDir() if (!runtimeDir) throw new Error('runtime missing') - this.manifest = readMacWechatRuntimeManifest(runtimeDir) + this.manifest = this.manifestCache.read(runtimeDir) } catch (error) { const detail = error instanceof Error ? error.message : String(error) appLogger.write({ diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index 7fc7e1a..33e32fc 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -23,7 +23,7 @@ import type { import { loadSettings } from './settings-store' import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder' import { appLogger } from '../app-logger' -import { readLocalAccountIdentity } from './local-account-identity' +import { accountDirectoryBelongsToIdentity, readLocalAccountIdentity } from './local-account-identity' import { macWechatRuntimeManager } from './mac-wechat-runtime-manager' const execFileAsync = promisify(execFile) @@ -276,14 +276,18 @@ export function prepareWindowsImageFile(filePath: string): { return { filePath: temporaryPath, temporary: true } } -function prepareMacWechatImageFile(filePath: string): { filePath: string; md5: string } { +function prepareMacWechatImageFile( + filePath: string, + senderWxid: string, + wechatFilesRoot = WECHAT_FILES_ROOT +): { filePath: string; md5: string } { /* Stage the image in WeChat's temporary image directory using the * filename/hash layout required by the macOS native send path: * - stage inside the active account's ImageTemp tree selected by * findWechatImagePath(), not an arbitrary readable sandbox directory; * - append a per-send salt before calculating MD5, so the staged image and * the MD5 passed to the CDN task describe the same unique byte stream. */ - const temporaryRoot = findWechatImagePath() + const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid) if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录') mkdirSync(temporaryRoot, { recursive: true }) const extension = extname(filePath).toLowerCase() @@ -305,16 +309,36 @@ function prepareMacWechatImageFile(filePath: string): { filePath: string; md5: s } } +function stageMacWechatImageForMessageSourceSend( + filePath: string, + senderWxid: string, + wechatFilesRoot = WECHAT_FILES_ROOT +): string { + const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid) + if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录') + mkdirSync(temporaryRoot, { recursive: true }) + const extension = extname(filePath).toLowerCase() + const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png' + const stagedPath = join( + temporaryRoot, + `tm-${randomBytes(8).toString('hex')}-${Math.floor(Date.now() / 1000)}${safeExtension}` + ) + copyFileSync(filePath, stagedPath) + return stagedPath +} + /** Locate the current account's temporary image directory consumed by the image send path. */ export function findWechatImagePath( root = WECHAT_FILES_ROOT, - now = new Date() + now = new Date(), + senderWxid?: string ): string | undefined { try { const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}` const candidates: Array<{ path: string; mtime: number }> = [] const fallbacks: Array<{ path: string; mtime: number }> = [] for (const account of readdirSync(root)) { + if (senderWxid && !accountDirectoryBelongsToIdentity(account, senderWxid)) continue const tempRoot = join(root, account, 'temp') if (!existsSync(tempRoot)) continue fallbacks.push({ @@ -469,6 +493,10 @@ function safeFileSize(target: string): number { } } +function isDefinitiveImageSourcePreparationFailure(message: string): boolean { + return message.trim() === 'IMAGE_PREPARATION_FAILED:0' +} + /** * 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。 * @@ -547,6 +575,8 @@ async function requestWindowsHook( } export class PersonalWechatSendService { + constructor(private readonly wechatFilesRoot = WECHAT_FILES_ROOT) {} + async getStatus(): Promise { // macOS 发送能力完全由 native runtime(tm-wechat-host)提供, // 这里保持同源,避免出现第二套状态判断。 @@ -663,6 +693,32 @@ export class PersonalWechatSendService { error: initialStatus.message || '微信发送能力未就绪' } } + const sendMechanism = await macWechatRuntimeManager.getSendMechanism() + if (request.at && sendMechanism !== 'tm-message-source-send') { + return { + success: false, + status: initialStatus, + error: '当前微信发送组件不支持原生群聊 @,请升级微信与发送组件' + } + } + if (sendMechanism === 'tm-message-source-send') { + const result = await this.postMacHost( + '/sendMsg', + { + type: 'text', + to: request.to, + text: request.text, + is_group: Boolean(request.isGroup), + ...(request.at ? { at: request.at } : {}) + }, + 50_000 + ) + const status = await macWechatRuntimeManager.buildSenderStatus() + if (!result?.ok) { + return { success: false, status, error: result?.message || '文字发送失败' } + } + return { success: true, status } + } const payload = JSON.stringify({ to: request.to, @@ -700,7 +756,7 @@ export class PersonalWechatSendService { * the on-disk account identity instead. */ private async resolveMacSenderWxid(): Promise { - const identity = readLocalAccountIdentity(WECHAT_FILES_ROOT) + const identity = readLocalAccountIdentity(this.wechatFilesRoot) return identity?.wxid ?? '' } @@ -737,13 +793,42 @@ export class PersonalWechatSendService { } const filePath = String(request.filePath || '').trim() if (!filePath || !existsSync(filePath)) return fail('请选择有效的图片文件') - + const sendMechanism = await macWechatRuntimeManager.getSendMechanism() const sender = await this.resolveMacSenderWxid() if (!sender) return fail('无法识别当前微信账号 wxid') + if (sendMechanism === 'tm-message-source-send') { + let stagedPath = '' + let sourceError = '' + try { + stagedPath = stageMacWechatImageForMessageSourceSend(filePath, sender, this.wechatFilesRoot) + const sent = await this.postMacHost( + '/sendMsg', + { type: 'image', to: request.to, path: stagedPath }, + 55_000 + ) + const status = await macWechatRuntimeManager.buildSenderStatus() + if (!sent?.ok) { + sourceError = sent?.message || '图片发送失败' + } else { + return { success: true, status } + } + } catch (error) { + sourceError = error instanceof Error ? error.message : String(error) + } finally { + if (stagedPath) { + try { + unlinkSync(stagedPath) + } catch { + // Best-effort cleanup after WeChat has consumed the staged image. + } + } + } + if (!isDefinitiveImageSourcePreparationFailure(sourceError)) return fail(sourceError) + } let uploadPath = '' try { - const prepared = prepareMacWechatImageFile(filePath) + const prepared = prepareMacWechatImageFile(filePath, sender, this.wechatFilesRoot) uploadPath = prepared.filePath const upload = await this.postMacHost( '/uploadImage', @@ -791,9 +876,12 @@ export class PersonalWechatSendService { } const filePath = String(request.filePath || '').trim() if (!filePath || !existsSync(filePath)) return fail('请选择有效的语音文件') - - const sender = await this.resolveMacSenderWxid() - if (!sender) return fail('无法识别当前微信账号 wxid') + const sendMechanism = await macWechatRuntimeManager.getSendMechanism() + let sender = '' + if (sendMechanism !== 'tm-message-source-send') { + sender = await this.resolveMacSenderWxid() + if (!sender) return fail('无法识别当前微信账号 wxid') + } /* Reuse the Windows SILK preparation: it already normalizes any input to * SILK and reports the duration. */ @@ -816,6 +904,25 @@ export class PersonalWechatSendService { normalized_input_bytes: silkData.length, silk_duration_ms: durationMs }) + if (sendMechanism === 'tm-message-source-send') { + if (durationMs < 1000) return fail('原生语音发送要求时长至少 1 秒', 'duration') + const sent = await this.postMacHost( + '/sendMsg', + { + type: 'voice', + to: request.to, + voice_hex: silkData.toString('hex'), + duration_ms: durationMs + }, + 55_000 + ) + if (!sent?.ok) { + return fail(sent?.message || '语音发送失败', 'send') + } + const status = await macWechatRuntimeManager.buildSenderStatus() + logVoiceAttempt(requestId, 'completed', { send_result: '0' }) + return { success: true, status } + } const upload = await this.postMacHost( '/uploadVoice', diff --git a/src/main/services/wechat-action-gateway.ts b/src/main/services/wechat-action-gateway.ts index 8232c4d..57aa724 100644 --- a/src/main/services/wechat-action-gateway.ts +++ b/src/main/services/wechat-action-gateway.ts @@ -493,6 +493,20 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu if (contentType === 'text') { const text = String((content as { text?: unknown }).text || '').trim() if (!text || text.length > 2_000) return null + const rawAt = (content as { at?: unknown }).at + let at: Record | undefined + if (rawAt !== undefined) { + if (!rawAt || typeof rawAt !== 'object' || Array.isArray(rawAt)) return null + if (recipientType !== 'group' && !recipientId.endsWith('@chatroom')) return null + const entries = Object.entries(rawAt as Record) + if (entries.length > 50) return null + at = {} + for (const [rawWxid, rawName] of entries) { + const wxid = rawWxid.trim() + if (!wxid || typeof rawName !== 'string') return null + at[wxid] = rawName.trim() + } + } return { ...input, origin, @@ -509,7 +523,7 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu ? { name: String((recipient as { name?: unknown }).name).trim() } : {}) }, - content: { type: 'text', text } + content: { type: 'text', text, ...(at ? { at } : {}) } } as WechatActionRequest } if (contentType !== 'image' && contentType !== 'voice') return null @@ -560,7 +574,14 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech to: request.recipient.id, isGroup: request.recipient.type === 'group' } - if (request.content.type === 'text') return { ...base, type: 'text', text: request.content.text } + if (request.content.type === 'text') { + return { + ...base, + type: 'text', + text: request.content.text, + ...(request.content.at ? { at: request.content.at } : {}) + } + } if (request.content.type === 'image') { return { ...base, type: 'image', filePath: request.content.path } } diff --git a/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx b/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx index db4d70b..e3ec2b4 100644 --- a/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx +++ b/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx @@ -63,6 +63,7 @@ export function PersonalWechatSetupGuide({ canBind = true }: PersonalWechatSetupGuideProps): React.ReactElement { const runtimeUnavailable = senderStatus?.state === 'runtime_missing' + const runtimeError = senderStatus?.state === 'error' && !senderStatus.endpointReady const runtimeLabel = '发送运行时' const runtimeReady = senderStatus?.runtimeReady === true const connected = sessionBound && (senderStatus ? isWechatBound(senderStatus) : false) @@ -82,7 +83,11 @@ export function PersonalWechatSetupGuide({
    -
  1. +
  2. {runtimeReady ? '✓' : '1'}
    准备 {runtimeLabel} @@ -95,6 +100,10 @@ export function PersonalWechatSetupGuide({ ✓ {runtimeLabel}已就绪 ) : runtimeUnavailable ? ( 当前版本暂未提供微信消息发送功能 + ) : runtimeError ? ( + + {senderStatus.message || '发送运行时启动失败,请重新启动发送组件。'} + ) : ( 正在检查 {runtimeLabel}… )} @@ -183,7 +192,7 @@ export function PersonalWechatSetupGuide({ : '正在等待发送运行时完成初始化…'}

    )} - {senderStatus?.state === 'error' && ( + {senderStatus?.state === 'error' && !runtimeError && (

    {senderStatus.message || '发送能力初始化失败,请重新绑定。'}

    diff --git a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx index a479e45..ec4afec 100644 --- a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx +++ b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx @@ -317,7 +317,6 @@ export function PersonalWechatSendPage({ >([]) const [macResidualDialogOpen, setMacResidualDialogOpen] = useState(false) const [macResidualBusy, setMacResidualBusy] = useState(false) - const [macResidualRuntimeStopped, setMacResidualRuntimeStopped] = useState(false) const [macWechatRebindRequired, setMacWechatRebindRequired] = useState(false) const [mac4290PortStatus, setMac4290PortStatus] = useState< | { state: 'loading' | 'available' | 'error'; processes: [] } @@ -346,12 +345,9 @@ export function PersonalWechatSendPage({ } setError('') try { - const [nextCapability, nextSender] = await Promise.all([ - window.api.getPersonalWechatSendCapability(), - window.api.getPersonalWechatSenderStatus() - ]) + const nextCapability = await window.api.getPersonalWechatSendCapability() setCapability(nextCapability) - setSenderStatus(nextSender) + setSenderStatus(nextCapability.senderStatus) } catch (reason) { setError(reason instanceof Error ? reason.message : '微信发送能力读取失败') } finally { @@ -394,14 +390,13 @@ export function PersonalWechatSendPage({ setLoading(false) return } - const [nextCapability, nextSender, license] = await Promise.all([ + const [nextCapability, license] = await Promise.all([ window.api.getPersonalWechatSendCapability(), - window.api.getPersonalWechatSenderStatus(), window.api.getMacLicenseStatus() ]) if (!active) return setCapability(nextCapability) - setSenderStatus(nextSender) + setSenderStatus(nextCapability.senderStatus) setMacLicenseStatus(license) } catch (reason) { if (!active) return @@ -509,7 +504,8 @@ export function PersonalWechatSendPage({ : { state: 'available', processes: [] } ) if (targets.length === 0) { - onNotice('没有发现微信进程或占用 4290 端口的进程') + setMacResidualBusy(false) + await restartMacSendRuntime() return } setMacResidualDialogOpen(true) @@ -527,7 +523,6 @@ export function PersonalWechatSendPage({ const result = await window.api.cleanupMacWechatResidualProcesses( macResidualProcesses.map(({ pid, confirmationToken }) => ({ pid, confirmationToken })) ) - if (result.runtimeStopped) setMacResidualRuntimeStopped(true) if (result.stopped.some((target) => target.targets.includes('wechat'))) { setMacWechatRebindRequired(true) } @@ -540,8 +535,7 @@ export function PersonalWechatSendPage({ setMacResidualDialogOpen(false) setMacResidualProcesses([]) await refreshMac4290PortStatus() - await refresh() - onNotice('目标进程已退出,发送环境状态已刷新。') + await restartMacSendRuntime() return } if (result.remaining.length > 0) { @@ -558,9 +552,10 @@ export function PersonalWechatSendPage({ setMacResidualProcesses([]) } await refreshMac4290PortStatus() - await refresh() if (result.remaining.length === 0) { - onNotice('已结束 ' + result.stopped.length + ' 个残留进程;发送环境状态已刷新。') + await restartMacSendRuntime() + } else { + await refresh() } } catch (reason) { onNotice(reason instanceof Error ? reason.message : '清理残留进程失败') @@ -570,16 +565,15 @@ export function PersonalWechatSendPage({ } const restartMacSendRuntime = async (): Promise => { - if (macResidualBusy) return setMacResidualBusy(true) try { const snapshot = await window.api.startMacSendRuntime() if (snapshot.lifecycle !== 'online') { throw new Error(snapshot.error || '发送组件启动失败') } - setMacResidualRuntimeStopped(false) await refresh() - onNotice('发送组件已启动;如刚才关闭了微信,请重新打开微信并绑定。') + await refreshMac4290PortStatus() + onNotice('已清理并重启发送 Host;如刚才关闭了微信,请重新打开微信并绑定。') } catch (reason) { onNotice(reason instanceof Error ? reason.message : '发送组件启动失败') } finally { @@ -1019,16 +1013,6 @@ export function PersonalWechatSendPage({ > {macResidualBusy ? '检查中…' : '清理残留以及微信进程'} - {macResidualRuntimeStopped ? ( - - ) : null}
    {macUnavailable ? ( @@ -1049,8 +1033,8 @@ export function PersonalWechatSendPage({ 清理微信残留进程? - 将结束下面列出的微信进程或占用 4290 - 端口的进程。若列表包含微信,微信会关闭;如曾绑定发送组件,之后需要重新打开微信并绑定。 + 将结束下面列出的微信进程,以及所有 TraceMemo 发送 Host(包括未占用 4290 的 Host)。 + 完成清理后会自动重启发送 Host;若列表包含微信,微信会关闭,之后需要重新打开微信并绑定。
      @@ -1060,7 +1044,9 @@ export function PersonalWechatSendPage({ PID {item.pid} ·{' '} {item.targets - .map((target) => (target === 'wechat' ? '微信进程' : '4290 端口')) + .map((target) => + target === 'wechat' ? '微信进程' : target === 'host' ? '发送 Host' : '4290 端口' + ) .join('、')} diff --git a/src/renderer/src/styles/chat.scss b/src/renderer/src/styles/chat.scss index 0b17702..368e391 100644 --- a/src/renderer/src/styles/chat.scss +++ b/src/renderer/src/styles/chat.scss @@ -801,6 +801,12 @@ color: var(--wxex-success); } +.personal-wechat-steps>li.is-error .personal-wechat-step-number { + border-color: color-mix(in srgb, var(--wxex-danger) 45%, transparent); + background: color-mix(in srgb, var(--wxex-danger) 10%, var(--wxex-bg-elevated)); + color: var(--wxex-danger); +} + .personal-wechat-step-content { display: grid; gap: 7px; diff --git a/src/shared/personal-wechat-mac-runtime.ts b/src/shared/personal-wechat-mac-runtime.ts index 9635a62..d9f849c 100644 --- a/src/shared/personal-wechat-mac-runtime.ts +++ b/src/shared/personal-wechat-mac-runtime.ts @@ -25,7 +25,7 @@ export interface MacWechatSendRuntimeAvailabilityResult { export interface MacWechatResidualProcess { pid: number name: string - targets: Array<'wechat' | 'port_4290'> + targets: Array<'wechat' | 'host' | 'port_4290'> confirmationToken: string } diff --git a/src/shared/personal-wechat.ts b/src/shared/personal-wechat.ts index 18c4792..e8681a7 100644 --- a/src/shared/personal-wechat.ts +++ b/src/shared/personal-wechat.ts @@ -74,6 +74,7 @@ interface PersonalWechatSendBaseRequest { export interface PersonalWechatSendTextRequest extends PersonalWechatSendBaseRequest { type: 'text' text: string + at?: Record } export interface PersonalWechatSendImageRequest extends PersonalWechatSendBaseRequest { diff --git a/src/shared/wechat-action.ts b/src/shared/wechat-action.ts index 709a0cc..beb7182 100644 --- a/src/shared/wechat-action.ts +++ b/src/shared/wechat-action.ts @@ -72,7 +72,7 @@ export interface WechatActionRecipient { } export type WechatActionContent = - | { type: 'text'; text: string } + | { type: 'text'; text: string; at?: Record } | { type: 'image'; path: string } | { type: 'voice'; path: string } diff --git a/tests/component/personal-wechat-send-page.test.tsx b/tests/component/personal-wechat-send-page.test.tsx index 4683d4c..281c7f9 100644 --- a/tests/component/personal-wechat-send-page.test.tsx +++ b/tests/component/personal-wechat-send-page.test.tsx @@ -154,7 +154,7 @@ describe('PersonalWechatSendPage on macOS', () => { expect(cleanupResidualProcesses).not.toHaveBeenCalled() }) - it('cleans only the process the user confirmed and refreshes the runtime state', async () => { + it('cleans the confirmed runtime host and automatically restarts it', async () => { const onNotice = vi.fn() render() @@ -167,10 +167,22 @@ describe('PersonalWechatSendPage on macOS', () => { { pid: 202, confirmationToken: 'process-identity-202' } ]) }) - expect(onNotice).toHaveBeenCalledWith('已结束 1 个残留进程;发送环境状态已刷新。') - expect(await screen.findByRole('button', { name: '重新启动发送组件' })).toBeVisible() - fireEvent.click(screen.getByRole('button', { name: '重新启动发送组件' })) await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) + expect(onNotice).toHaveBeenCalledWith( + '已清理并重启发送 Host;如刚才关闭了微信,请重新打开微信并绑定。' + ) + }) + + it('uses the same cleanup button to start the runtime when no residual process exists', async () => { + listResidualProcesses.mockResolvedValue([]) + const onNotice = vi.fn() + render() + + await screen.findByText('运行环境已就绪') + fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) + + await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) + expect(screen.queryByRole('heading', { name: '清理微信残留进程?' })).not.toBeInTheDocument() }) it('shows that WeChat must be reopened and rebound after its process is cleaned', async () => { @@ -216,6 +228,11 @@ describe('PersonalWechatSendPage on macOS', () => { canSendVoice: false } getSenderStatus.mockReset().mockResolvedValueOnce(senderStatus).mockResolvedValue(stoppedStatus) + getCapability + .mockReset() + .mockResolvedValueOnce(capability) + .mockResolvedValue({ ...capability, senderStatus: stoppedStatus }) + rebindSender.mockReset().mockResolvedValueOnce(stoppedStatus).mockResolvedValueOnce(senderStatus) getMacLicenseStatus.mockResolvedValue({ deviceId: 'mac_test', state: 'valid', diff --git a/tests/component/personal-wechat-unavailable.test.tsx b/tests/component/personal-wechat-unavailable.test.tsx index 767719f..4eb8dfa 100644 --- a/tests/component/personal-wechat-unavailable.test.tsx +++ b/tests/component/personal-wechat-unavailable.test.tsx @@ -97,6 +97,30 @@ describe('personal WeChat unavailable product state', () => { expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument() }) + it('shows a runtime startup failure instead of an endless checking message', () => { + const failedRuntimeStatus: PersonalWechatSenderStatus = { + ...unavailableStatus, + state: 'error', + endpointReady: false, + runtimeReady: false, + message: '发送运行时启动失败(进程退出码 1)', + error: '发送运行时启动失败(进程退出码 1)' + } + + render( + + ) + + expect(screen.getByRole('alert')).toHaveTextContent('发送运行时启动失败(进程退出码 1)') + expect(screen.queryByText('正在检查 发送运行时…')).not.toBeInTheDocument() + }) + it('describes a ready runtime separately from pending send capability initialization', () => { const boundStatus: PersonalWechatSenderStatus = { ...unavailableStatus, diff --git a/tests/integration/automation-chain.test.ts b/tests/integration/automation-chain.test.ts index e45c80d..5027408 100644 --- a/tests/integration/automation-chain.test.ts +++ b/tests/integration/automation-chain.test.ts @@ -33,6 +33,8 @@ import type { import type { Wcdb4Client } from '../../src/main/wcdb4-client' import type { NormalizedIncomingMessage } from '../../src/main/services/message-listener-service' import { WechatActionGateway } from '../../src/main/services/wechat-action-gateway' +import { WechatSendGateway } from '../../src/main/services/wechat-send-gateway' +import { WechatSendLogService } from '../../src/main/services/wechat-send-log-service' import { AutomationRuleStore } from '../../src/main/services/automation-rule-store' import { AutomationExecutionLogService } from '../../src/main/services/automation-execution-log-service' import { AutomationActionRunner } from '../../src/main/services/automation-action-runner' @@ -120,14 +122,18 @@ function buildChain(): Chain { const sends: PersonalWechatSendRequest[] = [] const reports: string[] = [] + const sendGateway = new WechatSendGateway({ + log: new WechatSendLogService({ getUserDataPath: () => root }), + sendPersonal: async (request) => { + sends.push(request) + return { success: true, status: readyCapability().senderStatus } + } + }) const gateway = new WechatActionGateway({ getUserDataPath: () => root, getCapability: async () => readyCapability(), - // 传输层是唯一被替换的部分:其余(策略、幂等、审计、节流)都是真的。 - send: async (request) => { - sends.push(request) - return { success: true, status: readyCapability().senderStatus } - }, + // 从 Action Gateway 穿过真实 Send Gateway,只替换最终个人微信发送适配器。 + send: (request) => sendGateway.sendPersonal(request), // 节流本身要保留,但不想让测试真的等 3 秒。 wait: async () => undefined }) @@ -179,7 +185,8 @@ describe('automation end-to-end chain', () => { type: 'text', to: GROUP_ID, isGroup: true, - text: '收到,正在生成今日日报' + text: '收到,正在生成今日日报', + at: { wxid_sender: '张三' } }) expect(chain.sends[1]).toMatchObject({ type: 'image', diff --git a/tests/integration/wechat-send-api.test.ts b/tests/integration/wechat-send-api.test.ts index 4736aa6..b0913c5 100644 --- a/tests/integration/wechat-send-api.test.ts +++ b/tests/integration/wechat-send-api.test.ts @@ -202,6 +202,40 @@ describe('POST /api/v1/wechat/send', () => { expect(action.content).toEqual({ type: 'text', text: '你好' }) }) + it('验证并透传群聊原生 @ 成员映射', async () => { + const response = await post({ + to: 'fixture-room@chatroom', + isGroup: true, + type: 'text', + text: '早上好', + at: { wxid_fixture_member: '测试成员' } + }) + expect(response.status).toBe(200) + expect(lastAction().content).toEqual({ + type: 'text', + text: '早上好', + at: { wxid_fixture_member: '测试成员' } + }) + const invalid = await post({ + to: 'fixture-room@chatroom', + type: 'text', + text: '早上好', + at: ['wxid_fixture_member'] + }) + expect(invalid.status).toBe(400) + }) + + it('拒绝格式错误的群聊 @ 成员映射', async () => { + const response = await post({ + to: 'fixture-room@chatroom', + type: 'text', + text: '早上好', + at: ['wxid_fixture_member'] + }) + expect(response.status).toBe(400) + expect(execute).not.toHaveBeenCalled() + }) + it('type 省略时按文本发送', async () => { await post({ to: 'wxid_friend', text: 'hi' }) expect(lastAction().content).toEqual({ type: 'text', text: 'hi' }) diff --git a/tests/unit/automation-action-runner.test.ts b/tests/unit/automation-action-runner.test.ts index 3584d23..c0e470e 100644 --- a/tests/unit/automation-action-runner.test.ts +++ b/tests/unit/automation-action-runner.test.ts @@ -127,14 +127,16 @@ function buildRunner(options: { const run = ( runner: AutomationActionRunner, - rule: AutomationRule + rule: AutomationRule, + triggerSender?: { wxid: string; displayName: string } ): Promise>> => runner.run({ executionId: EXECUTION_ID, rule, conversationId: GROUP_ID, isGroup: true, - sourceDisplayName: '测试群' + sourceDisplayName: '测试群', + ...(triggerSender ? { triggerSender } : {}) }) const statusOf = ( @@ -145,7 +147,10 @@ const statusOf = ( describe('AutomationActionRunner', () => { it('按 收到消息 → 规则匹配 → 回复确认 → 生成日报 → 发送图片 的顺序执行', async () => { const { runner, calls, reports } = buildRunner({}) - const result = await run(runner, makeRule()) + const result = await run(runner, makeRule(), { + wxid: 'wxid_fixture_sender', + displayName: '测试成员' + }) expect(result.status).toBe('success') expect(result.pngPath).toBe('/tmp/report.png') @@ -167,13 +172,21 @@ describe('AutomationActionRunner', () => { // 先回文字,再发图片 —— 顺序反了用户会先收到图再收到"正在生成"。 expect(calls).toHaveLength(2) expect(calls[0].content.type).toBe('text') + expect(calls[0].content).toMatchObject({ + type: 'text', + at: { wxid_fixture_sender: '测试成员' } + }) expect(calls[1].content.type).toBe('image') + expect(calls[1].content).not.toHaveProperty('at') expect(reports).toEqual([{ group: GROUP_ID, range: 'today' }]) }) it('每一步都带独立的起止时间与耗时', async () => { const { runner } = buildRunner({}) - const result = await run(runner, makeRule()) + const result = await run(runner, makeRule(), { + wxid: 'wxid_fixture_sender', + displayName: '测试成员' + }) for (const step of result.steps) { expect(step.startedAt).toBeTypeOf('number') expect(step.finishedAt).toBeTypeOf('number') @@ -365,8 +378,36 @@ describe('AutomationActionRunner', () => { action.type === 'replyText' ? { ...action, text: ' ' } : action ) }) - await run(runner, rule) - expect(calls[0].content).toEqual({ type: 'text', text: '收到,正在生成今日日报' }) + await run(runner, rule, { wxid: 'wxid_fixture_sender', displayName: '测试成员' }) + expect(calls[0].content).toMatchObject({ + type: 'text', + text: '收到,正在生成今日日报', + at: { wxid_fixture_sender: '测试成员' } + }) + }) + + it('没有可用的触发者昵称时,确认回复不猜测 @ 对象', async () => { + const { runner, calls } = buildRunner({}) + await run(runner, makeRule()) + + expect(calls[0].content).toEqual({ + type: 'text', + text: '收到,正在生成今日日报' + }) + }) + + it('自定义规则确认回复不附加 @', async () => { + const { runner, calls } = buildRunner({}) + const rule = makeRule((item) => { + item.id = 'fixture-custom-rule' + }) + + await run(runner, rule, { wxid: 'wxid_fixture_sender', displayName: '测试成员' }) + + expect(calls[0].content).toEqual({ + type: 'text', + text: '收到,正在生成今日日报' + }) }) it('私聊场景下收件人类型是联系人', async () => { @@ -390,6 +431,7 @@ describe('AutomationActionRunner', () => { type: 'contact', id: 'wxid_friend' }) + expect(executeAction.mock.calls[0][0].content).not.toHaveProperty('at') }) /** diff --git a/tests/unit/mac-wechat-residual-cleanup.test.ts b/tests/unit/mac-wechat-residual-cleanup.test.ts index 5afd620..0b4a726 100644 --- a/tests/unit/mac-wechat-residual-cleanup.test.ts +++ b/tests/unit/mac-wechat-residual-cleanup.test.ts @@ -12,6 +12,7 @@ function createDependencies( return { platform: 'darwin', listWechatPids: vi.fn(async () => [101]), + listHostPids: vi.fn(async () => []), listPortPids: vi.fn(async () => [202]), processName: vi.fn(async (pid) => (pid === 101 ? 'WeChat' : 'tm-wechat-host')), processIdentity: vi.fn(async (pid) => 'identity-' + pid), @@ -45,6 +46,24 @@ describe('macOS WeChat residual cleanup', () => { expect(dependencies.processName).toHaveBeenCalledTimes(2) }) + it('lists every TraceMemo Host, including hosts that do not own port 4290', async () => { + const dependencies = createDependencies({ + listWechatPids: vi.fn(async () => []), + listHostPids: vi.fn(async () => [303]), + listPortPids: vi.fn(async () => []), + processName: vi.fn(async () => 'tm-wechat-host') + }) + + await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([ + { + pid: 303, + name: 'tm-wechat-host', + targets: ['host'], + confirmationToken: 'identity-303' + } + ]) + }) + it('does not signal a PID whose process identity changed after confirmation', async () => { const dependencies = createDependencies({ listWechatPids: vi.fn(async () => []), diff --git a/tests/unit/mac-wechat-runtime-artifact-cache.test.ts b/tests/unit/mac-wechat-runtime-artifact-cache.test.ts new file mode 100644 index 0000000..dd34515 --- /dev/null +++ b/tests/unit/mac-wechat-runtime-artifact-cache.test.ts @@ -0,0 +1,74 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, describe, expect, it } from 'vitest' + +import { MacWechatRuntimeManifestCache } from '../../src/main/services/mac-wechat-runtime-artifact' + +const directories: string[] = [] +const AGENT_HASH = 'a'.repeat(64) +const PROFILE_HASH = 'b'.repeat(64) +const FIXTURE_WECHAT_VERSION = 'fixture-wechat-version' + +function createRuntimeDirectory(version: string): string { + const runtimeDir = mkdtempSync(join(tmpdir(), 'tracememo-runtime-cache-')) + directories.push(runtimeDir) + const manifest = { + runtime: 'tm-wechat-native', + version, + platform: 'darwin-arm64', + architecture: 'arm64', + protocolVersion: 1, + tmSendSourceSha256: AGENT_HASH, + addressProfileSha256: PROFILE_HASH, + supportedWechatVersions: [FIXTURE_WECHAT_VERSION], + capabilities: ['text', 'image', 'voice'] + } + writeFileSync(join(runtimeDir, 'runtime-manifest.json'), JSON.stringify(manifest)) + writeFileSync(join(runtimeDir, 'tm-wechat-host'), Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01])) + writeFileSync(join(runtimeDir, 'libtmwechat.dylib'), Buffer.concat([ + Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01]), + Buffer.from(AGENT_HASH + PROFILE_HASH) + ])) + return runtimeDir +} + +afterEach(() => { + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true }) +}) + +describe('MacWechatRuntimeManifestCache', () => { + it('reuses the validated manifest while all runtime artifacts remain unchanged', () => { + const runtimeDir = createRuntimeDirectory('0.3.0') + const cache = new MacWechatRuntimeManifestCache() + const first = cache.read(runtimeDir, 'arm64') + const second = cache.read(runtimeDir, 'arm64') + expect(second).toBe(first) + }) + + it('revalidates when a runtime artifact changes', () => { + const runtimeDir = createRuntimeDirectory('0.3.0') + const cache = new MacWechatRuntimeManifestCache() + cache.read(runtimeDir, 'arm64') + writeFileSync(join(runtimeDir, 'runtime-manifest.json'), JSON.stringify({ + runtime: 'tm-wechat-native', + version: '0.3.1', + platform: 'darwin-arm64', + architecture: 'arm64', + protocolVersion: 1, + tmSendSourceSha256: AGENT_HASH, + addressProfileSha256: PROFILE_HASH, + supportedWechatVersions: [FIXTURE_WECHAT_VERSION], + capabilities: ['text', 'image', 'voice'] + })) + expect(cache.read(runtimeDir, 'arm64').version).toBe('0.3.1') + }) + + it('does not return a cached manifest after an artifact disappears', () => { + const runtimeDir = createRuntimeDirectory('0.3.0') + const cache = new MacWechatRuntimeManifestCache() + cache.read(runtimeDir, 'arm64') + rmSync(join(runtimeDir, 'tm-wechat-host')) + expect(() => cache.read(runtimeDir, 'arm64')).toThrow(/tm-wechat-host missing/) + }) +}) diff --git a/tests/unit/mac-wechat-runtime-manager.test.ts b/tests/unit/mac-wechat-runtime-manager.test.ts new file mode 100644 index 0000000..3e84b7c --- /dev/null +++ b/tests/unit/mac-wechat-runtime-manager.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, it } from 'vitest' + +import { + deriveMacWechatSenderStatus, + MacWechatRuntimeManager, + resolveMacWechatSendMechanism +} from '../../src/main/services/mac-wechat-runtime-manager' +import type { + MacWechatBindingStatus, + MacWechatRuntimeManifest, + MacWechatRuntimeSnapshot +} from '../../src/shared/personal-wechat-mac-runtime' + +const AGENT_HASH = 'a'.repeat(64) +const PROFILE_HASH = 'b'.repeat(64) +const MESSAGE_SOURCE_WECHAT_VERSION = 'fixture-message-source-version' +const NATIVE_OBJECT_WECHAT_VERSION = 'fixture-native-object-version' +const LEGACY_WECHAT_VERSION = 'fixture-legacy-version' + +function manifest(wechatVersion: string, textMechanism: string): MacWechatRuntimeManifest { + return { + runtime: 'tm-wechat-native', + version: '0.3.0', + platform: 'darwin-arm64', + architecture: 'arm64', + protocolVersion: 1, + buildCommit: 'fixture-build', + tmSendSourceSha256: AGENT_HASH, + addressProfileSha256: PROFILE_HASH, + supportedWechatVersions: [wechatVersion], + capabilities: ['text', 'image', 'voice'], + capabilitiesByVersion: { + [wechatVersion]: { + text: 'verified', + image: 'verified', + voice: 'verified', + textMechanism + } + } + } +} + +function snapshot(overrides: Partial = {}): MacWechatRuntimeSnapshot { + return { + lifecycle: 'online', + wechatRestartRequired: false, + endpoint: 'http://127.0.0.1:4290', + port: 4290, + ...overrides + } +} + +function binding( + wechatVersion: string, + overrides: Partial = {} +): MacWechatBindingStatus { + return { + runtime: true, + hostPid: 800, + runtimeState: 'ready', + runtimeVersion: 'tm-wechat-runtime/0.3.0', + embeddedAgentSha256: AGENT_HASH, + embeddedAddressProfileSha256: PROFILE_HASH, + wechatRunning: true, + wechatPid: 900, + wechatVersion, + supported: true, + bindingState: 'bound', + bound: true, + boundWechatPid: 900, + sessionAttached: true, + scriptLoaded: true, + sendContextReady: false, + canSendText: true, + canSendImage: true, + canSendVoice: true, + attachCount: 1, + ...overrides + } +} + +class ConcurrentStartManager extends MacWechatRuntimeManager { + startCalls = 0 + private resolveStart: ((snapshot: MacWechatRuntimeSnapshot) => void) | null = null + + protected override ensureStartedOnce(): Promise { + this.startCalls += 1 + return new Promise((resolve) => { + this.resolveStart = resolve + }) + } + + finishStart(result: MacWechatRuntimeSnapshot): void { + this.resolveStart?.(result) + } +} + +describe('deriveMacWechatSenderStatus', () => { + it('shares one in-flight start promise with concurrent status reads', async () => { + const manager = new ConcurrentStartManager() + + const first = manager.ensureStarted() + const second = manager.ensureStarted() + + expect(manager.startCalls).toBe(1) + manager.finishStart(snapshot()) + await expect(Promise.all([first, second])).resolves.toEqual([snapshot(), snapshot()]) + }) + + it('resolves the send mechanism only for a binding that matches the runtime manifest', () => { + const currentBinding = binding(MESSAGE_SOURCE_WECHAT_VERSION) + const currentManifest = manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send') + + expect(resolveMacWechatSendMechanism(currentBinding, currentManifest)).toBe( + 'tm-message-source-send' + ) + expect( + resolveMacWechatSendMechanism( + { ...currentBinding, embeddedAgentSha256: 'c'.repeat(64) }, + currentManifest + ) + ).toBeUndefined() + expect(resolveMacWechatSendMechanism(null, currentManifest)).toBeUndefined() + }) + + it('marks message-source sending ready without a captured send context', () => { + const result = deriveMacWechatSenderStatus({ + snapshot: snapshot(), + binding: binding(MESSAGE_SOURCE_WECHAT_VERSION), + manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'), + arch: 'arm64' + }) + + expect(result).toMatchObject({ + state: 'online', + runtimeReady: true, + attachReady: true, + messageListenerReady: true, + canSend: true, + canSendText: true, + canSendImage: true, + canSendVoice: true + }) + }) + + it('keeps native message-object readiness unchanged', () => { + const result = deriveMacWechatSenderStatus({ + snapshot: snapshot(), + binding: binding(NATIVE_OBJECT_WECHAT_VERSION), + manifest: manifest(NATIVE_OBJECT_WECHAT_VERSION, 'native-msg-object'), + arch: 'arm64' + }) + + expect(result.state).toBe('online') + expect(result.canSend).toBe(true) + }) + + it('continues waiting for the captured context on the legacy mechanism', () => { + const result = deriveMacWechatSenderStatus({ + snapshot: snapshot(), + binding: binding(LEGACY_WECHAT_VERSION), + manifest: manifest(LEGACY_WECHAT_VERSION, 'legacy-req2buf'), + arch: 'arm64' + }) + + expect(result.state).toBe('hook_not_ready') + expect(result.canSend).toBe(false) + }) + + it('surfaces a crashed host as an error instead of an unbound runtime check', () => { + const result = deriveMacWechatSenderStatus({ + snapshot: snapshot({ + lifecycle: 'crashed_unbound', + error: '发送运行时启动失败(进程退出码 1)' + }), + binding: null, + manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'), + arch: 'arm64' + }) + + expect(result).toMatchObject({ + state: 'error', + runtimeReady: false, + endpointReady: false, + message: '发送运行时启动失败(进程退出码 1)' + }) + }) + + it('surfaces stopped startup failures instead of an unbound runtime check', () => { + const result = deriveMacWechatSenderStatus({ + snapshot: snapshot({ lifecycle: 'stopped', error: 'runtime host missing' }), + binding: null, + manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'), + arch: 'arm64' + }) + + expect(result).toMatchObject({ + state: 'error', + runtimeReady: false, + endpointReady: false, + message: 'runtime host missing' + }) + }) + + it.each([ + ['session is not attached', { sessionAttached: false }], + ['agent script is not loaded', { scriptLoaded: false }], + ['runtime is still initializing', { runtimeState: 'initializing' as const }] + ])('does not mark the message-source mechanism ready when %s', (_reason, overrides) => { + const result = deriveMacWechatSenderStatus({ + snapshot: snapshot(), + binding: binding(MESSAGE_SOURCE_WECHAT_VERSION, overrides), + manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'), + arch: 'arm64' + }) + + expect(result.state).toBe('hook_not_ready') + expect(result.canSend).toBe(false) + }) +}) diff --git a/tests/unit/personal-wechat-send-service.test.ts b/tests/unit/personal-wechat-send-service.test.ts index 8db3089..c5806c5 100644 --- a/tests/unit/personal-wechat-send-service.test.ts +++ b/tests/unit/personal-wechat-send-service.test.ts @@ -1,4 +1,5 @@ import { + existsSync, mkdirSync, mkdtempSync, readFileSync, @@ -9,7 +10,14 @@ import { } from 'fs' import { tmpdir } from 'os' import { join, sep } from 'path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const runtimeMocks = vi.hoisted(() => ({ + ensureStarted: vi.fn(), + buildSenderStatus: vi.fn(), + getSendMechanism: vi.fn(), + getPort: vi.fn(() => 4290) +})) vi.mock('electron', () => ({ app: { @@ -18,6 +26,27 @@ vi.mock('electron', () => ({ isPackaged: false } })) +vi.mock('../../src/main/services/mac-wechat-runtime-manager', () => ({ + macWechatRuntimeManager: runtimeMocks +})) +vi.mock('../../src/main/voice-pipeline/audio-decoder', () => ({ + SilkAudioDecoder: class { + async decode() { + return { pcm: Buffer.alloc(48_000), channels: 1, sampleRate: 24_000 } + } + }, + SilkAudioEncoder: class {} +})) +vi.mock('../../src/main/services/local-account-identity', () => ({ + readLocalAccountIdentity: () => ({ wxid: 'wxid_fixture_self' }), + accountDirectoryBelongsToIdentity: (directory: string, wxid: string) => { + const normalizedDirectory = directory.toLowerCase() + const normalizedWxid = wxid.toLowerCase() + if (normalizedDirectory === normalizedWxid) return true + if (!normalizedDirectory.startsWith(`${normalizedWxid}_`)) return false + return /^[a-z0-9]{4}$/.test(normalizedDirectory.slice(normalizedWxid.length + 1)) + } +})) import { buildPersonalWechatVoiceDiagnostic, @@ -29,6 +58,7 @@ import { prepareWindowsImageFile, WindowsHookHttpError } from '../../src/main/services/personal-wechat-send-service' +import { PersonalWechatSendService } from '../../src/main/services/personal-wechat-send-service' const temporaryDirectories: string[] = [] @@ -39,11 +69,254 @@ function temporaryDirectory(): string { } afterEach(() => { + vi.unstubAllGlobals() while (temporaryDirectories.length > 0) { rmSync(temporaryDirectories.pop()!, { recursive: true, force: true }) } }) +beforeEach(() => { + runtimeMocks.ensureStarted.mockReset().mockResolvedValue(undefined) + runtimeMocks.buildSenderStatus + .mockReset() + .mockResolvedValue({ canSendText: true, canSendImage: true, canSendVoice: true }) + runtimeMocks.getSendMechanism.mockReset().mockResolvedValue('legacy-req2buf') + runtimeMocks.getPort.mockReset().mockReturnValue(4290) +}) + +describe('macOS message-source send routing', () => { + it('sends a message-source image through one local-path request without CDN upload', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-image.png') + writeFileSync(filePath, 'fixture-image') + const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11') + mkdirSync(imageTemp, { recursive: true }) + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + let stagedPath = '' + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + fetchMock.mockImplementation(async (_url, init) => { + stagedPath = String((JSON.parse(String(init?.body)) as { path: string }).path) + expect(stagedPath).toContain(imageTemp) + expect(readFileSync(stagedPath, 'utf8')).toBe('fixture-image') + return { + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + } as Response + }) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService(root).send({ + type: 'image', to: 'fixture-contact', isGroup: false, filePath + }) + + expect(result.success).toBe(true) + expect(fetchMock).toHaveBeenCalledOnce() + expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg') + expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({ + type: 'image', to: 'fixture-contact', path: stagedPath + }) + expect(stagedPath).not.toBe(filePath) + expect(existsSync(stagedPath)).toBe(false) + }) + + it('uses the legacy image path only when source preparation is definitively rejected', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-image.png') + writeFileSync(filePath, 'fixture-image') + const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11') + mkdirSync(imageTemp, { recursive: true }) + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + const fetchMock = vi.fn().mockImplementation(async (url: string) => ({ + ok: true, + status: 200, + json: async () => String(url).endsWith('/sendMsg') + ? { code: 6, ok: false, message: 'IMAGE_PREPARATION_FAILED:0' } + : { code: 0, ok: true, message: 'sent' } + })) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService(root).send({ + type: 'image', to: 'fixture-contact', isGroup: false, filePath + }) + + expect(result.success).toBe(true) + expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ + 'http://127.0.0.1:4290/sendMsg', + 'http://127.0.0.1:4290/uploadImage', + 'http://127.0.0.1:4290/sendImage' + ]) + const uploadBody = JSON.parse(String(fetchMock.mock.calls[1][1]?.body)) as Record< + string, + unknown + > + expect(String(uploadBody.filePath)).toContain(imageTemp) + }) + + it('does not retry image submission after a timeout or an ambiguous failure', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-image.png') + writeFileSync(filePath, 'fixture-image') + const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11') + mkdirSync(imageTemp, { recursive: true }) + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + const fetchMock = vi.fn().mockRejectedValue(new Error('request timed out')) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService(root).send({ + type: 'image', to: 'fixture-contact', isGroup: false, filePath + }) + + expect(result.success).toBe(false) + expect(result.error).toBe('图片发送失败') + expect(fetchMock).toHaveBeenCalledOnce() + expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg') + }) + + it('keeps other image mechanisms on the upload-then-send endpoints', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-image.png') + writeFileSync(filePath, 'fixture-image') + const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11') + mkdirSync(imageTemp, { recursive: true }) + runtimeMocks.getSendMechanism.mockResolvedValue('native-msg-object') + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService(root).send({ + type: 'image', to: 'fixture-contact', isGroup: false, filePath + }) + + expect(result.success).toBe(true) + expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ + 'http://127.0.0.1:4290/uploadImage', + 'http://127.0.0.1:4290/sendImage' + ]) + const uploadBody = JSON.parse(String(fetchMock.mock.calls[0][1]?.body)) as Record< + string, + unknown + > + expect(String(uploadBody.filePath)).toContain(imageTemp) + }) + + it('sends message-source text and its mention map through the unified endpoint', async () => { + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService().send({ + type: 'text', + to: 'fixture-room@chatroom', + isGroup: true, + text: '早上好', + at: { wxid_fixture_member: '测试成员' } + }) + + expect(result.success).toBe(true) + expect(fetchMock).toHaveBeenCalledOnce() + expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg') + expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({ + type: 'text', + to: 'fixture-room@chatroom', + text: '早上好', + is_group: true, + at: { wxid_fixture_member: '测试成员' } + }) + }) + + it('sends a message-source SILK voice through the unified request', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-voice.silk') + writeFileSync(filePath, Buffer.concat([Buffer.from('\x02#!SILK_V3'), Buffer.from([1, 2, 3])])) + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService().send({ + type: 'voice', to: 'fixture-contact', isGroup: false, filePath, durationMs: 1200 + }) + + expect(result.success).toBe(true) + expect(fetchMock).toHaveBeenCalledOnce() + expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg') + expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({ + type: 'voice', to: 'fixture-contact', voice_hex: expect.any(String), duration_ms: 1200 + }) + }) + + it('rejects a sub-second message-source voice instead of sending an invalid duration', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-voice.silk') + writeFileSync(filePath, Buffer.concat([Buffer.from('\x02#!SILK_V3'), Buffer.from([1, 2, 3])])) + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService().send({ + type: 'voice', to: 'fixture-contact', isGroup: false, filePath, durationMs: 500 + }) + + expect(result.success).toBe(false) + expect(result.error).toContain('至少 1 秒') + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('keeps other text mechanisms on the existing endpoint', async () => { + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService().send({ + type: 'text', to: 'fixture-contact', isGroup: false, text: 'hello' + }) + + expect(result.success).toBe(true) + expect(fetchMock).toHaveBeenCalledOnce() + expect(fetchMock.mock.calls[0][0]).toContain('/sendText') + }) + + it('keeps other voice mechanisms on the upload-then-send endpoints', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-voice.silk') + writeFileSync(filePath, Buffer.concat([Buffer.from('\x02#!SILK_V3'), Buffer.from([1, 2, 3])])) + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + vi.stubGlobal('fetch', fetchMock) + + const result = await new PersonalWechatSendService().send({ + type: 'voice', to: 'fixture-contact', isGroup: false, filePath, durationMs: 1200 + }) + + expect(result.success).toBe(true) + expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ + 'http://127.0.0.1:4290/uploadVoice', + 'http://127.0.0.1:4290/sendVoice' + ]) + }) +}) + describe('personal WeChat voice diagnostics', () => { it('keeps voice diagnostics to the safe metadata allowlist', () => { const diagnostic = buildPersonalWechatVoiceDiagnostic('request-1', 'completed', { @@ -224,4 +497,19 @@ describe('personal WeChat runtime discovery', () => { `${join(tempRoot, 'ImageTemp', '2026-08')}${sep}` ) }) + + it('does not choose a newer image directory belonging to another WeChat account', () => { + const root = temporaryDirectory() + const ownPath = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-08') + const otherPath = join(root, 'wxid_other_account', 'temp', 'ImageTemp', '2026-08') + mkdirSync(ownPath, { recursive: true }) + mkdirSync(otherPath, { recursive: true }) + utimesSync(ownPath, new Date('2026-08-01'), new Date('2026-08-01')) + utimesSync(otherPath, new Date('2026-08-05'), new Date('2026-08-05')) + + expect(findWechatImagePath(root, new Date('2026-08-06'), 'wxid_fixture_self')).toBe( + `${ownPath}${sep}` + ) + expect(findWechatImagePath(root, new Date('2026-08-06'), 'wxid_missing_account')).toBeUndefined() + }) }) diff --git a/tests/unit/runtime-packaging.test.ts b/tests/unit/runtime-packaging.test.ts index dbccdeb..c0e052f 100644 --- a/tests/unit/runtime-packaging.test.ts +++ b/tests/unit/runtime-packaging.test.ts @@ -492,6 +492,19 @@ describe('production runtime packaging', () => { expect(stub.calls).toContainEqual(['--verify', '--strict', '--arch', 'x86_64', helperPath]) }) + it('always re-signs the Native Host before packaging', () => { + const runtimeDirectory = join(root, 'runtime-sign-resources', 'runtime', 'darwin-arm64') + mkdirSync(runtimeDirectory, { recursive: true }) + const hostPath = join(runtimeDirectory, 'tm-wechat-host') + writeFileSync(hostPath, 'fixture') + const stub = createCodesignStub() + + expect(signMacosHelpers(join(root, 'runtime-sign-resources'), stub.run)).toEqual([hostPath]) + expect(stub.calls[0]).toEqual(['--force', '--sign', '-', hostPath]) + expect(stub.calls).toContainEqual(['--verify', '--strict', '--arch', 'arm64', hostPath]) + expect(stub.calls).toContainEqual(['--verify', '--strict', '--arch', 'x86_64', hostPath]) + }) + it('fails packaging when a helper signature cannot be repaired', () => { const resources = join(root, 'helper-broken-resources', 'resources') mkdirSync(resources, { recursive: true }) diff --git a/tests/unit/wechat-action-gateway.test.ts b/tests/unit/wechat-action-gateway.test.ts index 1701727..3894872 100644 --- a/tests/unit/wechat-action-gateway.test.ts +++ b/tests/unit/wechat-action-gateway.test.ts @@ -100,6 +100,25 @@ describe('WechatActionGateway', () => { ]) }) + it('preserves the native mention map when forwarding a manual text action', async () => { + const gateway = createGateway() + await gateway.execute({ + origin: 'user_manual', + purpose: 'manual_text', + triggerType: 'user', + recipient: { type: 'group', id: 'fixture-room@chatroom' }, + content: { type: 'text', text: '早上好', at: { wxid_fixture: '测试成员' } } + }) + + expect(mocks.sender.send).toHaveBeenCalledWith({ + type: 'text', + to: 'fixture-room@chatroom', + isGroup: true, + text: '早上好', + at: { wxid_fixture: '测试成员' } + }) + }) + it('deduplicates the same leave event across repeated execution calls', async () => { const gateway = createGateway() const first = await leaveNotificationAction(gateway)