mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: mac发送能力重构为libtmwechat
- 发送改走本地host, 在微信登录时触发 - 删除旧OneBot及对应UI控制面
This commit is contained in:
1 parent
069d836dea
commit
7268188e40
50 files changed
+2442
-4141
No files matched your search
@@ -0,0 +1,101 @@
|
||||
import { existsSync, readFileSync, statSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
import type { MacWechatRuntimeManifest } from '../../shared/personal-wechat-mac-runtime'
|
||||
|
||||
const REQUIRED_CAPABILITIES = ['text', 'image', 'voice'] as const
|
||||
|
||||
function assertFile(path: string, label: string): void {
|
||||
if (!existsSync(path) || !statSync(path).isFile()) {
|
||||
throw new Error(`${label} missing: ${path}`)
|
||||
}
|
||||
}
|
||||
|
||||
function assertMachOArm64(path: string, label: string): void {
|
||||
const binary = readFileSync(path)
|
||||
if (binary.length < 8 || binary.readUInt32LE(0) !== 0xfeedfacf) {
|
||||
throw new Error(`${label} is not a 64-bit Mach-O binary`)
|
||||
}
|
||||
if (binary.readUInt32LE(4) !== 0x0100000c) {
|
||||
throw new Error(`${label} is not arm64`)
|
||||
}
|
||||
}
|
||||
|
||||
export function readMacWechatRuntimeManifest(
|
||||
runtimeDir: string,
|
||||
architecture = process.arch
|
||||
): MacWechatRuntimeManifest {
|
||||
const manifestPath = join(runtimeDir, 'runtime-manifest.json')
|
||||
const hostPath = join(runtimeDir, 'tm-wechat-host')
|
||||
const dylibPath = join(runtimeDir, 'libtmwechat.dylib')
|
||||
assertFile(manifestPath, 'runtime manifest')
|
||||
assertFile(hostPath, 'runtime host')
|
||||
assertFile(dylibPath, 'runtime dylib')
|
||||
|
||||
let manifest: MacWechatRuntimeManifest
|
||||
try {
|
||||
manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as MacWechatRuntimeManifest
|
||||
} catch (error) {
|
||||
throw new Error(`runtime manifest is unreadable: ${String(error)}`)
|
||||
}
|
||||
|
||||
if (manifest.runtime !== 'tm-wechat-native') {
|
||||
throw new Error(`unexpected runtime name: ${String(manifest.runtime)}`)
|
||||
}
|
||||
if (manifest.platform !== 'darwin-arm64') {
|
||||
throw new Error(`runtime platform must be darwin-arm64: ${String(manifest.platform)}`)
|
||||
}
|
||||
if (manifest.architecture !== 'arm64' || architecture !== 'arm64') {
|
||||
throw new Error(
|
||||
`runtime architecture mismatch: artifact=${String(manifest.architecture)} process=${architecture}`
|
||||
)
|
||||
}
|
||||
if (manifest.protocolVersion !== 1) {
|
||||
throw new Error(`unsupported runtime protocolVersion: ${String(manifest.protocolVersion)}`)
|
||||
}
|
||||
if (!/^[a-f0-9]{64}$/.test(manifest.tmSendSourceSha256 || '')) {
|
||||
throw new Error('runtime manifest has no valid tmSendSourceSha256')
|
||||
}
|
||||
if (!/^[a-f0-9]{64}$/.test(manifest.addressProfileSha256 || '')) {
|
||||
throw new Error('runtime manifest has no valid addressProfileSha256')
|
||||
}
|
||||
if (
|
||||
!Array.isArray(manifest.supportedWechatVersions) ||
|
||||
manifest.supportedWechatVersions.length === 0
|
||||
) {
|
||||
throw new Error('runtime manifest has no supported WeChat versions')
|
||||
}
|
||||
const capabilities = new Set(manifest.capabilities || [])
|
||||
for (const capability of REQUIRED_CAPABILITIES) {
|
||||
if (!capabilities.has(capability)) {
|
||||
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'))) {
|
||||
throw new Error('runtime dylib embedded agent hash does not match manifest')
|
||||
}
|
||||
if (!readFileSync(dylibPath).includes(Buffer.from(manifest.addressProfileSha256, 'utf8'))) {
|
||||
throw new Error('runtime dylib embedded address profile hash does not match manifest')
|
||||
}
|
||||
return manifest
|
||||
}
|
||||
|
||||
export function bindingMatchesRuntimeManifest(
|
||||
binding: {
|
||||
hostPid?: number
|
||||
runtimeVersion?: string
|
||||
embeddedAgentSha256?: string
|
||||
embeddedAddressProfileSha256?: string
|
||||
},
|
||||
manifest: MacWechatRuntimeManifest
|
||||
): boolean {
|
||||
return (
|
||||
Number.isInteger(binding.hostPid) &&
|
||||
Number(binding.hostPid) > 0 &&
|
||||
binding.runtimeVersion === `tm-wechat-runtime/${manifest.version}` &&
|
||||
binding.embeddedAgentSha256 === manifest.tmSendSourceSha256 &&
|
||||
binding.embeddedAddressProfileSha256 === manifest.addressProfileSha256
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,710 @@
|
||||
import { spawn, type ChildProcess } from 'child_process'
|
||||
import { chmodSync, existsSync } from 'fs'
|
||||
import { get } from 'http'
|
||||
import { join } from 'path'
|
||||
|
||||
import { app } from 'electron'
|
||||
|
||||
import { appLogger } from '../app-logger'
|
||||
import { isPackagedRuntime } from '../runtime-mode'
|
||||
import type {
|
||||
MacWechatBindResult,
|
||||
MacWechatBindingStatus,
|
||||
MacWechatRuntimeManifest,
|
||||
MacWechatRuntimeLifecycle,
|
||||
MacWechatRuntimeSnapshot
|
||||
} from '../../shared/personal-wechat-mac-runtime'
|
||||
import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
|
||||
import {
|
||||
bindingMatchesRuntimeManifest,
|
||||
readMacWechatRuntimeManifest
|
||||
} from './mac-wechat-runtime-artifact'
|
||||
|
||||
/*
|
||||
* MacWechatRuntimeManager — lifecycle owner of the built-in macOS native
|
||||
* WeChat runtime (tm-wechat-host + libtmwechat.dylib).
|
||||
*
|
||||
* Process isolation is a hard requirement: Electron NEVER dlopens the dylib.
|
||||
* It spawns tm-wechat-host, which is the ONLY binding owner, and talks to it
|
||||
* over 127.0.0.1 HTTP. A native crash therefore cannot take Electron down.
|
||||
*
|
||||
* Binding lifecycle is "bind once per WeChat process":
|
||||
* - starting the host NEVER attaches to WeChat (the host is lazy)
|
||||
* - bind happens only on an explicit user action
|
||||
* - a host crash while bound leaves an orphaned frida agent inside WeChat
|
||||
* that frida cannot remove from the outside; the only recovery is
|
||||
* restarting WeChat. Surfaced as wechatRestartRequired. This was verified
|
||||
* experimentally (2026-09-21) — do not "fix" it by auto-restarting and
|
||||
* auto-binding, that path dead-ends in a 20s attach timeout every time.
|
||||
*/
|
||||
|
||||
const PORT = 4290
|
||||
const HOST = '127.0.0.1'
|
||||
const START_TIMEOUT_MS = 15_000
|
||||
const REQUEST_TIMEOUT_MS = 30_000
|
||||
const CRASH_RESTART_DELAY_MS = 1_500
|
||||
|
||||
interface MacWechatSenderStatusInput {
|
||||
snapshot: MacWechatRuntimeSnapshot
|
||||
binding: MacWechatBindingStatus | null
|
||||
manifest: MacWechatRuntimeManifest
|
||||
arch?: string
|
||||
}
|
||||
|
||||
export function shouldClearWechatRestartRequired(
|
||||
orphanWechatPid: number,
|
||||
currentWechatPid: number
|
||||
): boolean {
|
||||
return orphanWechatPid > 0 && currentWechatPid > 0 && orphanWechatPid !== currentWechatPid
|
||||
}
|
||||
|
||||
export function deriveMacWechatSenderStatus({
|
||||
snapshot,
|
||||
binding,
|
||||
manifest,
|
||||
arch = process.arch
|
||||
}: MacWechatSenderStatusInput): PersonalWechatSenderStatus {
|
||||
const identityMatches = binding !== null && bindingMatchesRuntimeManifest(binding, manifest)
|
||||
const stale = binding?.bindingState === 'stale'
|
||||
|
||||
let state: PersonalWechatSenderStatus['state'] = 'stopped'
|
||||
let message = '正在初始化微信发送能力'
|
||||
if (snapshot.wechatRestartRequired) {
|
||||
state = 'error'
|
||||
message = '微信发送组件异常退出。由于当前微信进程中可能残留上一发送会话,请重启微信后重新绑定。'
|
||||
} else if (binding && !identityMatches) {
|
||||
state = 'error'
|
||||
message = '运行中的微信发送 host 与当前 Native Runtime 不一致,请退出旧 host 后重启 TraceMemo。'
|
||||
} else if (binding && !binding.wechatRunning) {
|
||||
state = 'wechat_not_running'
|
||||
message = '微信未运行'
|
||||
} else if (binding?.bindingState === 'ready') {
|
||||
state = 'online'
|
||||
message = '个人微信已准备好发送日报'
|
||||
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
|
||||
state = 'hook_not_ready'
|
||||
message = '已绑定,等待捕获微信发送上下文'
|
||||
} else if (stale) {
|
||||
state = 'stopped'
|
||||
message = '检测到微信已重启,请重新绑定'
|
||||
} else if (binding?.bindingState === 'failed') {
|
||||
state = 'error'
|
||||
message = '微信绑定失败'
|
||||
} else {
|
||||
state = 'stopped'
|
||||
message = '尚未绑定当前微信,可点击"绑定微信"'
|
||||
}
|
||||
|
||||
const runtimeCapabilities = new Set(manifest.capabilities)
|
||||
const bindingReady = identityMatches && state === 'online' && binding?.sendContextReady === true
|
||||
const canSendText =
|
||||
bindingReady && runtimeCapabilities.has('text') && binding?.canSendText === true
|
||||
const canSendImage =
|
||||
bindingReady && runtimeCapabilities.has('image') && binding?.canSendImage === true
|
||||
const canSendVoice =
|
||||
bindingReady && runtimeCapabilities.has('voice') && binding?.canSendVoice === true
|
||||
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
|
||||
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
|
||||
|
||||
return {
|
||||
state,
|
||||
platform: 'darwin',
|
||||
arch,
|
||||
// 当前 gadget runtime 不依赖宿主 SIP 状态;该字段仅用于兼容旧 sender contract。
|
||||
sipDisabled: true,
|
||||
wechatRunning: binding?.wechatRunning ?? false,
|
||||
wechatPid: binding?.wechatPid ?? 0,
|
||||
boundWechatPid: binding?.boundWechatPid ?? 0,
|
||||
endpoint: snapshot.endpoint,
|
||||
endpointReady: snapshot.lifecycle === 'online',
|
||||
wechatVersion: binding?.wechatVersion,
|
||||
runtimeReady: snapshot.lifecycle === 'online' && identityMatches,
|
||||
attachReady: sessionAttached,
|
||||
baseAddressReady: sessionAttached,
|
||||
textHookInstalled: scriptLoaded,
|
||||
textHookReady: identityMatches && (binding?.sendContextReady ?? false),
|
||||
imageHookInstalled: identityMatches && (binding?.canSendImage ?? false),
|
||||
imageHookReady: identityMatches && (binding?.canSendImage ?? false),
|
||||
messageListenerReady: scriptLoaded,
|
||||
canSend: canSendText || canSendImage || canSendVoice,
|
||||
canSendText,
|
||||
canSendImage,
|
||||
canSendVoice,
|
||||
message,
|
||||
error: state === 'error' ? message : undefined
|
||||
}
|
||||
}
|
||||
|
||||
class MacWechatRuntimeManager {
|
||||
private child: ChildProcess | null = null
|
||||
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
|
||||
private wechatRestartRequired = false
|
||||
/* The WeChat pid that was bound when the host died / bind hit the orphan
|
||||
* wall. The orphan agent lives INSIDE that process; once WeChat is restarted
|
||||
* the pid changes and the orphan is gone, so the flag must auto-clear. */
|
||||
private orphanWechatPid = 0
|
||||
private lastBinding: MacWechatBindingStatus | null = null
|
||||
private manifest: MacWechatRuntimeManifest | null = null
|
||||
private lastError: string | null = null
|
||||
private restartTimer: NodeJS.Timeout | null = null
|
||||
|
||||
getPort(): number {
|
||||
return PORT
|
||||
}
|
||||
|
||||
getSnapshot(): MacWechatRuntimeSnapshot {
|
||||
return {
|
||||
lifecycle: this.lifecycle,
|
||||
wechatRestartRequired: this.wechatRestartRequired,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
port: PORT,
|
||||
runtimeDir: this.resolveRuntimeDir(),
|
||||
manifest: this.manifest ?? undefined,
|
||||
error: this.lastError ?? undefined,
|
||||
binding: this.lastBinding ?? undefined
|
||||
}
|
||||
}
|
||||
|
||||
private resolveRuntimeDir(): string {
|
||||
const base = isPackagedRuntime() ? process.resourcesPath : app.getAppPath()
|
||||
return join(base, 'resources', 'runtime', 'darwin-arm64')
|
||||
}
|
||||
|
||||
private resolveHostPath(): string {
|
||||
return join(this.resolveRuntimeDir(), 'tm-wechat-host')
|
||||
}
|
||||
|
||||
/** Runtime binaries present and executable? Cheap check for the settings UI. */
|
||||
isRuntimePresent(): boolean {
|
||||
try {
|
||||
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the host if it is not already running. Deliberately lazy: the host
|
||||
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
|
||||
* online" and "WeChat bound" stay two independent states.
|
||||
*/
|
||||
async ensureStarted(): Promise<MacWechatRuntimeSnapshot> {
|
||||
if (this.lifecycle === 'starting') {
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
const runtimeDir = this.resolveRuntimeDir()
|
||||
try {
|
||||
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
|
||||
appLogger.write({
|
||||
level: 'info',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'runtime_artifact_validated',
|
||||
details: {
|
||||
runtime: this.manifest.runtime,
|
||||
version: this.manifest.version,
|
||||
protocolVersion: this.manifest.protocolVersion,
|
||||
agentSha256: this.manifest.tmSendSourceSha256,
|
||||
addressProfileSha256: this.manifest.addressProfileSha256
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
this.manifest = null
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'runtime_artifact_unavailable',
|
||||
details: { detail }
|
||||
})
|
||||
this.lastError = '暂无发送能力'
|
||||
this.lifecycle = 'stopped'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
if (this.lifecycle === 'online') {
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
this.lastBinding &&
|
||||
this.manifest &&
|
||||
bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
return this.getSnapshot()
|
||||
}
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = '运行中的 host 与 runtime manifest 不一致'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
/*
|
||||
* Adopt-first: the host is designed to OUTLIVE TraceMemo ("keep the send
|
||||
* capability process"), so a previous app session may have left it running
|
||||
* with a live, bound session. If something is already answering on our
|
||||
* port, adopt it instead of spawning a second one (which would just die on
|
||||
* the occupied port). Adopting is pure HTTP — the running host keeps its
|
||||
* frida session, so the app is immediately ready with NO re-bind, exactly
|
||||
* the "keep the send capability process" behaviour the user asked to carry over.
|
||||
*/
|
||||
if (await this.ping()) {
|
||||
this.lifecycle = 'online'
|
||||
this.child = null
|
||||
this.wechatRestartRequired = false
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
!this.lastBinding ||
|
||||
!this.manifest ||
|
||||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError =
|
||||
'检测到无法确认身份的微信发送 host。请先退出旧 host,再重新启动 TraceMemo。'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
if (this.lifecycle === 'crashed_bound' || this.wechatRestartRequired) {
|
||||
// Restarting the host is safe (it does not touch WeChat), but binding is
|
||||
// not: the orphaned agent from the previous session is still inside the
|
||||
// current WeChat process. Start anyway so the UI can show live status.
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'restart_host_after_bound_crash',
|
||||
details: { note: 'bind stays blocked until WeChat restarts' }
|
||||
})
|
||||
}
|
||||
|
||||
const hostPath = this.resolveHostPath()
|
||||
if (!existsSync(hostPath)) {
|
||||
this.lastError = `runtime host missing: ${hostPath}`
|
||||
this.lifecycle = 'stopped'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
try {
|
||||
chmodSync(hostPath, 0o755)
|
||||
} catch {
|
||||
/* best effort — dev checkouts usually keep the exec bit */
|
||||
}
|
||||
|
||||
this.lifecycle = 'starting'
|
||||
this.lastError = null
|
||||
|
||||
try {
|
||||
/* Host stderr goes to /dev/null (stdio ignored, see note above), so the
|
||||
* host writes its own log file via TM_WECHAT_LOG_FILE. Without this the
|
||||
* agent's stage beacons (send-enter / cdn-enter / …) are invisible and a
|
||||
* media/CDN stall is undiagnosable. info level so stage beacons show. */
|
||||
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
|
||||
this.child = spawn(
|
||||
hostPath,
|
||||
[
|
||||
'--port',
|
||||
String(PORT),
|
||||
'--manifest',
|
||||
join(runtimeDir, 'runtime-manifest.json'),
|
||||
'--log-level',
|
||||
'info'
|
||||
],
|
||||
{
|
||||
cwd: runtimeDir,
|
||||
stdio: 'ignore',
|
||||
detached: false,
|
||||
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = String(error)
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
this.child.on('exit', (code) => {
|
||||
const wasBound =
|
||||
this.lastBinding?.bound === true ||
|
||||
this.lastBinding?.sessionAttached === true ||
|
||||
this.lastBinding?.bindingState === 'binding'
|
||||
const orphanPid = this.lastBinding?.boundWechatPid || this.lastBinding?.wechatPid || 0
|
||||
this.child = null
|
||||
this.lastBinding = null
|
||||
if (this.lifecycle === 'stopped') return // deliberate shutdown
|
||||
|
||||
if (wasBound) {
|
||||
this.lifecycle = 'crashed_bound'
|
||||
this.wechatRestartRequired = true
|
||||
this.orphanWechatPid = orphanPid
|
||||
appLogger.write({
|
||||
level: 'error',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_died_while_bound',
|
||||
details: { code: code ?? null, orphanWechatPid: orphanPid }
|
||||
})
|
||||
} else {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
// Wait for /healthz
|
||||
const deadline = Date.now() + START_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (await this.ping()) {
|
||||
this.lifecycle = 'online'
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
!this.lastBinding ||
|
||||
!this.manifest ||
|
||||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '运行中的 host 与 runtime manifest 不一致'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
if (this.child === null) break // died during startup
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
}
|
||||
|
||||
if (this.lifecycle === 'starting') {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = 'host did not answer /healthz in time'
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
private request(
|
||||
method: string,
|
||||
path: string,
|
||||
timeoutMs = REQUEST_TIMEOUT_MS
|
||||
): Promise<{ status: number | null; body: string }> {
|
||||
return new Promise((resolve) => {
|
||||
const request = get(
|
||||
{ host: HOST, port: PORT, path, method, timeout: timeoutMs },
|
||||
(response) => {
|
||||
let body = ''
|
||||
response.on('data', (chunk) => {
|
||||
body += chunk
|
||||
})
|
||||
response.on('end', () => {
|
||||
resolve({ status: response.statusCode ?? null, body })
|
||||
})
|
||||
}
|
||||
)
|
||||
request.on('timeout', () => {
|
||||
request.destroy()
|
||||
resolve({ status: null, body: '' })
|
||||
})
|
||||
request.on('error', () => {
|
||||
resolve({ status: null, body: '' })
|
||||
})
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
|
||||
async ping(): Promise<boolean> {
|
||||
const { status } = await this.request('GET', '/healthz', 3_000)
|
||||
if (status === 200) return true
|
||||
|
||||
/*
|
||||
* Adopted hosts have no child handle, so their death is only observable
|
||||
* through failed probes. Classify here: dying while bound means WeChat
|
||||
* keeps an orphaned agent (restart required); dying while unbound is
|
||||
* auto-recoverable.
|
||||
*/
|
||||
if (this.lifecycle === 'online') {
|
||||
const wasBound =
|
||||
this.lastBinding?.bound === true ||
|
||||
this.lastBinding?.sessionAttached === true ||
|
||||
this.lastBinding?.bindingState === 'binding'
|
||||
const orphanPid = this.lastBinding?.boundWechatPid || this.lastBinding?.wechatPid || 0
|
||||
this.lastBinding = null
|
||||
if (wasBound) {
|
||||
this.lifecycle = 'crashed_bound'
|
||||
this.wechatRestartRequired = true
|
||||
this.orphanWechatPid = orphanPid
|
||||
appLogger.write({
|
||||
level: 'error',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'adopted_host_died_while_bound',
|
||||
details: { note: 'WeChat restart required', orphanWechatPid: orphanPid }
|
||||
})
|
||||
} else {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Pull /bindingStatus and cache it for crash classification. */
|
||||
async refreshBinding(): Promise<MacWechatBindingStatus | null> {
|
||||
const { status, body } = await this.request('GET', '/bindingStatus')
|
||||
if (status !== 200) return null
|
||||
try {
|
||||
this.lastBinding = JSON.parse(body) as MacWechatBindingStatus
|
||||
/*
|
||||
* A 20s bind timeout is NOT proof of the orphan-agent wall: in the
|
||||
* stale-rebind path the host worker waits up to 45s for the old session
|
||||
* teardown before attaching, so the HTTP response times out while the
|
||||
* attach quietly succeeds afterwards. When the binding is later observed
|
||||
* alive and matching, the restart-required verdict was a false positive
|
||||
* and must be withdrawn — otherwise the manager keeps rejecting every
|
||||
* further bind locally while WeChat is actually bound and working.
|
||||
*/
|
||||
if (
|
||||
this.wechatRestartRequired &&
|
||||
(this.lastBinding.bound === true || this.lastBinding.bindingState === 'ready') &&
|
||||
this.lastBinding.boundWechatPid === this.lastBinding.wechatPid
|
||||
) {
|
||||
this.wechatRestartRequired = false
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'restart_required_withdrawn',
|
||||
details: { note: 'binding observed alive after bind timeout' }
|
||||
})
|
||||
}
|
||||
return this.lastBinding
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async getBindingStatus(): Promise<MacWechatBindingStatus | null> {
|
||||
if (this.lifecycle !== 'online') return this.lastBinding
|
||||
await this.refreshBinding().catch(() => null)
|
||||
return this.lastBinding
|
||||
}
|
||||
|
||||
/*
|
||||
* Build the legacy PersonalWechatSenderStatus contract from the live mac
|
||||
* runtime state. Lives here (not in the capability service) so BOTH the
|
||||
* capability mapping and the send path report the same facts without a
|
||||
* circular import.
|
||||
*/
|
||||
async buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
|
||||
/* Self-heal the status card too: if WeChat was restarted, drop the stale
|
||||
* restartRequired before it is read into the UI as an error. */
|
||||
try {
|
||||
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'runtime_artifact_unavailable',
|
||||
details: { detail }
|
||||
})
|
||||
const message = '暂无发送能力'
|
||||
this.manifest = null
|
||||
this.lastError = message
|
||||
return {
|
||||
state: 'runtime_missing',
|
||||
platform: 'darwin',
|
||||
arch: process.arch,
|
||||
sipDisabled: true,
|
||||
wechatRunning: false,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
endpointReady: false,
|
||||
runtimeReady: false,
|
||||
attachReady: false,
|
||||
baseAddressReady: false,
|
||||
textHookInstalled: false,
|
||||
textHookReady: false,
|
||||
imageHookInstalled: false,
|
||||
imageHookReady: false,
|
||||
messageListenerReady: false,
|
||||
canSend: false,
|
||||
canSendText: false,
|
||||
canSendImage: false,
|
||||
canSendVoice: false,
|
||||
message,
|
||||
error: message
|
||||
}
|
||||
}
|
||||
await this.clearRestartRequiredIfWechatRestarted()
|
||||
const snapshot = this.getSnapshot()
|
||||
const binding = await this.getBindingStatus()
|
||||
return deriveMacWechatSenderStatus({ snapshot, binding, manifest: this.manifest })
|
||||
}
|
||||
|
||||
/*
|
||||
* The orphan agent lives inside ONE specific WeChat process. If the WeChat
|
||||
* pid we recorded when restartRequired was raised no longer matches the
|
||||
* WeChat pid the host currently sees, WeChat has been restarted and the
|
||||
* orphan is gone — the flag must clear or every later bind is rejected
|
||||
* forever even though the user DID restart WeChat (the reported bug).
|
||||
*/
|
||||
private async clearRestartRequiredIfWechatRestarted(): Promise<void> {
|
||||
if (!this.wechatRestartRequired) return
|
||||
await this.refreshBinding().catch(() => null)
|
||||
const currentPid = this.lastBinding?.wechatPid ?? 0
|
||||
if (shouldClearWechatRestartRequired(this.orphanWechatPid, currentPid)) {
|
||||
this.wechatRestartRequired = false
|
||||
this.orphanWechatPid = 0
|
||||
if (this.lifecycle === 'crashed_bound') this.lifecycle = 'online'
|
||||
appLogger.write({
|
||||
level: 'info',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'restart_required_cleared_wechat_restarted',
|
||||
details: { currentWechatPid: currentPid }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicit user action only. Idempotent on the host side: binding the same
|
||||
* live WeChat pid again returns attached=false and never double-attaches.
|
||||
*/
|
||||
async bind(): Promise<MacWechatBindResult> {
|
||||
if (this.lifecycle !== 'online') {
|
||||
const snapshot = await this.ensureStarted()
|
||||
if (snapshot.lifecycle !== 'online') {
|
||||
return {
|
||||
ok: false,
|
||||
attached: false,
|
||||
state: 'runtime_offline',
|
||||
message: snapshot.error ?? 'Runtime 未在线,无法绑定'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Auto-clear if WeChat was restarted since the flag was raised —
|
||||
* otherwise this branch rejects every bind forever (the reported bug). */
|
||||
await this.clearRestartRequiredIfWechatRestarted()
|
||||
|
||||
if (this.wechatRestartRequired) {
|
||||
return {
|
||||
ok: false,
|
||||
attached: false,
|
||||
state: 'wechat_restart_required',
|
||||
message:
|
||||
'Previous WeChat send session was not fully released. ' + 'Restart WeChat and bind again.'
|
||||
}
|
||||
}
|
||||
|
||||
const { status, body } = await this.request('POST', '/bindWeChat')
|
||||
await this.refreshBinding().catch(() => null)
|
||||
|
||||
if (status !== 200) {
|
||||
return {
|
||||
ok: false,
|
||||
attached: false,
|
||||
state: 'host_error',
|
||||
message: `host 返回 HTTP ${status ?? '无响应'}`
|
||||
}
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(body) as MacWechatBindResult
|
||||
if (!parsed.ok && parsed.message?.includes('not fully released')) {
|
||||
this.wechatRestartRequired = true
|
||||
this.orphanWechatPid = this.lastBinding?.boundWechatPid || this.lastBinding?.wechatPid || 0
|
||||
appLogger.write({
|
||||
level: 'error',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'bind_hit_orphan_agent_wall',
|
||||
details: { note: 'WeChat restart required', orphanWechatPid: this.orphanWechatPid }
|
||||
})
|
||||
}
|
||||
return parsed
|
||||
} catch {
|
||||
return { ok: false, attached: false, state: 'bad_response', message: body.slice(0, 200) }
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 重新加载发送组件:优雅停掉当前 host 进程,再启动一个新实例。
|
||||
* 用于:更新二进制后换新代码;或 host 卡死时的手动恢复。
|
||||
* 注意:若当前 host 已绑定微信,此操作会让微信里留下孤儿 agent,
|
||||
* 需要重启微信后重新绑定(UI 会提示)。
|
||||
*/
|
||||
async reload(): Promise<MacWechatRuntimeSnapshot> {
|
||||
await this.shutdown().catch(() => undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 2_000))
|
||||
return this.ensureStarted()
|
||||
}
|
||||
|
||||
private isProcessAlive(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return false
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Graceful stop only. A bound host must never be force-killed: doing so can
|
||||
* leave its injected agent inside WeChat and make the next attach hang.
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
if (this.restartTimer) {
|
||||
clearTimeout(this.restartTimer)
|
||||
this.restartTimer = null
|
||||
}
|
||||
|
||||
if (this.lifecycle === 'stopped' && this.child === null) return
|
||||
|
||||
const reachable = await this.ping()
|
||||
if (!reachable && this.child === null) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastBinding = null
|
||||
return
|
||||
}
|
||||
|
||||
await this.refreshBinding().catch(() => null)
|
||||
const child = this.child
|
||||
const hostPid = this.lastBinding?.hostPid ?? 0
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = null
|
||||
|
||||
const response = await this.request('POST', '/shutdown', 5_000)
|
||||
if (response.status !== 200) {
|
||||
this.lifecycle = 'online'
|
||||
this.lastError = 'Native Runtime 未确认退出请求,已保留 host 以避免微信残留会话。'
|
||||
throw new Error(this.lastError)
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 55_000
|
||||
let transportClosedAt = 0
|
||||
while (Date.now() < deadline) {
|
||||
const childExited = child !== null && child.exitCode !== null
|
||||
const pidExited = hostPid > 0 && !this.isProcessAlive(hostPid)
|
||||
if (childExited || pidExited) {
|
||||
this.child = null
|
||||
this.lastBinding = null
|
||||
return
|
||||
}
|
||||
if (child === null && hostPid === 0) {
|
||||
const transportOpen = await this.ping()
|
||||
if (!transportOpen) {
|
||||
if (transportClosedAt === 0) transportClosedAt = Date.now()
|
||||
/* Compatibility with a pre-hostPid runtime during one upgrade:
|
||||
* its teardown waits at most 45s after closing the listen socket. */
|
||||
if (Date.now() - transportClosedAt >= 46_000) {
|
||||
this.lastBinding = null
|
||||
return
|
||||
}
|
||||
} else {
|
||||
transportClosedAt = 0
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 250))
|
||||
}
|
||||
|
||||
this.lastError = 'Native Runtime 安全退出超时;未强制结束绑定态 host,请先退出微信后再重试。'
|
||||
throw new Error(this.lastError)
|
||||
}
|
||||
}
|
||||
|
||||
export const macWechatRuntimeManager = new MacWechatRuntimeManager()
|
||||
@@ -7,15 +7,28 @@ import {
|
||||
personalWechatSendService,
|
||||
type PersonalWechatSendService
|
||||
} from './personal-wechat-send-service'
|
||||
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
|
||||
|
||||
/**
|
||||
* Converts the detailed sender diagnostics into a small contract that other
|
||||
* features can consume without knowing about OneBot, Hook or platform details.
|
||||
* features can consume without knowing about the macOS native runtime, the
|
||||
* Windows hook transport, or platform details.
|
||||
*
|
||||
* On macOS the capability is derived only from MacWechatRuntimeManager and its
|
||||
* validated runtime manifest. Windows continues to use the existing sender.
|
||||
*/
|
||||
export class PersonalWechatCapabilityService {
|
||||
constructor(private readonly sender: Pick<PersonalWechatSendService, 'getStatus'>) {}
|
||||
constructor(
|
||||
private readonly sender: Pick<PersonalWechatSendService, 'getStatus'>,
|
||||
private readonly platform: NodeJS.Platform = process.platform,
|
||||
private readonly getMacStatus: () => Promise<PersonalWechatSenderStatus> = () =>
|
||||
macWechatRuntimeManager.buildSenderStatus()
|
||||
) {}
|
||||
|
||||
async getPersonalWechatSendCapability(): Promise<PersonalWechatSendCapability> {
|
||||
if (this.platform === 'darwin') {
|
||||
return this.fromMacRuntime()
|
||||
}
|
||||
const senderStatus = await this.sender.getStatus()
|
||||
return this.fromSenderStatus(senderStatus)
|
||||
}
|
||||
@@ -49,6 +62,16 @@ export class PersonalWechatCapabilityService {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* macOS capability from the native runtime. Builds a senderStatus snapshot
|
||||
* aligned with the mac binding state and reuses the shared mapping, so the
|
||||
* settings header and the binding card can never disagree.
|
||||
*/
|
||||
private async fromMacRuntime(): Promise<PersonalWechatSendCapability> {
|
||||
const senderStatus = await this.getMacStatus()
|
||||
return this.fromSenderStatus(senderStatus)
|
||||
}
|
||||
|
||||
private mapState(senderStatus: PersonalWechatSenderStatus): PersonalWechatSendCapabilityState {
|
||||
if (senderStatus.platform === 'win32') {
|
||||
if (senderStatus.canSend) return 'ready'
|
||||
@@ -60,6 +83,7 @@ export class PersonalWechatCapabilityService {
|
||||
return 'unsupported'
|
||||
}
|
||||
if (senderStatus.state === 'error') return 'error'
|
||||
if (senderStatus.state === 'runtime_missing') return 'unconfigured'
|
||||
const hasCurrentBinding = Boolean(
|
||||
senderStatus.endpointReady &&
|
||||
senderStatus.attachReady &&
|
||||
|
||||
@@ -1,603 +0,0 @@
|
||||
import { createHash } from 'crypto'
|
||||
import { execFile } from 'child_process'
|
||||
import { app, net } from 'electron'
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs'
|
||||
import { chmod, copyFile, cp, mkdir, mkdtemp, open, rename, rm, stat } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { dirname, join } from 'path'
|
||||
import { promisify } from 'util'
|
||||
import type {
|
||||
PersonalWechatRuntimeDownloadResult,
|
||||
PersonalWechatRuntimeStatus
|
||||
} from '../../shared/personal-wechat-runtime'
|
||||
import { findPersonalWechatRuntime } from './personal-wechat-send-service'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const RUNTIME_VERSION = 'v0.0.18'
|
||||
const ARCHIVE_NAME = 'onebot_mac_arm64.tar.gz'
|
||||
const ARCHIVE_URL = `https://github.com/yincongcyincong/wechat_chatter/releases/download/${RUNTIME_VERSION}/${ARCHIVE_NAME}`
|
||||
const ARCHIVE_SIZE = 66_599_785
|
||||
const ARCHIVE_SHA256 = 'ee1e11bccef7cec1cf944cd8b2ac3fadaadb9376ba24cd823e3409143e107dab'
|
||||
|
||||
function patchPerSendPayload(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (!source.includes('var activeTriggerX1Payload = ptr(0);')) return
|
||||
|
||||
const activeSend = ` const payloadData = hexToByteArray(payloadHex);
|
||||
activeTriggerX1Payload = Memory.alloc(payloadData.length);
|
||||
activeTriggerX1Payload.writeByteArray(payloadData);
|
||||
activeTriggerX1Payload.add(0x18).writePointer(info.cgiAddr);
|
||||
activeTriggerX1Payload.add(0xb8).writePointer(activeTriggerX1Payload.add(0xc0));
|
||||
activeTriggerX1Payload.add(0x190).writePointer(activeTriggerX1Payload.add(0x198));`
|
||||
const upstreamSend = ` const payloadData = hexToByteArray(payloadHex);
|
||||
triggerX1Payload.writeByteArray(payloadData);
|
||||
triggerX1Payload.add(0x18).writePointer(info.cgiAddr);
|
||||
triggerX1Payload.add(0xb8).writePointer(triggerX1Payload.add(0xc0));
|
||||
triggerX1Payload.add(0x190).writePointer(triggerX1Payload.add(0x198));`
|
||||
if (!source.includes(activeSend)) {
|
||||
throw new Error('下载的发送组件与当前应用不兼容')
|
||||
}
|
||||
source = source.replace('var triggerX1Payload;\nvar activeTriggerX1Payload = ptr(0);\nvar triggerX0;', 'var triggerX1Payload;\nvar triggerX0;')
|
||||
.replace(activeSend, upstreamSend)
|
||||
.replace(' MMStartTask(triggerX0, activeTriggerX1Payload);', ' MMStartTask(triggerX0, triggerX1Payload);')
|
||||
.replace(' activeTriggerX1Payload = ptr(0);\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);', ' console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);')
|
||||
.replace('\t\t\t\tpendingSendMsgType = "";\n\t\t\t\tactiveTriggerX1Payload = ptr(0);\n\t\t\t\treturn', '\t\t\t\tpendingSendMsgType = "";\n\t\t\t\treturn')
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchSendContextCapture(scriptPath: string, strict = true): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('function isLikelySendContext(')) return
|
||||
const original = `function AttachSendFunc() {
|
||||
Interceptor.attach(sendFuncAddr.add(0x10), {
|
||||
onEnter: function (args) {
|
||||
|
||||
if (triggerX1Payload) {
|
||||
return
|
||||
}
|
||||
|
||||
triggerX0 = this.context.x0;
|
||||
triggerX1Payload = this.context.x1;
|
||||
console.log(\`[+] 捕获到 StartTask 调用,X0:\${triggerX0}, Payload: \${triggerX1Payload}\`);
|
||||
}
|
||||
})
|
||||
}`
|
||||
const patched = `function isLikelySendContext(candidateX0, candidateX1) {
|
||||
try {
|
||||
if (!isReadablePointer(candidateX0) || !isReadablePointer(candidateX1)) return false;
|
||||
var manager = readPointerIfReadable(candidateX0.add(0x18));
|
||||
var cgi = readUtf8StringIfReadable(readPointerIfReadable(candidateX1.add(0x18)));
|
||||
console.log("[debug] StartTask candidate x0=" + candidateX0 + " x1=" + candidateX1 + " x0+0x18=" + manager + " cgi=" + cgi);
|
||||
return !manager.equals(ptr(0));
|
||||
} catch (e) {
|
||||
console.error("[debug] StartTask candidate inspect failed: " + e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function AttachSendFunc() {
|
||||
Interceptor.attach(sendFuncAddr.add(0x10), {
|
||||
onEnter: function (args) {
|
||||
if (triggerX1Payload) return;
|
||||
var candidateX0 = this.context.x0;
|
||||
var candidateX1 = this.context.x1;
|
||||
if (!isLikelySendContext(candidateX0, candidateX1)) return;
|
||||
triggerX0 = candidateX0;
|
||||
triggerX1Payload = candidateX1;
|
||||
console.log(\`[+] 捕获到有效 StartTask 上下文,X0:\${triggerX0}, Payload: \${triggerX1Payload}\`);
|
||||
}
|
||||
})
|
||||
}`
|
||||
if (!source.includes(original)) {
|
||||
if (strict) throw new Error('下载的微信版本与当前应用不兼容')
|
||||
return
|
||||
}
|
||||
source = source.replace(original, patched)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchVoiceAudioBuffer(scriptPath: string, strict = true): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('voiceAudioDataAddr = Memory.alloc(audioLen + 1);')) return
|
||||
|
||||
const staticAllocation = 'voiceAudioDataAddr = Memory.alloc(5 * 1024 * 1024); // 预分配5MB'
|
||||
if (!source.includes(staticAllocation)) {
|
||||
if (strict) throw new Error('下载的语音组件与当前应用不兼容')
|
||||
return
|
||||
}
|
||||
source = source.replace(
|
||||
staticAllocation,
|
||||
'voiceAudioDataAddr = Memory.alloc(1); // 上传前按语音长度重新分配'
|
||||
)
|
||||
const audioLengthMarker = ' const audioLen = audioBytes.length;\n'
|
||||
if (!source.includes(audioLengthMarker)) {
|
||||
if (strict) throw new Error('下载的语音组件与当前应用不兼容')
|
||||
return
|
||||
}
|
||||
source = source.replace(
|
||||
audioLengthMarker,
|
||||
`${audioLengthMarker} voiceAudioDataAddr = Memory.alloc(audioLen + 1);\n`
|
||||
)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchImageHookReadiness(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (
|
||||
source.includes('捕获到图片上传上下文,uploadGlobalX0') &&
|
||||
source.includes('图片上传 Hook Setup Complete')
|
||||
) {
|
||||
return
|
||||
}
|
||||
const original = `\t\t\tuploadGlobalX0 = this.context.x0;`
|
||||
const patched = `\t\t\tconst capturedUploadX0 = this.context.x0;
|
||||
\t\t\tif (uploadGlobalX0.equals(ptr(0)) && !capturedUploadX0.equals(ptr(0))) {
|
||||
\t\t\t\tconsole.log("[+] 捕获到图片上传上下文,uploadGlobalX0:" + capturedUploadX0);
|
||||
\t\t\t}
|
||||
\t\t\tuploadGlobalX0 = capturedUploadX0;`
|
||||
if (!source.includes(original)) throw new Error('下载的媒体组件与当前应用不兼容')
|
||||
source = source.replace(original, patched)
|
||||
source = source.replace(
|
||||
' })\n}\n\n\n\nfunction patchCdnOnComplete()',
|
||||
' })\n console.log("[+] 图片上传 Hook Setup Complete.");\n}\n\n\n\nfunction patchCdnOnComplete()'
|
||||
)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchCdnColdStart(scriptPath: string, strict = true): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('function resolveCdnManager()')) return
|
||||
|
||||
const initAddresses = ` uploadImageAddr = baseAddr.add({{.uploadImageAddr}});
|
||||
cndOnCompleteAddr = baseAddr.add({{.cndOnCompleteAddr}});`
|
||||
const patchedInitAddresses = ` uploadImageAddr = baseAddr.add({{.uploadImageAddr}});
|
||||
cndOnCompleteAddr = baseAddr.add({{.cndOnCompleteAddr}});
|
||||
// 冷启动 CdnManager 解析(旧版本缺少可选键时保持 hook 捕获行为)
|
||||
{{if .cdnGetServiceAddr}}cdnGetServiceAddr = baseAddr.add({{.cdnGetServiceAddr}});{{end}}
|
||||
{{if .cdnManagerGetterAddr}}cdnManagerGetterAddr = baseAddr.add({{.cdnManagerGetterAddr}});{{end}}`
|
||||
if (!source.includes(initAddresses)) {
|
||||
if (strict) throw new Error('下载的微信版本配置与当前应用不兼容')
|
||||
return
|
||||
}
|
||||
source = source.replace(initAddresses, patchedInitAddresses)
|
||||
|
||||
const downloadChunkEnd = `}
|
||||
|
||||
function fillUploadX1AndStart`
|
||||
const resolver = `}
|
||||
|
||||
// 上传和下载共用同一个 mars::cdn::CdnManager。冷启动时通过服务定位器
|
||||
// 取得 [ctx + 0x40],避免必须先手动发送图片才能让 Hook 捕获上下文。
|
||||
function resolveCdnManager() {
|
||||
if (cdnGetServiceAddr.equals(ptr(0)) || cdnManagerGetterAddr.equals(ptr(0))) {
|
||||
return ptr(0);
|
||||
}
|
||||
try {
|
||||
// libc++ SSO 短字符串:数据在 +0,长度写在 +0x17。
|
||||
var strDefault = Memory.alloc(24);
|
||||
strDefault.writeUtf8String("default");
|
||||
strDefault.add(0x17).writeU8(7);
|
||||
|
||||
var getService = new NativeFunction(cdnGetServiceAddr, 'pointer', ['pointer']);
|
||||
var svc = getService(strDefault);
|
||||
if (!isReadablePointer(svc)) {
|
||||
console.error("[!] GetService(\\"default\\") 返回不可读: " + svc);
|
||||
return ptr(0);
|
||||
}
|
||||
var getCtx = new NativeFunction(cdnManagerGetterAddr, 'pointer', ['pointer']);
|
||||
var ctx = getCtx(svc);
|
||||
if (!isReadablePointer(ctx)) {
|
||||
console.error("[!] CdnManager getter 返回不可读: " + ctx);
|
||||
return ptr(0);
|
||||
}
|
||||
var mgr = readPointerIfReadable(ctx.add(0x40));
|
||||
if (!isReadablePointer(mgr)) {
|
||||
console.error("[!] ctx+0x40 管理器指针不可读: ctx=" + ctx);
|
||||
return ptr(0);
|
||||
}
|
||||
return mgr;
|
||||
} catch (e) {
|
||||
console.error("[!] resolveCdnManager 异常: " + e);
|
||||
return ptr(0);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureCdnManagerX0() {
|
||||
if (uploadGlobalX0.equals(ptr(0)) && downloadGlobalX0 && !downloadGlobalX0.equals(ptr(0))) {
|
||||
uploadGlobalX0 = downloadGlobalX0;
|
||||
console.log("[+] downloadGlobalX0 回填 uploadGlobalX0: " + uploadGlobalX0);
|
||||
}
|
||||
if ((!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) && !uploadGlobalX0.equals(ptr(0))) {
|
||||
downloadGlobalX0 = uploadGlobalX0;
|
||||
console.log("[+] uploadGlobalX0 回填 downloadGlobalX0: " + downloadGlobalX0);
|
||||
}
|
||||
if (uploadGlobalX0.equals(ptr(0))) {
|
||||
var mgr = resolveCdnManager();
|
||||
if (!mgr.equals(ptr(0))) {
|
||||
uploadGlobalX0 = mgr;
|
||||
if (!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) {
|
||||
downloadGlobalX0 = mgr;
|
||||
}
|
||||
console.log("[+] 冷启动服务定位器解析 CdnManager: " + mgr);
|
||||
}
|
||||
}
|
||||
return !uploadGlobalX0.equals(ptr(0));
|
||||
}
|
||||
|
||||
function fillUploadX1AndStart`
|
||||
if (!source.includes(downloadChunkEnd)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 媒体上传逻辑')
|
||||
return
|
||||
}
|
||||
source = source.replace(downloadChunkEnd, resolver)
|
||||
|
||||
const declarations = 'var uploadImageAddr;\n'
|
||||
const patchedDeclarations =
|
||||
'var uploadImageAddr;\nvar cdnGetServiceAddr = ptr(0);\nvar cdnManagerGetterAddr = ptr(0);\n'
|
||||
if (!source.includes(declarations)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 媒体地址声明')
|
||||
return
|
||||
}
|
||||
source = source.replace(declarations, patchedDeclarations)
|
||||
|
||||
const uploadGuard = `function fillUploadX1AndStart(idAddr, pathAddr, x1Buffer, receiver, md5, filePath, payloadHex) {
|
||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
||||
const patchedUploadGuard = `function fillUploadX1AndStart(idAddr, pathAddr, x1Buffer, receiver, md5, filePath, payloadHex) {
|
||||
if (uploadGlobalX0.equals(ptr(0))) {
|
||||
ensureCdnManagerX0();
|
||||
}
|
||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
||||
if (!source.includes(uploadGuard)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 媒体上传入口')
|
||||
return
|
||||
}
|
||||
source = source.replace(uploadGuard, patchedUploadGuard)
|
||||
|
||||
const voiceGuard = `function triggerUploadVoice(receiver, voicePath, payloadHex, audioDataHex, durationMs) {
|
||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
||||
const patchedVoiceGuard = `function triggerUploadVoice(receiver, voicePath, payloadHex, audioDataHex, durationMs) {
|
||||
if (uploadGlobalX0.equals(ptr(0))) {
|
||||
ensureCdnManagerX0();
|
||||
}
|
||||
if (uploadGlobalX0.equals(ptr(0))) {`
|
||||
if (!source.includes(voiceGuard)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 语音上传入口')
|
||||
return
|
||||
}
|
||||
source = source.replace(voiceGuard, patchedVoiceGuard)
|
||||
|
||||
const uploadHook = `\t\t\tuploadGlobalX0 = capturedUploadX0;`
|
||||
const patchedUploadHook = `\t\t\tuploadGlobalX0 = capturedUploadX0;
|
||||
if ((!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) && !capturedUploadX0.equals(ptr(0))) {
|
||||
downloadGlobalX0 = capturedUploadX0;
|
||||
console.log("[+] 上传hook回填 downloadGlobalX0: " + downloadGlobalX0);
|
||||
}`
|
||||
if (!source.includes(uploadHook)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 图片 Hook')
|
||||
return
|
||||
}
|
||||
source = source.replace(uploadHook, patchedUploadHook)
|
||||
|
||||
const downloadHook = ` downloadGlobalX0 = this.context.x0;`
|
||||
const patchedDownloadHook = ` downloadGlobalX0 = this.context.x0;
|
||||
if (uploadGlobalX0.equals(ptr(0)) && !downloadGlobalX0.equals(ptr(0))) {
|
||||
uploadGlobalX0 = downloadGlobalX0;
|
||||
console.log("[+] 下载hook回填 uploadGlobalX0: " + uploadGlobalX0);
|
||||
}`
|
||||
if (!source.includes(downloadHook)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 下载 Hook')
|
||||
return
|
||||
}
|
||||
source = source.replace(downloadHook, patchedDownloadHook)
|
||||
|
||||
const downloadGuard = `function triggerDownload(receiver, cdnUrl, aesKey, filePath, fileType) {
|
||||
if (!downloadGlobalX0) {`
|
||||
const patchedDownloadGuard = `function triggerDownload(receiver, cdnUrl, aesKey, filePath, fileType) {
|
||||
if (!downloadGlobalX0 || downloadGlobalX0.equals(ptr(0))) {
|
||||
ensureCdnManagerX0();
|
||||
}
|
||||
if (!downloadGlobalX0) {`
|
||||
if (!source.includes(downloadGuard)) {
|
||||
if (strict) throw new Error('无法定位 wechat_chatter 媒体下载入口')
|
||||
return
|
||||
}
|
||||
source = source.replace(downloadGuard, patchedDownloadGuard)
|
||||
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchCdnColdStartConfig(configPath: string, strict = true): void {
|
||||
let config: Record<string, unknown>
|
||||
try {
|
||||
config = JSON.parse(readFileSync(configPath, 'utf8')) as Record<string, unknown>
|
||||
} catch {
|
||||
if (strict) throw new Error('4.1.11.53 版本配置不是有效 JSON')
|
||||
return
|
||||
}
|
||||
config.cdnGetServiceAddr = '0x50a15d0'
|
||||
config.cdnManagerGetterAddr = '0x5259290'
|
||||
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`)
|
||||
}
|
||||
|
||||
function patchWechatCoreModuleBase(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('WeChat core module base:')) return
|
||||
const initMarker = 'function initAddresses() {'
|
||||
const initIndex = source.indexOf(initMarker)
|
||||
if (initIndex < 0 || !source.startsWith('var targetPath = ')) {
|
||||
throw new Error('下载的微信版本配置与当前应用不兼容')
|
||||
}
|
||||
const patchedHeader = `var targetPath = "/Applications/WeChat.app/Contents/Resources/wechat.dylib";
|
||||
var module = Process.enumerateModules().find(function(m) {
|
||||
return m.path === targetPath || m.path.endsWith("/Contents/Resources/wechat.dylib");
|
||||
});
|
||||
if (!module) {
|
||||
throw new Error("[-] Cannot find WeChat core module: " + targetPath);
|
||||
}
|
||||
var moduleBase = module.base;
|
||||
var baseAddr = moduleBase;
|
||||
console.log("[+] WeChat core module base: " + baseAddr + " path=" + module.path);
|
||||
setImmediate(initAddresses);
|
||||
|
||||
`
|
||||
source = patchedHeader + source.slice(initIndex)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function addModifiedWorkNotice(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('TraceMemo wechat_chatter compatibility modifications')) return
|
||||
source = `/*
|
||||
* TraceMemo wechat_chatter compatibility modifications
|
||||
* Modified: 2026-08-17
|
||||
* Upstream: https://github.com/yincongcyincong/wechat_chatter
|
||||
* Runtime version: v0.0.18
|
||||
* License: GNU General Public License version 3 (GPL-3.0)
|
||||
* Changes: WeChat module discovery, per-send payload isolation, dynamic voice upload buffers,
|
||||
* CdnManager cold-start resolution, media hook backfill, and image Hook readiness logging.
|
||||
* These modifications are not provided by the upstream author.
|
||||
*/
|
||||
|
||||
${source}`
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
export class PersonalWechatRuntimeManager {
|
||||
private downloadController: AbortController | null = null
|
||||
private downloadPromise: Promise<PersonalWechatRuntimeDownloadResult> | null = null
|
||||
private downloadedBytes = 0
|
||||
private lastProgressAt = 0
|
||||
private progressListener: ((status: PersonalWechatRuntimeStatus) => void) | null = null
|
||||
|
||||
get directory(): string {
|
||||
return join(app.getPath('userData'), 'connectors', 'wechat-personal', 'darwin-arm64')
|
||||
}
|
||||
|
||||
private get archivePath(): string {
|
||||
return join(
|
||||
app.getPath('userData'),
|
||||
'downloads',
|
||||
`wechat-chatter-${RUNTIME_VERSION}-${ARCHIVE_NAME}`
|
||||
)
|
||||
}
|
||||
|
||||
setProgressListener(listener: ((status: PersonalWechatRuntimeStatus) => void) | null): void {
|
||||
this.progressListener = listener
|
||||
}
|
||||
|
||||
async getStatus(): Promise<PersonalWechatRuntimeStatus> {
|
||||
if (!this.isSupported()) {
|
||||
return this.buildStatus(
|
||||
'unsupported',
|
||||
0,
|
||||
process.platform === 'darwin'
|
||||
? 'Intel Mac 不支持个人微信发送组件'
|
||||
: process.platform === 'win32'
|
||||
? 'Windows 暂不支持个人微信发送组件'
|
||||
: '当前系统不支持个人微信发送组件'
|
||||
)
|
||||
}
|
||||
if (this.downloadPromise) return this.buildStatus('downloading', this.downloadedBytes)
|
||||
|
||||
const runtime = findPersonalWechatRuntime()
|
||||
if (runtime) {
|
||||
try {
|
||||
// Apply compatibility fixes to runtimes installed before this version.
|
||||
patchWechatCoreModuleBase(join(runtime.workingDirectory, 'script.js'))
|
||||
patchPerSendPayload(join(runtime.workingDirectory, 'script.js'))
|
||||
patchSendContextCapture(join(runtime.workingDirectory, 'script.js'), false)
|
||||
patchVoiceAudioBuffer(join(runtime.workingDirectory, 'script.js'), false)
|
||||
patchImageHookReadiness(join(runtime.workingDirectory, 'script.js'))
|
||||
patchCdnColdStart(join(runtime.workingDirectory, 'script.js'), false)
|
||||
addModifiedWorkNotice(join(runtime.workingDirectory, 'script.js'))
|
||||
patchCdnColdStartConfig(join(runtime.root, 'wechat_version', '4_1_11_53_mac.json'), false)
|
||||
} catch {
|
||||
// Status discovery should remain available even if an old runtime is read-only.
|
||||
}
|
||||
return this.buildStatus('ready', ARCHIVE_SIZE, undefined, runtime.root)
|
||||
}
|
||||
|
||||
const hasPartialInstall = await this.hasPartialInstall()
|
||||
return this.buildStatus(
|
||||
hasPartialInstall ? 'invalid' : 'missing',
|
||||
0,
|
||||
hasPartialInstall ? '发送组件文件不完整,请重新下载' : undefined,
|
||||
hasPartialInstall ? this.directory : undefined
|
||||
)
|
||||
}
|
||||
|
||||
download(): Promise<PersonalWechatRuntimeDownloadResult> {
|
||||
if (!this.isSupported()) {
|
||||
return this.getStatus().then((status) => ({ success: false, status, error: status.error }))
|
||||
}
|
||||
if (this.downloadPromise) return this.downloadPromise
|
||||
this.downloadedBytes = 0
|
||||
this.downloadController = new AbortController()
|
||||
this.downloadPromise = this.runDownload(this.downloadController.signal).finally(() => {
|
||||
this.downloadPromise = null
|
||||
this.downloadController = null
|
||||
})
|
||||
return this.downloadPromise
|
||||
}
|
||||
|
||||
cancelDownload(): boolean {
|
||||
if (!this.downloadController) return false
|
||||
this.downloadController.abort()
|
||||
return true
|
||||
}
|
||||
|
||||
async remove(): Promise<PersonalWechatRuntimeStatus> {
|
||||
if (this.downloadPromise) return this.buildStatus('downloading', this.downloadedBytes)
|
||||
await Promise.all([
|
||||
rm(this.directory, { recursive: true, force: true }),
|
||||
rm(this.archivePath, { force: true }),
|
||||
rm(`${this.archivePath}.partial`, { force: true })
|
||||
])
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
private async runDownload(signal: AbortSignal): Promise<PersonalWechatRuntimeDownloadResult> {
|
||||
const archive = this.archivePath
|
||||
const downloadsDirectory = dirname(archive)
|
||||
const partial = `${archive}.partial`
|
||||
let extractionDirectory = ''
|
||||
let stagedDirectory = ''
|
||||
try {
|
||||
await mkdir(downloadsDirectory, { recursive: true })
|
||||
await rm(partial, { force: true })
|
||||
const response = await net.fetch(ARCHIVE_URL, { signal })
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`发送组件下载失败:HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
const handle = await open(partial, 'w')
|
||||
const hash = createHash('sha256')
|
||||
try {
|
||||
const reader = response.body.getReader()
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
if (signal.aborted) throw new DOMException('Download cancelled', 'AbortError')
|
||||
const chunk = Buffer.from(value)
|
||||
await handle.write(chunk)
|
||||
hash.update(chunk)
|
||||
this.downloadedBytes += chunk.length
|
||||
this.reportProgress(this.buildStatus('downloading', this.downloadedBytes))
|
||||
}
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
|
||||
if (this.downloadedBytes !== ARCHIVE_SIZE || hash.digest('hex') !== ARCHIVE_SHA256) {
|
||||
throw new Error('发送组件校验失败,请重新下载')
|
||||
}
|
||||
await rm(archive, { force: true })
|
||||
await rename(partial, archive)
|
||||
|
||||
extractionDirectory = await mkdtemp(join(tmpdir(), 'wechat-chatter-extract-'))
|
||||
await execFileAsync('/usr/bin/tar', ['-xzf', archive, '-C', extractionDirectory])
|
||||
stagedDirectory = `${this.directory}.installing-${process.pid}`
|
||||
await rm(stagedDirectory, { recursive: true, force: true })
|
||||
await mkdir(dirname(stagedDirectory), { recursive: true })
|
||||
await mkdir(join(stagedDirectory, 'onebot'), { recursive: true })
|
||||
|
||||
const sourceOneBot = join(extractionDirectory, 'onebot')
|
||||
const sourceVersions = join(extractionDirectory, 'wechat_version')
|
||||
await Promise.all([
|
||||
cp(sourceVersions, join(stagedDirectory, 'wechat_version'), {
|
||||
recursive: true,
|
||||
force: true
|
||||
}),
|
||||
copyFile(join(sourceOneBot, 'onebot'), join(stagedDirectory, 'onebot', 'onebot')),
|
||||
copyFile(join(sourceOneBot, 'script.js'), join(stagedDirectory, 'onebot', 'script.js'))
|
||||
])
|
||||
|
||||
const executable = join(stagedDirectory, 'onebot', 'onebot')
|
||||
const script = join(stagedDirectory, 'onebot', 'script.js')
|
||||
const configPath = join(stagedDirectory, 'wechat_version', '4_1_11_53_mac.json')
|
||||
patchCdnColdStartConfig(configPath)
|
||||
patchWechatCoreModuleBase(script)
|
||||
patchPerSendPayload(script)
|
||||
patchSendContextCapture(script)
|
||||
patchVoiceAudioBuffer(script)
|
||||
patchImageHookReadiness(script)
|
||||
patchCdnColdStart(script)
|
||||
addModifiedWorkNotice(script)
|
||||
await chmod(executable, 0o755)
|
||||
|
||||
for (const required of [
|
||||
executable,
|
||||
script,
|
||||
join(stagedDirectory, 'wechat_version', '4_1_11_53_mac.json')
|
||||
]) {
|
||||
if (!existsSync(required)) throw new Error('发送组件解压后文件不完整')
|
||||
}
|
||||
|
||||
await rm(this.directory, { recursive: true, force: true })
|
||||
await rename(stagedDirectory, this.directory)
|
||||
stagedDirectory = ''
|
||||
const status = this.buildStatus('ready', ARCHIVE_SIZE, undefined, this.directory)
|
||||
this.reportProgress(status, true)
|
||||
return { success: true, status }
|
||||
} catch (error) {
|
||||
const cancelled = signal.aborted
|
||||
const message = cancelled
|
||||
? '发送组件下载已取消'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
await rm(partial, { force: true })
|
||||
const status = this.buildStatus(
|
||||
cancelled ? 'missing' : 'error',
|
||||
this.downloadedBytes,
|
||||
message
|
||||
)
|
||||
this.reportProgress(status, true)
|
||||
return { success: false, status, error: message }
|
||||
} finally {
|
||||
if (extractionDirectory) await rm(extractionDirectory, { recursive: true, force: true })
|
||||
if (stagedDirectory) await rm(stagedDirectory, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async hasPartialInstall(): Promise<boolean> {
|
||||
try {
|
||||
await stat(this.directory)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private isSupported(): boolean {
|
||||
return process.platform === 'darwin' && process.arch === 'arm64'
|
||||
}
|
||||
|
||||
private buildStatus(
|
||||
state: PersonalWechatRuntimeStatus['state'],
|
||||
downloadedBytes: number,
|
||||
error?: string,
|
||||
directory?: string
|
||||
): PersonalWechatRuntimeStatus {
|
||||
return {
|
||||
version: RUNTIME_VERSION,
|
||||
state,
|
||||
downloadedBytes,
|
||||
totalBytes: ARCHIVE_SIZE,
|
||||
progress: ARCHIVE_SIZE ? Math.min(1, downloadedBytes / ARCHIVE_SIZE) : 0,
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
supported: this.isSupported(),
|
||||
removable: directory === this.directory,
|
||||
...(directory ? { directory } : {}),
|
||||
...(error ? { error } : {})
|
||||
}
|
||||
}
|
||||
|
||||
private reportProgress(status: PersonalWechatRuntimeStatus, force = false): void {
|
||||
const now = Date.now()
|
||||
if (!force && now - this.lastProgressAt < 100) return
|
||||
this.lastProgressAt = now
|
||||
this.progressListener?.(status)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,11 +7,8 @@ import type {
|
||||
PersonalWechatVoiceRuntimeComponent
|
||||
} from '../../shared/personal-wechat-voice-runtime'
|
||||
import { PERSONAL_WECHAT_PILK_VERSION } from '../../shared/personal-wechat-voice-runtime'
|
||||
import {
|
||||
buildPersonalWechatRuntimeEnvironment,
|
||||
findPersonalWechatRuntime
|
||||
} from './personal-wechat-send-service'
|
||||
import type { RuntimeLayout } from './personal-wechat-send-service'
|
||||
import { buildPersonalWechatRuntimeEnvironment } from './personal-wechat-send-service'
|
||||
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
|
||||
import { appLogger } from '../app-logger'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
@@ -37,8 +34,8 @@ type CommandRunner = (
|
||||
interface PersonalWechatVoiceEnvironmentServiceOptions {
|
||||
platform?: NodeJS.Platform
|
||||
architecture?: string
|
||||
findRuntime?: () => RuntimeLayout | null
|
||||
buildEnvironment?: (runtimeRoot?: string) => NodeJS.ProcessEnv
|
||||
isRuntimePresent?: () => boolean
|
||||
buildEnvironment?: () => NodeJS.ProcessEnv
|
||||
runCommand?: CommandRunner
|
||||
now?: () => Date
|
||||
}
|
||||
@@ -100,18 +97,26 @@ function unsupportedEnvironment(): PersonalWechatVoiceEncodingEnvironment {
|
||||
}
|
||||
}
|
||||
|
||||
function defaultIsRuntimePresent(): boolean {
|
||||
try {
|
||||
return macWechatRuntimeManager.isRuntimePresent()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export class PersonalWechatVoiceEnvironmentService {
|
||||
private readonly platform: NodeJS.Platform
|
||||
private readonly architecture: string
|
||||
private readonly findRuntime: () => RuntimeLayout | null
|
||||
private readonly buildEnvironment: (runtimeRoot?: string) => NodeJS.ProcessEnv
|
||||
private readonly isRuntimePresent: () => boolean
|
||||
private readonly buildEnvironment: () => NodeJS.ProcessEnv
|
||||
private readonly runCommand: CommandRunner
|
||||
private readonly now: () => Date
|
||||
|
||||
constructor(options: PersonalWechatVoiceEnvironmentServiceOptions = {}) {
|
||||
this.platform = options.platform || process.platform
|
||||
this.architecture = options.architecture || process.arch
|
||||
this.findRuntime = options.findRuntime || findPersonalWechatRuntime
|
||||
this.isRuntimePresent = options.isRuntimePresent || defaultIsRuntimePresent
|
||||
this.buildEnvironment = options.buildEnvironment || buildPersonalWechatRuntimeEnvironment
|
||||
this.runCommand = options.runCommand || runCommand
|
||||
this.now = options.now || (() => new Date())
|
||||
@@ -123,8 +128,8 @@ export class PersonalWechatVoiceEnvironmentService {
|
||||
}
|
||||
|
||||
logEnvironmentLine('Checking voice encoding environment')
|
||||
const runtime = this.findRuntime()
|
||||
const environment = this.buildEnvironment(runtime?.root)
|
||||
const runtimeReady = this.isRuntimePresent()
|
||||
const environment = this.buildEnvironment()
|
||||
const python = blankComponent()
|
||||
const pilk = blankComponent()
|
||||
const ffmpeg = blankComponent()
|
||||
@@ -197,26 +202,25 @@ export class PersonalWechatVoiceEnvironmentService {
|
||||
logEnvironmentWarning('ffmpeg: unavailable', { error: ffmpeg.error })
|
||||
}
|
||||
|
||||
const ready = Boolean(runtime && python.ready && pilk.ready && ffmpeg.ready)
|
||||
const ready = Boolean(runtimeReady && python.ready && pilk.ready && ffmpeg.ready)
|
||||
const result: PersonalWechatVoiceEncodingEnvironment = {
|
||||
state: ready ? 'ready' : 'incomplete',
|
||||
ready,
|
||||
checkedAt: this.now().toISOString(),
|
||||
runtimeReady: Boolean(runtime),
|
||||
...(runtime ? { runtimeRoot: runtime.root } : {}),
|
||||
runtimeReady,
|
||||
python,
|
||||
pilk,
|
||||
ffmpeg,
|
||||
encoder: pilk.ready
|
||||
? 'pilk'
|
||||
: runtime && python.ready && ffmpeg.ready
|
||||
? 'go-silk'
|
||||
: runtimeReady && python.ready && ffmpeg.ready
|
||||
? 'silk'
|
||||
: 'unavailable',
|
||||
message: ready
|
||||
? '语音编码环境正常,可以使用 pilk 编码'
|
||||
: runtime
|
||||
? '语音编码环境不完整,OneBot 可能回退到 go-silk'
|
||||
: '微信发送组件尚未安装,请先准备 OneBot 运行时'
|
||||
: runtimeReady
|
||||
? '语音编码环境不完整,语音将回退到内置 SILK 编码'
|
||||
: '当前版本暂未提供微信消息发送功能'
|
||||
}
|
||||
logEnvironmentLine(
|
||||
ready ? 'Voice encoding environment is ready' : 'Voice encoding environment is NOT ready',
|
||||
@@ -245,7 +249,7 @@ export class PersonalWechatVoiceEnvironmentService {
|
||||
pythonExecutable,
|
||||
['-m', 'pip', 'install', '--user', `pilk==${PERSONAL_WECHAT_PILK_VERSION}`],
|
||||
{
|
||||
env: this.buildEnvironment(before.runtimeRoot || undefined),
|
||||
env: this.buildEnvironment(),
|
||||
timeout: INSTALL_TIMEOUT_MS
|
||||
}
|
||||
)
|
||||
|
||||
@@ -39,9 +39,8 @@ export interface AppSettings {
|
||||
showStartupProgress: boolean
|
||||
ttsSelectedVoiceId: string
|
||||
ttsModel: TextToSpeechModel
|
||||
/** Keep a running personal-WeChat OneBot process across app restarts. */
|
||||
keepPersonalWechatProcess?: boolean
|
||||
windowsWechatPort: string
|
||||
reportImagePostfixText: string
|
||||
/**
|
||||
* Query Agent 是否为桌面「问问微信」与 Agent Hub 查询类问题的主路径。
|
||||
* 默认开启;关闭后回退到 Legacy AI Search Pipeline(仅作 runtime regression 时的回退开关,
|
||||
@@ -130,8 +129,8 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
showStartupProgress: true,
|
||||
ttsSelectedVoiceId: '',
|
||||
ttsModel: 's2.1-pro-free',
|
||||
keepPersonalWechatProcess: false,
|
||||
windowsWechatPort: '',
|
||||
reportImagePostfixText: '今日日报',
|
||||
queryAgentEnabled: true
|
||||
}
|
||||
|
||||
@@ -150,7 +149,10 @@ export function loadSettings(): AppSettings {
|
||||
if (cache) return cache
|
||||
try {
|
||||
if (fs.existsSync(SETTINGS_FILE)) {
|
||||
const raw = fs.readJsonSync(SETTINGS_FILE) as Partial<AppSettings>
|
||||
const stored = fs.readJsonSync(SETTINGS_FILE) as Partial<AppSettings> & {
|
||||
keepPersonalWechatProcess?: unknown
|
||||
}
|
||||
const { keepPersonalWechatProcess: retiredKeepProcess, ...raw } = stored
|
||||
cache = { ...DEFAULT_SETTINGS, ...raw }
|
||||
if (raw.autoLogin === undefined) {
|
||||
const hasSavedDatabaseKey = fs.existsSync(
|
||||
@@ -176,7 +178,7 @@ export function loadSettings(): AppSettings {
|
||||
}
|
||||
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
|
||||
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
|
||||
if (cache.recallProtectionEnabled) {
|
||||
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
|
||||
cache.recallProtectionEnabled = false
|
||||
saveSettings(cache)
|
||||
}
|
||||
@@ -192,7 +194,11 @@ export function loadSettings(): AppSettings {
|
||||
export function saveSettings(next: AppSettings): AppSettings {
|
||||
// 防撤回已下线:所有写入路径(含 settings:set 补丁)统一收敛为 false,
|
||||
// 避免遗留入口或旧版本把它重新打开。
|
||||
cache = { ...next, recallProtectionEnabled: false }
|
||||
const sanitized = { ...next } as AppSettings & {
|
||||
keepPersonalWechatProcess?: unknown
|
||||
}
|
||||
delete sanitized.keepPersonalWechatProcess
|
||||
cache = { ...sanitized, recallProtectionEnabled: false }
|
||||
try {
|
||||
ensureDir()
|
||||
fs.writeJsonSync(SETTINGS_FILE, cache, { spaces: 2 })
|
||||
|
||||
@@ -30,9 +30,22 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
|
||||
// `AUTOMATION_SEND_PURPOSE` 保持一致,否则会被下面 evaluateWechatActionPolicy
|
||||
// 以 ACTION_NOT_ALLOWED 拦下 —— 那是有意的闸门,不是 bug。
|
||||
'automation_reply',
|
||||
'automation_report'
|
||||
'automation_report',
|
||||
'manual_report_image',
|
||||
'manual_report_postfix'
|
||||
])
|
||||
|
||||
export interface ReportImageSequenceRequest {
|
||||
recipient: WechatActionRequest['recipient']
|
||||
imagePath: string
|
||||
postfixText: string
|
||||
}
|
||||
|
||||
export interface ReportImageSequenceResult {
|
||||
image: WechatActionResult
|
||||
postfix?: WechatActionResult
|
||||
}
|
||||
|
||||
export interface WechatActionGatewayDependencies {
|
||||
getCapability?: () => Promise<PersonalWechatSendCapability>
|
||||
send?: (request: PersonalWechatSendRequest) => Promise<PersonalWechatSendResult>
|
||||
@@ -111,6 +124,35 @@ export class WechatActionGateway {
|
||||
this.memberEvents.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户确认后的日报发送序列。两步都进入 automation 发送队列,从而复用既有 3 秒间隔;
|
||||
* 后置词 action 只在图片明确 sent 后创建,图片失败/blocked 时严格短路。
|
||||
*/
|
||||
async executeReportImageSequence(
|
||||
request: ReportImageSequenceRequest
|
||||
): Promise<ReportImageSequenceResult> {
|
||||
const image = await this.execute({
|
||||
origin: 'user_manual',
|
||||
purpose: 'manual_report_image',
|
||||
triggerType: 'automation',
|
||||
recipient: request.recipient,
|
||||
content: { type: 'image', path: String(request.imagePath || '') }
|
||||
})
|
||||
if (image.status !== 'sent') return { image }
|
||||
|
||||
const postfixText = String(request.postfixText || '').trim()
|
||||
if (!postfixText) return { image }
|
||||
|
||||
const postfix = await this.execute({
|
||||
origin: 'user_manual',
|
||||
purpose: 'manual_report_postfix',
|
||||
triggerType: 'automation',
|
||||
recipient: request.recipient,
|
||||
content: { type: 'text', text: postfixText }
|
||||
})
|
||||
return { image, postfix }
|
||||
}
|
||||
|
||||
listAuditRecords(): WechatActionAuditRecord[] {
|
||||
return this.loadAuditState().records.map((record) => ({ ...record }))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user