mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 发送支持群聊@成员
生命周期整理 清理残留整理 完善skill
This commit is contained in:
1 parent
804466aad8
commit
5d4ba73771
28 files changed
+1214
-103
No files matched your search
@@ -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 || '回复确认失败')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user