mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 发送支持群聊@成员
生命周期整理 清理残留整理 完善skill
This commit is contained in:
1 parent
804466aad8
commit
5d4ba73771
28 files changed
+1214
-103
No files matched your search
@@ -127,14 +127,16 @@ function buildRunner(options: {
|
||||
|
||||
const run = (
|
||||
runner: AutomationActionRunner,
|
||||
rule: AutomationRule
|
||||
rule: AutomationRule,
|
||||
triggerSender?: { wxid: string; displayName: string }
|
||||
): Promise<Awaited<ReturnType<AutomationActionRunner['run']>>> =>
|
||||
runner.run({
|
||||
executionId: EXECUTION_ID,
|
||||
rule,
|
||||
conversationId: GROUP_ID,
|
||||
isGroup: true,
|
||||
sourceDisplayName: '测试群'
|
||||
sourceDisplayName: '测试群',
|
||||
...(triggerSender ? { triggerSender } : {})
|
||||
})
|
||||
|
||||
const statusOf = (
|
||||
@@ -145,7 +147,10 @@ const statusOf = (
|
||||
describe('AutomationActionRunner', () => {
|
||||
it('按 收到消息 → 规则匹配 → 回复确认 → 生成日报 → 发送图片 的顺序执行', async () => {
|
||||
const { runner, calls, reports } = buildRunner({})
|
||||
const result = await run(runner, makeRule())
|
||||
const result = await run(runner, makeRule(), {
|
||||
wxid: 'wxid_fixture_sender',
|
||||
displayName: '测试成员'
|
||||
})
|
||||
|
||||
expect(result.status).toBe('success')
|
||||
expect(result.pngPath).toBe('/tmp/report.png')
|
||||
@@ -167,13 +172,21 @@ describe('AutomationActionRunner', () => {
|
||||
// 先回文字,再发图片 —— 顺序反了用户会先收到图再收到"正在生成"。
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(calls[0].content.type).toBe('text')
|
||||
expect(calls[0].content).toMatchObject({
|
||||
type: 'text',
|
||||
at: { wxid_fixture_sender: '测试成员' }
|
||||
})
|
||||
expect(calls[1].content.type).toBe('image')
|
||||
expect(calls[1].content).not.toHaveProperty('at')
|
||||
expect(reports).toEqual([{ group: GROUP_ID, range: 'today' }])
|
||||
})
|
||||
|
||||
it('每一步都带独立的起止时间与耗时', async () => {
|
||||
const { runner } = buildRunner({})
|
||||
const result = await run(runner, makeRule())
|
||||
const result = await run(runner, makeRule(), {
|
||||
wxid: 'wxid_fixture_sender',
|
||||
displayName: '测试成员'
|
||||
})
|
||||
for (const step of result.steps) {
|
||||
expect(step.startedAt).toBeTypeOf('number')
|
||||
expect(step.finishedAt).toBeTypeOf('number')
|
||||
@@ -365,8 +378,36 @@ describe('AutomationActionRunner', () => {
|
||||
action.type === 'replyText' ? { ...action, text: ' ' } : action
|
||||
)
|
||||
})
|
||||
await run(runner, rule)
|
||||
expect(calls[0].content).toEqual({ type: 'text', text: '收到,正在生成今日日报' })
|
||||
await run(runner, rule, { wxid: 'wxid_fixture_sender', displayName: '测试成员' })
|
||||
expect(calls[0].content).toMatchObject({
|
||||
type: 'text',
|
||||
text: '收到,正在生成今日日报',
|
||||
at: { wxid_fixture_sender: '测试成员' }
|
||||
})
|
||||
})
|
||||
|
||||
it('没有可用的触发者昵称时,确认回复不猜测 @ 对象', async () => {
|
||||
const { runner, calls } = buildRunner({})
|
||||
await run(runner, makeRule())
|
||||
|
||||
expect(calls[0].content).toEqual({
|
||||
type: 'text',
|
||||
text: '收到,正在生成今日日报'
|
||||
})
|
||||
})
|
||||
|
||||
it('自定义规则确认回复不附加 @', async () => {
|
||||
const { runner, calls } = buildRunner({})
|
||||
const rule = makeRule((item) => {
|
||||
item.id = 'fixture-custom-rule'
|
||||
})
|
||||
|
||||
await run(runner, rule, { wxid: 'wxid_fixture_sender', displayName: '测试成员' })
|
||||
|
||||
expect(calls[0].content).toEqual({
|
||||
type: 'text',
|
||||
text: '收到,正在生成今日日报'
|
||||
})
|
||||
})
|
||||
|
||||
it('私聊场景下收件人类型是联系人', async () => {
|
||||
@@ -390,6 +431,7 @@ describe('AutomationActionRunner', () => {
|
||||
type: 'contact',
|
||||
id: 'wxid_friend'
|
||||
})
|
||||
expect(executeAction.mock.calls[0][0].content).not.toHaveProperty('at')
|
||||
})
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ function createDependencies(
|
||||
return {
|
||||
platform: 'darwin',
|
||||
listWechatPids: vi.fn(async () => [101]),
|
||||
listHostPids: vi.fn(async () => []),
|
||||
listPortPids: vi.fn(async () => [202]),
|
||||
processName: vi.fn(async (pid) => (pid === 101 ? 'WeChat' : 'tm-wechat-host')),
|
||||
processIdentity: vi.fn(async (pid) => 'identity-' + pid),
|
||||
@@ -45,6 +46,24 @@ describe('macOS WeChat residual cleanup', () => {
|
||||
expect(dependencies.processName).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('lists every TraceMemo Host, including hosts that do not own port 4290', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
listHostPids: vi.fn(async () => [303]),
|
||||
listPortPids: vi.fn(async () => []),
|
||||
processName: vi.fn(async () => 'tm-wechat-host')
|
||||
})
|
||||
|
||||
await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([
|
||||
{
|
||||
pid: 303,
|
||||
name: 'tm-wechat-host',
|
||||
targets: ['host'],
|
||||
confirmationToken: 'identity-303'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('does not signal a PID whose process identity changed after confirmation', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { MacWechatRuntimeManifestCache } from '../../src/main/services/mac-wechat-runtime-artifact'
|
||||
|
||||
const directories: string[] = []
|
||||
const AGENT_HASH = 'a'.repeat(64)
|
||||
const PROFILE_HASH = 'b'.repeat(64)
|
||||
const FIXTURE_WECHAT_VERSION = 'fixture-wechat-version'
|
||||
|
||||
function createRuntimeDirectory(version: string): string {
|
||||
const runtimeDir = mkdtempSync(join(tmpdir(), 'tracememo-runtime-cache-'))
|
||||
directories.push(runtimeDir)
|
||||
const manifest = {
|
||||
runtime: 'tm-wechat-native',
|
||||
version,
|
||||
platform: 'darwin-arm64',
|
||||
architecture: 'arm64',
|
||||
protocolVersion: 1,
|
||||
tmSendSourceSha256: AGENT_HASH,
|
||||
addressProfileSha256: PROFILE_HASH,
|
||||
supportedWechatVersions: [FIXTURE_WECHAT_VERSION],
|
||||
capabilities: ['text', 'image', 'voice']
|
||||
}
|
||||
writeFileSync(join(runtimeDir, 'runtime-manifest.json'), JSON.stringify(manifest))
|
||||
writeFileSync(join(runtimeDir, 'tm-wechat-host'), Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01]))
|
||||
writeFileSync(join(runtimeDir, 'libtmwechat.dylib'), Buffer.concat([
|
||||
Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01]),
|
||||
Buffer.from(AGENT_HASH + PROFILE_HASH)
|
||||
]))
|
||||
return runtimeDir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('MacWechatRuntimeManifestCache', () => {
|
||||
it('reuses the validated manifest while all runtime artifacts remain unchanged', () => {
|
||||
const runtimeDir = createRuntimeDirectory('0.3.0')
|
||||
const cache = new MacWechatRuntimeManifestCache()
|
||||
const first = cache.read(runtimeDir, 'arm64')
|
||||
const second = cache.read(runtimeDir, 'arm64')
|
||||
expect(second).toBe(first)
|
||||
})
|
||||
|
||||
it('revalidates when a runtime artifact changes', () => {
|
||||
const runtimeDir = createRuntimeDirectory('0.3.0')
|
||||
const cache = new MacWechatRuntimeManifestCache()
|
||||
cache.read(runtimeDir, 'arm64')
|
||||
writeFileSync(join(runtimeDir, 'runtime-manifest.json'), JSON.stringify({
|
||||
runtime: 'tm-wechat-native',
|
||||
version: '0.3.1',
|
||||
platform: 'darwin-arm64',
|
||||
architecture: 'arm64',
|
||||
protocolVersion: 1,
|
||||
tmSendSourceSha256: AGENT_HASH,
|
||||
addressProfileSha256: PROFILE_HASH,
|
||||
supportedWechatVersions: [FIXTURE_WECHAT_VERSION],
|
||||
capabilities: ['text', 'image', 'voice']
|
||||
}))
|
||||
expect(cache.read(runtimeDir, 'arm64').version).toBe('0.3.1')
|
||||
})
|
||||
|
||||
it('does not return a cached manifest after an artifact disappears', () => {
|
||||
const runtimeDir = createRuntimeDirectory('0.3.0')
|
||||
const cache = new MacWechatRuntimeManifestCache()
|
||||
cache.read(runtimeDir, 'arm64')
|
||||
rmSync(join(runtimeDir, 'tm-wechat-host'))
|
||||
expect(() => cache.read(runtimeDir, 'arm64')).toThrow(/tm-wechat-host missing/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,220 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
deriveMacWechatSenderStatus,
|
||||
MacWechatRuntimeManager,
|
||||
resolveMacWechatSendMechanism
|
||||
} from '../../src/main/services/mac-wechat-runtime-manager'
|
||||
import type {
|
||||
MacWechatBindingStatus,
|
||||
MacWechatRuntimeManifest,
|
||||
MacWechatRuntimeSnapshot
|
||||
} from '../../src/shared/personal-wechat-mac-runtime'
|
||||
|
||||
const AGENT_HASH = 'a'.repeat(64)
|
||||
const PROFILE_HASH = 'b'.repeat(64)
|
||||
const MESSAGE_SOURCE_WECHAT_VERSION = 'fixture-message-source-version'
|
||||
const NATIVE_OBJECT_WECHAT_VERSION = 'fixture-native-object-version'
|
||||
const LEGACY_WECHAT_VERSION = 'fixture-legacy-version'
|
||||
|
||||
function manifest(wechatVersion: string, textMechanism: string): MacWechatRuntimeManifest {
|
||||
return {
|
||||
runtime: 'tm-wechat-native',
|
||||
version: '0.3.0',
|
||||
platform: 'darwin-arm64',
|
||||
architecture: 'arm64',
|
||||
protocolVersion: 1,
|
||||
buildCommit: 'fixture-build',
|
||||
tmSendSourceSha256: AGENT_HASH,
|
||||
addressProfileSha256: PROFILE_HASH,
|
||||
supportedWechatVersions: [wechatVersion],
|
||||
capabilities: ['text', 'image', 'voice'],
|
||||
capabilitiesByVersion: {
|
||||
[wechatVersion]: {
|
||||
text: 'verified',
|
||||
image: 'verified',
|
||||
voice: 'verified',
|
||||
textMechanism
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function snapshot(overrides: Partial<MacWechatRuntimeSnapshot> = {}): MacWechatRuntimeSnapshot {
|
||||
return {
|
||||
lifecycle: 'online',
|
||||
wechatRestartRequired: false,
|
||||
endpoint: 'http://127.0.0.1:4290',
|
||||
port: 4290,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function binding(
|
||||
wechatVersion: string,
|
||||
overrides: Partial<MacWechatBindingStatus> = {}
|
||||
): MacWechatBindingStatus {
|
||||
return {
|
||||
runtime: true,
|
||||
hostPid: 800,
|
||||
runtimeState: 'ready',
|
||||
runtimeVersion: 'tm-wechat-runtime/0.3.0',
|
||||
embeddedAgentSha256: AGENT_HASH,
|
||||
embeddedAddressProfileSha256: PROFILE_HASH,
|
||||
wechatRunning: true,
|
||||
wechatPid: 900,
|
||||
wechatVersion,
|
||||
supported: true,
|
||||
bindingState: 'bound',
|
||||
bound: true,
|
||||
boundWechatPid: 900,
|
||||
sessionAttached: true,
|
||||
scriptLoaded: true,
|
||||
sendContextReady: false,
|
||||
canSendText: true,
|
||||
canSendImage: true,
|
||||
canSendVoice: true,
|
||||
attachCount: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
class ConcurrentStartManager extends MacWechatRuntimeManager {
|
||||
startCalls = 0
|
||||
private resolveStart: ((snapshot: MacWechatRuntimeSnapshot) => void) | null = null
|
||||
|
||||
protected override ensureStartedOnce(): Promise<MacWechatRuntimeSnapshot> {
|
||||
this.startCalls += 1
|
||||
return new Promise((resolve) => {
|
||||
this.resolveStart = resolve
|
||||
})
|
||||
}
|
||||
|
||||
finishStart(result: MacWechatRuntimeSnapshot): void {
|
||||
this.resolveStart?.(result)
|
||||
}
|
||||
}
|
||||
|
||||
describe('deriveMacWechatSenderStatus', () => {
|
||||
it('shares one in-flight start promise with concurrent status reads', async () => {
|
||||
const manager = new ConcurrentStartManager()
|
||||
|
||||
const first = manager.ensureStarted()
|
||||
const second = manager.ensureStarted()
|
||||
|
||||
expect(manager.startCalls).toBe(1)
|
||||
manager.finishStart(snapshot())
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([snapshot(), snapshot()])
|
||||
})
|
||||
|
||||
it('resolves the send mechanism only for a binding that matches the runtime manifest', () => {
|
||||
const currentBinding = binding(MESSAGE_SOURCE_WECHAT_VERSION)
|
||||
const currentManifest = manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send')
|
||||
|
||||
expect(resolveMacWechatSendMechanism(currentBinding, currentManifest)).toBe(
|
||||
'tm-message-source-send'
|
||||
)
|
||||
expect(
|
||||
resolveMacWechatSendMechanism(
|
||||
{ ...currentBinding, embeddedAgentSha256: 'c'.repeat(64) },
|
||||
currentManifest
|
||||
)
|
||||
).toBeUndefined()
|
||||
expect(resolveMacWechatSendMechanism(null, currentManifest)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('marks message-source sending ready without a captured send context', () => {
|
||||
const result = deriveMacWechatSenderStatus({
|
||||
snapshot: snapshot(),
|
||||
binding: binding(MESSAGE_SOURCE_WECHAT_VERSION),
|
||||
manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'),
|
||||
arch: 'arm64'
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'online',
|
||||
runtimeReady: true,
|
||||
attachReady: true,
|
||||
messageListenerReady: true,
|
||||
canSend: true,
|
||||
canSendText: true,
|
||||
canSendImage: true,
|
||||
canSendVoice: true
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps native message-object readiness unchanged', () => {
|
||||
const result = deriveMacWechatSenderStatus({
|
||||
snapshot: snapshot(),
|
||||
binding: binding(NATIVE_OBJECT_WECHAT_VERSION),
|
||||
manifest: manifest(NATIVE_OBJECT_WECHAT_VERSION, 'native-msg-object'),
|
||||
arch: 'arm64'
|
||||
})
|
||||
|
||||
expect(result.state).toBe('online')
|
||||
expect(result.canSend).toBe(true)
|
||||
})
|
||||
|
||||
it('continues waiting for the captured context on the legacy mechanism', () => {
|
||||
const result = deriveMacWechatSenderStatus({
|
||||
snapshot: snapshot(),
|
||||
binding: binding(LEGACY_WECHAT_VERSION),
|
||||
manifest: manifest(LEGACY_WECHAT_VERSION, 'legacy-req2buf'),
|
||||
arch: 'arm64'
|
||||
})
|
||||
|
||||
expect(result.state).toBe('hook_not_ready')
|
||||
expect(result.canSend).toBe(false)
|
||||
})
|
||||
|
||||
it('surfaces a crashed host as an error instead of an unbound runtime check', () => {
|
||||
const result = deriveMacWechatSenderStatus({
|
||||
snapshot: snapshot({
|
||||
lifecycle: 'crashed_unbound',
|
||||
error: '发送运行时启动失败(进程退出码 1)'
|
||||
}),
|
||||
binding: null,
|
||||
manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'),
|
||||
arch: 'arm64'
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'error',
|
||||
runtimeReady: false,
|
||||
endpointReady: false,
|
||||
message: '发送运行时启动失败(进程退出码 1)'
|
||||
})
|
||||
})
|
||||
|
||||
it('surfaces stopped startup failures instead of an unbound runtime check', () => {
|
||||
const result = deriveMacWechatSenderStatus({
|
||||
snapshot: snapshot({ lifecycle: 'stopped', error: 'runtime host missing' }),
|
||||
binding: null,
|
||||
manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'),
|
||||
arch: 'arm64'
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'error',
|
||||
runtimeReady: false,
|
||||
endpointReady: false,
|
||||
message: 'runtime host missing'
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['session is not attached', { sessionAttached: false }],
|
||||
['agent script is not loaded', { scriptLoaded: false }],
|
||||
['runtime is still initializing', { runtimeState: 'initializing' as const }]
|
||||
])('does not mark the message-source mechanism ready when %s', (_reason, overrides) => {
|
||||
const result = deriveMacWechatSenderStatus({
|
||||
snapshot: snapshot(),
|
||||
binding: binding(MESSAGE_SOURCE_WECHAT_VERSION, overrides),
|
||||
manifest: manifest(MESSAGE_SOURCE_WECHAT_VERSION, 'tm-message-source-send'),
|
||||
arch: 'arm64'
|
||||
})
|
||||
|
||||
expect(result.state).toBe('hook_not_ready')
|
||||
expect(result.canSend).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
@@ -9,7 +10,14 @@ import {
|
||||
} from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join, sep } from 'path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const runtimeMocks = vi.hoisted(() => ({
|
||||
ensureStarted: vi.fn(),
|
||||
buildSenderStatus: vi.fn(),
|
||||
getSendMechanism: vi.fn(),
|
||||
getPort: vi.fn(() => 4290)
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
@@ -18,6 +26,27 @@ vi.mock('electron', () => ({
|
||||
isPackaged: false
|
||||
}
|
||||
}))
|
||||
vi.mock('../../src/main/services/mac-wechat-runtime-manager', () => ({
|
||||
macWechatRuntimeManager: runtimeMocks
|
||||
}))
|
||||
vi.mock('../../src/main/voice-pipeline/audio-decoder', () => ({
|
||||
SilkAudioDecoder: class {
|
||||
async decode() {
|
||||
return { pcm: Buffer.alloc(48_000), channels: 1, sampleRate: 24_000 }
|
||||
}
|
||||
},
|
||||
SilkAudioEncoder: class {}
|
||||
}))
|
||||
vi.mock('../../src/main/services/local-account-identity', () => ({
|
||||
readLocalAccountIdentity: () => ({ wxid: 'wxid_fixture_self' }),
|
||||
accountDirectoryBelongsToIdentity: (directory: string, wxid: string) => {
|
||||
const normalizedDirectory = directory.toLowerCase()
|
||||
const normalizedWxid = wxid.toLowerCase()
|
||||
if (normalizedDirectory === normalizedWxid) return true
|
||||
if (!normalizedDirectory.startsWith(`${normalizedWxid}_`)) return false
|
||||
return /^[a-z0-9]{4}$/.test(normalizedDirectory.slice(normalizedWxid.length + 1))
|
||||
}
|
||||
}))
|
||||
|
||||
import {
|
||||
buildPersonalWechatVoiceDiagnostic,
|
||||
@@ -29,6 +58,7 @@ import {
|
||||
prepareWindowsImageFile,
|
||||
WindowsHookHttpError
|
||||
} from '../../src/main/services/personal-wechat-send-service'
|
||||
import { PersonalWechatSendService } from '../../src/main/services/personal-wechat-send-service'
|
||||
|
||||
const temporaryDirectories: string[] = []
|
||||
|
||||
@@ -39,11 +69,254 @@ function temporaryDirectory(): string {
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
while (temporaryDirectories.length > 0) {
|
||||
rmSync(temporaryDirectories.pop()!, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMocks.ensureStarted.mockReset().mockResolvedValue(undefined)
|
||||
runtimeMocks.buildSenderStatus
|
||||
.mockReset()
|
||||
.mockResolvedValue({ canSendText: true, canSendImage: true, canSendVoice: true })
|
||||
runtimeMocks.getSendMechanism.mockReset().mockResolvedValue('legacy-req2buf')
|
||||
runtimeMocks.getPort.mockReset().mockReturnValue(4290)
|
||||
})
|
||||
|
||||
describe('macOS message-source send routing', () => {
|
||||
it('sends a message-source image through one local-path request without CDN upload', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-image.png')
|
||||
writeFileSync(filePath, 'fixture-image')
|
||||
const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11')
|
||||
mkdirSync(imageTemp, { recursive: true })
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send')
|
||||
let stagedPath = ''
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
})
|
||||
fetchMock.mockImplementation(async (_url, init) => {
|
||||
stagedPath = String((JSON.parse(String(init?.body)) as { path: string }).path)
|
||||
expect(stagedPath).toContain(imageTemp)
|
||||
expect(readFileSync(stagedPath, 'utf8')).toBe('fixture-image')
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
} as Response
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService(root).send({
|
||||
type: 'image', to: 'fixture-contact', isGroup: false, filePath
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg')
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({
|
||||
type: 'image', to: 'fixture-contact', path: stagedPath
|
||||
})
|
||||
expect(stagedPath).not.toBe(filePath)
|
||||
expect(existsSync(stagedPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('uses the legacy image path only when source preparation is definitively rejected', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-image.png')
|
||||
writeFileSync(filePath, 'fixture-image')
|
||||
const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11')
|
||||
mkdirSync(imageTemp, { recursive: true })
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send')
|
||||
const fetchMock = vi.fn().mockImplementation(async (url: string) => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => String(url).endsWith('/sendMsg')
|
||||
? { code: 6, ok: false, message: 'IMAGE_PREPARATION_FAILED:0' }
|
||||
: { code: 0, ok: true, message: 'sent' }
|
||||
}))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService(root).send({
|
||||
type: 'image', to: 'fixture-contact', isGroup: false, filePath
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
|
||||
'http://127.0.0.1:4290/sendMsg',
|
||||
'http://127.0.0.1:4290/uploadImage',
|
||||
'http://127.0.0.1:4290/sendImage'
|
||||
])
|
||||
const uploadBody = JSON.parse(String(fetchMock.mock.calls[1][1]?.body)) as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
expect(String(uploadBody.filePath)).toContain(imageTemp)
|
||||
})
|
||||
|
||||
it('does not retry image submission after a timeout or an ambiguous failure', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-image.png')
|
||||
writeFileSync(filePath, 'fixture-image')
|
||||
const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11')
|
||||
mkdirSync(imageTemp, { recursive: true })
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send')
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error('request timed out'))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService(root).send({
|
||||
type: 'image', to: 'fixture-contact', isGroup: false, filePath
|
||||
})
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toBe('图片发送失败')
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg')
|
||||
})
|
||||
|
||||
it('keeps other image mechanisms on the upload-then-send endpoints', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-image.png')
|
||||
writeFileSync(filePath, 'fixture-image')
|
||||
const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11')
|
||||
mkdirSync(imageTemp, { recursive: true })
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('native-msg-object')
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService(root).send({
|
||||
type: 'image', to: 'fixture-contact', isGroup: false, filePath
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
|
||||
'http://127.0.0.1:4290/uploadImage',
|
||||
'http://127.0.0.1:4290/sendImage'
|
||||
])
|
||||
const uploadBody = JSON.parse(String(fetchMock.mock.calls[0][1]?.body)) as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
expect(String(uploadBody.filePath)).toContain(imageTemp)
|
||||
})
|
||||
|
||||
it('sends message-source text and its mention map through the unified endpoint', async () => {
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send')
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService().send({
|
||||
type: 'text',
|
||||
to: 'fixture-room@chatroom',
|
||||
isGroup: true,
|
||||
text: '早上好',
|
||||
at: { wxid_fixture_member: '测试成员' }
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg')
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({
|
||||
type: 'text',
|
||||
to: 'fixture-room@chatroom',
|
||||
text: '早上好',
|
||||
is_group: true,
|
||||
at: { wxid_fixture_member: '测试成员' }
|
||||
})
|
||||
})
|
||||
|
||||
it('sends a message-source SILK voice through the unified request', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-voice.silk')
|
||||
writeFileSync(filePath, Buffer.concat([Buffer.from('\x02#!SILK_V3'), Buffer.from([1, 2, 3])]))
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send')
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService().send({
|
||||
type: 'voice', to: 'fixture-contact', isGroup: false, filePath, durationMs: 1200
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('/sendMsg')
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({
|
||||
type: 'voice', to: 'fixture-contact', voice_hex: expect.any(String), duration_ms: 1200
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a sub-second message-source voice instead of sending an invalid duration', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-voice.silk')
|
||||
writeFileSync(filePath, Buffer.concat([Buffer.from('\x02#!SILK_V3'), Buffer.from([1, 2, 3])]))
|
||||
runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send')
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService().send({
|
||||
type: 'voice', to: 'fixture-contact', isGroup: false, filePath, durationMs: 500
|
||||
})
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toContain('至少 1 秒')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps other text mechanisms on the existing endpoint', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService().send({
|
||||
type: 'text', to: 'fixture-contact', isGroup: false, text: 'hello'
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
expect(fetchMock.mock.calls[0][0]).toContain('/sendText')
|
||||
})
|
||||
|
||||
it('keeps other voice mechanisms on the upload-then-send endpoints', async () => {
|
||||
const root = temporaryDirectory()
|
||||
const filePath = join(root, 'fixture-voice.silk')
|
||||
writeFileSync(filePath, Buffer.concat([Buffer.from('\x02#!SILK_V3'), Buffer.from([1, 2, 3])]))
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ code: 0, ok: true, message: 'sent' })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await new PersonalWechatSendService().send({
|
||||
type: 'voice', to: 'fixture-contact', isGroup: false, filePath, durationMs: 1200
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
|
||||
'http://127.0.0.1:4290/uploadVoice',
|
||||
'http://127.0.0.1:4290/sendVoice'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('personal WeChat voice diagnostics', () => {
|
||||
it('keeps voice diagnostics to the safe metadata allowlist', () => {
|
||||
const diagnostic = buildPersonalWechatVoiceDiagnostic('request-1', 'completed', {
|
||||
@@ -224,4 +497,19 @@ describe('personal WeChat runtime discovery', () => {
|
||||
`${join(tempRoot, 'ImageTemp', '2026-08')}${sep}`
|
||||
)
|
||||
})
|
||||
|
||||
it('does not choose a newer image directory belonging to another WeChat account', () => {
|
||||
const root = temporaryDirectory()
|
||||
const ownPath = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-08')
|
||||
const otherPath = join(root, 'wxid_other_account', 'temp', 'ImageTemp', '2026-08')
|
||||
mkdirSync(ownPath, { recursive: true })
|
||||
mkdirSync(otherPath, { recursive: true })
|
||||
utimesSync(ownPath, new Date('2026-08-01'), new Date('2026-08-01'))
|
||||
utimesSync(otherPath, new Date('2026-08-05'), new Date('2026-08-05'))
|
||||
|
||||
expect(findWechatImagePath(root, new Date('2026-08-06'), 'wxid_fixture_self')).toBe(
|
||||
`${ownPath}${sep}`
|
||||
)
|
||||
expect(findWechatImagePath(root, new Date('2026-08-06'), 'wxid_missing_account')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -492,6 +492,19 @@ describe('production runtime packaging', () => {
|
||||
expect(stub.calls).toContainEqual(['--verify', '--strict', '--arch', 'x86_64', helperPath])
|
||||
})
|
||||
|
||||
it('always re-signs the Native Host before packaging', () => {
|
||||
const runtimeDirectory = join(root, 'runtime-sign-resources', 'runtime', 'darwin-arm64')
|
||||
mkdirSync(runtimeDirectory, { recursive: true })
|
||||
const hostPath = join(runtimeDirectory, 'tm-wechat-host')
|
||||
writeFileSync(hostPath, 'fixture')
|
||||
const stub = createCodesignStub()
|
||||
|
||||
expect(signMacosHelpers(join(root, 'runtime-sign-resources'), stub.run)).toEqual([hostPath])
|
||||
expect(stub.calls[0]).toEqual(['--force', '--sign', '-', hostPath])
|
||||
expect(stub.calls).toContainEqual(['--verify', '--strict', '--arch', 'arm64', hostPath])
|
||||
expect(stub.calls).toContainEqual(['--verify', '--strict', '--arch', 'x86_64', hostPath])
|
||||
})
|
||||
|
||||
it('fails packaging when a helper signature cannot be repaired', () => {
|
||||
const resources = join(root, 'helper-broken-resources', 'resources')
|
||||
mkdirSync(resources, { recursive: true })
|
||||
|
||||
@@ -100,6 +100,25 @@ describe('WechatActionGateway', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('preserves the native mention map when forwarding a manual text action', async () => {
|
||||
const gateway = createGateway()
|
||||
await gateway.execute({
|
||||
origin: 'user_manual',
|
||||
purpose: 'manual_text',
|
||||
triggerType: 'user',
|
||||
recipient: { type: 'group', id: 'fixture-room@chatroom' },
|
||||
content: { type: 'text', text: '早上好', at: { wxid_fixture: '测试成员' } }
|
||||
})
|
||||
|
||||
expect(mocks.sender.send).toHaveBeenCalledWith({
|
||||
type: 'text',
|
||||
to: 'fixture-room@chatroom',
|
||||
isGroup: true,
|
||||
text: '早上好',
|
||||
at: { wxid_fixture: '测试成员' }
|
||||
})
|
||||
})
|
||||
|
||||
it('deduplicates the same leave event across repeated execution calls', async () => {
|
||||
const gateway = createGateway()
|
||||
const first = await leaveNotificationAction(gateway)
|
||||
|
||||
Reference in new issue
Block a user