fix: 完善微信发送运行时状态识别

This commit is contained in:
Wxw-Gu committed 2026-10-29 17:16:44 +08:00
1 parent d6d837e6f6
commit 84737a7407
7 files changed
+43 -278

No files matched your search

@@ -66,6 +66,16 @@ export function deriveMacWechatSenderStatus({
}: MacWechatSenderStatusInput): PersonalWechatSenderStatus {
const identityMatches = binding !== null && bindingMatchesRuntimeManifest(binding, manifest)
const stale = binding?.bindingState === 'stale'
const versionCapabilities = binding?.wechatVersion
? manifest.capabilitiesByVersion?.[binding.wechatVersion]
: undefined
const nativeMechanism = versionCapabilities?.textMechanism === 'native-msg-object'
const nativeBindingReady =
identityMatches &&
nativeMechanism &&
binding?.runtimeState === 'ready' &&
binding.sessionAttached &&
binding.scriptLoaded
let state: PersonalWechatSenderStatus['state'] = 'stopped'
let message = '正在初始化微信发送能力'
@@ -78,12 +88,17 @@ export function deriveMacWechatSenderStatus({
} else if (binding && !binding.wechatRunning) {
state = 'wechat_not_running'
message = '微信未运行'
} else if (binding?.bindingState === 'ready') {
} else if (binding?.runtimeState === 'unsupported_version') {
state = 'error'
message = binding.wechatVersion
? `当前微信版本是 ${binding.wechatVersion},不在支持列表`
: '当前微信版本不在支持列表'
} else if (binding?.bindingState === 'ready' || nativeBindingReady) {
state = 'online'
message = '个人微信已准备好发送日报'
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
state = 'hook_not_ready'
message = '已绑定,等待捕获微信发送上下文'
message = nativeMechanism ? '已绑定,等待原生发送 hook 就绪' : '已绑定,等待捕获微信发送上下文'
} else if (stale) {
state = 'stopped'
message = '检测到微信已重启,请重新绑定'
@@ -96,13 +111,20 @@ export function deriveMacWechatSenderStatus({
}
const runtimeCapabilities = new Set(manifest.capabilities)
const bindingReady = identityMatches && state === 'online' && binding?.sendContextReady === true
const supportsCapability = (name: 'text' | 'image' | 'voice'): boolean => {
if (manifest.capabilitiesByVersion) return versionCapabilities?.[name] === 'verified'
return runtimeCapabilities.has(name)
}
const bindingReady =
identityMatches &&
state === 'online' &&
(binding?.sendContextReady === true || nativeBindingReady)
const canSendText =
bindingReady && runtimeCapabilities.has('text') && binding?.canSendText === true
bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage =
bindingReady && runtimeCapabilities.has('image') && binding?.canSendImage === true
bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice =
bindingReady && runtimeCapabilities.has('voice') && binding?.canSendVoice === true
bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -159,7 +181,6 @@ class MacWechatRuntimeManager {
endpoint: `http://${HOST}:${PORT}`,
port: PORT,
runtimeDir: this.resolveRuntimeDir(),
manifest: this.manifest ?? undefined,
error: this.lastError ?? undefined,
binding: this.lastBinding ?? undefined
}
@@ -450,7 +471,11 @@ class MacWechatRuntimeManager {
const { status, body } = await this.request('GET', '/bindingStatus')
if (status !== 200) return null
try {
this.lastBinding = JSON.parse(body) as MacWechatBindingStatus
const binding = JSON.parse(body) as MacWechatBindingStatus & {
supportedVersions?: string
}
delete binding.supportedVersions
this.lastBinding = binding
/*
* 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
+10 -2
View File
@@ -45,6 +45,16 @@ export interface MacWechatRuntimeManifest {
addressProfileSha256: string
supportedWechatVersions: string[]
capabilities: Array<'text' | 'image' | 'voice'>
capabilitiesByVersion?: Record<
string,
{
text?: 'verified' | 'addresses-only' | 'unsupported'
image?: 'verified' | 'addresses-only' | 'unsupported'
voice?: 'verified' | 'addresses-only' | 'unsupported'
downloadImage?: 'verified' | 'addresses-only' | 'unsupported'
textMechanism?: string
}
>
}
export interface MacWechatBindingStatus {
@@ -60,7 +70,6 @@ export interface MacWechatBindingStatus {
wechatPid: number
wechatVersion?: string
supported: boolean
supportedVersions?: string
bindingState: MacWechatBindingState
bound: boolean
boundWechatPid: number
@@ -82,7 +91,6 @@ export interface MacWechatRuntimeSnapshot {
endpoint: string
port: number
runtimeDir?: string
manifest?: MacWechatRuntimeManifest
error?: string
binding?: MacWechatBindingStatus
}
@@ -41,7 +41,6 @@ const readyStatus = {
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
@@ -23,7 +23,6 @@ const senderStatus = {
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
-1
View File
@@ -663,7 +663,6 @@ handle('wechat-personal:getStatus', () => ({
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
@@ -1,127 +0,0 @@
import { createRequire } from 'module'
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { describe, expect, it } from 'vitest'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
} from '../../src/main/services/mac-wechat-runtime-artifact'
const nodeRequire = createRequire(import.meta.url)
const { readAndValidateArtifact, syncArtifact } = nodeRequire(
'../../scripts/prepare-wechat-native-runtime.cjs'
) as {
readAndValidateArtifact: (sourceDir: string) => { manifest: { tmSendSourceSha256: string } }
syncArtifact: (sourceDir: string, targetDir: string) => unknown
}
const AGENT_HASH = 'a'.repeat(64)
const ADDRESS_PROFILE_HASH = 'b'.repeat(64)
function writeMachOArm64(filePath: string, suffix = Buffer.alloc(0)): void {
const header = Buffer.alloc(32)
header.writeUInt32LE(0xfeedfacf, 0)
header.writeUInt32LE(0x0100000c, 4)
writeFileSync(filePath, Buffer.concat([header, suffix]))
}
function createArtifact(root: string): void {
writeMachOArm64(join(root, 'tm-wechat-host'))
writeMachOArm64(
join(root, 'libtmwechat.dylib'),
Buffer.from(`${AGENT_HASH}${ADDRESS_PROFILE_HASH}`)
)
writeFileSync(
join(root, 'runtime-manifest.json'),
JSON.stringify({
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: ADDRESS_PROFILE_HASH,
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
})
)
}
describe('macOS self-contained WeChat runtime artifact', () => {
it('validates the manifest, architecture, capabilities and embedded agent identity', () => {
const root = mkdtempSync(join(tmpdir(), 'tm-native-runtime-'))
createArtifact(root)
const manifest = readMacWechatRuntimeManifest(root, 'arm64')
expect(manifest.tmSendSourceSha256).toBe(AGENT_HASH)
expect(
bindingMatchesRuntimeManifest(
{
hostPid: 123,
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH,
embeddedAddressProfileSha256: ADDRESS_PROFILE_HASH
},
manifest
)
).toBe(true)
expect(
bindingMatchesRuntimeManifest(
{ hostPid: 123, runtimeVersion: 'tm-wechat-runtime/0.1.0' },
manifest
)
).toBe(false)
expect(
bindingMatchesRuntimeManifest(
{
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH
},
manifest
)
).toBe(false)
})
it('rejects a manifest whose embedded address profile hash is absent from the dylib', () => {
const root = mkdtempSync(join(tmpdir(), 'tm-native-runtime-profile-mismatch-'))
createArtifact(root)
writeFileSync(
join(root, 'runtime-manifest.json'),
JSON.stringify({
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: 'c'.repeat(64),
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
})
)
expect(() => readMacWechatRuntimeManifest(root, 'arm64')).toThrow(/address profile hash/)
})
it('prepares an exact runtime tree and removes old external agent and table directories', () => {
const source = mkdtempSync(join(tmpdir(), 'tm-native-source-'))
const target = mkdtempSync(join(tmpdir(), 'tm-native-target-parent-'))
const targetRuntime = join(target, 'darwin-arm64')
createArtifact(source)
mkdirSync(join(targetRuntime, 'scripts'), { recursive: true })
writeFileSync(join(targetRuntime, 'scripts', 'tm_send.js'), 'old external agent')
mkdirSync(join(targetRuntime, 'wechat_version'), { recursive: true })
writeFileSync(join(targetRuntime, 'wechat_version', '4_1_11_53_mac.json'), '{}')
expect(readAndValidateArtifact(source).manifest.tmSendSourceSha256).toBe(AGENT_HASH)
syncArtifact(source, targetRuntime)
expect(existsSync(join(targetRuntime, 'scripts'))).toBe(false)
expect(existsSync(join(targetRuntime, 'wechat_version'))).toBe(false)
expect(existsSync(join(targetRuntime, 'runtime-manifest.json'))).toBe(true)
expect(readAndValidateArtifact(targetRuntime).manifest.tmSendSourceSha256).toBe(AGENT_HASH)
})
})
@@ -1,138 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({
app: {
getAppPath: () => '/fixture/app',
isPackaged: false
}
}))
import {
deriveMacWechatSenderStatus,
shouldClearWechatRestartRequired
} from '../../src/main/services/mac-wechat-runtime-manager'
import type {
MacWechatBindingStatus,
MacWechatRuntimeManifest,
MacWechatRuntimeSnapshot
} from '../../src/shared/personal-wechat-mac-runtime'
const AGENT_HASH = 'a'.repeat(64)
const ADDRESS_PROFILE_HASH = 'b'.repeat(64)
const manifest: MacWechatRuntimeManifest = {
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: ADDRESS_PROFILE_HASH,
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
}
function snapshot(overrides: Partial<MacWechatRuntimeSnapshot> = {}): MacWechatRuntimeSnapshot {
return {
lifecycle: 'online',
wechatRestartRequired: false,
endpoint: 'http://127.0.0.1:4290',
port: 4290,
manifest,
...overrides
}
}
function binding(overrides: Partial<MacWechatBindingStatus> = {}): MacWechatBindingStatus {
return {
runtime: true,
hostPid: 123,
runtimeState: 'ready',
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH,
embeddedAddressProfileSha256: ADDRESS_PROFILE_HASH,
wechatRunning: true,
wechatPid: 456,
wechatVersion: '4.1.11.53',
supported: true,
bindingState: 'ready',
bound: true,
boundWechatPid: 456,
sessionAttached: true,
scriptLoaded: true,
sendContextReady: true,
canSendText: true,
canSendImage: true,
canSendVoice: true,
attachCount: 1,
...overrides
}
}
describe('macOS native runtime sender status mapping', () => {
it('exposes capabilities only for a ready binding with matching runtime identity', () => {
expect(
deriveMacWechatSenderStatus({ snapshot: snapshot(), binding: binding(), manifest })
).toMatchObject({
state: 'online',
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
messageListenerReady: true,
canSend: true,
canSendText: true,
canSendImage: true,
canSendVoice: true
})
})
it('rejects a live host whose embedded runtime identity does not match the manifest', () => {
const status = deriveMacWechatSenderStatus({
snapshot: snapshot(),
binding: binding({ embeddedAgentSha256: 'b'.repeat(64) }),
manifest
})
expect(status).toMatchObject({
state: 'error',
runtimeReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false
})
expect(status.error).toContain('Native Runtime 不一致')
})
it('maps a stale binding to a rebind-required stopped state', () => {
expect(
deriveMacWechatSenderStatus({
snapshot: snapshot(),
binding: binding({ bindingState: 'stale', sendContextReady: false }),
manifest
})
).toMatchObject({
state: 'stopped',
message: '检测到微信已重启,请重新绑定',
canSend: false
})
})
it('keeps restart-required errors above otherwise ready binding state', () => {
expect(
deriveMacWechatSenderStatus({
snapshot: snapshot({ wechatRestartRequired: true }),
binding: binding(),
manifest
})
).toMatchObject({ state: 'error', canSend: false })
})
it('clears restart-required only after WeChat has a different positive pid', () => {
expect(shouldClearWechatRestartRequired(100, 200)).toBe(true)
expect(shouldClearWechatRestartRequired(100, 100)).toBe(false)
expect(shouldClearWechatRestartRequired(0, 200)).toBe(false)
expect(shouldClearWechatRestartRequired(100, 0)).toBe(false)
})
})