feat: 发送支持群聊@成员

生命周期整理
清理残留整理
完善skill
This commit is contained in:
Wxw-Gu committed 2026-11-12 11:18:32 +08:00
1 parent 804466aad8
commit 5d4ba73771
28 files changed
+1214 -103

No files matched your search

+3 -1
View File
@@ -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;不要假设数据库已就绪,也不要声称读取了没有调用过的消息。
## 连接信息
+3 -1
View File
@@ -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)
+15 -1
View File
@@ -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<string, string> | 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<string, unknown>)
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) {
+11 -3
View File
@@ -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
+14 -1
View File
@@ -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 || '回复确认失败')
+9 -1
View File
@@ -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 = {
@@ -13,6 +13,7 @@ type PidCommandRunner = (
export interface MacWechatResidualCleanupDependencies {
platform: NodeJS.Platform
listWechatPids: () => Promise<number[]>
listHostPids: () => Promise<number[]>
listPortPids: () => Promise<number[]>
processName: (pid: number) => Promise<string>
processIdentity: (pid: number) => Promise<string>
@@ -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<number, string>,
processIdentities: Map<number, string>
): ObservedTarget[] {
const targets = new Map<number, Set<'wechat' | 'port_4290'>>()
const targets = new Map<number, Set<'wechat' | 'host' | 'port_4290'>>()
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<ObservedTarget[]> {
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<void> => {
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'))) {
@@ -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
+120 -16
View File
@@ -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<MacWechatRuntimeSnapshot> | 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<PersonalWechatSenderStatus> | 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<MacWechatRuntimeSnapshot> {
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<MacWechatRuntimeSnapshot> {
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<string | undefined> {
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<PersonalWechatSenderStatus> {
buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
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<PersonalWechatSenderStatus> {
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({
+117 -10
View File
@@ -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<PersonalWechatSenderStatus> {
// 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<string> {
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',
+23 -2
View File
@@ -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<string, string> | 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<string, unknown>)
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 }
}
@@ -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({
</div>
<ol className="personal-wechat-steps">
<li className={runtimeReady ? 'is-complete' : 'is-current'}>
<li
className={
runtimeReady ? 'is-complete' : runtimeError ? 'is-error' : 'is-current'
}
>
<span className="personal-wechat-step-number">{runtimeReady ? '✓' : '1'}</span>
<div className="personal-wechat-step-content">
<strong>准备 {runtimeLabel}</strong>
@@ -95,6 +100,10 @@ export function PersonalWechatSetupGuide({
<span className="personal-wechat-step-status">✓ {runtimeLabel}已就绪</span>
) : runtimeUnavailable ? (
<span className="personal-wechat-step-error">当前版本暂未提供微信消息发送功能</span>
) : runtimeError ? (
<span className="personal-wechat-step-error" role="alert">
{senderStatus.message || '发送运行时启动失败,请重新启动发送组件。'}
</span>
) : (
<span className="personal-wechat-step-status">正在检查 {runtimeLabel}…</span>
)}
@@ -183,7 +192,7 @@ export function PersonalWechatSetupGuide({
: '正在等待发送运行时完成初始化…'}
</p>
)}
{senderStatus?.state === 'error' && (
{senderStatus?.state === 'error' && !runtimeError && (
<p className="personal-wechat-step-hint" role="status">
{senderStatus.message || '发送能力初始化失败,请重新绑定。'}
</p>
@@ -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<void> => {
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 ? '检查中…' : '清理残留以及微信进程'}
</Button>
{macResidualRuntimeStopped ? (
<Button
className="mt-2 w-full"
variant="outline"
disabled={macResidualBusy}
onClick={() => void restartMacSendRuntime()}
>
{macResidualBusy ? '启动中…' : '重新启动发送组件'}
</Button>
) : null}
</div>
</section>
{macUnavailable ? (
@@ -1049,8 +1033,8 @@ export function PersonalWechatSendPage({
<AlertDialogHeader>
<AlertDialogTitle>清理微信残留进程?</AlertDialogTitle>
<AlertDialogDescription>
将结束下面列出的微信进程或占用 4290
端口的进程。若列表包含微信,微信会关闭;如曾绑定发送组件,之后需要重新打开微信并绑定。
将结束下面列出的微信进程,以及所有 TraceMemo 发送 Host(包括未占用 4290 的 Host)。
完成清理后会自动重启发送 Host;若列表包含微信,微信会关闭,之后需要重新打开微信并绑定。
</AlertDialogDescription>
</AlertDialogHeader>
<ul className="grid gap-2 rounded-md border border-border-subtle p-3 text-sm">
@@ -1060,7 +1044,9 @@ export function PersonalWechatSendPage({
<span className="shrink-0 text-muted-foreground">
PID {item.pid} ·{' '}
{item.targets
.map((target) => (target === 'wechat' ? '微信进程' : '4290 端口'))
.map((target) =>
target === 'wechat' ? '微信进程' : target === 'host' ? '发送 Host' : '4290 端口'
)
.join('、')}
</span>
</li>
+6
View File
@@ -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;
+1 -1
View File
@@ -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
}
+1
View File
@@ -74,6 +74,7 @@ interface PersonalWechatSendBaseRequest {
export interface PersonalWechatSendTextRequest extends PersonalWechatSendBaseRequest {
type: 'text'
text: string
at?: Record<string, string>
}
export interface PersonalWechatSendImageRequest extends PersonalWechatSendBaseRequest {
+1 -1
View File
@@ -72,7 +72,7 @@ export interface WechatActionRecipient {
}
export type WechatActionContent =
| { type: 'text'; text: string }
| { type: 'text'; text: string; at?: Record<string, string> }
| { type: 'image'; path: string }
| { type: 'voice'; path: string }
@@ -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(<PersonalWechatSendPage onNotice={onNotice} />)
@@ -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(<PersonalWechatSendPage onNotice={onNotice} />)
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',
@@ -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(
<PersonalWechatSetupGuide
senderStatus={failedRuntimeStatus}
binding={false}
detecting={false}
sessionBound={false}
showBindAction={false}
/>
)
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,
+13 -6
View File
@@ -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',
+34
View File
@@ -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' })
+48 -6
View File
@@ -127,14 +127,16 @@ function buildRunner(options: {
const run = (
runner: AutomationActionRunner,
rule: AutomationRule
rule: AutomationRule,
triggerSender?: { wxid: string; displayName: string }
): Promise<Awaited<ReturnType<AutomationActionRunner['run']>>> =>
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')
})
/**
@@ -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 () => []),
@@ -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/)
})
})
@@ -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> = {}): MacWechatRuntimeSnapshot {
return {
lifecycle: 'online',
wechatRestartRequired: false,
endpoint: 'http://127.0.0.1:4290',
port: 4290,
...overrides
}
}
function binding(
wechatVersion: string,
overrides: Partial<MacWechatBindingStatus> = {}
): 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<MacWechatRuntimeSnapshot> {
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)
})
})
+289 -1
View File
@@ -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()
})
})
+13
View File
@@ -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 })
+19
View File
@@ -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)