feat: 新增拓展中心功能, 提供 关键词回复 去水印模板

This commit is contained in:
Wxw-Gu committed 2026-11-13 17:54:37 +08:00
1 parent aca103cb96
commit b9ad4e1d71
85 files changed
+14750 -106

No files matched your search

+182 -26
View File
@@ -19,8 +19,21 @@ import {
renderLeaveNotificationText,
type GroupMemberExitedEvent
} from '../../shared/group-exit-event'
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { SaveGeneratedReportRequest, SaveGeneratedReportResult } from '../../shared/report-history'
import type {
WechatActionContent,
WechatActionRequest,
WechatActionResult
} from '../../shared/wechat-action'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import {
canExtensionSendText,
invokeExtensionAction
} from '../extensions/extension-automation-bridge'
import type {
SaveGeneratedReportRequest,
SaveGeneratedReportResult
} from '../../shared/report-history'
import {
generateAgentGroupReport,
type AgentGroupReportRequest,
@@ -45,6 +58,21 @@ import type { AutomationTargetResolution } from './automation-wechat-target'
/** 一步执行完毕后,后续步骤的处置方式。 */
const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send']
/**
* 配了扩展动作时的步骤顺序。
*
* 只有规则真的配了扩展动作才把这一步加进来:给每条日报都渲染一条
* 「执行扩展动作 已跳过」是纯噪声,用户会以为规则配错了。
*/
const EXTENSION_STEP_ORDER: AutomationStepKey[] = [
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
]
/** 退群通知的步骤顺序(与消息型规则**不共用**)。 */
const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
'exit_received',
@@ -74,6 +102,7 @@ const SCHEDULED_REPORT_STEP_ORDER: AutomationStepKey[] = [
*/
const SKIPPED_AFTER_REPLY_FAILURE = '前置步骤失败(回复确认未成功),本次不再继续。'
const SKIPPED_AFTER_REPORT_FAILURE = '前置步骤失败(日报未生成),没有图片可发送。'
const SKIPPED_AFTER_EXTENSION_FAILURE = '前置步骤失败(扩展动作未成功),本次不再继续。'
/**
* 定时日报「生成 / 落库」失败时,后续步骤的 `skipReason`。
@@ -102,6 +131,8 @@ export interface AutomationRunInput {
sourceDisplayName: string
/** 群消息触发者;仅内置日报确认回复会使用它构造 @。 */
triggerSender?: { wxid: string; displayName: string }
/** 触发本次执行的消息(扩展动作的运行时上下文)。 */
message?: ExtensionMessageEvent
}
export interface AutomationRunResult {
@@ -185,6 +216,22 @@ export interface ScheduledReportRunResult {
export interface AutomationActionRunnerDependencies {
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
/**
* 扩展动作调用。默认走 `ExtensionManager`;单测注入假实现即可绕开子进程。
*/
invokeExtensionAction?: (
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
) => Promise<ExtensionAutomationActionOutput>
/** 扩展是否具备发送文本的权限。默认读扩展中心授予集合。 */
canExtensionSendText?: (extensionId: string) => boolean
now?: () => number
/** 延迟实现。默认真 sleep;单测注入即时 resolve 的假实现,避免真的等 2 秒。 */
delay?: (ms: number) => Promise<void>
@@ -246,7 +293,9 @@ function actionErrorMessage(code: string | undefined, fallback: string | undefin
}
export class AutomationActionRunner {
private readonly generateReport: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
private readonly generateReport: (
request: AgentGroupReportRequest
) => Promise<AgentGroupReportResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly now: () => number
private readonly delay: (ms: number) => Promise<void>
@@ -257,21 +306,31 @@ export class AutomationActionRunner {
AutomationActionRunnerDependencies['resolveReportContact']
>
private readonly getContactAvatars: (usernames: string[]) => Promise<Record<string, string>>
private readonly invokeExtensionAction: NonNullable<
AutomationActionRunnerDependencies['invokeExtensionAction']
>
private readonly canExtensionSendText: (extensionId: string) => boolean
constructor(dependencies: AutomationActionRunnerDependencies = {}) {
this.generateReport = dependencies.generateReport ?? generateAgentGroupReport
this.executeAction = dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.executeAction =
dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.now = dependencies.now ?? (() => Date.now())
this.delay =
dependencies.delay ??
((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
dependencies.delay ?? ((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
this.saveGeneratedReport = dependencies.saveGeneratedReport ?? saveGeneratedReport
this.resolveReportContact = dependencies.resolveReportContact ?? ((raw) => resolveMd5(raw))
this.getContactAvatars = dependencies.getContactAvatars ?? ((ids) => getContactAvatars(ids))
this.invokeExtensionAction =
dependencies.invokeExtensionAction ??
((id, actionId, input, context) => invokeExtensionAction(id, actionId, input, context))
this.canExtensionSendText = dependencies.canExtensionSendText ?? canExtensionSendText
}
async run(input: AutomationRunInput): Promise<AutomationRunResult> {
const steps = STEP_ORDER.map((key) => createStep(key))
const extensionAction = findAction(input.rule, 'extensionAction')
const order = extensionAction ? EXTENSION_STEP_ORDER : STEP_ORDER
const steps = order.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -282,25 +341,77 @@ export class AutomationActionRunner {
const reportAction = findAction(input.rule, 'generateReport')
const sendAction = findAction(input.rule, 'sendReportImage')
// ---- 步骤 3:回复确认 ----
// ---- 步骤 3:扩展动作 ----
//
// 回复等待:规则一命中就秒回,看起来就是个机器人(消息刚到、回复就到)。
// 等待时长是**规则自己的一项执行参数**(`rule.replyDelaySeconds`,在
// 「编辑自动化 → 3 · 触发后执行」里配),所以不同规则可以不一样。
//
// 等待刻意放在 `reply` 步骤计时**之外** —— `reply.durationMs` 只应该反映发送本身,
// 否则用户看到「回复确认 2000ms」会误以为是发送慢。
// 已经命中就不再回头重判规则:等待窗口里规则被停用/删掉也不中断本次执行,
// 与 cooldown、同消息幂等的口径一致(都是「命中那一刻」的快照)。
if (replyAction) {
// 扩展动作先跑,它产出的 `reply` 会成为下一步「回复确认」的内容。
// 扩展本身**不发送**:内容交回宿主,由宿主在权限与授权都通过后经 Gateway 发出。
let extensionOutput: ExtensionAutomationActionOutput | undefined
if (extensionAction) {
const extensionStep = stepAt('extension_action')
extensionStep.status = 'running'
extensionStep.startedAt = this.now()
try {
extensionOutput = await this.invokeExtensionAction(
String(extensionAction.extensionId || ''),
String(extensionAction.actionId || ''),
extensionAction.input ?? {},
{
conversationId: input.conversationId,
isGroup: input.isGroup,
accountId: input.message?.accountId ?? '',
...(input.message ? { message: input.message } : {})
}
)
} catch (error) {
markFailed(
extensionStep,
this.now(),
error instanceof Error ? error.message : '扩展动作执行失败'
)
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (!extensionOutput || extensionOutput.success === false) {
markFailed(extensionStep, this.now(), extensionOutput?.error || '扩展动作返回失败')
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (extensionOutput.reply) extensionStep.detail = '已生成回复内容'
markSuccess(extensionStep, this.now())
}
const extensionReply = extensionOutput?.reply
// 步骤 4:回复确认。
// 命中即视为快照:等待窗口内规则被停用/删除也不中断本次执行。
// 等待时长来自 rule.replyDelaySeconds,且不计入 reply.durationMs。
const willReply = Boolean(extensionReply) || Boolean(replyAction)
if (willReply) {
// 用共享的归一化函数,而不是 `Number(...) || 0`:旧版 rules.json 里没有这个字段,
// 那应该按**默认 2 秒**处理(否则「默认 2 秒」要等用户手动进编辑页才会生效)。
const replyDelayMs = normalizeReplyDelaySeconds(input.rule.replyDelaySeconds) * 1_000
if (replyDelayMs > 0) await this.delay(replyDelayMs)
}
if (!replyAction) {
if (!willReply) {
markSkipped(stepAt('reply'))
} else if (extensionReply) {
const replyStep = stepAt('reply')
const extensionId = String(extensionAction?.extensionId || '')
if (!this.canExtensionSendText(extensionId)) {
markFailed(replyStep, this.now(), '扩展没有 wechat.send.text 权限,回复未发送')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
replyStep.status = 'running'
replyStep.startedAt = this.now()
const sent = await this.sendExtensionReply(input, extensionId, extensionReply)
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
} else {
const replyStep = stepAt('reply')
replyStep.status = 'running'
@@ -316,12 +427,12 @@ export class AutomationActionRunner {
: undefined
const sent = await this.sendThroughGateway(input, 'reply', {
type: 'text',
text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT,
text: replyAction?.text?.trim() || DEFAULT_REPLY_TEXT,
...(confirmationAt ? { at: confirmationAt } : {})
})
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
@@ -346,7 +457,7 @@ export class AutomationActionRunner {
}
if (!result.success || !result.pngPath) {
markFailed(reportStep, this.now(), result.error || '日报生成失败')
markRemainingSkipped(steps, 'report', SKIPPED_AFTER_REPORT_FAILURE)
markRemainingSkipped(steps, order, 'report', SKIPPED_AFTER_REPORT_FAILURE)
return { steps, status: 'failed', errorSummary: reportStep.error }
}
pngPath = result.pngPath
@@ -395,6 +506,43 @@ export class AutomationActionRunner {
return { steps, status: 'success', pngPath }
}
/**
* 发送扩展产出的回复。
*
* 内容来自扩展,**发送动作来自宿主**:`origin` / `purpose` / 幂等键都在这里填,
* 扩展返回的只是「想说什么」。所以扩展无法借这条链路绕过发送策略。
*/
private async sendExtensionReply(
input: AutomationRunInput,
extensionId: string,
reply: NonNullable<ExtensionAutomationActionOutput['reply']>
): Promise<{ ok: boolean; error?: string }> {
try {
const result = await this.executeAction({
idempotencyKey: `extension_action:${input.executionId}`,
origin: 'extension',
purpose: 'extension_action',
triggerType: 'automation',
executionId: input.executionId,
recipient: {
type: input.isGroup ? 'group' : 'contact',
id: input.conversationId,
name: input.sourceDisplayName
},
content: {
type: 'text',
text: reply.text,
...(reply.at ? { at: reply.at } : {})
},
metadata: { extensionId }
})
if (result.status === 'sent') return { ok: true }
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 把「@我生成日报」产出的日报写进**日报历史**。
*
@@ -522,7 +670,9 @@ export class AutomationActionRunner {
generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊',
contactAvatar,
source: 'scheduled',
dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel(input.config.report.range),
dateRange:
generated.reportMetadata?.dateRange ||
scheduledReportRangeLabel(input.config.report.range),
reportDate: generated.reportMetadata?.reportDate,
messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0,
generatedAt: new Date(this.now()).toISOString(),
@@ -674,7 +824,9 @@ export class AutomationActionRunner {
* 与 `run()` 的差别:没有动作链、没有回复等待、没有 cooldown
* (退群是低频事件,且**不能被时间窗合并** —— 两个成员先后退出就是两条通知)。
*/
async runLeaveNotification(input: LeaveNotificationRunInput): Promise<LeaveNotificationRunResult> {
async runLeaveNotification(
input: LeaveNotificationRunInput
): Promise<LeaveNotificationRunResult> {
const steps = LEAVE_NOTIFICATION_STEP_ORDER.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -792,18 +944,22 @@ export class AutomationActionRunner {
}
}
function findAction(rule: AutomationRule, type: AutomationAction['type']): AutomationAction | undefined {
function findAction(
rule: AutomationRule,
type: AutomationAction['type']
): AutomationAction | undefined {
return rule.actions.find((action) => action.type === type && action.enabled)
}
/** 把 `after` 之后的步骤全部标成 `skipped`(前一步挂了,后面的不许再动)。 */
function markRemainingSkipped(
steps: AutomationStep[],
order: AutomationStepKey[],
after: AutomationStepKey,
skipReason?: string
): void {
const from = STEP_ORDER.indexOf(after) + 1
for (const key of STEP_ORDER.slice(from)) {
const from = order.indexOf(after) + 1
for (const key of order.slice(from)) {
const step = steps.find((item) => item.key === key)
if (step) markSkipped(step, skipReason)
}
+31 -18
View File
@@ -1,8 +1,5 @@
import { createHash, randomUUID } from 'node:crypto'
import {
matchAutomationRule,
type AutomationMatchInput
} from '../../shared/automation-matcher'
import { matchAutomationRule, type AutomationMatchInput } from '../../shared/automation-matcher'
import {
AUTOMATION_SEND_PURPOSE,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
@@ -14,6 +11,8 @@ import {
type ScheduledRuleRunOutcome
} from '../../shared/automation'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { buildExtensionMessageEvent } from '../../shared/extensions/events'
import { buildEventId } from '../extensions/extension-event-bus'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { Wcdb4Client } from '../wcdb4-client'
import type { NormalizedIncomingMessage } from './message-listener-service'
@@ -28,18 +27,12 @@ import {
scheduledReportSourceDisplayName
} from './scheduled-report-target'
import type { AutomationTargetContact } from './automation-wechat-target'
import {
automationRuleStore,
type AutomationRuleStore
} from './automation-rule-store'
import { automationRuleStore, type AutomationRuleStore } from './automation-rule-store'
import {
automationExecutionLogService,
type AutomationExecutionLogService
} from './automation-execution-log-service'
import {
automationActionRunner,
type AutomationActionRunner
} from './automation-action-runner'
import { automationActionRunner, type AutomationActionRunner } from './automation-action-runner'
/**
* AutomationService —— Automation v1 的编排层。
*
@@ -137,9 +130,7 @@ export function leaveNotificationIdempotencyKey(eventId: string): string {
* 「立即执行」会因为幂等而被静默吞掉。
*/
export function scheduledReportExecutionId(ruleId: string, slot: string): string {
return createHash('sha1')
.update(`scheduled_report\u0001${ruleId}\u0001${slot}`)
.digest('hex')
return createHash('sha1').update(`scheduled_report\u0001${ruleId}\u0001${slot}`).digest('hex')
}
/** 定时日报一次执行的结果(定义在 shared 层,便于 IPC / 渲染层共用)。 */
@@ -291,7 +282,7 @@ export class AutomationService {
const sourceDisplayName = this.resolveDisplayName(message)
try {
await this.execute(rule, message, sourceDisplayName)
await this.execute(rule, message, sourceDisplayName, selfUsernames)
} finally {
// 无论 success / failed / 抛异常都要解除 in-flight。
// 漏掉这一步会让这条规则在这个会话里**永久锁死**。
@@ -660,7 +651,10 @@ export class AutomationService {
return true
}
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ id: string; name: string }> {
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{
id: string
name: string
}> {
try {
return listContacts()
.filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom'))
@@ -683,7 +677,8 @@ export class AutomationService {
private async execute(
rule: AutomationRule,
message: NormalizedIncomingMessage,
sourceDisplayName: string
sourceDisplayName: string,
selfUsernames: string[]
): Promise<void> {
const executionId = randomUUID()
const startedAt = this.now()
@@ -727,6 +722,24 @@ export class AutomationService {
displayName: message.senderNickname
}
}
: {}),
...(rule.actions.some((action) => action.type === 'extensionAction' && action.enabled)
? {
message: buildExtensionMessageEvent({
eventId: buildEventId(message.sessionId, message.localId),
accountId: String(getSelfAccountInfo()?.wxid || ''),
conversationId: message.sessionId,
messageId: message.serverId || message.localId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
isGroup: message.isGroup,
isSelf: message.isSelf,
messageType: message.messageType,
...(message.content !== undefined ? { content: message.content } : {}),
mentionsMe: message.mentionTargets.some((target) => selfUsernames.includes(target)),
createTimeSeconds: message.createTime
})
}
: {})
})
} catch (error) {
+16 -19
View File
@@ -112,9 +112,7 @@ export function formatMacWechatHostStartupFailure(code: number | null, diagnosti
const lines = diagnostic.trim().split('\n').filter(Boolean)
const detail = lines[lines.length - 1]
if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}`
return code === null
? '发送运行时在启动过程中退出'
: `发送运行时启动失败(进程退出码 ${code})`
return code === null ? '发送运行时在启动过程中退出' : `发送运行时启动失败(进程退出码 ${code})`
}
export function resolveMacWechatSendMechanism(
@@ -201,6 +199,12 @@ export function deriveMacWechatSenderStatus({
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
/*
* 视频复用图片的媒体通道(Host 的 `/SendMsg` type=video)。
* Runtime manifest 不单独声明 video 能力,因此以图片通道是否可用作为判据;
* 真正的发送结果仍以 Host 返回为准,不在 UI 层假装支持。
*/
const canSendVideo = bindingReady && binding?.canSendImage === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -224,10 +228,11 @@ export function deriveMacWechatSenderStatus({
imageHookInstalled: identityMatches && (binding?.canSendImage ?? false),
imageHookReady: identityMatches && (binding?.canSendImage ?? false),
messageListenerReady: scriptLoaded,
canSend: canSendText || canSendImage || canSendVoice,
canSend: canSendText || canSendImage || canSendVoice || canSendVideo,
canSendText,
canSendImage,
canSendVoice,
canSendVideo,
message,
error: state === 'error' ? message : undefined
}
@@ -349,9 +354,7 @@ export class MacWechatRuntimeManager {
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
* online" and "WeChat bound" stay two independent states.
*/
ensureStarted(
options: { allowManualRestart?: boolean } = {}
): Promise<MacWechatRuntimeSnapshot> {
ensureStarted(options: { allowManualRestart?: boolean } = {}): Promise<MacWechatRuntimeSnapshot> {
if (this.startInFlight) return this.startInFlight
const startPromise = this.ensureStartedOnce(options)
@@ -367,9 +370,9 @@ export class MacWechatRuntimeManager {
return startPromise
}
protected async ensureStartedOnce(
options: { allowManualRestart?: boolean }
): Promise<MacWechatRuntimeSnapshot> {
protected async ensureStartedOnce(options: {
allowManualRestart?: boolean
}): Promise<MacWechatRuntimeSnapshot> {
if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot()
if (options.allowManualRestart) this.manuallyStopped = false
if (isMacNativeRuntimeUnavailable()) {
@@ -481,19 +484,13 @@ export class MacWechatRuntimeManager {
}
try {
if (!app.isPackaged) {
execFileSync('/usr/bin/codesign', [
'--force',
'--sign',
'-',
'--timestamp=none',
hostPath
])
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', '--timestamp=none', hostPath])
}
execFileSync('/usr/bin/codesign', ['--verify', '--strict', hostPath])
} catch (error) {
this.lifecycle = 'stopped'
this.lastError = '无法验证发送 Host 签名:' +
(error instanceof Error ? error.message : String(error))
this.lastError =
'无法验证发送 Host 签名:' + (error instanceof Error ? error.message : String(error))
appLogger.write({
level: 'error',
scope: 'mac-wechat-runtime',
+43 -3
View File
@@ -137,14 +137,39 @@ export function extractMentionTargets(source: string | undefined): string[] {
if (!match) return []
const inner = match[1].trim()
const unwrapped = inner.replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, '').trim()
return unwrapped ? [unwrapped] : []
if (!unwrapped) return []
return unwrapped
.split(',')
.map((item) => item.trim())
.filter(Boolean)
}
/** 把 WCDB 的 `source` 列(zstd 压缩的 Buffer)还原成 XML 文本。 */
/** 把 WCDB 的 `source` 列(明文 XML 字符串或 zstd 压缩的 Buffer)还原成 XML 文本。 */
export function decodeSourcePayload(value: unknown): string | undefined {
if (typeof value === 'string') {
const trimmed = value.trim()
if (!trimmed) return undefined
if (
trimmed.length >= 8 &&
trimmed.length % 2 === 0 &&
/^28b52ffd[0-9a-f]+$/i.test(trimmed)
) {
try {
return Buffer.from(zstdDecompress(Buffer.from(trimmed, 'hex'))).toString('utf8')
} catch {
return undefined
}
}
return trimmed
}
let buffer: Buffer | null = null
if (Buffer.isBuffer(value)) {
buffer = value
} else if (value instanceof Uint8Array) {
buffer = Buffer.from(value)
} else if (Array.isArray(value)) {
buffer = Buffer.from(value)
} else {
const candidate = value as { type?: string; data?: unknown } | null
if (candidate?.type === 'Buffer' && Array.isArray(candidate.data)) {
@@ -193,6 +218,7 @@ export class MessageListenerService {
private readonly pendingSessions = new Set<string>()
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
private readbackInFlight = false
private pendingReadback = false
private disposed = false
private readonly coalesceMs: number
@@ -282,8 +308,13 @@ export class MessageListenerService {
* - **legacy(protocol v1,旧 runtime)**:只能退回「最近活跃会话」`getSessions()[0]`。
*/
private async readback(): Promise<void> {
if (this.disposed || this.readbackInFlight) return
if (this.disposed) return
if (this.readbackInFlight) {
this.pendingReadback = true
return
}
this.readbackInFlight = true
this.pendingReadback = false
const startedAt = Date.now()
const preciseSessions = Array.from(this.pendingSessions)
@@ -321,6 +352,15 @@ export class MessageListenerService {
)
} finally {
this.readbackInFlight = false
if (!this.disposed && (this.pendingReadback || this.pendingSessions.size > 0)) {
this.pendingReadback = false
if (!this.coalesceTimer) {
this.coalesceTimer = setTimeout(() => {
this.coalesceTimer = null
void this.readback()
}, this.coalesceMs)
}
}
}
}
@@ -37,7 +37,8 @@ export class PersonalWechatCapabilityService {
const capabilities = {
text: Boolean(senderStatus.canSendText),
image: Boolean(senderStatus.canSendImage),
voice: Boolean(senderStatus.canSendVoice)
voice: Boolean(senderStatus.canSendVoice),
video: Boolean(senderStatus.canSendVideo)
}
const status = this.mapState(senderStatus)
const ready = status === 'ready'
+166 -13
View File
@@ -23,7 +23,10 @@ import type {
import { loadSettings } from './settings-store'
import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder'
import { appLogger } from '../app-logger'
import { accountDirectoryBelongsToIdentity, readLocalAccountIdentity } from './local-account-identity'
import {
accountDirectoryBelongsToIdentity,
readLocalAccountIdentity
} from './local-account-identity'
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
const execFileAsync = promisify(execFile)
@@ -31,6 +34,8 @@ const WINDOWS_LOOPBACK_HOST = '127.0.0.1'
const REQUEST_TIMEOUT_MS = 20_000
const MAX_IMAGE_BYTES = 20 * 1024 * 1024
const MAX_VOICE_BYTES = 20 * 1024 * 1024
/** 视频与扩展发送通道的上限保持一致。 */
const MAX_VIDEO_BYTES = 100 * 1024 * 1024
// 语音编码由 native runtime 内的 SILK 实现完成,不再是外部编码器进程。
const VOICE_ENCODER_NAME = 'silk'
const VOICE_ENCODER_VERSION = 'tm-wechat-native'
@@ -327,6 +332,73 @@ function stageMacWechatImageForMessageSourceSend(
return stagedPath
}
const MAC_VIDEO_STAGE_PREFIX = 'tm-video-'
const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000
/**
* macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`
* 只能读取 `~/Library/Containers/com.tencent.xinWeChat/Data/...` 容器内路径,
* 直接传 `~/Library/Application Support/TraceMemo/...` 会触发 `VIDEO_PREPARATION_FAILED:0`。
* 因此发送前需将容器外视频暂存到微信容器的 `Documents` 目录。
*/
export function stageMacWechatVideoForSend(
filePath: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { stagedPath: string; cleanup: () => void } {
const normalized = String(filePath || '').trim()
const containerDataRoot = dirname(dirname(wechatFilesRoot))
if (
containerDataRoot.includes('com.tencent.xinWeChat') &&
normalized.startsWith(`${containerDataRoot}${sep}`)
) {
return { stagedPath: normalized, cleanup: () => {} }
}
const documentsDir = dirname(wechatFilesRoot)
const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot
mkdirSync(stageDir, { recursive: true })
// 顺手清理超过 10 分钟的历史暂存视频,防止异常退出残留。
const now = Date.now()
try {
for (const entry of readdirSync(stageDir)) {
if (!entry.startsWith(MAC_VIDEO_STAGE_PREFIX)) continue
const candidate = join(stageDir, entry)
try {
if (now - statSync(candidate).mtimeMs > MAC_VIDEO_STAGE_RETENTION_MS) {
unlinkSync(candidate)
}
} catch {
// Best-effort stale file cleanup.
}
}
} catch {
// Ignore directory listing errors.
}
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.mp4'
const stagedPath = join(
stageDir,
`${MAC_VIDEO_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}`
)
copyFileSync(normalized, stagedPath)
return {
stagedPath,
cleanup: () => {
const timer = setTimeout(() => {
try {
unlinkSync(stagedPath)
} catch {
// Best-effort delayed cleanup after WeChat finishes asynchronous video upload.
}
}, 120_000)
timer.unref?.()
}
}
}
/** Locate the current account's temporary image directory consumed by the image send path. */
export function findWechatImagePath(
root = WECHAT_FILES_ROOT,
@@ -443,6 +515,12 @@ export function buildWindowsWechatRequest(
body: { toWxid: target, type: 'image', msg: String(request.filePath || '').trim() }
}
}
if (request.type === 'video') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'video', msg: String(request.filePath || '').trim() }
}
}
const fromId = String(request.fromId || '').trim()
const filePath = String(options.filePath || request.filePath || '').trim()
@@ -609,6 +687,7 @@ export class PersonalWechatSendService {
if (request.type === 'text') return this.sendMacText(request)
if (request.type === 'image') return this.sendMacImage(request)
if (request.type === 'voice') return this.sendMacVoice(request)
if (request.type === 'video') return this.sendMacVideo(request)
}
return {
success: false,
@@ -772,11 +851,78 @@ export class PersonalWechatSendService {
signal: AbortSignal.timeout(timeoutMs)
}).catch(() => null)
if (response === null || !response.ok) return null
return (await response.json().catch(() => null)) as {
code: number
ok: boolean
message: string
} | null
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null
if (!payload) return null
/*
* 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`,
* `/SendMsg` 兼容层可能返回 `{status:true}` 或 Windows 风格的 `{ret:0}`。
* 这里统一收敛,避免「实际已发送、界面报失败」。
*/
const explicitFailure = payload.ok === false || payload.status === false
const ok =
!explicitFailure &&
(payload.ok === true || payload.status === true || payload.ret === 0 || payload.code === 0)
return {
code: Number(payload.code ?? payload.ret ?? (ok ? 0 : 1)),
ok,
message: String(payload.message ?? payload.msg ?? '')
}
}
/**
* macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。
*
* 微信运行在 App Sandbox 容器中,注入的 `libtmwechat.dylib` 在微信进程内执行,
* 只能访问微信沙盒容器目录(`~/Library/Containers/com.tencent.xinWeChat/Data/...`)。
* 因此先将容器外视频暂存到微信容器 `Documents` 目录,再调用 `/SendMsg`。
*/
private async sendMacVideo(
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
): Promise<PersonalWechatSendResult> {
await macWechatRuntimeManager.ensureStarted()
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!status.canSendVideo) {
return {
success: false,
status,
error: status.message || '当前微信发送组件不支持视频,请升级后重试'
}
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) {
return { success: false, status, error: '请选择有效的视频文件' }
}
const size = statSync(filePath).size
if (size <= 0 || size > MAX_VIDEO_BYTES) {
return { success: false, status, error: '视频必须小于 100 MB' }
}
let staged: { stagedPath: string; cleanup: () => void } | null = null
try {
staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot)
} catch (error) {
const latest = await macWechatRuntimeManager.buildSenderStatus()
return {
success: false,
status: latest,
error: error instanceof Error ? error.message : '无法将视频暂存到微信沙盒目录'
}
}
try {
const result = await this.postMacHost(
'/SendMsg',
{ toWxid: request.to, type: 'video', msg: staged.stagedPath },
180_000
)
const latest = await macWechatRuntimeManager.buildSenderStatus()
if (!result?.ok) {
return { success: false, status: latest, error: result?.message || '视频发送失败' }
}
return { success: true, status: latest }
} finally {
staged.cleanup()
}
}
private async sendMacImage(
@@ -974,21 +1120,24 @@ export class PersonalWechatSendService {
request = { ...request, to, text }
} else {
const filePath = String(request.filePath || '').trim()
const label = request.type === 'voice' ? '语音' : request.type === 'video' ? '视频' : '图片'
const limit =
request.type === 'voice'
? MAX_VOICE_BYTES
: request.type === 'video'
? MAX_VIDEO_BYTES
: MAX_IMAGE_BYTES
if (!filePath || !existsSync(filePath)) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件`
}
return { success: false, status, error: `请选择有效的${label}文件` }
}
const size = statSync(filePath).size
if (size <= 0 || size > (request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES)) {
if (size <= 0 || size > limit) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB`
error: `${label}必须小于 ${Math.round(limit / (1024 * 1024))} MB`
}
}
request = { ...request, to, filePath }
@@ -1019,6 +1168,10 @@ export class PersonalWechatSendService {
filePath: preparedImage.filePath
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
} else if (request.type === 'video') {
// 视频不复制到临时目录:原生 Host 直接按绝对路径读取。
const windowsRequest = buildWindowsWechatRequest(request)
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000)
} else if (request.type === 'voice') {
const fromId = String(request.fromId || '').trim()
if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音')
+76 -6
View File
@@ -39,7 +39,15 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
// purpose,各自有幂等位 —— 少这一条会被 evaluateWechatActionPolicy 拦下。
'automation_scheduled_report_postfix',
'manual_report_image',
'manual_report_postfix'
'manual_report_postfix',
/*
* 扩展来源的两个用途。
*
* 扩展不能自己决定 purpose:`ExtensionSendGateway` 与自动化 runner 分别填这两个值,
* 且 `evaluateWechatActionPolicy` 要求 `origin === 'extension'`,两边同时成立才放行。
*/
'extension_send',
'extension_action'
])
export interface ReportImageSequenceRequest {
@@ -137,6 +145,46 @@ export class WechatActionGateway {
return this.loadAuditState().records.map((record) => ({ ...record }))
}
/**
* 扩展来源的发送入口。
*
* 与 `execute()` 的区别只有一个:`origin` / `purpose` / `metadata.extensionId`
* 由这里按宿主规则填,扩展侧传不进来。其余检查(能力、审计、幂等、
* 自动化发送节流)与普通发送完全一致。
*/
async executeFromExtension(input: {
extensionId: string
purpose: 'extension_send' | 'extension_action'
recipient: WechatActionRequest['recipient']
content: WechatActionContent
idempotencyKey?: string
executionId?: string
}): Promise<WechatActionResult> {
const extensionId = String(input.extensionId || '').trim()
const startedAt = this.deps.now().toISOString()
if (!extensionId) {
return {
actionId: randomUUID(),
status: 'blocked',
decision: 'block',
errorCode: 'INVALID_REQUEST',
reason: '扩展发送缺少扩展标识',
startedAt,
finishedAt: startedAt
}
}
return this.execute({
...(input.idempotencyKey ? { idempotencyKey: String(input.idempotencyKey) } : {}),
...(input.executionId ? { executionId: String(input.executionId) } : {}),
origin: 'extension',
purpose: input.purpose,
triggerType: 'automation',
recipient: input.recipient,
content: input.content,
metadata: { extensionId }
})
}
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
const normalized = normalizeActionRequest(request)
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
@@ -256,9 +304,10 @@ export class WechatActionGateway {
const queued = this.automationSendTail.then(async () => {
const now = this.deps.now().getTime()
const remaining = this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
const remaining =
this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
if (remaining > 0) await this.deps.wait(remaining)
this.lastAutomationSendStartedAt = this.deps.now().getTime()
return this.deps.send(sendRequest)
@@ -393,14 +442,20 @@ export class WechatActionGateway {
!request.content ||
(request.content.type !== 'text' &&
request.content.type !== 'image' &&
request.content.type !== 'video' &&
request.content.type !== 'voice')
) {
return
}
const state = this.loadAuditState()
const extensionId =
request.metadata && typeof request.metadata.extensionId === 'string'
? request.metadata.extensionId.trim().slice(0, 128)
: ''
const record: WechatActionAuditRecord = {
actionId: result.actionId,
...(idempotencyKey ? { idempotencyKey } : {}),
...(extensionId ? { extensionId } : {}),
origin: request.origin,
purpose: request.purpose,
triggerType: request.triggerType,
@@ -465,6 +520,18 @@ export function evaluateWechatActionPolicy(request: WechatActionRequest): Policy
reason: `自动化动作不允许执行 purpose=${request.purpose}`
}
}
/*
* 扩展用途必须来自扩展来源。少了这一条,任何能构造 `WechatActionRequest` 的
* 内部调用都可以用 `extension_send` 绕过自动化用途白名单。
*/
if (String(request.purpose).startsWith('extension_') && request.origin !== 'extension') {
return {
decision: 'block',
source: 'deterministic',
reasonCode: 'ACTION_NOT_ALLOWED',
reason: '扩展发送用途只能用于扩展来源的请求'
}
}
return { decision: 'allow', source: 'deterministic' }
}
@@ -526,7 +593,7 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu
content: { type: 'text', text, ...(at ? { at } : {}) }
} as WechatActionRequest
}
if (contentType !== 'image' && contentType !== 'voice') return null
if (contentType !== 'image' && contentType !== 'video' && contentType !== 'voice') return null
const filePath = String((content as { path?: unknown }).path || '').trim()
if (!filePath) return null
return {
@@ -585,6 +652,9 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech
if (request.content.type === 'image') {
return { ...base, type: 'image', filePath: request.content.path }
}
if (request.content.type === 'video') {
return { ...base, type: 'video', filePath: request.content.path }
}
const metadata = request.metadata && typeof request.metadata === 'object' ? request.metadata : {}
const fromId = typeof metadata.fromId === 'string' ? metadata.fromId.trim() : ''
const durationMs =
@@ -638,7 +708,7 @@ function contentAudit(
}
function contentTypeLabel(type: WechatActionContent['type']): string {
return type === 'text' ? '文字' : type === 'image' ? '图片' : '语音'
return type === 'text' ? '文字' : type === 'image' ? '图片' : type === 'video' ? '视频' : '语音'
}
function normalizeAuditRecords(values: unknown[]): WechatActionAuditRecord[] {