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

+3 -1
View File
@@ -32,8 +32,10 @@ task_plan.md
debug-originals
/build/mac-staging/
# 去水印脚本
# 去水印脚本与群聊机器人核心引擎
/examples/extensions/douyin-sender/scripts/douyin.py
/examples/extensions/group-chat-bot/lib/
/examples/extensions/group-chat-bot/tests/
# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
/build/extension-templates/
+4
View File
@@ -31,6 +31,7 @@
| `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` |
| `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` |
| `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video |
| `wechat.send.voice` | 高 | `tm.wechat.send({ type: 'voice' })`,支持传入 `text` 用宿主 TTS 音色合成发送或传入音频 `path` |
| `ai.chat` | 中 | `tm.ai.chat` |
| `storage` | 低 | `tm.storage.*` 与页面存储 |
| `automation.action` | 中 | `tm.automation.registerAction` |
@@ -75,6 +76,9 @@ await tm.wechat.send({ type: 'image', to, path: '/abs/path/cover.png', dedupeKey
// 视频(原生 Host 以 {toWxid, type:'video', msg:<路径>} 提交)
await tm.wechat.send({ type: 'video', to, path: '/abs/path/clip.mp4', dedupeKey? })
// 语音(传 text 由宿主用已配置的 TTS 音色合成发送,或传 path 发送音频文件)
await tm.wechat.send({ type: 'voice', to, text: '你好呀', voiceId?, dedupeKey? })
// → { actionId, status: 'sent' }
```
+4 -2
View File
@@ -1,19 +1,21 @@
# 扩展示例
两个可直接安装的示例,用来验证扩展中心从安装到发送的完整链路。
三个可直接安装的官方模板示例,用来验证扩展中心从安装到发送的完整链路。
| 目录 | 用途 | 申请权限 |
| --- | --- | --- |
| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` |
| `group-chat-bot/` | 多套群聊人格、单群长期与短期记忆、结合 TraceMemo 音色随机回复文字或发送语音 | `messages.subscribe`、`messages.query`、`contacts.list`、`wechat.send.text`、`wechat.send.voice`、`ai.chat`、`storage` |
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
## 安装
TraceMemo → 左侧「扩展」→「安装目录」,选择对应目录即可。
TraceMemo → 左侧「扩展」→「官方模板」一键安装,或点「安装目录」选择对应目录。
安装后扩展默认**未启用**:
- `keyword-bot` 的 `enabled` 为 `false`,需要在配置页手动打开才会回复;
- `group-chat-bot` 需要本机已配置 AI Provider(需要语音回复时在「设置 → 文字转语音」配置音色),并在配置页勾选生效群聊;
- `douyin-sender` 依赖本机的 `python3`、Chrome 和抖音解析脚本,安装前先看它自己的 README。
## 测试建议
@@ -0,0 +1,32 @@
# 群聊机器人 (`com.example.group-chat-bot`)
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型与文字转语音(TTS)音色,在指定微信群聊中按角色设定自然接话,支持单群长期记忆与随机回复文字 / 随机发送语音。
## 核心特性
1. **多套群聊人格(Persona)**:内置「日常群友」「技术搭子」「温柔捧场王」「幽默气氛组」四套预设人格,支持新建、修改或删除自定义人格(独立配置人设背景、说话风格、字数上限与追问约束),并可为不同微信群绑定不同人格。
2. **短期上下文 + 单群长期记忆(Memory)**:
- **短期记忆**:接话时自动读取本群最近 N 条文本消息作为多轮对话上下文。
- **长期记忆**:按群独立维护「固定背景记忆(手动置顶的群规、群友称呼偏好)」与「AI 自动提炼的互动摘要(常聊话题、近期约定)」。可按对话轮数自动更新,也可在配置页随时手动触发 AI 提炼或修订。
3. **自然群聊节奏控制**:支持「仅 @我」「命中唤醒词」「@我 或唤醒词」「自然活跃接话(@我必回 + 普通群消息按概率随机搭话)」四种触发模式,区分直接唤醒冷却与环境闲聊冷却,并支持重复表达抑制。
4. **随机回复文字 / 随机发送语音 + TraceMemo 音色同步展示**:
- 配置页直接展示 TraceMemo「设置 → 文字转语音」中当前选定的音色(名称、ID、标签、合成模型与样本试听)。
- 支持「随机混合(按概率随机回复文字或发送语音)」「仅回复文字」「仅发送语音」三种模式,单群可独立覆盖;当语音未就绪或发送失败时支持自动降级为发送文字。
## 申请权限
| 权限 | 用途 |
| --- | --- |
| `messages.subscribe` | 接收微信群聊新文本消息事件 |
| `messages.query` | 读取触发群聊最近的上下文消息 |
| `contacts.list` | 在配置页读取群聊列表供勾选生效范围 |
| `wechat.send.text` | 经 TraceMemo Gateway 发送群聊文字回复 |
| `wechat.send.voice` | 经 TraceMemo 文字转语音服务与 Gateway 发送群聊语音气泡 |
| `ai.chat` | 调用 TraceMemo 已配置的 AI Provider 进行思考回复与记忆提炼 |
| `storage` | 保存机器人配置、单群长期记忆与今日统计 |
## 测试
```bash
node --test examples/extensions/group-chat-bot/tests/bot-engine.test.mjs
```
@@ -0,0 +1,31 @@
'use strict'
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,缺失时保持静默空操作且不报错。 */
let engine = null
try {
engine = require('../lib/bot-engine')
} catch {
engine = null
}
function registerFallbackHandlers(tm) {
if (!tm || !tm.page || typeof tm.page.onRequest !== 'function') return
const unavailable = async () => {
throw new Error('当前功能暂不可用')
}
tm.page.onRequest('previewReply', unavailable)
tm.page.onRequest('refreshGroupMemory', unavailable)
tm.page.onRequest('testSend', unavailable)
}
module.exports = function activate(api) {
if (engine && typeof engine.activateBotRuntime === 'function') {
engine.activateBotRuntime(api)
} else {
registerFallbackHandlers(api)
}
if (api && api.log && typeof api.log.info === 'function') {
api.log.info('群聊机器人已启动')
}
}
@@ -0,0 +1,39 @@
{
"manifestVersion": 1,
"id": "com.example.group-chat-bot",
"name": "群聊机器人",
"version": "1.0.0",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "支持多套群聊人格设定、群聊长期与短期记忆、自然接话节奏,并可结合 TraceMemo 音色随机回复文字或发送语音。",
"author": "TraceMemo Examples",
"permissions": [
"messages.subscribe",
"messages.query",
"contacts.list",
"wechat.send.text",
"wechat.send.voice",
"ai.chat",
"storage"
],
"entrypoints": {
"page": "ui/index.html",
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": [
"text"
],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
},
"contributions": {
"pages": [
{
"id": "settings",
"title": "群聊机器人设置"
}
]
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,467 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>群聊机器人设置</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main class="page">
<header class="hero">
<div>
<p class="eyebrow">TraceMemo 官方扩展模板 · com.example.group-chat-bot</p>
<div class="hero-title-row">
<h1>群聊机器人</h1>
<span id="hero-send-warn" class="send-warn-badge" hidden>
<span class="send-warn-bang" aria-hidden="true">!</span>
当前暂无发送能力
</span>
</div>
<p class="subtitle">
支持多套群聊人格设定、基于本机聊天记录的群记忆提炼、敏感探测安全拦截,并可结合
TraceMemo 已选音色随机回复文字或发送微信语音。
</p>
</div>
<div class="hero-stats">
<div class="stat-pill">
<span>今日回复</span>
<strong id="stat-total">0</strong>
</div>
<div class="stat-pill">
<span>文字 / 语音</span>
<strong id="stat-split">0 / 0</strong>
</div>
</div>
</header>
<div id="send-unavailable-mask" class="send-unavailable-mask" hidden>
<div class="send-unavailable-dialog">
<button
id="close-send-mask-btn"
type="button"
class="send-unavailable-close"
aria-label="关闭提示并预览界面"
title="关闭提示(可浏览界面,无法保存启用)"
>
×
</button>
<div class="send-unavailable-icon" aria-hidden="true">!</div>
<h2>当前暂无发送能力</h2>
<p id="send-unavailable-reason">
当前尚未绑定个人微信或发送组件未就绪。你可以点击右上角 × 关闭遮罩预览界面,但无法保存启用。
</p>
<div class="send-unavailable-actions">
<button id="recheck-send-cap-btn" type="button" class="primary">重新检测发送能力</button>
<button id="preview-only-btn" type="button" class="ghost">关闭并预览界面</button>
</div>
</div>
</div>
<section class="capability-bar" aria-label="宿主能力状态">
<div class="cap-item">
<span class="cap-dot" id="cap-ai-dot"></span>
<span>AI 模型:<strong id="cap-ai-text">检测中…</strong></span>
</div>
<div class="cap-item">
<span class="cap-dot" id="cap-send-dot"></span>
<span>微信发送:<strong id="cap-send-text">检测中…</strong></span>
</div>
<div class="cap-item">
<span class="cap-dot" id="cap-tts-dot"></span>
<span>语音合成:<strong id="cap-tts-text">检测中…</strong></span>
</div>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>语音回复与 TraceMemo 音色</h2>
<p class="hint">
自动同步展示 TraceMemo「设置 → 文字转语音」中选定的音色,可配置随机回复文字或随机发送语音。
</p>
</div>
<button id="refresh-voice-btn" type="button" class="ghost">刷新音色状态</button>
</div>
<div class="voice-showcase" id="voice-showcase">
<div class="voice-avatar" id="voice-avatar">音</div>
<div class="voice-info">
<div class="voice-title-row">
<strong id="voice-name">正在读取 TraceMemo 选定音色…</strong>
<span class="badge" id="voice-badge">未检测</span>
<span class="badge muted" id="voice-model-badge">s2.1-pro-free</span>
</div>
<p class="voice-desc" id="voice-desc">
在 TraceMemo「设置 → 文字转语音」中选择音色后,这里会自动展示当前音色详情。
</p>
<div class="voice-meta-row" id="voice-tags"></div>
</div>
<div class="voice-actions">
<button id="voice-preview-btn" type="button" class="ghost" hidden>试听音色样本</button>
</div>
</div>
<div class="grid two">
<label class="field">
<span>默认回复形式</span>
<select id="delivery-mode">
<option value="random_mix">随机混合(随机回复文字 / 随机发送语音)</option>
<option value="text_only">仅回复文字</option>
<option value="voice_only">仅发送语音</option>
</select>
</label>
<label class="field" id="voice-chance-field">
<span>随机发送语音概率(0–100%)</span>
<input id="voice-chance" type="number" min="0" max="100" value="35" />
</label>
</div>
<div class="grid two">
<label class="field">
<span>单条语音最大字数(超出自动改发文字)</span>
<input id="voice-max-chars" type="number" min="20" max="400" value="120" />
</label>
<label class="field">
<span>指定覆盖音色 ID(可选,留空跟随上方 TraceMemo 音色)</span>
<input
id="custom-voice-id"
type="text"
maxlength="80"
placeholder="留空则默认使用 TraceMemo 当前选定的音色"
/>
</label>
</div>
<label class="check">
<input id="voice-fallback" type="checkbox" checked />
<span>当语音合成未就绪或发送失败时,自动降级为发送文字回复(推荐开启,避免漏回)</span>
</label>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>群聊人格设定</h2>
<p class="hint">
可准备多套群聊人格(人设背景 + 说话风格),支持全局默认人格或为不同微信群分配专属人格。
</p>
</div>
<div class="inline-actions">
<select id="preset-import-select" aria-label="选择预设人格导入">
<option value="">+ 导入预设人格…</option>
<option value="casual-friend">日常群友</option>
<option value="tech-partner">技术搭子</option>
<option value="warm-listener">温柔捧场王</option>
<option value="witty-vibe">幽默气氛组</option>
</select>
<button id="persona-add-btn" type="button" class="ghost">新建人格</button>
<button id="persona-delete-btn" type="button" class="ghost danger">删除当前</button>
</div>
</div>
<div class="grid two">
<label class="field">
<span>当前编辑的人格</span>
<select id="persona-select"></select>
</label>
<label class="field">
<span>人格显示名称</span>
<input id="persona-name" type="text" maxlength="36" placeholder="例如:日常群友" />
</label>
</div>
<label class="field">
<span>人设背景与角色定位</span>
<textarea
id="persona-identity"
rows="3"
maxlength="3000"
placeholder="描述机器人在群里的身份、性格特点与处事原则"
></textarea>
</label>
<label class="field">
<span>说话风格与语气约束</span>
<textarea
id="persona-style"
rows="2"
maxlength="1500"
placeholder="例如:口语化短句,1-2句话说清,不端架子,不用列表和客服腔"
></textarea>
</label>
<div class="grid two">
<label class="field">
<span>该人格回复字数上限(40–500)</span>
<input id="persona-max-chars" type="number" min="40" max="500" value="180" />
</label>
<label class="field">
<span>单次回复允许反问上限(0–2,0 代表不主动追问)</span>
<input id="persona-follow-up" type="number" min="0" max="2" value="0" />
</label>
</div>
</section>
<section class="card">
<h2>触发策略、节奏与安全防护</h2>
<label class="check">
<input id="bot-enabled" type="checkbox" />
<span>启用群聊机器人自动接话(需同时在扩展中心启用本扩展并选择生效群聊)</span>
</label>
<div class="grid two">
<label class="field">
<span>触发方式</span>
<select id="trigger-mode">
<option value="mention">仅被 @我 时接话</option>
<option value="mention_or_wake">被 @我 或命中唤醒词时接话</option>
<option value="wake_word">仅命中唤醒词时接话</option>
<option value="ambient">自然活跃接话(@我必回 + 普通群消息按概率随机搭话)</option>
</select>
</label>
<label class="field">
<span>全局默认人格</span>
<select id="default-persona-select"></select>
</label>
</div>
<label class="field" id="wake-words-field">
<span>唤醒词列表(逗号分隔,最多 16 个)</span>
<input id="wake-words" type="text" placeholder="例如:小助手, 搭子, 机器人" />
</label>
<div class="grid three">
<label class="field">
<span>直接唤醒冷却(秒)</span>
<input id="cooldown-seconds" type="number" min="3" max="600" value="20" />
</label>
<label class="field" id="ambient-chance-field">
<span>普通群消息随机接话概率(%)</span>
<input id="ambient-chance" type="number" min="0" max="100" value="25" />
</label>
<label class="field" id="ambient-cooldown-field">
<span>环境闲聊冷却(秒)</span>
<input id="ambient-cooldown" type="number" min="5" max="1800" value="45" />
</label>
</div>
<div class="grid two">
<label class="field">
<span>短期记忆:每次读取本群最近消息条数(4–40)</span>
<input id="context-limit" type="number" min="4" max="40" value="18" />
</label>
<label class="field">
<span>长期记忆:每回复多少轮自动更新一次群摘要(3–50)</span>
<input id="memory-interval" type="number" min="3" max="50" value="8" />
</label>
</div>
<div class="check-row">
<label class="check">
<input id="suppress-duplicate" type="checkbox" checked />
<span>开启重复表达抑制(防止环境闲聊连续发送相同回复)</span>
</label>
<label class="check">
<input id="memory-enabled" type="checkbox" checked />
<span>启用群聊长期记忆(按群独立保存固定记忆与历史摘要)</span>
</label>
</div>
<hr style="border: 0; border-top: 1px solid var(--border); margin: 14px 0" />
<label class="check" style="margin-top: 4px">
<input id="security-guard-enabled" type="checkbox" checked />
<span
><strong>开启敏感探测与 AI 二次安全拦截</strong>(第一层:正则确定性阻断提示词套取、敏感词过滤规则试探、端口/root/IP
探测及编码外带;第二层:调用 AI 时注入二次安全审查指令,识别伪装话术并拦截)</span
>
</label>
<div class="grid two">
<label class="field">
<span>命中安全拦截时的处理方式</span>
<select id="security-reply-mode">
<option value="refuse">返回安全拒答话术</option>
<option value="silent">静默忽略不回复</option>
</select>
</label>
<label class="field">
<span>安全拒答话术</span>
<input
id="security-refuse-text"
type="text"
maxlength="120"
value="这个话题我没法回答哈,咱们聊点别的吧~"
/>
</label>
</div>
<label class="field">
<span>AI 二次安全审查拦截提示词(调用模型时注入,识别“通用示例/假设场景”等伪装套话并触发 SECURITY_BLOCK)</span>
<textarea
id="ai-security-prompt"
rows="2"
maxlength="600"
placeholder="定义需要 AI 在推理时二次识别并拦截的诱导场景…"
></textarea>
</label>
<label class="field">
<span>自定义敏感屏蔽词(可选,逗号分隔,最多 32 个)</span>
<input
id="blocked-keywords"
type="text"
placeholder="例如:内部接口, 测试密码, 后台地址"
/>
</label>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>生效群聊与单群策略</h2>
<p class="hint">
只对下方勾选的群聊生效。可为每个群单独分配人格、回复形式(文字/语音/随机)与群聊记忆。
</p>
</div>
<button id="reload-groups-btn" type="button" class="ghost">刷新群列表</button>
</div>
<div class="field">
<span>搜索并添加微信群聊</span>
<div id="roster-picker" class="roster-picker">
<div id="roster-chips" class="roster-chips" hidden></div>
<input
id="roster-search"
type="text"
autocomplete="off"
placeholder="输入群名称或 chatroom ID 搜索并勾选…"
/>
<div id="roster-menu" class="roster-menu" hidden></div>
</div>
</div>
<div class="group-table-header">
<span>群聊名称</span>
<span>绑定人格</span>
<span>回复形式</span>
<span>群记忆</span>
<span>操作</span>
</div>
<div id="group-list" class="group-list"></div>
<p id="group-empty" class="empty-hint">
暂未选择任何群聊。请在上方搜索框中选择需要启用机器人的群聊。
</p>
</section>
<section class="card">
<div class="card-header">
<div>
<h2>群聊记忆管理(基于本机聊天记录均衡采样提炼)</h2>
<p class="hint">
从 TraceMemo 本机微信记录提炼群记忆:自动按「每人基础条数上限(7 天 12 条/人、30 天 15 条/人)」均衡采样,若总条数未满上限(100/160 条)则自动轮询扩充余量,防止单人刷屏占满上下文。
</p>
</div>
<div class="inline-actions">
<select id="memory-group-select" aria-label="选择要管理记忆的群聊">
<option value="">选择群聊查看记忆…</option>
</select>
<button id="memory-extract-7d-btn" type="button" class="ghost">
提炼最近 7 天记录
</button>
<button id="memory-extract-30d-btn" type="button" class="ghost">
提炼最近 30 天记录
</button>
<button id="memory-clear-btn" type="button" class="ghost danger">清空该群记忆</button>
</div>
</div>
<p class="meta-line" id="memory-meta">
请先在上方下拉框选择一个群聊,即可查看或从本机最近 7 天 / 30 天聊天记录提炼群记忆。
</p>
<label class="field">
<span>本群固定记忆与背景备注(手动维护,每次对话最高优先级注入)</span>
<textarea
id="memory-pinned"
rows="2"
maxlength="800"
placeholder="例如:群主是老王;每周五晚 9 点固定组队;大家喜欢聊独立开发与数码产品。"
></textarea>
</label>
<label class="field">
<span>本群长期互动记忆摘要(可根据最近 7 天 / 30 天本机聊天记录提炼,也可手动修订)</span>
<textarea
id="memory-summary"
rows="4"
maxlength="800"
placeholder="点击右上角「提炼最近 7 天记录」或「提炼最近 30 天记录」,即可从 TraceMemo 本机微信数据库中读取该群历史发言并生成长期记忆摘要。"
></textarea>
</label>
<div class="inline-actions">
<button id="memory-save-btn" type="button" class="ghost">保存该群记忆修改</button>
</div>
</section>
<section class="card">
<h2>AI 回复预览与发送测试</h2>
<p class="hint">
使用 TraceMemo 当前配置的 AI 模型测试人格思考与安全拦截效果,或向指定群测试文字/语音发送(需先在扩展中心启用本扩展)。
</p>
<div class="grid two">
<label class="field">
<span>测试目标群聊(可选,用于读取群记忆或测试真实发送)</span>
<select id="test-group-select">
<option value="">不指定群聊(仅用当前人格预览)</option>
</select>
</label>
<label class="field">
<span>模拟群友昵称</span>
<input id="test-sender-name" type="text" maxlength="32" value="测试群友" />
</label>
</div>
<label class="field">
<span>模拟群友消息 / 测试发送内容</span>
<input
id="test-message-input"
type="text"
maxlength="400"
value="今晚大家有什么安排?出来聊五毛钱的~"
/>
</label>
<div class="inline-actions">
<button id="preview-reply-btn" type="button" class="ghost">
预览 AI 思考回复(不发微信)
</button>
<button id="test-send-auto-btn" type="button" class="ghost">
按配置随机测试发送
</button>
<button id="test-send-text-btn" type="button" class="ghost">
测试发送文字
</button>
<button id="test-send-voice-btn" type="button" class="ghost">
测试发送语音
</button>
</div>
<pre id="test-output" class="preview-box" hidden></pre>
</section>
<footer class="footer-bar">
<div class="footer-buttons">
<button id="save-config-btn" type="button" class="primary">保存全部配置</button>
<button id="reload-config-btn" type="button" class="ghost">重新读取</button>
</div>
<span id="status-banner" class="status-banner" role="status" aria-live="polite"></span>
</footer>
</main>
<script src="./app.js"></script>
</body>
</html>
@@ -0,0 +1,637 @@
:root {
color-scheme: light dark;
--bg: #f6f7f9;
--surface: #ffffff;
--surface-subtle: #f1f5f9;
--border: #e2e8f0;
--text: #0f172a;
--muted: #64748b;
--accent: #059669;
--accent-hover: #047857;
--accent-soft: rgba(5, 150, 105, 0.12);
--warn: #d97706;
--danger: #dc2626;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0b0f17;
--surface: #131b26;
--surface-subtle: #1c2636;
--border: #263244;
--text: #f1f5f9;
--muted: #94a3b8;
--accent: #10b981;
--accent-hover: #059669;
--accent-soft: rgba(16, 185, 129, 0.16);
--warn: #f59e0b;
--danger: #f87171;
}
}
* {
box-sizing: border-box;
}
[hidden] {
display: none !important;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 14px/1.55 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
}
.page {
max-width: 900px;
margin: 0 auto;
padding: 20px 24px 48px;
}
.hero {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
margin-bottom: 14px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--muted);
font-size: 12px;
}
h1 {
margin: 0 0 6px;
font-size: 22px;
font-weight: 700;
}
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
.subtitle,
.hint,
.meta-line {
margin: 4px 0 0;
color: var(--muted);
font-size: 13px;
}
.hero-stats {
display: flex;
gap: 10px;
flex-shrink: 0;
}
.stat-pill {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 8px 14px;
min-width: 100px;
text-align: right;
}
.stat-pill span {
display: block;
font-size: 11px;
color: var(--muted);
}
.stat-pill strong {
font-size: 16px;
font-weight: 700;
}
.capability-bar {
display: flex;
flex-wrap: wrap;
gap: 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 14px;
margin-bottom: 14px;
font-size: 13px;
}
.cap-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.cap-dot {
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--muted);
}
.cap-dot.ok {
background: var(--accent);
}
.cap-dot.warn {
background: var(--warn);
}
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px 18px;
margin-bottom: 14px;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
margin-bottom: 12px;
}
.voice-showcase {
display: flex;
align-items: center;
gap: 14px;
background: var(--surface-subtle);
border: 1px solid var(--border);
border-radius: 10px;
padding: 12px 14px;
margin-bottom: 14px;
}
.voice-avatar {
width: 46px;
height: 46px;
border-radius: 10px;
background: var(--accent-soft);
color: var(--accent);
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: 700;
flex-shrink: 0;
overflow: hidden;
}
.voice-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.voice-info {
flex: 1;
min-width: 0;
}
.voice-title-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.voice-desc {
margin: 4px 0 6px;
color: var(--muted);
font-size: 12px;
}
.voice-meta-row {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
background: var(--accent-soft);
color: var(--accent);
}
.badge.muted {
background: var(--surface);
border: 1px solid var(--border);
color: var(--muted);
font-weight: 500;
}
.badge.warn {
background: rgba(217, 119, 6, 0.14);
color: var(--warn);
}
.grid.two {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.grid.three {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 12px;
}
@media (max-width: 680px) {
.grid.two,
.grid.three {
grid-template-columns: 1fr;
}
.hero,
.card-header {
flex-direction: column;
}
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
margin-top: 10px;
}
.field > span {
font-size: 12px;
font-weight: 500;
color: var(--muted);
}
input[type="text"],
input[type="number"],
select,
textarea {
width: 100%;
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px 10px;
background: var(--bg);
color: var(--text);
font: inherit;
}
textarea {
resize: vertical;
}
.check {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 12px;
cursor: pointer;
font-size: 13px;
}
.check-row {
display: flex;
flex-wrap: wrap;
gap: 18px;
}
.inline-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 10px;
}
.card-header .inline-actions {
margin-top: 0;
}
button {
border-radius: 8px;
padding: 7px 13px;
font: inherit;
font-weight: 600;
cursor: pointer;
border: 1px solid transparent;
transition: opacity 0.15s ease;
}
button:disabled {
opacity: 0.55;
cursor: not-allowed;
}
button.primary {
background: var(--accent);
color: #ffffff;
}
button.primary:hover:not(:disabled) {
background: var(--accent-hover);
}
button.ghost {
background: transparent;
border-color: var(--border);
color: var(--text);
}
button.ghost.danger {
color: var(--danger);
}
.roster-picker {
position: relative;
}
.roster-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 8px;
}
.roster-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 9px;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--surface-subtle);
font-size: 12px;
}
.roster-chip button {
padding: 0 3px;
border: 0;
background: transparent;
color: var(--muted);
font-size: 14px;
}
.roster-menu {
position: absolute;
z-index: 20;
left: 0;
right: 0;
top: calc(100% + 4px);
max-height: 230px;
overflow-y: auto;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 6px;
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.18);
}
.roster-option {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
}
.roster-option:hover {
background: var(--surface-subtle);
}
.roster-empty {
padding: 10px;
color: var(--muted);
font-size: 13px;
}
.group-table-header {
display: grid;
grid-template-columns: minmax(140px, 1.4fr) minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
gap: 8px;
margin-top: 14px;
padding: 0 8px 6px;
border-bottom: 1px solid var(--border);
color: var(--muted);
font-size: 12px;
}
.group-list {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 8px;
}
.group-row {
display: grid;
grid-template-columns: minmax(140px, 1.4fr) minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
gap: 8px;
align-items: center;
padding: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-subtle);
}
.group-title {
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-title small {
display: block;
color: var(--muted);
font-size: 11px;
font-weight: 400;
}
@media (max-width: 720px) {
.group-table-header {
display: none;
}
.group-row {
grid-template-columns: 1fr;
}
}
.empty-hint {
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
}
.preview-box {
margin: 12px 0 0;
padding: 12px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--surface-subtle);
white-space: pre-wrap;
word-break: break-word;
font-size: 13px;
}
.footer-bar {
position: sticky;
bottom: 0;
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}
.footer-buttons {
display: flex;
gap: 8px;
}
.status-banner {
font-size: 13px;
color: var(--muted);
}
.status-banner[data-tone="ok"] {
color: var(--accent);
}
.status-banner[data-tone="error"] {
color: var(--danger);
}
.hero-title-row {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.send-warn-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 3px 10px;
border-radius: 999px;
background: rgba(220, 38, 38, 0.12);
border: 1px solid rgba(220, 38, 38, 0.3);
color: #dc2626;
font-size: 12px;
font-weight: 700;
}
.send-warn-bang {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border-radius: 50%;
background: #dc2626;
color: #ffffff;
font-size: 11px;
font-weight: 800;
}
.send-unavailable-mask {
position: fixed;
inset: 0;
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(15, 23, 42, 0.38);
backdrop-filter: blur(4px);
}
.send-unavailable-mask[hidden] {
display: none !important;
}
.send-unavailable-dialog {
position: relative;
max-width: 440px;
width: 100%;
padding: 26px 28px;
border-radius: 14px;
border: 1px solid rgba(220, 38, 38, 0.28);
background: var(--surface);
box-shadow: 0 20px 44px rgba(0, 0, 0, 0.2);
text-align: center;
}
.send-unavailable-close {
position: absolute;
top: 10px;
right: 10px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--muted);
font-size: 18px;
line-height: 1;
cursor: pointer;
}
.send-unavailable-close:hover {
background: var(--surface-subtle);
color: var(--text);
}
.send-unavailable-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 50%;
background: #dc2626;
color: #ffffff;
font-size: 24px;
font-weight: 800;
box-shadow: 0 6px 16px rgba(220, 38, 38, 0.3);
}
.send-unavailable-dialog h2 {
margin: 12px 0 8px;
color: #dc2626;
font-size: 18px;
}
.send-unavailable-dialog p {
margin: 0 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.65;
}
.send-unavailable-actions {
display: flex;
justify-content: center;
gap: 10px;
}
+4
View File
@@ -13,6 +13,10 @@
"sha256": "d33559d6620ca173c97a19aafc8570521bf6426f6420e6fb8f90923333b554c8",
"bytes": 33471
},
"group-chat-bot@1.0.0": {
"sha256": "7ba441c89a04d386ff97c854278bc9af3dbd8d6e8e10d1dba48b7ac9c3497d26",
"bytes": 23997
},
"keyword-bot@1.0.0": {
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
"bytes": 19121
+33 -21
View File
@@ -1,10 +1,4 @@
/**
* TraceMemo 扩展 SDK v1 —— 仅类型定义。
*
* 运行期没有这个包:宿主在后台子进程里注入全局 `tm`,扩展入口只需要
* `module.exports = function activate(tm: TraceMemoApi) {}`。
* 把本文件放进扩展仓库即可获得补全与类型检查。
*/
/** TraceMemo 扩展 SDK v1:仅类型定义,运行期由宿主注入全局 tm。 */
export type ExtensionMessageType =
| 'text'
@@ -58,9 +52,7 @@ export interface TraceMemoSendTextRequest {
dedupeKey?: string
}
/**
* 图片发送。
*/
/** 图片发送。 */
export interface TraceMemoSendImageRequest {
type: 'image'
to: string
@@ -68,10 +60,7 @@ export interface TraceMemoSendImageRequest {
dedupeKey?: string
}
/**
* 视频发送。原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。
* 路径必须位于扩展数据目录或系统临时目录。
*/
/** 视频发送。原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交;路径必须位于扩展数据目录或系统临时目录。 */
export interface TraceMemoSendVideoRequest {
type: 'video'
to: string
@@ -79,10 +68,23 @@ export interface TraceMemoSendVideoRequest {
dedupeKey?: string
}
export interface TraceMemoSendVoiceRequest {
type: 'voice'
to: string
/** 传 `text` 时由宿主使用已配置的文字转语音服务合成并发送。 */
text?: string
/** 传 `path` 时发送扩展数据目录或系统临时目录中的音频文件。 */
path?: string
/** 可选音色 ID;省略时使用 TraceMemo 设置页选定的默认音色。 */
voiceId?: string
dedupeKey?: string
}
export type TraceMemoSendRequest =
| TraceMemoSendTextRequest
| TraceMemoSendImageRequest
| TraceMemoSendVideoRequest
| TraceMemoSendVoiceRequest
export interface TraceMemoAutomationActionDefinition {
id: string
@@ -116,10 +118,26 @@ export interface TraceMemoCapabilities {
canSendText: boolean
canSendImage: boolean
canSendVideo: boolean
canSendVoice?: boolean
licensed: boolean
message: string
}
ai: { configured: boolean; modelName: string }
tts?: {
configured: boolean
model: string
selectedVoiceId: string
selectedVoice: {
id: string
name: string
description: string
tags: string[]
languages: string[]
authorName?: string
previewUrl?: string
coverImage?: string
} | null
}
}
export interface TraceMemoApi {
@@ -174,13 +192,7 @@ export interface TraceMemoApi {
}
}
/**
* 后台入口签名。
*
* ```js
* module.exports = function activate(tm) { ... }
* ```
*/
/** 后台入口签名。 */
export type TraceMemoActivate = (tm: TraceMemoApi) => void | Promise<void>
declare global {
+15 -29
View File
@@ -1,17 +1,6 @@
#!/usr/bin/env node
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
/**
* 把 `examples/extensions` 里的官方模板打成确定性 ZIP,并生成索引。
*
* 为什么不用 archiver:ZIP 里的时间戳来自文件 mtime,同一份源码在不同机器上
* 会产出不同字节,索引里的 sha256 就失去「内容是否变化」的意义。
* 这里手写 ZIP:固定时间戳、固定权限、按路径排序,相同输入必然得到相同哈希。
*
* 用法:
* node scripts/build-extension-templates.cjs 构建并校验
* node scripts/build-extension-templates.cjs --update-lock 内容变了但版本未升时强制更新基线
* node scripts/build-extension-templates.cjs --check 只校验产物是否为最新,不写盘
*/
/** 把官方模板打成确定性 ZIP 并生成索引;手写 ZIP 才能固定时间戳、权限与条目顺序。 */
const fs = require('node:fs')
const path = require('node:path')
const zlib = require('node:zlib')
@@ -22,12 +11,7 @@ const SOURCE_ROOT = path.join(ROOT, 'examples', 'extensions')
const OUTPUT_DIR = path.join(ROOT, 'build', 'extension-templates')
const LOCK_FILE = path.join(SOURCE_ROOT, 'template-lock.json')
/**
* 官方模板白名单。
*
* 只有列在这里的目录才会进包;新增模板必须显式登记,避免「仓库里多一个目录
* 就被静默发布」。
*/
/** 模板白名单:只有显式登记的目录才进包,避免新增目录被静默发布。 */
const TEMPLATE_SPECS = [
{
id: 'keyword-bot',
@@ -39,6 +23,16 @@ const TEMPLATE_SPECS = [
},
platforms: ['darwin', 'win32']
},
{
id: 'group-chat-bot',
dir: 'group-chat-bot',
requires: {
python: false,
chrome: false,
externalScript: false
},
platforms: ['darwin', 'win32']
},
{
id: 'douyin-sender',
dir: 'douyin-sender',
@@ -72,7 +66,7 @@ const EXCLUDED_DIRECTORIES = new Set([
])
const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
/** 即使本机存在也不进包:来源与分发许可未确认,或属于本机私有脚本。 */
const EXCLUDED_RELATIVE_PATHS = new Set(['scripts/douyin.py'])
const EXCLUDED_RELATIVE_PATHS = new Set(['scripts/douyin.py', 'lib/bot-engine.js'])
const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log', '.env', '.local'])
const CRC_TABLE = (() => {
@@ -108,11 +102,7 @@ function isSafeRelativePath(value) {
return true
}
/**
* 收集模板文件。
*
* 返回按路径排序的列表:ZIP 内条目顺序会影响字节,固定顺序是可重复构建的前提。
*/
/** 收集模板文件。 */
function collectTemplateFiles(spec, sourceRoot = SOURCE_ROOT) {
const root = path.join(sourceRoot, spec.dir)
if (!fs.existsSync(root)) {
@@ -263,11 +253,7 @@ function writeLock(lock, lockFile = LOCK_FILE) {
fs.writeFileSync(lockFile, `${JSON.stringify(sorted, null, 2)}\n`, 'utf8')
}
/**
* 构建入口。
*
* 返回 `{ templates, warnings }`;校验失败直接抛错,调用方负责中止打包。
*/
/** 构建入口。 */
function buildTemplates(options = {}) {
const updateLock = options.updateLock === true
const checkOnly = options.check === true
+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 {
@@ -3,12 +3,7 @@ import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { ExtensionTemplateCatalog } from '../../src/main/extensions/extension-template-catalog'
/**
* 打包产物验证:只读 `Resources/extension-templates`,不碰源码树。
*
* 这一步回答的是「删掉 examples 之后用户还能不能看到模板」——如果目录不存在
* (例如只跑了单元测试),整组跳过,不影响常规 CI。
*/
/** 打包产物验证:只读 `Resources/extension-templates`,不碰源码树。 */
const CANDIDATES = [
'dist/mac-arm64/TraceMemo.app/Contents/Resources/extension-templates',
'dist/mac/TraceMemo.app/Contents/Resources/extension-templates',
@@ -21,7 +16,7 @@ const packagedRoot = CANDIDATES.map((relative) => path.join(process.cwd(), relat
)
describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
it('产物目录自带两个模板与索引', async () => {
it('产物目录自带三个模板与索引', async () => {
const catalog = new ExtensionTemplateCatalog({
templateRoot: packagedRoot as string,
getRecord: () => undefined,
@@ -34,6 +29,7 @@ describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
const list = await catalog.list()
expect(list.map((item) => item.template.templateId).sort()).toEqual([
'douyin-sender',
'group-chat-bot',
'keyword-bot'
])
// 资源自包含:索引里的 zip 就在同一目录,且哈希匹配(damaged 会暴露不一致)。
@@ -49,7 +45,7 @@ describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
probePython: () => '/usr/bin/python3',
probeChrome: () => '/usr/bin/chrome'
})
for (const templateId of ['keyword-bot', 'douyin-sender']) {
for (const templateId of ['keyword-bot', 'group-chat-bot', 'douyin-sender']) {
const resolved = await catalog.resolveZip(templateId)
expect(fs.existsSync(resolved.path)).toBe(true)
expect(resolved.template.sha256).toMatch(/^[a-f0-9]{64}$/)
+72
View File
@@ -336,3 +336,75 @@ describe('extension send gateway / video', () => {
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
})
describe('extension send gateway / voice', () => {
const cleanup: string[] = []
function tempDir(prefix: string): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
cleanup.push(root)
return root
}
afterEach(() => {
for (const root of cleanup.splice(0)) fs.rmSync(root, { recursive: true, force: true })
})
const voiceContext = {
extensionId: 'com.example.group-chat-bot',
permissions: ['wechat.send.voice' as const],
conversationScope: [] as string[]
}
it('缺少 wechat.send.voice 权限时拒绝', async () => {
const { instance } = gateway({ dataRoot: tempDir('tm-ext-voice-') })
await expect(
instance.sendVoice(
{ ...voiceContext, permissions: [] },
{ to: 'fixture@chatroom', text: '你好' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('传入 text 时委托宿主 TTS 合成、经 Gateway 发送并在结束后清理临时音频', async () => {
const dataRoot = tempDir('tm-ext-voice-')
const generatedAudio = path.join(dataRoot, 'tts-sample.mp3')
fs.writeFileSync(generatedAudio, Buffer.from('fixture-audio'))
const synthesizeVoice = vi.fn(async () => ({ filePath: generatedAudio }))
const cleanupVoice = vi.fn()
const executeAction = vi.fn(async () => sentResult)
const instance = new ExtensionSendGateway({
getCapability: async () => ({
...readyCapability,
capabilities: { text: true, image: true, voice: true, video: true }
}),
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: executeAction as never,
getExtensionDataRoot: () => dataRoot,
synthesizeVoice,
cleanupVoice,
getFromId: () => 'wxid_self',
now: () => 1_000_000
})
const result = await instance.sendVoice(voiceContext, {
to: 'fixture@chatroom',
text: '大家晚上好',
voiceId: 'voice-123',
dedupeKey: 'evt-voice-1'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
expect(synthesizeVoice).toHaveBeenCalledWith({ text: '大家晚上好', voiceId: 'voice-123' })
expect(executeAction).toHaveBeenCalledWith(
expect.objectContaining({
origin: 'extension',
purpose: 'extension_send',
content: { type: 'voice', path: fs.realpathSync(generatedAudio) },
metadata: { extensionId: 'com.example.group-chat-bot', fromId: 'wxid_self' }
})
)
expect(cleanupVoice).toHaveBeenCalledWith(generatedAudio)
})
})
@@ -75,11 +75,12 @@ function record(overrides: Partial<ExtensionRegistryRecord>): ExtensionRegistryR
}
describe('官方模板目录', () => {
it('列出两个模板,未安装时状态为 not-installed', async () => {
it('列出三个模板,未安装时状态为 not-installed', async () => {
const { catalog } = setup()
const list = await catalog.list()
expect(list.map((item) => item.template.templateId).sort()).toEqual([
'douyin-sender',
'group-chat-bot',
'keyword-bot'
])
expect(list.every((item) => item.state === 'not-installed')).toBe(true)
+3 -2
View File
@@ -39,18 +39,19 @@ function stageExamples(): { sourceRoot: string; lockFile: string } {
}
describe('官方模板构建', () => {
it('产出两个模板与索引,索引指向真实文件', () => {
it('产出三个模板与索引,索引指向真实文件', () => {
const { sourceRoot, lockFile } = stageExamples()
const outputDir = path.join(tempRoot(), 'out')
const result = buildTemplates({ sourceRoot, outputDir, lockFile })
expect(result.templates.map((item) => item.templateId).sort()).toEqual([
'douyin-sender',
'group-chat-bot',
'keyword-bot'
])
const index = fs.readJsonSync(path.join(outputDir, 'index.json'))
expect(index.version).toBe(1)
expect(index.templates).toHaveLength(2)
expect(index.templates).toHaveLength(3)
for (const template of index.templates) {
expect(fs.existsSync(path.join(outputDir, template.file))).toBe(true)
expect(template.sha256).toMatch(/^[a-f0-9]{64}$/)