feat: 拓展中心加入机器人

This commit is contained in:
Wxw-Gu committed 2026-11-18 11:22:39 +08:00
1 parent 4eaddc2d75
commit a81b3733fa
31 files changed
+3510 -566

No files matched your search

+24 -64
View File
@@ -19,7 +19,8 @@ import {
type ExtensionSendImageRequest,
type ExtensionSendTextRequest,
type ExtensionSendTextResult,
type ExtensionSendVideoRequest
type ExtensionSendVideoRequest,
type ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
@@ -49,12 +50,7 @@ const STDERR_WINDOW_BYTES = 64 * 1024
const STDERR_WINDOW_ENTRIES = 20
const STDERR_MAX_CHUNK_CHARS = 400
/**
* stderr 里常见的凭据写法。
*
* 扩展的 stderr 是任意文本,可能包含用户配置的 Cookie / Token;
* 落日志前统一抹掉值,只保留键名。
*/
/** stderr 里的凭据形态;落日志前只保留键名。 */
const SECRET_ASSIGNMENT =
/\b(cookie|token|authorization|password|passwd|secret|api[_-]?key)\b(\s*[:=]\s*)(?!Bearer\b)([^\s,;"']{4,})/gi
const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi
@@ -79,10 +75,7 @@ export interface ExtensionHostChild {
on(event: 'error', listener: (error: Error) => void): void
once?(event: 'exit', listener: () => void): void
readonly pid?: number
/**
* 子进程的 stderr。必须被消费:管道写满会让子进程在 `write` 上阻塞,
* 表现为「扩展还活着但不再响应」。
*/
/** stderr 必须持续消费,否则管道写满会让子进程阻塞在 write。 */
readonly stderr?: NodeJS.ReadableStream | null
}
@@ -119,6 +112,10 @@ export interface ExtensionHostDependencies {
extensionId: string,
request: ExtensionSendVideoRequest
) => Promise<ExtensionSendTextResult>
sendVoice?: (
extensionId: string,
request: ExtensionSendVoiceRequest
) => Promise<ExtensionSendTextResult>
aiChat?: (
extensionId: string,
messages: Array<{ role: string; content: string }>
@@ -155,15 +152,7 @@ interface ActivationWaiter {
child: ExtensionHostChild
}
/**
* 单个扩展的后台进程。
*
* **隔离边界**:每个扩展一个独立 Node 子进程,`require` 只发生在那里面;
* 主进程从不 `require` 扩展代码。子进程拿不到 Electron API、数据库句柄、
* 授权凭据或原生发送通道 —— 它只能通过本类转发的白名单 RPC 申请能力。
*
* ⚠️ 独立进程不等于强沙箱:后台仍是任意 Node 代码,安装时按「受信任本地开发者扩展」处理。
*/
/** 单个扩展的后台进程:独立 Node 子进程,主进程从不 require 扩展代码。 */
export class ExtensionHost {
private readonly dependencies: ExtensionHostDependencies
private readonly storage: ExtensionStorage
@@ -216,16 +205,11 @@ export class ExtensionHost {
return Array.from(this.actions.values()).map((action) => ({ ...action }))
}
/**
* 把页面请求转给同扩展的后台处理器。
*
* 这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。
* 响应大小与超时都在这里收口,避免页面被一个坏 handler 拖死。
*/
/** 把页面请求转给同扩展的后台处理器;这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。 */
async requestPage(
method: string,
params: Record<string, unknown>,
timeoutMs = 10_000
timeoutMs = 90_000
): Promise<unknown> {
const child = this.child
if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
@@ -310,13 +294,7 @@ export class ExtensionHost {
return this.activation
}
/**
* 停止后台进程。
*
* 三段式:先请扩展自行退出,超时后结束整棵进程树,再等真实的 exit 事件。
* 只有收到 exit 才算停止完成——只发信号就返回,会让上层在进程仍占用
* 文件时去替换扩展目录(Windows 上必然失败,POSIX 上会留下旧代码在跑)。
*/
/** 停止后台:等真实 exit 才算完成,只发信号会在进程占用文件时替换失败。 */
async stop(): Promise<void> {
this.stopping = true
if (this.restartTimer) {
@@ -353,15 +331,7 @@ export class ExtensionHost {
this.setState('inactive')
}
/**
* 结束扩展进程及其派生进程。
*
* POSIX 依赖 `fork` 时的 `detached` 建立独立进程组,`kill(-pid)` 一次覆盖整组;
* 组不存在时退化为只杀直接子进程,并记一条降级日志。
*
* Windows 用 `taskkill /T /F`,且必须**在父进程仍存活时**执行:
* 父进程先退出后,进程树的父子关系消失,`/T` 再也找不到孙进程。
*/
/** 结束进程树;Windows 的 taskkill /T 必须在父进程存活时执行,否则找不到孙进程。 */
private killTree(child: ExtensionHostChild): void {
const pid = child.pid
if (!pid) {
@@ -392,12 +362,7 @@ export class ExtensionHost {
})
}
/**
* 投递消息事件。
*
* 令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志,
* 也不能让主进程的监听回调被拖垮。
*/
/** 投递消息事件;令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志, 也不能让主进程的监听回调被拖垮。 */
deliverEvent(envelope: ExtensionEventEnvelope): boolean {
if (this.state.state !== 'active' || !this.child) return false
this.refillTokens()
@@ -554,13 +519,7 @@ export class ExtensionHost {
this.consumeStderr(child)
}
/**
* 消费子进程 stderr。
*
* 两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞),
* 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。
* 凭据形态的字段在落日志前抹掉值。
*/
/** 消费子进程 stderr;两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞), 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。 */
private consumeStderr(child: ExtensionHostChild): void {
const stream = child.stderr
if (!stream || typeof stream.on !== 'function') return
@@ -832,6 +791,14 @@ export class ExtensionHost {
params as unknown as ExtensionSendVideoRequest
)
}
case 'wechat.send.voice': {
this.requirePermission('wechat.send.voice')
if (!this.dependencies.sendVoice) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendVoice(
extensionId,
params as unknown as ExtensionSendVoiceRequest
)
}
case 'ai.chat': {
this.requirePermission('ai.chat')
if (!this.dependencies.aiChat) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
@@ -907,14 +874,7 @@ export class ExtensionHost {
}
}
/**
* 结束 `pid` 对应的进程树。
*
* 返回值表示实际使用的手段:
* - `group`:POSIX 进程组,覆盖扩展派生的全部子进程;
* - `taskkill`:Windows 进程树,必须在父进程仍存活时调用;
* - `fallback`:只能结束进程本身,调用方应记录降级。
*/
/** 结束 `pid` 对应的进程树;`taskkill`:Windows 进程树,必须在父进程仍存活时调用。 */
export function killProcessTree(
pid: number | undefined,
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {}
+79 -120
View File
@@ -31,6 +31,7 @@ import type {
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
ExtensionTtsCapabilitySnapshot,
InstalledExtension
} from '../../shared/extensions/types'
import type {
@@ -40,7 +41,8 @@ import type {
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest
ExtensionSendVideoRequest,
ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
@@ -84,6 +86,13 @@ export interface ExtensionManagerDependencies {
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
/** 当前 AI 是否已配置;不暴露 key、endpoint 或任何凭据。 */
aiStatus?: () => { configured: boolean; modelName: string }
/** 当前文字转语音配置与选定音色摘要;不暴露 key。 */
ttsStatus?: () => Promise<ExtensionTtsCapabilitySnapshot> | ExtensionTtsCapabilitySnapshot
synthesizeVoice?: (request: {
text: string
voiceId?: string
}) => Promise<{ filePath: string }>
cleanupVoice?: (filePath: string) => void
getAccountId: () => string
getSelfUsernames: () => string[]
isDatabaseReady: () => boolean
@@ -112,16 +121,7 @@ const PAGE_METHODS: ExtensionPageMethod[] = [
'extension.info'
]
/**
* 扩展系统的编排层。
*
* 职责边界:
* - **只做编排**:清单读取、安装、启停、进程托管、事件分发、能力转发;
* - 不实现消息监听(复用 `MessageListenerService`)、不实现发送(复用
* `WechatActionGateway`)、不实现自动化规则存储(复用 `AutomationRuleStore`)。
*
* 所有扩展代码都在 `ExtensionHost` 的子进程里运行;本类不 `require` 任何扩展文件。
*/
/** 扩展系统的编排层:只管编排,不实现消息监听、发送与规则存储。 */
export class ExtensionManager {
private readonly dependencies: ExtensionManagerDependencies
private readonly paths: ExtensionPaths
@@ -187,6 +187,9 @@ export class ExtensionManager {
checkEntitlement: dependencies.checkEntitlement,
executeAction: dependencies.executeAction,
getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId),
synthesizeVoice: dependencies.synthesizeVoice,
cleanupVoice: dependencies.cleanupVoice,
getFromId: () => dependencies.getAccountId(),
now: this.now
})
this.eventBus = new ExtensionEventBus({
@@ -275,12 +278,7 @@ export class ExtensionManager {
}
}
/**
* 校验状态记录与磁盘上的 manifest 是否描述同一个版本。
*
* 升级会在「换代码」与「写状态」之间留下一个窗口;进程在该窗口被杀时,
* 磁盘上是新代码、状态里是旧版本。这种扩展不能带着旧授权直接跑。
*/
/** 校验状态记录与磁盘上的 manifest 是否描述同一个版本;这种扩展不能带着旧授权直接跑。 */
private checkInstallConsistency(
record: ExtensionRegistryRecord,
manifest: ExtensionManifest
@@ -343,14 +341,7 @@ export class ExtensionManager {
return this.templates.list()
}
/**
* 安装官方模板。
*
* 三条硬约束:
* 1. 只接受模板索引里的 id,ZIP 路径由目录服务解析并校验哈希;
* 2. 同 id 已被非模板来源占用时拒绝接管;
* 3. 安装只落代码,不启用——启用仍需用户确认权限。
*/
/** 安装官方模板;同 id 被非模板来源占用时拒绝接管。 */
async installTemplate(templateId: string): Promise<ExtensionInstallResult> {
const templates = this.templates
if (!templates) {
@@ -393,22 +384,12 @@ export class ExtensionManager {
)
}
/**
* 该扩展当前是否被暂停(配置待确认 / 版本不一致)。
*
* 这是唯一的判断入口:事件投递、动作调用、发送出口都走它,
* 避免出现「某处放行、某处拦截」的不一致状态。
*/
/** 该扩展是否被暂停(配置待确认 / 版本不一致);事件、动作、发送都看它。 */
private isSuspended(extensionId: string): boolean {
return this.storageHolds.has(extensionId) || this.inconsistencies.has(extensionId)
}
/**
* 运行期检测到配置回退:立刻收住这个扩展。
*
* 顺序很重要:先停后台(切断正在跑的回复循环),再改状态、记日志。
* 已经交给 Native Host 的发送请求无法撤回,属于已知边界。
*/
/** 运行期检测到配置回退:立刻收住这个扩展。 */
private handleStorageHealthChange(
extensionId: string,
health: { state: string; message?: string }
@@ -442,12 +423,7 @@ export class ExtensionManager {
}
}
/**
* 链接外部开发项目。
*
* 只读用户显式选择的目录:校验 manifest、入口文件、路径边界与 ID 冲突,
* 然后登记为 `development` 来源。**不复制代码**,也不写回源码目录。
*/
/** 链接外部开发项目:只读用户选的目录,不复制代码,也不写回源码目录。 */
async linkDevelopmentProject(directory: string): Promise<ExtensionInstallResult> {
const raw = String(directory || '').trim()
if (!raw) {
@@ -553,12 +529,7 @@ export class ExtensionManager {
return { success: true, ...(extension ? { extension } : {}) }
}
/**
* 重新加载开发项目。
*
* 停后台 → 清 manifest 缓存 → 重新解析 → 权限取交集 → 原本启用则重启。
* 页面侧由界面刷新 iframe 完成,两者互不依赖。
*/
/** 重新加载开发项目。 */
async reloadDevelopment(extensionId: string): Promise<ExtensionOperationResult> {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
@@ -627,12 +598,7 @@ export class ExtensionManager {
return { success: true }
}
/**
* 移除开发链接。
*
* 绝不删除外部源码目录。若安装副本还在,把来源退回安装副本;
* 否则移除 Registry 记录。用户数据按 `keepData` 决定。
*/
/** 移除开发链接:有安装副本就退回它,否则删记录;外部目录永不删除。 */
async unlinkDevelopment(
extensionId: string,
options: { keepData: boolean }
@@ -681,11 +647,7 @@ export class ExtensionManager {
return { success: true }
}
/**
* 把开发项目转成正式安装副本。
*
* 只复制代码;用户配置本来就在 `extensions-data`,不受影响。
*/
/** 把开发项目转成正式安装副本。 */
async convertDevelopmentToInstalled(extensionId: string): Promise<ExtensionOperationResult> {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
@@ -728,12 +690,7 @@ export class ExtensionManager {
return { success: true }
}
/**
* 从官方模板生成一个独立项目(不安装、不启用)。
*
* ZIP 来自官方模板目录并已校验哈希;生成过程在暂存目录完成,
* 目标目录非空时不会写入任何文件。
*/
/** 从官方模板生成一个独立项目(不安装、不启用)。 */
async createProjectFromTemplate(
templateId: string,
targetDirectory: string,
@@ -789,12 +746,7 @@ export class ExtensionManager {
}
}
/**
* 把已安装副本导出成外部项目,并把来源切换为 development。
*
* 导出的必须是**用户改过的安装副本**,不能重新解压官方 ZIP——
* 那样会把二开内容换回原版。原安装副本保留,作为显式恢复来源。
*/
/** 把已安装副本导出成外部项目,并把来源切换为 development。 */
async exportInstalledAsProject(
extensionId: string,
targetDirectory: string
@@ -895,12 +847,7 @@ export class ExtensionManager {
}
}
/**
* 授予扩展已声明的权限。
*
* 只接受 manifest 里出现过的权限:渲染层传来的字符串不能扩大扩展的能力面。
* 权限在子进程启动时快照,因此已启用的扩展需要重启后台才会生效。
*/
/** 授予扩展已声明的权限;只接受 manifest 里出现过的权限:渲染层传来的字符串不能扩大扩展的能力面。 */
async grantPermissions(
extensionId: string,
permissions: ExtensionPermission[]
@@ -1040,11 +987,7 @@ export class ExtensionManager {
return { success: true }
}
/**
* 采用磁盘上的代码版本:把状态记录的版本对齐到 manifest。
*
* 用于「上次升级中断」后的修复。授权按新 manifest 取交集,不会扩大能力。
*/
/** 采用磁盘上的代码版本:把状态记录的版本对齐到 manifest。 */
adoptInstalledCode(extensionId: string): ExtensionOperationResult {
const record = this.registry.get(extensionId)
const manifest = this.readManifest(extensionId)
@@ -1137,12 +1080,7 @@ export class ExtensionManager {
}
}
/**
* 扩展页面可调用的能力。
*
* 页面**没有**发送 / 查询 / AI 权限:那些能力只从后台进程按权限申请。
* 页面与后台共享同一个 `storage` 命名空间,所以配置页保存的内容后台能直接读到。
*/
/** 扩展页面可调用的能力。 */
async pageRequest(
extensionId: string,
method: string,
@@ -1214,7 +1152,7 @@ export class ExtensionManager {
result: await host.requestPage(
inner,
(rawParams as Record<string, unknown> | undefined) ?? {},
10_000
90_000
)
}
}
@@ -1273,12 +1211,7 @@ export class ExtensionManager {
return this.actions.list()
}
/**
* 供自动化编辑器使用的动作列表。
*
* `registered` 只是「后台注册过」,是否可用要逐条判断:停用、代码缺失、
* 权限未授予、Storage 暂停、Schema 非法,任一成立都不可执行。
*/
/** 供自动化编辑器使用的动作列表。 */
listActions(): ExtensionActionInfo[] {
return this.actions.list().map((action) => {
const record = this.registry.get(action.extensionId)
@@ -1322,13 +1255,7 @@ export class ExtensionManager {
await Promise.all(ids.map((id) => this.stopHost(id)))
}
/**
* 安装 / 升级的编排。
*
* 顺序是「停旧进程 → 换代码 → 写状态 → 起新进程」,任何一步失败都要让
* 磁盘与 Registry 回到同一个版本。仅靠多次 rename 不构成跨进程事务,
* 所以失败时显式回滚,并把错误原样返回给界面,不吞成成功。
*/
/** 安装 / 升级的编排。 */
private async install(
run: (
beforeReplace: (
@@ -1404,12 +1331,7 @@ export class ExtensionManager {
return { success: true, ...(installed ? { extension: installed } : {}) }
}
/**
* 模板来源的「本地改动」检查。
*
* 只保护 `template` 来源:用户自己装的 ZIP / 目录本来就会被覆盖,
* 开发模式根本没有安装副本可覆盖。
*/
/** 模板来源的「本地改动」检查。 */
private assertTemplateCodeUntouched(record: ExtensionRegistryRecord): void {
const root = this.paths.installDir(record.id)
if (!fs.existsSync(path.join(root, 'manifest.json'))) return
@@ -1471,6 +1393,7 @@ export class ExtensionManager {
sendText: (id, request) => this.sendText(id, request),
sendImage: (id, request) => this.sendImage(id, request),
sendVideo: (id, request) => this.sendVideo(id, request),
sendVoice: (id, request) => this.sendVoice(id, request),
aiChat: (_id, messages) => this.dependencies.aiChat(messages),
capabilities: (id) => this.buildCapabilitySnapshot(id)
})
@@ -1544,14 +1467,14 @@ export class ExtensionManager {
if (!conversationId || conversationId.length > 128) {
throw new ExtensionError('INVALID_REQUEST', '会话 id 不合法')
}
const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 200))
const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 500))
const startTime = Number.isFinite(Number(request?.startTime))
? Number(request.startTime)
: Date.now() - 24 * 60 * 60 * 1000
const endTime = Number.isFinite(Number(request?.endTime)) ? Number(request.endTime) : Date.now()
if (endTime <= startTime) throw new ExtensionError('INVALID_REQUEST', '时间范围不合法')
if (endTime - startTime > 7 * 24 * 60 * 60 * 1000) {
throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 7 天')
if (endTime - startTime > 35 * 24 * 60 * 60 * 1000) {
throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 35 天')
}
const record = this.registry.get(extensionId)
if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED')
@@ -1626,15 +1549,54 @@ export class ExtensionManager {
)
}
private async sendVoice(
extensionId: string,
request: ExtensionSendVoiceRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (this.isSuspended(extensionId)) {
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝')
}
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendVoice(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async buildCapabilitySnapshot(extensionId: string): Promise<ExtensionCapabilitySnapshot> {
const record = this.registry.get(extensionId)
const granted = record?.grantedPermissions ?? []
const capability = await this.dependencies.getCapability().catch(() => null)
let licensed = false
if (hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text')) {
if (
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text') ||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.voice') ||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.image') ||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.video')
) {
const entitlement = await this.dependencies.checkEntitlement().catch(() => null)
licensed = entitlement?.ok === true
}
let tts: ExtensionTtsCapabilitySnapshot | undefined
if (this.dependencies.ttsStatus) {
try {
tts = await this.dependencies.ttsStatus()
} catch {
tts = {
configured: false,
model: 's2.1-pro-free',
selectedVoiceId: '',
selectedVoice: null
}
}
}
return {
extensionId,
enabled: record?.enabled === true,
@@ -1647,6 +1609,7 @@ export class ExtensionManager {
canSendText: Boolean(capability?.capabilities?.text),
canSendImage: Boolean(capability?.capabilities?.image),
canSendVideo: Boolean(capability?.capabilities?.video),
canSendVoice: Boolean(capability?.capabilities?.voice),
licensed,
message: capability?.message || '暂时无法获知微信发送能力'
},
@@ -1659,7 +1622,8 @@ export class ExtensionManager {
} catch {
return { configured: false, modelName: '' }
}
})()
})(),
...(tts ? { tts } : {})
}
}
@@ -1720,12 +1684,7 @@ export class ExtensionManager {
}
}
/**
* 没有 Host 时的运行状态。
*
* 只有页面入口的扩展本来就不会有后台进程,必须与「启用但启动失败」区分开:
* 前者是 `inactive` 加说明,后者是 `error` 加原因。
*/
/** 没有 Host 时的运行状态。 */
private deriveIdleRuntime(
record: ExtensionRegistryRecord,
manifest: ExtensionManifest | null
+4 -11
View File
@@ -25,12 +25,7 @@ const MIME_TYPES: Record<string, string> = {
'.wasm': 'application/wasm'
}
/**
* 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在
* 扩展目录内;响应带严格 CSP(无外链、无内联脚本、无网络)。
*
* `registerSchemesAsPrivileged` 必须在 app ready 前调用。
*/
/** 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在。 */
export function registerExtensionScheme(): void {
protocol.registerSchemesAsPrivileged([
{
@@ -48,10 +43,7 @@ export function registerExtensionScheme(): void {
export interface ExtensionProtocolDependencies {
paths: ExtensionPaths
/**
* 解析扩展代码根目录。开发模式下是外部源码目录,
* 必须与后台进程、Manifest 读取使用同一个解析器,否则页面会读到旧副本。
*/
/** 解析代码根目录:开发模式指向外部源码,必须与后台/Manifest 用同一解析器。 */
resolveRoot: (extensionId: string) => string | null
}
@@ -86,7 +78,8 @@ export function installExtensionProtocolHandler(dependencies: ExtensionProtocolD
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"img-src 'self' data: https:",
"media-src 'self' data: https:",
"font-src 'self' data:",
"connect-src 'none'",
"object-src 'none'",
+128 -25
View File
@@ -11,7 +11,8 @@ import type {
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest
ExtensionSendVideoRequest,
ExtensionSendVoiceRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
@@ -19,6 +20,7 @@ import type { ExtensionEntitlementResult } from './extension-entitlement'
import { isPathInside } from './extension-paths'
const MAX_TEXT_LENGTH = 2_000
const MAX_VOICE_TEXT_LENGTH = 1_000
const MAX_RECIPIENT_LENGTH = 128
const MAX_MEDIA_BYTES = 100 * 1024 * 1024
const SEND_INTERVAL_MS = 2_000
@@ -27,6 +29,7 @@ const SEND_WINDOW_LIMIT = 10
/** 原生发送端把视频按 `type: 'video'` 提交,这里只放行常见容器。 */
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'])
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v'])
const VOICE_EXTENSIONS = new Set(['.mp3', '.wav', '.silk', '.amr', '.m4a', '.ogg'])
export interface ExtensionSendContext {
extensionId: string
@@ -41,20 +44,28 @@ export interface ExtensionSendGatewayDependencies {
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
/** 扩展数据目录;媒体文件只允许从这里或系统临时目录发送。 */
getExtensionDataRoot?: (extensionId: string) => string
/** 使用宿主已配置的文字转语音服务生成临时音频文件。 */
synthesizeVoice?: (request: {
text: string
voiceId?: string
}) => Promise<{ filePath: string }>
cleanupVoice?: (filePath: string) => void
getFromId?: () => string | Promise<string>
now?: () => number
}
/**
* 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。
*
* origin、purpose、triggerType、幂等键全部由宿主填写,扩展只描述
* 「发给谁、发什么」。
*/
/** 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。 */
export class ExtensionSendGateway {
private readonly getCapability: () => Promise<PersonalWechatSendCapability>
private readonly checkEntitlement: () => Promise<ExtensionEntitlementResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly getExtensionDataRoot: (extensionId: string) => string
private readonly synthesizeVoice?: (request: {
text: string
voiceId?: string
}) => Promise<{ filePath: string }>
private readonly cleanupVoice?: (filePath: string) => void
private readonly getFromId?: () => string | Promise<string>
private readonly now: () => number
private readonly sendHistory = new Map<string, number[]>()
@@ -63,6 +74,9 @@ export class ExtensionSendGateway {
this.checkEntitlement = dependencies.checkEntitlement
this.executeAction = dependencies.executeAction
this.getExtensionDataRoot = dependencies.getExtensionDataRoot ?? (() => '')
this.synthesizeVoice = dependencies.synthesizeVoice
this.cleanupVoice = dependencies.cleanupVoice
this.getFromId = dependencies.getFromId
this.now = dependencies.now ?? (() => Date.now())
}
@@ -124,12 +138,7 @@ export class ExtensionSendGateway {
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/**
* 发送图片。
*
* 文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件,
* 否则扩展就能借 TraceMemo 把本机任意文件发出去。
*/
/** 发送图片;文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件, 否则扩展就能借 TraceMemo 把本机任意文件发出去。 */
async sendImage(
context: ExtensionSendContext,
request: ExtensionSendImageRequest
@@ -188,12 +197,7 @@ export class ExtensionSendGateway {
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/**
* 发送视频。
*
* 与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。
* 文件边界与图片相同(扩展数据目录 / 临时目录、普通文件、≤ 100MB)。
*/
/** 发送视频;与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。 */
async sendVideo(
context: ExtensionSendContext,
request: ExtensionSendVideoRequest
@@ -252,6 +256,110 @@ export class ExtensionSendGateway {
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/** 发送语音气泡。 */
async sendVoice(
context: ExtensionSendContext,
request: ExtensionSendVoiceRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.voice')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.voice 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const rawPath = String(request?.path || '').trim()
const rawText = String(request?.text || '').trim()
if (!rawPath && !rawText) {
throw new ExtensionError('INVALID_REQUEST', '发送语音需要提供 text 或音频文件 path')
}
if (rawText.length > MAX_VOICE_TEXT_LENGTH) {
throw new ExtensionError(
'INVALID_REQUEST',
`语音合成文字不能超过 ${MAX_VOICE_TEXT_LENGTH} 字`
)
}
let directMediaPath = ''
if (rawPath) {
directMediaPath = assertSendableMediaPath(
rawPath,
this.getExtensionDataRoot(context.extensionId),
VOICE_EXTENSIONS
)
} else if (!this.synthesizeVoice) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前宿主未配置文字转语音合成能力')
}
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.voice) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '当前微信发送能力不支持语音'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
let synthesizedFile = ''
try {
let mediaPath = directMediaPath
if (!mediaPath && this.synthesizeVoice) {
const voiceId = String(request?.voiceId || '').trim() || undefined
const synthesized = await this.synthesizeVoice({ text: rawText, voiceId })
synthesizedFile = String(synthesized?.filePath || '').trim()
mediaPath = assertSendableMediaPath(
synthesizedFile,
this.getExtensionDataRoot(context.extensionId),
VOICE_EXTENSIONS
)
}
const fromId = this.getFromId ? String((await this.getFromId()) || '').trim() : ''
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'voice', path: mediaPath },
metadata: {
extensionId: context.extensionId,
...(fromId ? { fromId } : {})
}
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信语音发送失败')
} finally {
if (synthesizedFile && this.cleanupVoice) {
try {
this.cleanupVoice(synthesizedFile)
} catch {
// 临时语音清理失败不影响主流程结果。
}
}
}
}
/** 令牌窗口:同一扩展 60 秒内最多 10 条,且两条之间至少 2 秒。 */
private assertRateLimit(extensionId: string): void {
const now = this.now()
@@ -270,12 +378,7 @@ export class ExtensionSendGateway {
}
}
/**
* 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件。
*
* 用 realpath 复核,符号链接跳到目录外同样会被拒绝;这一层不能省,
* 否则 `wechat.send.image` 就等价于「读取并外发任意本机文件」。
*/
/** 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件;用 realpath 复核,符号链接跳到目录外同样会被拒绝。 */
function assertSendableMediaPath(value: unknown, dataRoot: string, allowed: Set<string>): string {
const raw = String(value ?? '').trim()
if (!raw || raw.length > 4_096) {
+94 -24
View File
@@ -10,6 +10,7 @@ import {
resolveMd5
} from '../services/chat-service'
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
import { TextToSpeechSettingsService } from '../services/text-to-speech-settings-service'
import { wechatActionGateway } from '../services/wechat-action-gateway'
import { ExtensionError } from '../../shared/extensions/errors'
import type {
@@ -22,12 +23,7 @@ import { getExtensionPaths } from './extension-paths'
let manager: ExtensionManager | null = null
/**
* 官方模板资源根目录。
*
* 打包后是 `<resources>/extension-templates`;开发态读构建产物目录。
* 两者都不指向 `examples/extensions`——源码树不是运行时依赖。
*/
/** 官方模板资源根目录;两者都不指向 `examples/extensions`——源码树不是运行时依赖。 */
function resolveTemplateRoot(): string {
const override = process.env.TRACEMEMO_EXTENSION_TEMPLATES_DIR
if (override && override.trim()) return path.resolve(override.trim())
@@ -40,14 +36,10 @@ export interface ExtensionSystemOptions {
onChange: (extensionId: string, reason: string) => void
}
/**
* 扩展系统的主进程接线。
*
* 这里只做依赖注入:所有能力都来自既有服务,扩展系统自己不实现第二套
* 消息监听、发送通道或 AI Provider。
*/
/** 扩展系统的主进程接线。 */
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
if (manager) return
const ttsService = new TextToSpeechSettingsService()
manager = new ExtensionManager({
paths: getExtensionPaths(),
appVersion: options.appVersion,
@@ -73,6 +65,50 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
const config = new AIProviderService().getRuntimeConfig()
return { configured: config.configured, modelName: config.modelName }
},
ttsStatus: async () => {
const status = await ttsService.getVoiceStatus()
return {
configured: status.configured,
model: status.model,
selectedVoiceId: status.selectedVoiceId,
selectedVoice: status.selectedVoice
? {
id: status.selectedVoice.id,
name: status.selectedVoice.name,
description: status.selectedVoice.description,
tags: status.selectedVoice.tags,
languages: status.selectedVoice.languages,
...(status.selectedVoice.authorName
? { authorName: status.selectedVoice.authorName }
: {}),
...(status.selectedVoice.previewUrl
? { previewUrl: status.selectedVoice.previewUrl }
: {}),
...(status.selectedVoice.coverImage
? { coverImage: status.selectedVoice.coverImage }
: {})
}
: null
}
},
synthesizeVoice: async ({ text, voiceId }) => {
const current = ttsService.get()
const referenceId = String(voiceId || current.settings.selectedVoiceId || '').trim()
if (!referenceId) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '请先在文字转语音设置中选择音色')
}
const synthesized = await ttsService.synthesize({ text, referenceId })
if (!synthesized.success || !synthesized.filePath) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
synthesized.error || '文字转语音生成失败'
)
}
return { filePath: synthesized.filePath }
},
cleanupVoice: (filePath) => {
ttsService.removeGeneratedAudio(filePath)
},
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
getSelfUsernames: () => {
try {
@@ -114,29 +150,63 @@ export async function disposeExtensionSystem(): Promise<void> {
if (current) await current.dispose()
}
function normalizeQueriedMessageType(rawType: string | undefined): {
type: string
isTextLike: boolean
} {
const value = String(rawType ?? '').trim()
if (value === 'text' || value === '普通文本' || value === '1') {
return { type: 'text', isTextLike: true }
}
if (value === '引用消息') {
return { type: 'text', isTextLike: true }
}
if (value === '图片' || value === 'image') return { type: 'image', isTextLike: false }
if (value === '语音' || value === 'voice') return { type: 'voice', isTextLike: false }
if (value === '视频' || value === 'video') return { type: 'video', isTextLike: false }
if (value === '表情包' || value === 'sticker') return { type: 'sticker', isTextLike: false }
if (value === '系统消息' || value === 'system') return { type: 'system', isTextLike: false }
return { type: value || 'other', isTextLike: false }
}
async function queryConversationMessages(
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
const contact = resolveMd5(request.conversationId)
if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接')
const messages = await listMessagesAsync(
const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500))
const rawMessages = await listMessagesAsync(
contact.md5,
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
Math.floor((request.endTime ?? Date.now()) / 1000),
{ limit: request.limit ?? 50 },
undefined,
'',
'unknown'
)
return messages.map((message) => ({
messageId: message.serverId || String(message.localId ?? message.id),
conversationId: request.conversationId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.name ? { senderName: message.name } : {}),
isSelf: message.isSender === true,
type: message.type,
...(message.type === 'text' ? { text: message.content } : {}),
timestamp: Math.round((message.createTime ?? 0) * 1000)
}))
const sorted = [...rawMessages]
.sort((left, right) => (left.createTime ?? 0) - (right.createTime ?? 0))
.slice(-limit)
return sorted.map((message) => {
const normalizedType = normalizeQueriedMessageType(message.type)
const quoteText =
message.contentData &&
typeof message.contentData === 'object' &&
message.contentData.type === 'quote' &&
typeof message.contentData.content === 'string'
? message.contentData.content
: ''
const resolvedText = String(message.content || quoteText || '').trim()
return {
messageId: message.serverId || String(message.localId ?? message.id),
conversationId: request.conversationId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.name ? { senderName: message.name } : {}),
isSelf: message.isSender === true,
type: normalizedType.type,
...(normalizedType.isTextLike && resolvedText ? { text: resolvedText } : {}),
timestamp: Math.round((message.createTime ?? 0) * 1000)
}
})
}
async function chatWithConfiguredProvider(
+32 -36
View File
@@ -1,12 +1,4 @@
/**
* 扩展后台进程入口。
*
* 这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、
* 把请求转成白名单 RPC。任何 `require` 都只发生在这里,主进程永远不会加载
* 第三方扩展代码。
*
* 与主进程的协议见 `src/shared/extensions/rpc.ts`。
*/
/** 扩展后台进程入口;这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、 把请求转成白名单 RPC。 */
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
@@ -108,12 +100,7 @@ const tm = {
return [...permissions]
}
},
/**
* 页面 → 同扩展后台的通用请求处理器注册。
*
* 不需要额外权限:注册本身不产生任何能力,handler 内部若调用
* `tm.wechat.send` 等能力,仍然各自走权限检查。
*/
/** 页面 → 同扩展后台的通用请求处理器注册。 */
page: {
onRequest(method: string, handler: (params: Record<string, unknown>) => unknown): void {
const name = String(method || '').trim()
@@ -123,12 +110,7 @@ const tm = {
pageHandlers.set(name, handler)
}
},
/**
* 扩展私有凭据。
*
* 真正加密发生在主进程(`safeStorage`);子进程只在需要时拿到明文。
* 每个扩展一个命名空间,A 扩展拿不到 B 的密钥。
*/
/** 扩展私有凭据。 */
secrets: {
async get(key: string): Promise<string | null> {
requirePermission('secrets')
@@ -166,27 +148,45 @@ const tm = {
limit?: number
}): Promise<{ messages: unknown[] }> {
requirePermission('messages.query')
const result = (await callHost('messages.query', { ...request })) as { messages: unknown[] }
const result = (await callHost('messages.query', { ...request }, 25_000)) as {
messages: unknown[]
}
return result
}
},
wechat: {
/**
* 发送文本、图片或视频。
*
* 兼容旧调用:不传 `type` 视为 `text`。视频走独立的 video 通道,
* 原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。
*/
/** 发送文本、图片、视频或语音。 */
async send(request: {
type?: 'text' | 'image' | 'video'
type?: 'text' | 'image' | 'video' | 'voice'
to: string
text?: string
path?: string
voiceId?: string
at?: Record<string, string>
dedupeKey?: string
}) {
const type =
request && (request.type === 'image' || request.type === 'video') ? request.type : 'text'
request &&
(request.type === 'image' || request.type === 'video' || request.type === 'voice')
? request.type
: 'text'
if (type === 'voice') {
requirePermission('wechat.send.voice')
return (await callHost(
'wechat.send.voice',
{
to: request.to,
...(request.path ? { path: request.path } : {}),
...(request.text ? { text: request.text } : {}),
...(request.voiceId ? { voiceId: request.voiceId } : {}),
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
150_000
)) as {
actionId: string
status: 'sent'
}
}
if (type === 'image' || type === 'video') {
requirePermission(type === 'video' ? 'wechat.send.video' : 'wechat.send.image')
return (await callHost(
@@ -383,11 +383,7 @@ async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
}
}
/**
* 与 UI 共用同一套校验规则。
*
* 两套实现一定会在某个边界上分叉,用户看到的就是「表单填得进去、执行时说参数错」。
*/
/** 与 UI 共用同一套校验规则。 */
function validateActionInput(
schema: Record<string, unknown> | undefined,
input: Record<string, unknown>
@@ -414,7 +410,7 @@ async function handlePageRequest(message: ExtensionHostPageRequest): Promise<voi
try {
const raw = await withTimeout(
Promise.resolve(handler(message.params ?? {})),
Math.max(1_000, Math.min(message.timeoutMs - 500, 30_000))
Math.max(1_000, Math.min(message.timeoutMs - 500, 90_000))
)
// 只允许纯 JSON:函数、循环引用、类实例都在这一步被拒绝。
const serialized = JSON.stringify(raw ?? null)
@@ -74,11 +74,7 @@ export function buildPersonalWechatRuntimePath(): string {
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
}
/**
* Build the environment used by TraceMemo's local voice encoding helpers.
* Keep this in one place so environment checks cannot accidentally inspect a
* different ffmpeg than the sender process.
*/
/** Build the environment used by TraceMemo's local voice encoding helpers.。 */
export function buildPersonalWechatRuntimeEnvironment(): NodeJS.ProcessEnv {
return {
...process.env,
@@ -217,13 +213,15 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
)
const pcm = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(result.stdout || '')
if (!pcm.length) throw new Error('语音转换失败:没有得到 PCM 音频数据')
const pcmDurationMs = Math.round((pcm.length / 2 / 24_000) * 1000)
const encoded = await new SilkAudioEncoder().encode(pcm, 24_000)
if (!encoded.data.length) throw new Error('语音转换失败:没有得到 SILK 数据')
const durationMs = encoded.durationMs >= 1000 ? encoded.durationMs : pcmDurationMs
const convertedPath = join(tmpdir(), `tracememo-voice-${randomBytes(8).toString('hex')}.silk`)
writeFileSync(convertedPath, encoded.data)
return {
filePath: convertedPath,
...(encoded.durationMs > 0 ? { durationMs: encoded.durationMs } : {}),
...(durationMs > 0 ? { durationMs } : {}),
temporary: true
}
}
@@ -297,12 +295,7 @@ function prepareMacWechatImageFile(
senderWxid: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { filePath: string; md5: string } {
/* Stage the image in WeChat's temporary image directory using the
* filename/hash layout required by the macOS native send path:
* - stage inside the active account's ImageTemp tree selected by
* findWechatImagePath(), not an arbitrary readable sandbox directory;
* - append a per-send salt before calculating MD5, so the staged image and
* the MD5 passed to the CDN task describe the same unique byte stream. */
/** Stage the image in WeChat's temporary image directory using the。 */
const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid)
if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录')
mkdirSync(temporaryRoot, { recursive: true })
@@ -346,12 +339,7 @@ function stageMacWechatImageForMessageSourceSend(
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` 目录。
*/
/** macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`。 */
export function stageMacWechatVideoForSend(
filePath: string,
wechatFilesRoot = WECHAT_FILES_ROOT
@@ -587,14 +575,7 @@ function isDefinitiveImageSourcePreparationFailure(message: string): boolean {
return message.trim() === 'IMAGE_PREPARATION_FAILED:0'
}
/**
* 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。
*
* 只有在设置里打开「调试模式」时才输出,所以正常使用不会刷屏。
*
* **隐私约束**:只允许输出类型、字节数、HTTP 状态码、hook 的 `ret` 这类结构性字段。
* 文件名、完整路径、wxid、群名、消息正文不进日志。
*/
/** 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。 */
function logSendDiagnostic(
stage: string,
detail: Record<string, string | number | boolean | null>
@@ -607,16 +588,7 @@ function logSendDiagnostic(
console.log(`[SendDiag] ${stage} ${JSON.stringify(detail)}`)
}
/**
* 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。
*
* 为什么留这个开关:`finally` 里的删除发生在 **hook 返回之后**,这隐含假设
* 「hook 返回时发送已经完成」。如果 hook 其实是「先回 200、后台再读文件」,
* 文件就可能在它读到之前已经被删掉 —— 现象正好是「hook 报成功、微信里没有消息」。
*
* 置为非 0 时可分辨两类失败:保留期间图片到了 ⇒ 删除时机问题(修法与 hook 约定文件生命周期);
* 仍然没到 ⇒ 与文件生命周期无关。
*/
/** 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。 */
const WINDOWS_TEMP_IMAGE_GRACE_MS = 0
/** 视频上传在 send_message 返回后才开始,删早了接收端只能拿到空文件。 */
@@ -784,10 +756,7 @@ export class PersonalWechatSendService {
}
}
/*
* macOS native runtime 的文字发送:HTTP POST /sendText 到 tm-wechat-host。
* 绑定状态由 host 侧保证;未绑定/未就绪时返回与旧契约一致的结果结构。
*/
/** macOS native runtime 的文字发送:HTTP POST /sendText 到 tm-wechat-host。 */
private async sendMacText(
request: Extract<PersonalWechatSendRequest, { type: 'text' }>
): Promise<PersonalWechatSendResult> {
@@ -856,12 +825,7 @@ export class PersonalWechatSendService {
return { success: true, status: resultStatus }
}
/*
* Resolve the bound account's own wxid from the local WeChat data root.
* The media proto embeds the sender, and the mac runtime does not learn it
* from inbound traffic, so it is read from
* the on-disk account identity instead.
*/
/** Resolve the bound account's own wxid from the local WeChat data root.。 */
private async resolveMacSenderWxid(): Promise<string> {
const identity = readLocalAccountIdentity(this.wechatFilesRoot)
return identity?.wxid ?? ''
@@ -881,11 +845,7 @@ export class PersonalWechatSendService {
if (response === null || !response.ok) return 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}`。
* 这里统一收敛,避免「实际已发送、界面报失败」。
*/
/** 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`。 */
const explicitFailure = payload.ok === false || payload.status === false
const ok =
!explicitFailure &&
@@ -897,13 +857,7 @@ export class PersonalWechatSendService {
}
}
/**
* macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。
*
* 微信运行在 App Sandbox 容器中,注入的 `libtmwechat.dylib` 在微信进程内执行,
* 只能访问微信沙盒容器目录(`~/Library/Containers/com.tencent.xinWeChat/Data/...`)。
* 因此先将容器外视频暂存到微信容器 `Documents` 目录,再调用 `/SendMsg`。
*/
/** macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。 */
private async sendMacVideo(
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
): Promise<PersonalWechatSendResult> {
@@ -1057,8 +1011,7 @@ export class PersonalWechatSendService {
if (!sender) return fail('无法识别当前微信账号 wxid')
}
/* Reuse the Windows SILK preparation: it already normalizes any input to
* SILK and reports the duration. */
/** Reuse the Windows SILK preparation: it already normalizes any input to。 */
let temporaryVoicePath: string | undefined
try {
const prepared = await prepareWindowsVoiceFile(filePath)
@@ -22,6 +22,20 @@ const FISH_AUDIO_PUBLIC_ASSET_URL = 'https://public-platform.r2.fish.audio/'
const DEFAULT_PAGE_SIZE = 24
const MAX_PAGE_SIZE = 100
const GENERATED_AUDIO_MAX_AGE_MS = 24 * 60 * 60 * 1000
const VOICE_META_CACHE_TTL_MS = 10 * 60 * 1000
const voiceMetaCache = new Map<string, { voice: TextToSpeechVoice; cachedAt: number }>()
function cacheVoiceMeta(voice: TextToSpeechVoice): void {
if (!voice?.id) return
voiceMetaCache.set(voice.id, { voice, cachedAt: Date.now() })
}
function getCachedVoiceMeta(id: string): TextToSpeechVoice | null {
const entry = voiceMetaCache.get(id)
if (!entry) return null
if (Date.now() - entry.cachedAt > VOICE_META_CACHE_TTL_MS) return null
return entry.voice
}
interface FishAudioModelEntity {
_id: string
@@ -128,6 +142,7 @@ export class TextToSpeechSettingsService {
let items = payload.items
.filter((model) => model.type === 'tts' && model.state === 'trained')
.map(toVoice)
for (const item of items) cacheVoiceMeta(item)
const selectedVoiceId = normalizeSelectedVoiceId(loadSettings().ttsSelectedVoiceId)
if (
@@ -138,7 +153,10 @@ export class TextToSpeechSettingsService {
) {
if (!items.some((item) => item.id === selectedVoiceId)) {
const selected = await this.getVoice(selectedVoiceId, resolved.key)
if (selected) items = [selected, ...items]
if (selected) {
cacheVoiceMeta(selected)
items = [selected, ...items]
}
}
}
@@ -229,6 +247,37 @@ export class TextToSpeechSettingsService {
}
}
async getVoiceStatus(): Promise<{
configured: boolean
model: TextToSpeechModel
selectedVoiceId: string
selectedVoice: TextToSpeechVoice | null
}> {
const resolved = this.resolveKey()
const settings = loadSettings()
const selectedVoiceId = normalizeSelectedVoiceId(settings.ttsSelectedVoiceId)
const model = normalizeModel(settings.ttsModel)
const configured = Boolean(resolved.key && selectedVoiceId)
if (!selectedVoiceId) {
return { configured: false, model, selectedVoiceId: '', selectedVoice: null }
}
const cached = getCachedVoiceMeta(selectedVoiceId)
if (cached) {
return { configured, model, selectedVoiceId, selectedVoice: cached }
}
if (!resolved.key) {
return { configured: false, model, selectedVoiceId, selectedVoice: null }
}
const fetched = await this.getVoice(selectedVoiceId, resolved.key)
if (fetched) cacheVoiceMeta(fetched)
return {
configured,
model,
selectedVoiceId,
selectedVoice: fetched
}
}
private resolveKey(): {
success: boolean
key?: string
@@ -299,7 +348,7 @@ function toVoice(model: FishAudioModelEntity): TextToSpeechVoice {
languages: Array.isArray(model.languages) ? model.languages : [],
source: 'fish-audio',
coverImage: resolvePublicAssetUrl(model.cover_image || model.author?.avatar),
previewUrl: sample?.audio || undefined,
previewUrl: resolvePublicAssetUrl(sample?.audio),
previewText: sample?.text || model.default_text || undefined,
authorName: model.author?.nickname || undefined,
taskCount: model.task_count,
+8 -48
View File
@@ -267,24 +267,13 @@ function App(): React.ReactElement {
const [activePage, setActivePage] = useState<AppPage>('archive')
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
/**
* 「退群监控 ⇄ 自动化」之间的跨页深链。
*
* 项目没有 react-router,一级菜单就是 `activePage` 这一份 state,
* 所以深链同样是 state —— 用一个单调递增的 requestId 表达"又点了一次",
* 子页面据此重新落位(同一个对象引用不会重复触发 effect)。
*/
/** 「退群监控 ⇄ 自动化」之间的跨页深链。 */
const [automationOpenRuleRequest, setAutomationOpenRuleRequest] =
React.useState<AutomationOpenRuleRequest | null>(null)
const [exitMonitorOpenViewRequest, setExitMonitorOpenViewRequest] =
React.useState<GroupExitMonitorOpenViewRequest | null>(null)
const [archiveJumpTime, setArchiveJumpTime] = useState<number | null>(null)
/**
* 精确跳转目标(规范化后的消息 id)。
*
* 与 `archiveJumpTime` 并存而不是替代:时间只能定位到"附近",秒级时间戳在群聊里
* 经常对应多条消息。有 messageRef 时用 id 精确定位,没有时才退回按时间找。
*/
/** 精确跳转目标(规范化后的消息 id);与 `archiveJumpTime` 并存而不是替代:时间只能定位到"附近",秒级时间戳在群聊里 经常对应多条消息。 */
const [archiveJumpMessageId, setArchiveJumpMessageId] = useState<string | null>(null)
const [settingsCategory, setSettingsCategory] = useState<SettingsCategoryId>('account-database')
const [reportSourceContact, setReportSourceContact] = useState<Contact | null>(null)
@@ -1338,15 +1327,7 @@ function App(): React.ReactElement {
}
}
/**
* 跳转到证据的原聊天。
*
* 只靠「真实会话 id + 秒级时间戳」定位不可靠:会话 id 若是展示层合成的 key 就选不中任何
* 真实会话,而时间戳在同一秒有多条消息时会挑错。这里从 `messageRef` 还原真实会话 id →
* 选中会话 → 用 `getMessagesAround` 按稳定消息 id 在有界窗口内精确锚定 → 高亮那一条。
*
* 窗口内找不到时**不静默失败**,明确提示"已打开对应会话,但暂时无法定位原消息"。
*/
/** 跳转到证据的原聊天。 */
const handleOpenSearchEvidence = async (evidence: EvidenceItem): Promise<void> => {
const anchor = decodeMessageRef(evidence.messageRef)
if (!anchor) {
@@ -1666,12 +1647,7 @@ function App(): React.ReactElement {
setActivePage('settings')
}
/**
* 跳到「设置 · 本地索引」。
*
* 用在群统计这类场景:结果不完整的原因是索引没追平,用户需要一个**可操作的去处**,
* 而不是只看到一句「结果可能不完整」却不知道去哪解决。
*/
/** 跳到「设置 · 本地索引」。 */
const openLocalIndexSettings = (): void => {
setSettingsCategory('local-index')
setActivePage('settings')
@@ -1681,23 +1657,13 @@ function App(): React.ReactElement {
setActivePage('agent-hub')
}
/**
* 「退群监控 → 退群通知自动化」。
*
* 直接落到「自动化 → 规则 → 退群通知」,不是只跳到自动化首页。
* 这是纯导航:不改退群监控的任何配置,也不触发任何发送。
*/
/** 「退群监控 → 退群通知自动化」;直接落到「自动化 → 规则 → 退群通知」,不是只跳到自动化首页。 */
const openLeaveNotificationAutomation = (): void => {
setAutomationOpenRuleRequest({ ruleType: 'leave_notification', requestId: Date.now() })
setActivePage('automation')
}
/**
* 「定时日报」已正式迁入自动化,日报页只保留「今日日报 | 社区模板市场」两个 Tab。
*
* 这里仍然留一个导航入口:用户是从日报页产生"要定时发日报"这个念头的,
* 不给路会显得功能被删了。它**不是**第三个 Tab,只是一句去处的说明。
*/
/** 「定时日报」已正式迁入自动化,日报页只保留「今日日报 | 社区模板市场」两个 Tab;它**不是**第三个 Tab,只是一句去处的说明。 */
const openScheduledReportAutomation = (): void => {
setAutomationOpenRuleRequest({ ruleType: 'scheduled_report', requestId: Date.now() })
setActivePage('automation')
@@ -2002,14 +1968,7 @@ function App(): React.ReactElement {
社区模板市场
</button>
</div>
{/*
「定时日报已并入自动化」的指引条。
这里以前是裸 `<p>` + 裸 `<button>`,并且挂了 `.report-workspace-hint` /
`.report-workspace-hint-link` 两个**样式表里根本不存在**的类 ——
于是就成了一条没样式的文字 + 一个长得不像系统里任何按钮的按钮。
现在补上真实样式,按钮统一走 UI 组件库。
*/}
{/** 「定时日报已并入自动化」的指引条。 */}
<div className="report-workspace-hint">
<span>需要「定时日报」?它已经并入「自动化」,可以按时间自动生成并发送日报。</span>
<Button variant="link" size="sm" onClick={openScheduledReportAutomation}>
@@ -2161,6 +2120,7 @@ function App(): React.ReactElement {
<ExtensionWorkspace
deepLink={extensionDeepLink}
onConsumeDeepLink={() => setExtensionDeepLink(null)}
onOpenSendSettings={openWechatSendSettings}
/>
)
case 'api':
@@ -110,6 +110,27 @@ export function PrimaryNavigation({
onPageChange
}: PrimaryNavigationProps): React.ReactElement {
const [unreadExitCount, setUnreadExitCount] = React.useState(0)
const [sendUnavailable, setSendUnavailable] = React.useState(false)
React.useEffect(() => {
const api = typeof window !== 'undefined' ? window.api : undefined
if (!api || typeof api.getPersonalWechatSendCapability !== 'function') return
let disposed = false
const checkSendCapability = (): void => {
void api
.getPersonalWechatSendCapability()
.then((cap) => {
if (!disposed) setSendUnavailable(Boolean(cap && cap.ready === false))
})
.catch(() => undefined)
}
checkSendCapability()
const timer = window.setInterval(checkSendCapability, 8_000)
return () => {
disposed = true
window.clearInterval(timer)
}
}, [activePage])
React.useEffect(() => {
const api = typeof window !== 'undefined' ? window.api : undefined
@@ -147,13 +168,22 @@ export function PrimaryNavigation({
type="button"
className={`primary-nav-item ${activePage === item.id ? 'active' : ''}`}
onClick={() => onPageChange(item.id)}
title={item.label}
title={
item.id === 'extensions' && sendUnavailable
? `${item.label}(当前暂无发送能力)`
: item.label
}
>
<span className="primary-nav-mark" aria-hidden>
<NavIcon page={item.id} />
{item.id === 'exit-monitor' && unreadExitCount > 0 && (
<span className="primary-nav-badge">{Math.min(unreadExitCount, 99)}</span>
)}
{item.id === 'extensions' && sendUnavailable && (
<span className="primary-nav-badge" title="当前暂无发送能力">
!
</span>
)}
</span>
<span className="primary-nav-label">{item.label}</span>
</button>
@@ -41,16 +41,30 @@ function statusTone(extension: InstalledExtension): 'success' | 'warning' | 'dan
return 'warning'
}
const SEND_PERMISSIONS: ReadonlySet<ExtensionPermission> = new Set([
'wechat.send.text',
'wechat.send.image',
'wechat.send.video',
'wechat.send.voice'
])
function extensionRequiresSend(extension: InstalledExtension): boolean {
return extension.permissions.some((permission) => SEND_PERMISSIONS.has(permission))
}
export interface ExtensionWorkspaceProps {
/** 从其它页面跳过来时的定位目标。 */
deepLink?: ExtensionDeepLink | null
/** 消费后清空,避免返回再进来又跳一次。 */
onConsumeDeepLink?: () => void
/** 跳转到「设置 → 微信发送」。 */
onOpenSendSettings?: () => void
}
export function ExtensionWorkspace({
deepLink,
onConsumeDeepLink
onConsumeDeepLink,
onOpenSendSettings
}: ExtensionWorkspaceProps = {}): React.ReactElement {
const { toast } = useToast()
const [extensions, setExtensions] = React.useState<InstalledExtension[]>([])
@@ -79,16 +93,27 @@ export function ExtensionWorkspace({
} | null>(null)
/** 「转为正式安装」的二次确认。 */
const [pendingConvert, setPendingConvert] = React.useState<InstalledExtension | null>(null)
const [sendCapability, setSendCapability] = React.useState<{
ready: boolean
message?: string
} | null>(null)
const [sendMaskDismissed, setSendMaskDismissed] = React.useState(false)
const refresh = React.useCallback(async (): Promise<void> => {
const [list, systemHealth, templateList] = await Promise.all([
const loadSendCap =
typeof window.api?.getPersonalWechatSendCapability === 'function'
? window.api.getPersonalWechatSendCapability().catch(() => null)
: Promise.resolve(null)
const [list, systemHealth, templateList, nextSendCap] = await Promise.all([
window.api.listExtensions(),
window.api.getExtensionHealth().catch(() => null),
window.api.listExtensionTemplates().catch(() => [])
window.api.listExtensionTemplates().catch(() => []),
loadSendCap
])
setExtensions(list)
setHealth(systemHealth)
setTemplates(templateList)
setSendCapability(nextSendCap)
setTemplatesLoading(false)
setSelectedId((current) => {
if (current && list.some((item) => item.id === current)) return current
@@ -104,10 +129,7 @@ export function ExtensionWorkspace({
return unsubscribe
}, [refresh])
/**
* 消费深链:只切视图与选中项,不触发任何安装/启用动作。
* 真正的操作仍要用户在界面上点。
*/
/** 消费深链:只切视图与选中项,不触发任何安装/启用动作。 */
React.useEffect(() => {
if (!deepLink) return
if (deepLink.development) {
@@ -128,6 +150,10 @@ export function ExtensionWorkspace({
() => extensions.find((item) => item.id === selectedId) ?? null,
[extensions, selectedId]
)
const sendUnavailable = Boolean(sendCapability && sendCapability.ready === false)
const selectedBlockedBySend = Boolean(
sendUnavailable && selected && extensionRequiresSend(selected)
)
const selectedIdForLogs = selected?.id
const selectedRuntimeState = selected?.runtime.state
@@ -200,6 +226,14 @@ export function ExtensionWorkspace({
}
const requestEnable = (extension: InstalledExtension): void => {
if (sendUnavailable && extensionRequiresSend(extension)) {
toast({
title: '当前暂无发送能力',
description: '当前仅支持打开页面预览,请先配置微信发送能力后再启用该扩展。',
variant: 'destructive'
})
return
}
const risky = extension.permissions.filter(
(permission) => EXTENSION_PERMISSION_INFO[permission].risk !== 'low'
)
@@ -524,13 +558,55 @@ export function ExtensionWorkspace({
if (page) {
return (
<ExtensionPageHost
descriptor={page}
onBack={() => {
setPage(null)
void refresh().catch(() => undefined)
}}
/>
<div className="extension-page-wrapper">
<ExtensionPageHost
descriptor={page}
onBack={() => {
setPage(null)
void refresh().catch(() => undefined)
}}
/>
{selectedBlockedBySend && !sendMaskDismissed && (
<div
className="extension-send-unavailable-mask"
role="region"
aria-label="当前暂无发送能力提示"
>
<div className="extension-send-unavailable-card">
<button
type="button"
className="extension-send-unavailable-close"
aria-label="关闭提示并预览界面"
title="关闭提示(仅预览界面,无法启用)"
onClick={() => setSendMaskDismissed(true)}
>
×
</button>
<div className="extension-send-unavailable-icon" aria-hidden>
!
</div>
<h3>当前暂无发送能力</h3>
<p>
{sendCapability?.message ||
'当前未绑定个人微信或发送组件尚未就绪。你可以点击右上角 × 关闭遮罩预览界面,但无法保存启用。'}
</p>
<div className="extension-send-unavailable-actions">
{onOpenSendSettings && (
<Button size="sm" onClick={onOpenSendSettings}>
前往配置微信发送能力
</Button>
)}
<Button size="sm" variant="outline" onClick={() => void refresh()}>
重新检测发送状态
</Button>
<Button size="sm" variant="ghost" onClick={() => setSendMaskDismissed(true)}>
仅预览界面
</Button>
</div>
</div>
</div>
)}
</div>
)
}
@@ -611,36 +687,103 @@ export function ExtensionWorkspace({
<div className="extension-list" role="listbox" aria-label="已安装扩展">
{extensions.length === 0 ? (
<p className="extension-empty">
还没有安装扩展。可以在 <code>examples/extensions</code> 下找到两个可直接安装的示例。
还没有安装扩展。可以在 <code>examples/extensions</code> 下找到三个可直接安装的示例。
</p>
) : (
extensions.map((extension) => (
<button
key={extension.id}
type="button"
role="option"
aria-selected={extension.id === selectedId}
className={`extension-list-item ${extension.id === selectedId ? 'is-active' : ''}`}
onClick={() => setSelectedId(extension.id)}
>
<span
className={`extension-status-dot tone-${statusTone(extension)}`}
aria-hidden
/>
<span className="extension-list-main">
<span className="extension-list-name">{extension.name}</span>
<span className="extension-list-meta">
v{extension.version} ·{' '}
{extension.enabled ? STATUS_LABELS[extension.runtime.state] : '已停用'}
extensions.map((extension) => {
const needsSend = extensionRequiresSend(extension)
const warnNoSend = sendUnavailable && needsSend
return (
<button
key={extension.id}
type="button"
role="option"
aria-selected={extension.id === selectedId}
className={`extension-list-item ${extension.id === selectedId ? 'is-active' : ''}`}
onClick={() => {
if (extension.id !== selectedId) setSendMaskDismissed(false)
setSelectedId(extension.id)
}}
>
<span
className={`extension-status-dot tone-${warnNoSend ? 'danger' : statusTone(extension)}`}
aria-hidden
/>
<span className="extension-list-main">
<span className="extension-list-name-row">
<span className="extension-list-name">{extension.name}</span>
{warnNoSend && (
<span
className="extension-send-warn-pill"
title="当前暂无发送能力,请先绑定个人微信"
>
<span className="extension-send-warn-bang" aria-hidden>
!
</span>
当前暂无发送能力
</span>
)}
</span>
<span className="extension-list-meta">
v{extension.version} ·{' '}
{warnNoSend
? '暂无发送能力(已暂停)'
: extension.enabled
? STATUS_LABELS[extension.runtime.state]
: '已停用'}
</span>
</span>
</span>
</button>
))
</button>
)
})
)}
</div>
</aside>
<section className="extension-detail" aria-label="扩展详情">
<section
className={`extension-detail ${selectedBlockedBySend && !sendMaskDismissed && view === 'extensions' ? 'is-send-blocked' : ''}`}
aria-label="扩展详情"
>
{selectedBlockedBySend && !sendMaskDismissed && view === 'extensions' && (
<div
className="extension-send-unavailable-mask"
role="region"
aria-label="当前暂无发送能力遮罩"
>
<div className="extension-send-unavailable-card">
<button
type="button"
className="extension-send-unavailable-close"
aria-label="关闭提示并预览界面"
title="关闭提示(可打开界面预览,无法启用)"
onClick={() => setSendMaskDismissed(true)}
>
×
</button>
<div className="extension-send-unavailable-icon" aria-hidden>
!
</div>
<h3>当前暂无发送能力</h3>
<p>
{sendCapability?.message ||
'当前未绑定个人微信或发送组件尚未就绪。可点击右上角 × 关闭遮罩并打开界面预览,但无法启用该扩展。'}
</p>
<div className="extension-send-unavailable-actions">
{onOpenSendSettings && (
<Button size="sm" onClick={onOpenSendSettings}>
前往配置微信发送能力
</Button>
)}
<Button size="sm" variant="outline" onClick={() => void refresh()}>
重新检测发送状态
</Button>
<Button size="sm" variant="ghost" onClick={() => setSendMaskDismissed(true)}>
关闭提示并预览
</Button>
</div>
</div>
</div>
)}
{view === 'guide' ? (
<DevelopmentGuide
onBack={() => setView('extensions')}
@@ -736,7 +879,16 @@ export function ExtensionWorkspace({
<Button
size="sm"
variant={selected.enabled ? 'outline' : 'default'}
disabled={busy || !selected.compatibility.compatible}
disabled={
busy ||
!selected.compatibility.compatible ||
(selectedBlockedBySend && !selected.enabled)
}
title={
selectedBlockedBySend && !selected.enabled
? '当前暂无发送能力,仅可打开页面预览,无法启用'
: undefined
}
onClick={() =>
selected.enabled ? void toggleEnabled(selected, false) : requestEnable(selected)
}
+136
View File
@@ -120,6 +120,15 @@
display: flex;
flex-direction: column;
min-width: 0;
flex: 1 1 auto;
}
.extension-list-name-row {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
flex-wrap: wrap;
}
.extension-list-name {
@@ -131,6 +140,35 @@
white-space: nowrap;
}
.extension-send-warn-pill {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 1px 6px;
border-radius: 999px;
background: rgba(220, 38, 38, 0.12);
border: 1px solid rgba(220, 38, 38, 0.28);
color: #dc2626;
font-size: 10px;
font-weight: 600;
line-height: 14px;
white-space: nowrap;
}
.extension-send-warn-bang {
display: inline-flex;
align-items: center;
justify-content: center;
width: 13px;
height: 13px;
border-radius: 50%;
background: #dc2626;
color: #ffffff;
font-size: 9px;
font-weight: 800;
line-height: 1;
}
.extension-list-meta {
color: var(--wxex-text-muted);
font-size: 11px;
@@ -144,7 +182,18 @@
line-height: 19px;
}
.extension-page-wrapper {
position: relative;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
}
.extension-detail {
position: relative;
display: flex;
flex-direction: column;
min-width: 0;
@@ -152,6 +201,93 @@
overflow: auto;
padding: 28px clamp(20px, 3vw, 40px) 32px;
gap: 18px;
&.is-send-blocked {
overflow: hidden;
}
}
.extension-send-unavailable-mask {
position: absolute;
inset: 0;
z-index: 25;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(248, 250, 252, 0.78);
backdrop-filter: blur(4px);
}
.extension-send-unavailable-card {
position: relative;
max-width: 440px;
width: 100%;
padding: 26px 28px;
border-radius: 14px;
border: 1px solid rgba(220, 38, 38, 0.25);
background: var(--wxex-bg-elevated, #ffffff);
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.12);
text-align: center;
h3 {
margin: 12px 0 8px;
color: #b91c1c;
font-size: 17px;
font-weight: 700;
}
p {
margin: 0 0 18px;
color: var(--wxex-text-secondary, #475569);
font-size: 13px;
line-height: 1.65;
}
}
.extension-send-unavailable-close {
position: absolute;
top: 12px;
right: 12px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--wxex-text-muted, #64748b);
font-size: 18px;
line-height: 1;
cursor: pointer;
&:hover {
background: rgba(15, 23, 42, 0.06);
color: var(--wxex-text-primary, #0f172a);
}
}
.extension-send-unavailable-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
border-radius: 50%;
background: #dc2626;
color: #ffffff;
font-size: 22px;
font-weight: 800;
box-shadow: 0 6px 16px rgba(220, 38, 38, 0.28);
}
.extension-send-unavailable-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
}
.extension-detail-empty {
+9 -12
View File
@@ -1,9 +1,4 @@
/**
* 扩展权限目录。
*
* 权限是**宿主授予**的,不是扩展自己声称的:manifest 里只声明「需要什么」,
* 真正生效的是 registry 里 `grantedPermissions` 与当前启用状态的交集。
*/
/** 扩展权限目录。 */
export const EXTENSION_PERMISSIONS = [
'messages.subscribe',
@@ -12,6 +7,7 @@ export const EXTENSION_PERMISSIONS = [
'wechat.send.text',
'wechat.send.image',
'wechat.send.video',
'wechat.send.voice',
'ai.chat',
'storage',
'automation.action',
@@ -68,6 +64,12 @@ export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPer
'经 TraceMemo 官方 Gateway 发送视频文件;原生 Host 以 video 类型提交,单文件不超过 100MB,仍需有效授权与发送能力。',
risk: 'high'
},
'wechat.send.voice': {
label: '发送微信语音',
description:
'经 TraceMemo 官方 Gateway 发送语音气泡,支持用已配置的文字转语音音色合成或发送扩展目录内的音频文件;仍需有效授权与发送能力。',
risk: 'high'
},
'ai.chat': {
label: '调用 AI 模型',
description: '使用 TraceMemo 已配置的 AI Provider 发起对话;扩展拿不到 API Key 明文。',
@@ -121,12 +123,7 @@ export function sortPermissionsByRisk(
})
}
/**
* 安装时自动授予的权限子集:只有低风险项。
*
* 高 / 中风险权限必须由用户在「启用扩展」时确认 —— 安装本身不应等于同意
* 读取消息或发送微信。
*/
/** 安装时自动授予的权限子集:只有低风险项;高 / 中风险权限必须由用户在「启用扩展」时确认 —— 安装本身不应等于同意 读取消息或发送微信。 */
export function autoGrantedPermissions(
permissions: readonly ExtensionPermission[]
): ExtensionPermission[] {
+16 -32
View File
@@ -1,14 +1,7 @@
import type { ExtensionEventEnvelope } from './events'
import type { ExtensionErrorPayload } from './errors'
/**
* 主进程 ↔ 扩展后台进程的私有协议。
*
* 只有主进程能构造 `invoke-action` / `event` / `call-result`;
* 扩展进程只能发 `call` / `register-action` / `log` / `action-result`。
* 任何「宿主可信元数据」(extensionId、origin、purpose、幂等键)都**由主进程填**,
* 不接受扩展侧传入。
*/
/** 主进程 ↔ 扩展后台进程的私有协议;扩展进程只能发 `call` / `register-action` / `log` / `action-result`。 */
export const EXTENSION_HOST_PROTOCOL_VERSION = 1
export type ExtensionHostCallMethod =
@@ -20,6 +13,7 @@ export type ExtensionHostCallMethod =
| 'wechat.send.text'
| 'wechat.send.image'
| 'wechat.send.video'
| 'wechat.send.voice'
| 'ai.chat'
| 'capabilities.get'
| 'secrets.get'
@@ -85,12 +79,7 @@ export interface ExtensionHostRegisterAction {
id: string
title: string
description?: string
/**
* 完整参数 Schema(未经校验的原始 JSON)。
*
* 宿主收到后统一走 `parseActionInputSchema`:非法或超限时**保留动作但不给 Schema**,
* 并把原因记进日志与动作信息,绝不静默截断。
*/
/** 完整参数 Schema(未经校验的原始 JSON)。 */
inputSchema?: unknown
/** 兼容字段:旧宿主只认这个布尔值。新宿主用 `inputSchema`。 */
hasInputSchema?: boolean
@@ -138,12 +127,7 @@ export interface ExtensionHostLog {
message: string
}
/**
* 扩展页面 → 同扩展后台的通用请求。
*
* 宿主只做路由与限额:页面拿不到任意 Node 能力,后台必须显式注册处理器。
* 这是移除「宿主硬编码某个具体扩展业务」的关键通道。
*/
/** 扩展页面 → 同扩展后台的通用请求;宿主只做路由与限额:页面拿不到任意 Node 能力,后台必须显式注册处理器。 */
export interface ExtensionHostPageRequest {
type: 'page-request'
version: number
@@ -182,12 +166,7 @@ export type ExtensionHostInboundMessage =
| ExtensionHostTestResult
| ExtensionHostPageRequest
/**
* 自动化动作的返回值。
*
* `reply` 是扩展**声明想发什么**,不是发送指令:真正的发送由宿主在
* 权限、授权校验、发送能力全部通过后经 `WechatActionGateway` 完成。
*/
/** 自动化动作的返回值。 */
export interface ExtensionAutomationActionOutput {
success: boolean
output?: Record<string, unknown>
@@ -231,12 +210,7 @@ export interface ExtensionSendTextRequest {
dedupeKey?: string
}
/**
* 图片发送。
*
* 图片与视频是两条独立通道:视频必须显式用 `type: 'video'`,
* 由原生 Host 的 `/SendMsg` 以 video 类型提交。
*/
/** 图片发送;图片与视频是两条独立通道:视频必须显式用 `type: 'video'`, 由原生 Host 的 `/SendMsg` 以 video 类型提交。 */
export interface ExtensionSendImageRequest {
to: string
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
@@ -251,6 +225,16 @@ export interface ExtensionSendVideoRequest {
dedupeKey?: string
}
/** 语音发送。 */
export interface ExtensionSendVoiceRequest {
to: string
path?: string
text?: string
/** 可选音色 ID;省略时使用 TraceMemo 设置页当前选定的音色。 */
voiceId?: string
dedupeKey?: string
}
export interface ExtensionSendTextResult {
actionId: string
status: 'sent'
+26 -29
View File
@@ -12,10 +12,7 @@ export interface ExtensionRuntimeSnapshot {
restarts: number
/** 面向用户的一句话;**不含**路径、wxid、聊天正文。 */
lastError?: string
/**
* 状态补充说明,用于区分「已停止」与「本来就没有后台任务」。
* 例如只有页面入口的扩展会得到 `inactive` + 本字段。
*/
/** 状态补充说明,用于区分「已停止」与「本来就没有后台任务」。 */
note?: string
}
@@ -53,21 +50,11 @@ export interface InstalledExtension {
source: ExtensionSource
/** 来源为官方模板时,记录模板 id 与安装时的模板版本。 */
template?: { id: string; version: string }
/**
* 开发模式的源码位置。
*
* `available === false` 表示目录被移动或删除:Registry 与用户配置都还在,
* 只是暂时跑不起来,界面要给「重新选择目录」而不是「扩展没了」。
*/
/** 开发模式的源码位置。 */
development?: { sourcePath: string; available: boolean }
permissions: ExtensionPermission[]
grantedPermissions: ExtensionPermission[]
/**
* manifest 声明但用户尚未授予的权限。
*
* 非空表示该扩展升级后新增了能力:这些能力当前**不可用**,
* 需要用户显式授权后才会下发到后台进程。
*/
/** manifest 声明但用户尚未授予的权限。 */
pendingPermissions: ExtensionPermission[]
runtime: ExtensionRuntimeSnapshot
pages: Array<{ id: string; title: string }>
@@ -77,12 +64,7 @@ export interface InstalledExtension {
storage: ExtensionStorageHealthSummary
}
/**
* 从其它页面跳到扩展中心时的定位目标。
*
* 只描述「去哪里」,不携带任何安装状态:扩展中心自己读 Registry,
* 避免两个页面各维护一份事实。
*/
/** 从其它页面跳到扩展中心时的定位目标。 */
export interface ExtensionDeepLink {
/** 定位官方模板(打开模板画廊并展开该卡片)。 */
templateId?: string
@@ -92,12 +74,7 @@ export interface ExtensionDeepLink {
development?: boolean
}
/**
* 单个扩展动作的完整可用性描述。
*
* `registered` 只说明后台注册过,`available` 才决定能不能用:
* 停用、代码缺失、权限未授予、Schema 非法、Storage 暂停都会让 available=false。
*/
/** 单个扩展动作的完整可用性描述。 */
export interface ExtensionActionInfo {
extensionId: string
extensionName: string
@@ -170,6 +147,24 @@ export interface ExtensionPageResponse {
error?: ExtensionErrorPayload
}
export interface ExtensionTtsVoiceSummary {
id: string
name: string
description: string
tags: string[]
languages: string[]
authorName?: string
previewUrl?: string
coverImage?: string
}
export interface ExtensionTtsCapabilitySnapshot {
configured: boolean
model: string
selectedVoiceId: string
selectedVoice: ExtensionTtsVoiceSummary | null
}
export interface ExtensionCapabilitySnapshot {
extensionId: string
enabled: boolean
@@ -183,7 +178,8 @@ export interface ExtensionCapabilitySnapshot {
/** 图片与视频是两条独立通道。 */
canSendImage: boolean
canSendVideo: boolean
/** 仅 `wechat.send.text` 被授予时才有意义。 */
canSendVoice?: boolean
/** 任一微信发送权限被授予时返回真实授权结果。 */
licensed: boolean
message: string
}
@@ -191,6 +187,7 @@ export interface ExtensionCapabilitySnapshot {
configured: boolean
modelName: string
}
tts?: ExtensionTtsCapabilitySnapshot
}
export interface ExtensionQuitBehavior {