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

+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 }