feat: 拓展中心

This commit is contained in:
Wxw-Gu committed 2026-11-18 17:42:17 +08:00
1 parent b171818df5
commit 116989a091
74 files changed
+11738 -379

No files matched your search

+3
View File
@@ -34,3 +34,6 @@ debug-originals
# 去水印脚本
/examples/extensions/douyin-sender/scripts/douyin.py
# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
/build/extension-templates/
+5
View File
@@ -39,6 +39,11 @@ extraResources:
- runtime/win32/**
- wcdb/win32/x64/**
- '!wcdb/**/tm-wcdb-config-helper*'
# 官方扩展模板(构建期由 scripts/build-extension-templates.cjs 生成)
- from: build/extension-templates
to: extension-templates
filter:
- '**/*'
# 默认不打包helper
# - from: resources/wcdb/win32/x64
# to: resources/wcdb/win32/x64
+6
View File
@@ -40,6 +40,12 @@ extraResources:
to: skill/tracememo-reader
filter:
- '**/*'
# 官方扩展模板:构建期由 scripts/build-extension-templates.cjs 生成,
# 安装包必须自带,运行时不依赖源码树或网络。
- from: build/extension-templates
to: extension-templates
filter:
- '**/*'
nsis:
oneClick: false
allowToChangeInstallationDirectory: true
@@ -29,6 +29,8 @@ const execFileAsync = promisify(execFile)
const CONFIG_KEY = 'config'
const STATS_KEY = 'stats'
/** 安全存储里的 Cookie 键名。 */
const SECRET_COOKIE_KEY = 'douyinCookie'
const PROGRESS_KEY = 'progress'
const TEST_RESULT_KEY = 'testResult'
const CONFIG_TTL_MS = 1000
@@ -312,23 +314,7 @@ function resolvePythonInvocation(pythonPath, scriptPath, args) {
if (process.platform !== 'darwin') {
return { file: pythonPath, args: [scriptPath, ...args] }
}
let resolvedPython = pythonPath
if (pythonPath === 'python3') {
const venvPython = path.join(
os.homedir(),
'Library',
'Caches',
'douyin-video',
'venv',
'bin',
'python'
)
try {
if (fsSync.existsSync(venvPython)) resolvedPython = venvPython
} catch {
// 缓存 venv 不可读时退回配置里的 pythonPath。
}
}
const resolvedPython = pythonPath
try {
if (fsSync.existsSync('/usr/bin/arch')) {
return {
@@ -343,10 +329,10 @@ function resolvePythonInvocation(pythonPath, scriptPath, args) {
}
/**
* 解析可用的抖音 Cookie:
* 1. 优先使用调用方显式传入的 cookieHeader(测试发送 / 测试下载);
* 2. 尝试向宿主读取已保存的 Cookie(若宿主暴露接口);
* 3. 回退读取扩展私有目录或桌面上的 `douyin-cookie` 文件(供 @我自己 自动回复链路使用)。
* 解析可用的抖音 Cookie。
*
* 只认两个来源:调用方显式传入的 header,以及扩展私有目录里由用户配置生成的文件。
* **不扫描桌面**——扩展不该去读用户没有明确交给它的文件。
*/
async function resolveCookieHeader(explicitHeader) {
const direct = String(explicitHeader || '').trim()
@@ -356,25 +342,49 @@ async function resolveCookieHeader(explicitHeader) {
const fromHost = String((await tm.douyin.getCookie()) || '').trim()
if (fromHost) return fromHost
} catch {
// 宿主未提供或读取失败时继续尝试本地文件。
// 宿主未提供或读取失败时按「未配置」处理。
}
}
const candidates = [
path.join(tm.extension.dataDir, 'douyin-cookie.txt'),
path.join(os.homedir(), 'Desktop', 'douyin-cookie'),
path.join(os.homedir(), 'Desktop', 'douyin-cookie.txt')
]
for (const file of candidates) {
// 优先用安全存储;未授权或不可用时再退回旧的扩展数据文件(迁移期兼容)。
if (tm.secrets) {
try {
const content = String(await fs.readFile(file, 'utf8')).trim()
if (content) return content
const stored = await tm.secrets.get(SECRET_COOKIE_KEY)
if (stored) return String(stored).trim()
} catch {
// 文件不存在或无权限时跳过。
// 未授予 secrets 权限或系统安全存储不可用:继续走兼容分支。
}
}
try {
const content = String(await fs.readFile(path.join(tm.extension.dataDir, 'douyin-cookie.txt'), 'utf8')).trim()
if (content) return content
} catch {
// 未配置 Cookie 时走游客模式。
}
return ''
}
/**
* 把旧的明文 Cookie 迁进安全存储,成功后删除明文文件。
*
* 只在「安全存储可用 + 用户已授权 secrets」时执行;否则保持原样,
* 绝不把加密数据降级成明文,也不谎报迁移成功。
*/
async function migrateLegacyCookie() {
if (!tm.secrets) return
try {
const existing = await tm.secrets.get(SECRET_COOKIE_KEY)
if (existing) return
const legacyPath = path.join(tm.extension.dataDir, 'douyin-cookie.txt')
const legacy = String(await fs.readFile(legacyPath, 'utf8')).trim()
if (!legacy) return
await tm.secrets.set(SECRET_COOKIE_KEY, legacy)
await fs.unlink(legacyPath).catch(() => undefined)
tm.log.info('已把旧版明文 Cookie 迁入系统安全存储,并删除明文文件')
} catch {
// 未授权或不可用时静默保留旧文件,由页面提示用户重新填写。
}
}
function resolveScriptPath(value) {
const expanded = expandHome(value)
if (!expanded) return path.resolve(__dirname, '..', 'scripts', 'douyin.py')
@@ -382,6 +392,27 @@ function resolveScriptPath(value) {
return path.resolve(__dirname, '..', expanded)
}
/**
* 解析脚本不随应用分发(来源与分发许可未确认),缺失时整条视频链路必须停住。
* 缺失提示只打一次,避免每条消息刷日志。
*/
let scriptMissingLogged = false
function ensureScriptReady(config) {
let ready = false
try {
ready = fsSync.existsSync(resolveScriptPath(config.scriptPath))
} catch {
ready = false
}
if (!ready && !scriptMissingLogged) {
scriptMissingLogged = true
safeLog('warn', '缺少解析脚本 scripts/douyin.py,视频处理已暂停;请按扩展说明自行提供后重启')
}
if (ready) scriptMissingLogged = false
return ready
}
/** 统一封装脚本调用:固定 cwd、超时、输出上限、UTF-8 与 macOS 原生 arm64 执行。 */
async function runPython(args, timeoutMs, config) {
// 首次启用时 dataDir 可能还没被创建;execFile 的 cwd 不存在会直接 ENOENT。
@@ -544,6 +575,7 @@ async function reportFailure(event, config, message) {
* 进度快照与统计都会落盘;失败原因只保留错误类型,不写 URL / 路径 / 标题。
*/
async function processLink(event, config, url, options = {}) {
if (!ensureScriptReady(config)) return
const jobId = event.eventId
let awemeId = ''
let stage = 'accepted'
@@ -609,6 +641,7 @@ async function processLink(event, config, url, options = {}) {
async function handleEvent(event) {
try {
const config = await loadConfig()
if (!ensureScriptReady(config)) return
const decision = shouldHandle(event, config, cooldownUntil, Date.now())
if (!decision.handle) return
@@ -2,12 +2,13 @@
"manifestVersion": 1,
"id": "com.example.douyin-sender",
"name": "抖音视频搬运",
"version": "1.0.3",
"version": "1.0.5",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。",
"description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。需要本机 Python、Chrome 与解析脚本。",
"author": "TraceMemo Examples",
"permissions": [
"secrets",
"messages.subscribe",
"contacts.list",
"wechat.send.video",
@@ -19,7 +20,9 @@
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": ["text"],
"messageTypes": [
"text"
],
"conversationIds": [],
"requireMentionMe": true,
"includeSelf": false
+10 -12
View File
@@ -22,10 +22,7 @@ const ALLOWED_METHODS = new Set([
'storage.list',
'capabilities.get',
'contacts.listGroups',
'test.send',
'douyin.cookie.get',
'douyin.cookie.set',
'douyin.cookie.clear',
'extension.request',
'extension.info'
])
@@ -484,7 +481,7 @@ async function loadConfig() {
async function loadCookieState() {
try {
const result = await callHost('douyin.cookie.get', {})
const result = await callHost('extension.request', { method: 'douyinCookie.status', params: {} })
cookieState.textContent =
result && result.configured ? '已保存 Cookie(内容不可回显)' : '未配置'
} catch {
@@ -529,11 +526,9 @@ document.getElementById('test-send').addEventListener('click', async () => {
activeTestId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
setTestResult('已提交,等待后台开始解析…', 'running')
try {
const submitted = callHost('test.send', {
id: activeTestId,
to,
text,
at: Date.now()
const submitted = callHost('extension.request', {
method: 'testSend',
params: { id: activeTestId, to, text, at: Date.now() }
})
void pollTestResult()
await submitted
@@ -550,7 +545,10 @@ document.getElementById('cookie-save').addEventListener('click', async () => {
return
}
try {
await callHost('douyin.cookie.set', { cookieHeader: value })
await callHost('extension.request', {
method: 'douyinCookie.set',
params: { cookieHeader: value }
})
cookieHeader.value = ''
await loadCookieState()
setStatus('Cookie 已安全保存。', 'ok')
@@ -561,7 +559,7 @@ document.getElementById('cookie-save').addEventListener('click', async () => {
document.getElementById('cookie-clear').addEventListener('click', async () => {
try {
await callHost('douyin.cookie.clear', {})
await callHost('extension.request', { method: 'douyinCookie.clear', params: {} })
cookieHeader.value = ''
await loadCookieState()
setStatus('Cookie 已清除。', 'ok')
@@ -149,6 +149,8 @@ function describeError(error) {
async function onMessage(event) {
try {
const config = await loadConfig()
// 交给自动化规则处理时,订阅路径必须彻底闭嘴,否则同一条消息回复两次。
if (config.executionMode === 'automation') return
const now = Date.now()
const verdict = shouldReply(event, config, cooldownUntil, now)
if (!verdict.reply || !verdict.rule) return
@@ -198,6 +200,10 @@ module.exports = function activate(api) {
if (!config.enabled) {
return { success: false, error: '机器人未启用' }
}
// 订阅模式下这条路径同样会发送:直接跳过,避免与事件路径重复回复。
if (config.executionMode === 'subscribe') {
return { success: true, output: { matched: false, skipped: 'subscribe-mode' } }
}
const rule = pickRule(input.text, config)
if (!rule) {
return { success: true, output: { matched: false } }
@@ -20,6 +20,15 @@ const MAX_GROUPS = 200
const MODES = new Set(['contains', 'exact', 'prefix'])
/**
* 两条回复入口的执行模式。
*
* 同一条消息若同时被「事件订阅」和「自动化动作」处理,会回复两次。
* 这里用互斥模式从根上避免:默认保留订阅(兼容旧用户),
* 切到 `automation` 后订阅路径完全不再发送。
*/
const EXECUTION_MODES = new Set(['subscribe', 'automation'])
/**
* 把任意来源的配置规范化为 `configVersion: 2`。
*
@@ -49,6 +58,7 @@ function normalizeConfig(raw) {
return {
configVersion: CONFIG_VERSION,
enabled: input.enabled === true,
executionMode: EXECUTION_MODES.has(input.executionMode) ? input.executionMode : 'subscribe',
rules,
scope: {
groups: Array.isArray(scope.groups)
@@ -204,6 +214,7 @@ function clampNumber(value, min, max) {
module.exports = {
CONFIG_VERSION,
EXECUTION_MODES,
normalizeConfig,
matchRule,
pickRule,
@@ -2,7 +2,7 @@
"manifestVersion": 1,
"id": "com.example.keyword-bot",
"name": "关键词回复机器人",
"version": "1.0.0",
"version": "1.0.1",
"apiVersion": "1",
"minAppVersion": "2.6.0",
"description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。",
@@ -19,7 +19,9 @@
"background": "background/index.js"
},
"subscriptions": {
"messageTypes": ["text"],
"messageTypes": [
"text"
],
"conversationIds": [],
"requireMentionMe": false,
"includeSelf": false
+25
View File
@@ -0,0 +1,25 @@
{
"version": 1,
"templates": {
"douyin-sender@1.0.3": {
"sha256": "01cd4b1a7af2b9e0208145b64e487af2a17f354ab7344f32cf9ff7565deb11a6",
"bytes": 32839
},
"douyin-sender@1.0.4": {
"sha256": "4fd4a478232d6b52a68187d2e0c3f42733acda1e65ce9f9594f99440e6edd3e5",
"bytes": 32981
},
"douyin-sender@1.0.5": {
"sha256": "d33559d6620ca173c97a19aafc8570521bf6426f6420e6fb8f90923333b554c8",
"bytes": 33471
},
"keyword-bot@1.0.0": {
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
"bytes": 19121
},
"keyword-bot@1.0.1": {
"sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41",
"bytes": 19517
}
}
}
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>TraceMemo(迹忆)</title>
<link rel="icon" type="image/svg+xml" href="./assets/brand-icon-DQrJvdgV.svg" />
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:; frame-src tm-extension:;"
/>
<script type="module" crossorigin src="./assets/index-CRoZdOvo.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DJPGPmFx.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
+10 -8
View File
@@ -60,20 +60,22 @@
"build": "npm run typecheck && electron-vite build",
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs && node scripts/ensure-electron-binary.cjs",
"build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir",
"build:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
"build:mac:arm64": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
"build:mac:arm64:send-runtime": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64",
"build:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
"build:mac:arm64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
"build:mac:arm64:send-runtime": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64",
"build:mac:public": "node scripts/build-macos-edition.cjs public",
"build:mac:native": "node scripts/build-macos-edition.cjs native",
"build:mac:x64": "npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
"build:mac:x64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
"release": "npm run release:mac && npm run release:win",
"release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
"release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
"release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
"release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
"release:mac:arm64": "npm run build:templates && npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
"release:mac:x64": "npm run build:templates && npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
"release:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
"release:stable": "npm run release",
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux"
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux",
"build:templates": "node scripts/build-extension-templates.cjs",
"prebuild": "node scripts/build-extension-templates.cjs"
},
"dependencies": {
"@electron-toolkit/preload": "^3.0.2",
+55
View File
@@ -768,6 +768,60 @@ function enforceSendRuntimeBoundary(
return null
}
/**
* 官方模板资源必须随包发布,且索引与 ZIP 的哈希一致。
*
* 这一层挡的是「打包时忘了跑构建脚本」:没有它,安装包会静默少两个模板,
* 而用户看到的只是空列表。
*/
function validateExtensionTemplates(runtimeResources) {
const root = path.join(runtimeResources, 'extension-templates')
const indexPath = path.join(root, 'index.json')
if (!existsSync(indexPath)) {
throw new Error(
'Missing extension templates: ' +
indexPath +
'. Run `node scripts/build-extension-templates.cjs` before packaging.'
)
}
let index
try {
index = JSON.parse(readFileSync(indexPath, 'utf8'))
} catch (error) {
throw new Error('Invalid extension template index: ' + error.message)
}
if (!index || index.version !== 1 || !Array.isArray(index.templates)) {
throw new Error('Invalid extension template index structure')
}
if (index.templates.length === 0) {
throw new Error('Extension template index is empty')
}
for (const template of index.templates) {
const fileName = String(template.file || '')
if (!fileName || fileName.includes('/') || fileName.includes('\\')) {
throw new Error('Invalid extension template file name: ' + fileName)
}
const zipPath = path.join(root, fileName)
if (!existsSync(zipPath)) {
throw new Error('Missing extension template archive: ' + fileName)
}
const digest = createHash('sha256').update(readFileSync(zipPath)).digest('hex')
if (digest !== template.sha256) {
throw new Error(
'Extension template checksum mismatch: ' +
fileName +
' (index=' +
template.sha256 +
', actual=' +
digest +
')'
)
}
}
console.log('[afterPack] extension templates verified: ' + index.templates.length)
}
exports.default = async function afterPack(context) {
const runtimeResources = getRuntimeResources(context)
const arch = normalizeBuilderArch(context.arch)
@@ -782,6 +836,7 @@ exports.default = async function afterPack(context) {
}
validateAsarRuntimeDependencies(runtimeResources)
validateReaderSkillRuntime(runtimeResources)
validateExtensionTemplates(runtimeResources)
validateSilkWasmRuntime(runtimeResources)
const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName)
validateElectronMainBinary(
+414
View File
@@ -0,0 +1,414 @@
#!/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 只校验产物是否为最新,不写盘
*/
const fs = require('node:fs')
const path = require('node:path')
const zlib = require('node:zlib')
const crypto = require('node:crypto')
const ROOT = path.resolve(__dirname, '..')
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',
dir: 'keyword-bot',
requires: {
python: false,
chrome: false,
externalScript: false
},
platforms: ['darwin', 'win32']
},
{
id: 'douyin-sender',
dir: 'douyin-sender',
requires: {
python: { required: true, minVersion: '3.10', reason: '解析与下载依赖本机 Python 脚本' },
chrome: { required: true, reason: '解析脚本通过本机 Chrome 读取页面' },
externalScript: {
required: true,
path: 'scripts/douyin.py',
reason: '解析脚本不随应用分发,需用户自行提供后才能处理视频'
}
},
platforms: ['darwin', 'win32']
}
]
/** 与安装器保持同一套路径规则:任何一段越界或不合法都会让安装失败。 */
const SAFE_SEGMENT = /^[A-Za-z0-9._@+\- ]+$/
const RESERVED_SEGMENT = /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i
const EXCLUDED_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv',
'tests',
'coverage'
])
const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
/** 即使本机存在也不进包:来源与分发许可未确认,或属于本机私有脚本。 */
const EXCLUDED_RELATIVE_PATHS = new Set(['scripts/douyin.py'])
const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log', '.env', '.local'])
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let index = 0; index < 256; index += 1) {
let value = index
for (let bit = 0; bit < 8; bit += 1) {
value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1
}
table[index] = value >>> 0
}
return table
})()
function crc32(buffer) {
let crc = 0xffffffff
for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)
return (crc ^ 0xffffffff) >>> 0
}
function isSafeRelativePath(value) {
if (typeof value !== 'string' || !value || value.length > 240) return false
if (value.includes('\0')) return false
const segments = value.split('/')
if (segments.length > 10) return false
for (const segment of segments) {
if (!segment || segment === '.' || segment === '..') return false
if (segment.length > 64) return false
if (!SAFE_SEGMENT.test(segment)) return false
if (/[. ]$/.test(segment)) return false
if (RESERVED_SEGMENT.test(segment)) return false
}
return true
}
/**
* 收集模板文件。
*
* 返回按路径排序的列表:ZIP 内条目顺序会影响字节,固定顺序是可重复构建的前提。
*/
function collectTemplateFiles(spec, sourceRoot = SOURCE_ROOT) {
const root = path.join(sourceRoot, spec.dir)
if (!fs.existsSync(root)) {
throw new Error(`模板目录不存在:${spec.dir}`)
}
const files = []
const walk = (directory, prefix) => {
for (const entry of fs
.readdirSync(directory, { withFileTypes: true })
.sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.isSymbolicLink()) {
throw new Error(`模板目录不能包含符号链接:${prefix}${entry.name}`)
}
if (entry.isDirectory()) {
if (EXCLUDED_DIRECTORIES.has(entry.name)) continue
walk(path.join(directory, entry.name), `${prefix}${entry.name}/`)
continue
}
if (!entry.isFile()) continue
if (EXCLUDED_FILES.has(entry.name)) continue
if (EXCLUDED_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue
const relative = `${prefix}${entry.name}`
if (EXCLUDED_RELATIVE_PATHS.has(relative)) continue
if (!isSafeRelativePath(relative)) {
throw new Error(`模板内文件路径不合法:${spec.dir}/${relative}`)
}
files.push({ path: relative, data: fs.readFileSync(path.join(directory, entry.name)) })
}
}
walk(root, '')
return files.sort((left, right) => left.path.localeCompare(right.path))
}
function validateManifest(spec, files) {
const manifestFile = files.find((file) => file.path === 'manifest.json')
if (!manifestFile) throw new Error(`模板 ${spec.id} 缺少 manifest.json`)
let manifest
try {
manifest = JSON.parse(manifestFile.data.toString('utf8'))
} catch {
throw new Error(`模板 ${spec.id} 的 manifest.json 不是合法 JSON`)
}
const idPattern =
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
if (manifest.manifestVersion !== 1) throw new Error(`模板 ${spec.id} 的 manifestVersion 必须是 1`)
if (!idPattern.test(String(manifest.id || ''))) {
throw new Error(`模板 ${spec.id} 的 id 不是反向域名格式`)
}
if (
!/^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[0-9A-Za-z.-]{1,40})?$/.test(String(manifest.version || ''))
) {
throw new Error(`模板 ${spec.id} 的 version 不是 x.y.z 格式`)
}
const names = new Set(files.map((file) => file.path))
const entrypoints = manifest.entrypoints || {}
for (const [key, value] of Object.entries(entrypoints)) {
if (!value) continue
if (!names.has(value)) {
throw new Error(`模板 ${spec.id} 的入口 ${key} 指向不存在的文件:${value}`)
}
}
if (!entrypoints.page && !entrypoints.background) {
throw new Error(`模板 ${spec.id} 至少需要一个页面或后台入口`)
}
return manifest
}
/** 固定时间戳(1980-01-01 00:00)与权限,保证相同内容得到相同字节。 */
const DOS_TIME = 0
const DOS_DATE = 0x21
function buildZip(entries) {
const locals = []
const centrals = []
let offset = 0
for (const entry of entries) {
const name = Buffer.from(entry.path, 'utf8')
const data = entry.data
const compressed = zlib.deflateRawSync(data, { level: 9 })
const checksum = crc32(data)
const local = Buffer.alloc(30)
local.writeUInt32LE(0x04034b50, 0)
local.writeUInt16LE(20, 4)
local.writeUInt16LE(0x0800, 6) // UTF-8 文件名
local.writeUInt16LE(8, 8) // deflate
local.writeUInt16LE(DOS_TIME, 10)
local.writeUInt16LE(DOS_DATE, 12)
local.writeUInt32LE(checksum, 14)
local.writeUInt32LE(compressed.length, 18)
local.writeUInt32LE(data.length, 22)
local.writeUInt16LE(name.length, 26)
local.writeUInt16LE(0, 28)
locals.push(local, name, compressed)
const central = Buffer.alloc(46)
central.writeUInt32LE(0x02014b50, 0)
central.writeUInt16LE(20, 4)
central.writeUInt16LE(20, 6)
central.writeUInt16LE(0x0800, 8)
central.writeUInt16LE(8, 10)
central.writeUInt16LE(DOS_TIME, 12)
central.writeUInt16LE(DOS_DATE, 14)
central.writeUInt32LE(checksum, 16)
central.writeUInt32LE(compressed.length, 20)
central.writeUInt32LE(data.length, 24)
central.writeUInt16LE(name.length, 28)
central.writeUInt16LE(0, 30)
central.writeUInt16LE(0, 32)
central.writeUInt16LE(0, 34)
central.writeUInt16LE(0, 36)
central.writeUInt32LE((0o100644 << 16) >>> 0, 38)
central.writeUInt32LE(offset, 42)
centrals.push(central, name)
offset += local.length + name.length + compressed.length
}
const centralBuffer = Buffer.concat(centrals)
const end = Buffer.alloc(22)
end.writeUInt32LE(0x06054b50, 0)
end.writeUInt16LE(entries.length, 8)
end.writeUInt16LE(entries.length, 10)
end.writeUInt32LE(centralBuffer.length, 12)
end.writeUInt32LE(offset, 16)
return Buffer.concat([...locals, centralBuffer, end])
}
function sha256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex')
}
function readLock(lockFile = LOCK_FILE) {
try {
const parsed = JSON.parse(fs.readFileSync(lockFile, 'utf8'))
if (!parsed || typeof parsed !== 'object') return { version: 1, templates: {} }
return { version: 1, templates: parsed.templates || {} }
} catch {
return { version: 1, templates: {} }
}
}
function writeLock(lock, lockFile = LOCK_FILE) {
const sorted = { version: 1, templates: {} }
for (const key of Object.keys(lock.templates).sort()) {
sorted.templates[key] = lock.templates[key]
}
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
const sourceRoot = options.sourceRoot || SOURCE_ROOT
const outputDir = options.outputDir || OUTPUT_DIR
const lockFile = options.lockFile || LOCK_FILE
const specs = options.specs || TEMPLATE_SPECS
const lock = readLock(lockFile)
const templates = []
const warnings = []
const seenIds = new Set()
const seenTemplateIds = new Set()
for (const spec of specs) {
if (seenTemplateIds.has(spec.id)) {
throw new Error(`模板 id 重复:${spec.id}`)
}
seenTemplateIds.add(spec.id)
const files = collectTemplateFiles(spec, sourceRoot)
if (!files.length) throw new Error(`模板 ${spec.id} 没有任何文件`)
const manifest = validateManifest(spec, files)
if (seenIds.has(manifest.id)) {
throw new Error(`模板扩展 id 重复:${manifest.id}`)
}
seenIds.add(manifest.id)
const zip = buildZip(files)
const digest = sha256(zip)
const fileName = `${spec.id}-${manifest.version}.zip`
const lockKey = `${spec.id}@${manifest.version}`
const previous = lock.templates[lockKey]
if (previous && previous.sha256 !== digest && !updateLock) {
throw new Error(
`模板 ${spec.id} 的版本仍为 ${manifest.version},但内容已变化。` +
`请升级 manifest.version,或确认后用 --update-lock 更新基线。`
)
}
if (!previous) {
// 新版本(或首次构建):允许,并把基线更新到当前内容。
lock.templates[lockKey] = { sha256: digest, bytes: zip.length }
} else if (updateLock) {
lock.templates[lockKey] = { sha256: digest, bytes: zip.length }
}
// 缺少外部脚本的模板必须显式标记,不能对外宣称开箱即用。
const externalScript = spec.requires.externalScript
if (externalScript && externalScript.required) {
const present = files.some((file) => file.path === externalScript.path)
if (present) {
warnings.push(
`模板 ${spec.id} 的依赖脚本 ${externalScript.path} 意外进入了发布包,请检查排除规则`
)
}
}
templates.push({
templateId: spec.id,
extensionId: manifest.id,
name: String(manifest.name || spec.id),
version: String(manifest.version),
...(manifest.description ? { description: String(manifest.description) } : {}),
permissions: Array.isArray(manifest.permissions) ? manifest.permissions : [],
file: fileName,
sha256: digest,
bytes: zip.length,
fileCount: files.length,
platforms: spec.platforms,
requires: spec.requires,
zip
})
}
if (!checkOnly) {
fs.mkdirSync(outputDir, { recursive: true })
// 删掉不属于本次产物的旧 ZIP,避免「旧版本文件还在、索引却指向新版本」。
const keep = new Set(templates.map((template) => template.file))
for (const name of fs.readdirSync(outputDir)) {
if (!name.endsWith('.zip')) continue
if (keep.has(name)) continue
fs.unlinkSync(path.join(outputDir, name))
}
for (const template of templates) {
fs.writeFileSync(path.join(outputDir, template.file), template.zip)
}
const index = {
version: 1,
templates: templates.map((template) => {
const copy = { ...template }
delete copy.zip
return copy
})
}
fs.writeFileSync(
path.join(outputDir, 'index.json'),
`${JSON.stringify(index, null, 2)}\n`,
'utf8'
)
writeLock(lock, lockFile)
}
return {
templates: templates.map((template) => {
const copy = { ...template }
delete copy.zip
return copy
}),
warnings
}
}
function main() {
const argv = process.argv.slice(2)
const updateLock = argv.includes('--update-lock')
const checkOnly = argv.includes('--check')
try {
const result = buildTemplates({ updateLock, checkOnly })
for (const template of result.templates) {
console.log(
`[templates] ${template.templateId} ${template.version} ` +
`${template.fileCount} files ${(template.bytes / 1024).toFixed(1)}KB ${template.sha256.slice(0, 12)}`
)
}
for (const warning of result.warnings) {
console.error(`[templates] WARN ${warning}`)
}
console.log(`[templates] 输出目录 ${path.relative(ROOT, OUTPUT_DIR)}`)
} catch (error) {
console.error(`[templates] ${error instanceof Error ? error.message : String(error)}`)
process.exit(1)
}
}
if (require.main === module) main()
module.exports = {
buildTemplates,
buildZip,
collectTemplateFiles,
TEMPLATE_SPECS,
OUTPUT_DIR,
LOCK_FILE
}
@@ -1,5 +1,6 @@
import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest'
import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types'
import type { ExtensionActionInputSchema } from '../../shared/extensions/action-schema'
export interface RegisteredExtensionAction {
extensionId: string
@@ -11,6 +12,9 @@ export interface RegisteredExtensionAction {
registered: boolean
/** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */
declared: boolean
inputSchema?: ExtensionActionInputSchema
/** Schema 校验失败的原因;有值时动作不可配置。 */
schemaError?: string
}
/**
@@ -25,7 +29,15 @@ export interface RegisteredExtensionAction {
export class ExtensionActionRegistry {
private readonly registered = new Map<
string,
Map<string, { title: string; description?: string }>
Map<
string,
{
title: string
description?: string
inputSchema?: ExtensionActionInputSchema
schemaError?: string
}
>
>()
private readonly declared = new Map<
string,
@@ -45,7 +57,13 @@ export class ExtensionActionRegistry {
setRegistered(
extensionId: string,
extensionName: string,
actions: Array<{ id: string; title: string; description?: string }>
actions: Array<{
id: string
title: string
description?: string
inputSchema?: ExtensionActionInputSchema
schemaError?: string
}>
): void {
this.names.set(extensionId, extensionName)
this.registered.set(
@@ -55,7 +73,9 @@ export class ExtensionActionRegistry {
action.id,
{
title: action.title,
...(action.description ? { description: action.description } : {})
...(action.description ? { description: action.description } : {}),
...(action.inputSchema ? { inputSchema: action.inputSchema } : {}),
...(action.schemaError ? { schemaError: action.schemaError } : {})
}
])
)
@@ -91,7 +111,9 @@ export class ExtensionActionRegistry {
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime),
declared: Boolean(declaredAction)
declared: Boolean(declaredAction),
...(runtime?.inputSchema ? { inputSchema: runtime.inputSchema } : {}),
...(runtime?.schemaError ? { schemaError: runtime.schemaError } : {})
}
}
@@ -0,0 +1,124 @@
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
/** 与安装器的排除规则保持一致:这些目录不属于扩展产物。 */
const DEFAULT_IGNORED_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv'
])
const DEFAULT_IGNORED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
const IGNORED_EXTENSIONS = new Set(['.pyc', '.log'])
export interface CodeDigestOptions {
ignoreDirectories?: Iterable<string>
ignoreFiles?: Iterable<string>
}
interface DigestEntry {
path: string
sha256: string
}
/**
* 计算一个目录的代码指纹。
*
* 只覆盖**代码与静态资源**:不包含 `extensions-data`、日志或缓存,
* 所以用户改配置不会让指纹变化,改一行 JS 就会。
*
* 细则:
* - 相对路径参与哈希,因此改名与改内容都能被发现;
* - 文件按路径排序后再累加,结果与遍历顺序无关;
* - 符号链接按链接目标字符串参与哈希,不跟随(避免读到宿主私有文件)。
*/
export function computeDirectoryDigest(root: string, options: CodeDigestOptions = {}): string {
const ignoreDirectories = new Set([
...DEFAULT_IGNORED_DIRECTORIES,
...(options.ignoreDirectories ?? [])
])
const ignoreFiles = new Set([...DEFAULT_IGNORED_FILES, ...(options.ignoreFiles ?? [])])
const entries: DigestEntry[] = []
const walk = (directory: string, prefix: string): void => {
let items: fs.Dirent[]
try {
items = fs.readdirSync(directory, { withFileTypes: true })
} catch {
return
}
for (const item of items) {
if (item.isDirectory()) {
if (ignoreDirectories.has(item.name)) continue
walk(path.join(directory, item.name), prefix ? `${prefix}/${item.name}` : item.name)
continue
}
if (ignoreFiles.has(item.name)) continue
if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue
const relative = prefix ? `${prefix}/${item.name}` : item.name
const absolute = path.join(directory, item.name)
if (item.isSymbolicLink()) {
try {
const target = fs.readlinkSync(absolute)
entries.push({
path: relative,
sha256: createHash('sha256').update(`link:${target}`).digest('hex')
})
} catch {
entries.push({ path: relative, sha256: 'link:unreadable' })
}
continue
}
if (!item.isFile()) continue
try {
const content = fs.readFileSync(absolute)
entries.push({
path: relative,
sha256: createHash('sha256').update(content).digest('hex')
})
} catch {
// 读不到的文件不应让整个指纹失效,但必须留下痕迹。
entries.push({ path: relative, sha256: 'unreadable' })
}
}
}
walk(root, '')
entries.sort((left, right) => left.path.localeCompare(right.path))
const hash = createHash('sha256')
for (const entry of entries) {
hash.update(`${entry.path}\0${entry.sha256}\n`)
}
return hash.digest('hex')
}
/** 列出参与指纹的文件数量;用于诊断「是不是把缓存算进去了」。 */
export function countDigestFiles(root: string): number {
let count = 0
const walk = (directory: string): void => {
let items: fs.Dirent[]
try {
items = fs.readdirSync(directory, { withFileTypes: true })
} catch {
return
}
for (const item of items) {
if (item.isDirectory()) {
if (DEFAULT_IGNORED_DIRECTORIES.has(item.name)) continue
walk(path.join(directory, item.name))
continue
}
if (DEFAULT_IGNORED_FILES.has(item.name)) continue
if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue
count += 1
}
}
walk(root)
return count
}
+329 -17
View File
@@ -1,4 +1,4 @@
import { fork, type ChildProcess } from 'node:child_process'
import { fork, spawn, type ChildProcess } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
@@ -23,7 +23,12 @@ import {
} from '../../shared/extensions/rpc'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
import {
parseActionInputSchema,
type ExtensionActionInputSchema
} from '../../shared/extensions/action-schema'
import type { ExtensionStorage } from './extension-storage'
import type { ExtensionSecretStore } from './extension-secret-store'
const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000
const DEFAULT_ACTION_TIMEOUT_MS = 15_000
@@ -33,14 +38,52 @@ const RESTART_BASE_DELAY_MS = 1_000
const EVENT_BUCKET_CAPACITY = 100
const EVENT_REFILL_PER_SECOND = 60
/** 发出 shutdown 后等待扩展自行退出的时间。 */
const GRACEFUL_EXIT_MS = 2_500
/** 结束进程树之后等待 exit 事件的时间。 */
const FORCE_EXIT_MS = 3_000
/** stderr 采样窗口:只把有代表性的片段写进日志,避免日志洪水拖住主进程。 */
const STDERR_WINDOW_MS = 10_000
const STDERR_WINDOW_BYTES = 64 * 1024
const STDERR_WINDOW_ENTRIES = 20
const STDERR_MAX_CHUNK_CHARS = 400
/**
* stderr 里常见的凭据写法。
*
* 扩展的 stderr 是任意文本,可能包含用户配置的 Cookie / Token;
* 落日志前统一抹掉值,只保留键名。
*/
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
export function redactSecrets(value: string): string {
// 顺序不能反:先抹 `Bearer <token>` 整体,再按「键=值」处理,
// 否则 `Authorization: Bearer xxx` 会只抹掉 `Bearer`,token 本体留在日志里。
return String(value ?? '')
.replace(BEARER_TOKEN, 'Bearer ***')
.replace(
SECRET_ASSIGNMENT,
(_match, name: string, separator: string) => `${name}${separator}***`
)
}
export interface ExtensionHostChild {
send(message: unknown): void
/** 终止本扩展的整棵进程树;实现方负责平台差异。 */
kill(): void
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
once?(event: 'exit', listener: () => void): void
readonly pid?: number
/**
* 子进程的 stderr。必须被消费:管道写满会让子进程在 `write` 上阻塞,
* 表现为「扩展还活着但不再响应」。
*/
readonly stderr?: NodeJS.ReadableStream | null
}
export interface ExtensionHostSpawnOptions {
@@ -55,6 +98,7 @@ export interface ExtensionHostDependencies {
dataDir: string
permissions: ExtensionPermission[]
storage: ExtensionStorage
secrets?: ExtensionSecretStore
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
onLog?: (level: 'info' | 'warn' | 'error', message: string) => void
onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void
@@ -83,6 +127,10 @@ export interface ExtensionHostDependencies {
now?: () => number
activateTimeoutMs?: number
actionTimeoutMs?: number
/** 覆盖「等扩展自行退出」的时间;生产默认 2.5s。 */
gracefulExitMs?: number
/** 覆盖「结束进程树后等 exit」的时间;生产默认 3s。 */
forceExitMs?: number
}
interface PendingAction {
@@ -95,6 +143,9 @@ interface RegisteredAction {
id: string
title: string
description?: string
/** 已校验的参数 Schema;非法时为 undefined 且 `schemaError` 有值。 */
inputSchema?: ExtensionActionInputSchema
schemaError?: string
}
interface ActivationWaiter {
@@ -133,17 +184,27 @@ export class ExtensionHost {
}
>()
private readonly actions = new Map<string, RegisteredAction>()
private readonly pendingPageRequests = new Map<
string,
{
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
>()
private eventTokens = EVENT_BUCKET_CAPACITY
private eventTokensAt: number
private droppedEvents = 0
private mutedDropLog = false
private restartTimestamps: number[] = []
private stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: 0 }
constructor(dependencies: ExtensionHostDependencies) {
this.dependencies = dependencies
this.storage = dependencies.storage
this.now = dependencies.now ?? (() => Date.now())
this.eventTokensAt = this.now()
this.stderrWindow.at = this.now()
this.state = { state: 'inactive', since: this.now(), restarts: 0 }
}
@@ -155,6 +216,51 @@ export class ExtensionHost {
return Array.from(this.actions.values()).map((action) => ({ ...action }))
}
/**
* 把页面请求转给同扩展的后台处理器。
*
* 这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。
* 响应大小与超时都在这里收口,避免页面被一个坏 handler 拖死。
*/
async requestPage(
method: string,
params: Record<string, unknown>,
timeoutMs = 10_000
): Promise<unknown> {
const child = this.child
if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
const requestId = randomUUID()
return new Promise<unknown>((resolve, reject) => {
const timer = setTimeout(
() => {
this.pendingPageRequests.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT', '页面请求超时'))
},
Math.max(1_000, timeoutMs)
)
this.pendingPageRequests.set(requestId, { resolve, reject, timer })
try {
child.send({
type: 'page-request',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
method,
params,
timeoutMs
})
} catch (error) {
clearTimeout(timer)
this.pendingPageRequests.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
async testSend(params: Record<string, unknown>): Promise<unknown> {
return this.runTestMessage('test-send', params)
}
@@ -204,6 +310,13 @@ export class ExtensionHost {
return this.activation
}
/**
* 停止后台进程。
*
* 三段式:先请扩展自行退出,超时后结束整棵进程树,再等真实的 exit 事件。
* 只有收到 exit 才算停止完成——只发信号就返回,会让上层在进程仍占用
* 文件时去替换扩展目录(Windows 上必然失败,POSIX 上会留下旧代码在跑)。
*/
async stop(): Promise<void> {
this.stopping = true
if (this.restartTimer) {
@@ -216,26 +329,66 @@ export class ExtensionHost {
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.actions.clear()
this.setState('inactive')
if (!child) return
if (!child) {
this.setState('inactive')
return
}
try {
child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION })
} catch {
// 进程可能已经断开;kill 兜底。
// 进程可能已经断开;后续按「未退出」处理。
}
await new Promise<void>((resolve) => {
const timer = setTimeout(() => {
try {
child.kill()
} catch {
// ignore
}
resolve()
}, 1_500)
child.once?.('exit', () => {
if (await this.waitForExit(child, this.dependencies.gracefulExitMs ?? GRACEFUL_EXIT_MS)) {
this.setState('inactive')
return
}
this.dependencies.onLog?.('warn', '扩展未在预期时间内退出,正在结束进程树')
this.killTree(child)
if (!(await this.waitForExit(child, this.dependencies.forceExitMs ?? FORCE_EXIT_MS))) {
this.dependencies.onLog?.('error', '扩展进程树未能退出,可能有子进程仍在运行')
}
this.setState('inactive')
}
/**
* 结束扩展进程及其派生进程。
*
* POSIX 依赖 `fork` 时的 `detached` 建立独立进程组,`kill(-pid)` 一次覆盖整组;
* 组不存在时退化为只杀直接子进程,并记一条降级日志。
*
* Windows 用 `taskkill /T /F`,且必须**在父进程仍存活时**执行:
* 父进程先退出后,进程树的父子关系消失,`/T` 再也找不到孙进程。
*/
private killTree(child: ExtensionHostChild): void {
const pid = child.pid
if (!pid) {
try {
child.kill()
} catch {
// ignore
}
return
}
const result = killProcessTree(pid)
if (result !== 'group' && process.platform !== 'win32') {
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
}
}
private waitForExit(child: ExtensionHostChild, timeoutMs: number): Promise<boolean> {
return new Promise<boolean>((resolve) => {
let settled = false
const finish = (exited: boolean): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolve()
})
resolve(exited)
}
const timer = setTimeout(() => finish(false), timeoutMs)
child.once?.('exit', () => finish(true))
})
}
@@ -398,6 +551,62 @@ export class ExtensionHost {
this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`)
})
child.on('exit', (code) => this.handleExit(child, code))
this.consumeStderr(child)
}
/**
* 消费子进程 stderr。
*
* 两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞),
* 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。
* 凭据形态的字段在落日志前抹掉值。
*/
private consumeStderr(child: ExtensionHostChild): void {
const stream = child.stderr
if (!stream || typeof stream.on !== 'function') return
const onData = (chunk: Buffer | string): void => {
try {
const now = this.now()
if (now - this.stderrWindow.at >= STDERR_WINDOW_MS) {
const dropped = this.stderrWindow.dropped
this.stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: now }
if (dropped > 0) {
this.dependencies.onLog?.('warn', `扩展 stderr 有 ${dropped} 字节省略未记录`)
}
}
const text = redactSecrets(String(chunk)).replace(/\s+/g, ' ').trim()
if (!text) return
const bytes = Buffer.byteLength(text, 'utf8')
if (
this.stderrWindow.entries >= STDERR_WINDOW_ENTRIES ||
this.stderrWindow.bytes + bytes > STDERR_WINDOW_BYTES
) {
this.stderrWindow.dropped += bytes
return
}
this.stderrWindow.bytes += bytes
this.stderrWindow.entries += 1
this.dependencies.onLog?.('warn', `[stderr] ${text.slice(0, STDERR_MAX_CHUNK_CHARS)}`)
} catch {
// stderr 处理失败不能影响扩展运行。
}
}
const onEnd = (): void => {
if (this.stderrWindow.dropped > 0) {
this.dependencies.onLog?.(
'warn',
`扩展 stderr 有 ${this.stderrWindow.dropped} 字节省略未记录`
)
this.stderrWindow.dropped = 0
}
stream.removeListener?.('data', onData)
stream.removeListener?.('end', onEnd)
}
stream.on('data', onData)
stream.on('end', onEnd)
}
private handleExit(child: ExtensionHostChild, code: number | null): void {
@@ -450,14 +659,45 @@ export class ExtensionHost {
case 'register-action': {
const action = message.action
if (!action || typeof action.id !== 'string') return
// Schema 不合法的动作仍然登记:界面上要能看到它,并显示具体原因,
// 而不是让它凭空消失。
let inputSchema: ExtensionActionInputSchema | undefined
let schemaError: string | undefined
if (action.inputSchema !== undefined) {
const parsed = parseActionInputSchema(action.inputSchema)
if (parsed.ok) inputSchema = parsed.schema
else schemaError = parsed.reason
}
this.actions.set(action.id, {
id: action.id,
title: String(action.title || action.id).slice(0, 60),
...(action.description ? { description: String(action.description).slice(0, 200) } : {})
...(action.description ? { description: String(action.description).slice(0, 200) } : {}),
...(inputSchema ? { inputSchema } : {}),
...(schemaError ? { schemaError } : {})
})
if (schemaError) {
this.dependencies.onLog?.(
'warn',
`动作 ${action.id} 的参数 Schema 不可用:${schemaError}`
)
}
this.dependencies.onActionsChanged?.()
return
}
case 'page-result': {
const pending = this.pendingPageRequests.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.pendingPageRequests.delete(message.requestId)
if (message.ok) {
pending.resolve(message.result)
} else {
pending.reject(
new ExtensionError('ACTION_FAILED', message.error?.message || '扩展页面请求失败')
)
}
return
}
case 'log':
this.dependencies.onLog?.(message.level, message.message)
return
@@ -533,6 +773,31 @@ export class ExtensionHost {
case 'storage.list':
this.requirePermission('storage')
return { entries: this.storage.list(extensionId) }
case 'secrets.get': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.secrets.get(extensionId, String(params.key ?? ''))
}
case 'secrets.set': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
this.dependencies.secrets.set(
extensionId,
String(params.key ?? ''),
String(params.value ?? '')
)
return { ok: true }
}
case 'secrets.delete': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return { removed: this.dependencies.secrets.delete(extensionId, String(params.key ?? '')) }
}
case 'secrets.has': {
this.requirePermission('secrets')
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.secrets.has(extensionId, String(params.key ?? ''))
}
case 'messages.query': {
this.requirePermission('messages.query')
if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
@@ -642,6 +907,49 @@ export class ExtensionHost {
}
}
/**
* 结束 `pid` 对应的进程树。
*
* 返回值表示实际使用的手段:
* - `group`:POSIX 进程组,覆盖扩展派生的全部子进程;
* - `taskkill`:Windows 进程树,必须在父进程仍存活时调用;
* - `fallback`:只能结束进程本身,调用方应记录降级。
*/
export function killProcessTree(
pid: number | undefined,
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {}
): 'group' | 'taskkill' | 'fallback' {
if (!pid) return 'fallback'
const platform = options.platform ?? process.platform
const signal = options.signal ?? 'SIGKILL'
if (platform === 'win32') {
try {
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
windowsHide: true,
stdio: 'ignore'
})
killer.on('error', () => undefined)
killer.unref?.()
return 'taskkill'
} catch {
return 'fallback'
}
}
try {
process.kill(-pid, signal)
return 'group'
} catch {
try {
process.kill(pid, signal)
} catch {
// 进程已经退出。
}
return 'fallback'
}
}
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
export function forkExtensionHost(
scriptPath: string
@@ -650,6 +958,9 @@ export function forkExtensionHost(
const child: ChildProcess = fork(scriptPath, [], {
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
serialization: 'advanced',
// POSIX 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。
// Windows 用 taskkill /T,不需要(也不支持)detached。
detached: process.platform !== 'win32',
env: {
...process.env,
ELECTRON_RUN_AS_NODE: '1',
@@ -671,6 +982,7 @@ export function forkExtensionHost(
once: (event, listener) => {
child.once(event, listener)
},
stderr: child.stderr,
...(child.pid ? { pid: child.pid } : {})
}
}
+218 -12
View File
@@ -1,4 +1,5 @@
import { promises as fs } from 'node:fs'
import * as nodeFs from 'node:fs'
import path from 'node:path'
import { Open } from 'unzipper'
import { ExtensionError } from '../../shared/extensions/errors'
@@ -9,23 +10,61 @@ import {
} from '../../shared/extensions/manifest'
import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry'
import { isPathInside, type ExtensionPaths } from './extension-paths'
import type { ExtensionSource } from '../../shared/extensions/source'
import { computeDirectoryDigest } from './extension-code-digest'
const MAX_FILES = 2_000
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
const MAX_FILE_BYTES = 20 * 1024 * 1024
const MAX_PACKAGE_BYTES = 100 * 1024 * 1024
/** 从「文件夹安装」时跳过的目录名;与打包脚本的白名单保持同一套判断。 */
const EXCLUDED_SOURCE_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv'
])
export interface InstallOptions {
/** 应用版本,用于 `minAppVersion` 兼容检查。 */
appVersion: string
source?: 'directory' | 'package'
source?: ExtensionSource
/** 模板安装时由可信入口填入;普通 ZIP/目录安装不得携带。 */
template?: { id: string; version: string }
/**
* 代码被替换之前的最后一步:用于停止旧的 Host。
*
* 抛错表示「不能安全替换」,安装整体中止,磁盘保持原样。
*/
beforeReplace?: (
manifest: ExtensionManifest,
previous: ExtensionRegistryRecord | undefined
) => Promise<void>
}
export interface InstallOutcome {
manifest: ExtensionManifest
installPath: string
previousVersion?: string
/** 安装前的 Registry 记录;首次安装时为 undefined。 */
previousRecord?: ExtensionRegistryRecord
upgraded: boolean
/**
* 把磁盘与 Registry 一起恢复到本次安装之前。
*
* 只在新版本启动失败时调用;调用后 `cleanup` 失效。
*/
rollback: () => Promise<void>
/**
* 删除旧版本的过渡备份。
*
* 新版本确认可用后调用;调用后 `rollback` 失效。
*/
cleanup: () => Promise<void>
}
export interface ExtensionInstallerDependencies {
@@ -71,7 +110,7 @@ export class ExtensionInstaller {
await fs.mkdir(staging, { recursive: true })
try {
await copyTree(root, staging, entries)
return await this.finalize(staging, manifest, options.source ?? 'directory')
return await this.finalize(staging, manifest, options.source ?? 'directory', options)
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
@@ -174,7 +213,7 @@ export class ExtensionInstaller {
)
}
}
return await this.finalize(staging, manifest, 'package')
return await this.finalize(staging, manifest, options.source ?? 'package', options)
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
@@ -192,13 +231,20 @@ export class ExtensionInstaller {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
const trash = `${target}.removed-${this.now()}`
// lstat 不跟随符号链接:目标断链时也要把链接本身清掉,否则会留下悬空目录项。
const exists = await fs
.stat(target)
.lstat(target)
.then(() => true)
.catch(() => false)
if (exists) {
await fs.rename(target, trash)
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
const trashStat = await fs.lstat(trash).catch(() => null)
if (trashStat?.isSymbolicLink()) {
// 只删链接本身;递归删除可能跟随链接进入用户自己的目录。
await fs.unlink(trash).catch(() => undefined)
} else {
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
}
}
if (!options.keepData) {
await fs
@@ -255,6 +301,9 @@ export class ExtensionInstaller {
const walk = async (directory: string, prefix: string): Promise<void> => {
const items = await fs.readdir(directory, { withFileTypes: true })
for (const item of items) {
// 版本库与依赖目录不属于扩展产物:复制它们既超体积上限,
// 也会把提交历史带进用户数据目录。
if (item.isDirectory() && EXCLUDED_SOURCE_DIRECTORIES.has(item.name)) continue
const relativePath = prefix ? `${prefix}/${item.name}` : item.name
if (!isSafeRelativeEntryPath(relativePath)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`)
@@ -292,11 +341,24 @@ export class ExtensionInstaller {
return entries
}
/** 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 */
/**
* 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。
*
* 事务边界(只覆盖「同一文件系统内的目录改名 + 一次 JSON 写入」):
* - 改名前先停旧 Host:Windows 上被进程占用的目录无法改名,且旧进程
* 继续运行会读到已被替换的代码。
* - 旧目录保留为 `.backup-<ts>`,由调用方在新版本确认可用后清理;
* 启动失败时用 `rollback()` 换回来。
* - Registry 写入失败时当场回滚目录,不把「代码已换、状态未换」留给上层。
*
* 不保证跨进程的强原子性:如果进程在 rename 之后、Registry 写入之前被杀,
* 磁盘上是新代码配旧记录;下次启动会以 manifest 为准做兼容性检查。
*/
private async finalize(
staging: string,
manifest: ExtensionManifest,
source: 'directory' | 'package'
source: ExtensionSource,
options: InstallOptions
): Promise<InstallOutcome> {
const target = this.paths.installDir(manifest.id)
if (!isPathInside(this.paths.extensionsDir, target)) {
@@ -311,6 +373,9 @@ export class ExtensionInstaller {
.then(() => true)
.catch(() => false)
// 旧 Host 必须在代码被替换之前停下;这一步失败则不触碰磁盘。
await options.beforeReplace?.(manifest, existingRecord)
if (targetExists) await fs.rename(target, backup)
try {
await fs.rename(staging, target)
@@ -321,7 +386,6 @@ export class ExtensionInstaller {
error instanceof Error ? error.message : '安装目录替换失败'
)
}
if (targetExists) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
const timestamp = this.now()
const record: ExtensionRegistryRecord = {
@@ -330,20 +394,162 @@ export class ExtensionInstaller {
apiVersion: manifest.apiVersion,
// 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。
enabled: existingRecord?.enabled ?? false,
grantedPermissions: existingRecord?.grantedPermissions ?? [],
// 只保留新 manifest 仍声明的授权:被删掉的权限必须立刻失效。
grantedPermissions: (existingRecord?.grantedPermissions ?? []).filter((permission) =>
manifest.permissions.includes(permission)
),
installedAt: existingRecord?.installedAt ?? timestamp,
updatedAt: timestamp,
source
source,
// 安装完成后立刻记录基线:之后判断「用户改没改」全靠它。
installedCodeDigest: computeDirectoryDigest(target),
...(options.template
? { templateId: options.template.id, templateVersion: options.template.version }
: existingRecord?.templateId
? {
templateId: existingRecord.templateId,
...(existingRecord.templateVersion
? { templateVersion: existingRecord.templateVersion }
: {})
}
: {})
}
this.registry.upsert(record)
try {
this.registry.upsert(record)
} catch (error) {
// 代码已经换进去了,但状态没写成:必须把磁盘也退回去,否则用户会看到
// 「旧版本号 + 新代码」。新目录直接删除,内容仍在安装源里。
await fs.rm(target, { recursive: true, force: true }).catch(() => undefined)
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
if (existingRecord) {
await Promise.resolve(this.registry.upsert(existingRecord)).catch(() => undefined)
}
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error
? `扩展状态写入失败,已回滚:${error.message}`
: '扩展状态写入失败,已回滚'
)
}
let settled = false
return {
manifest,
installPath: target,
previousRecord: existingRecord,
...(existingRecord ? { previousVersion: existingRecord.version } : {}),
upgraded: Boolean(existingRecord)
upgraded: Boolean(existingRecord),
rollback: async () => {
if (settled) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '该安装结果已完成清理,无法回滚')
}
settled = true
await fs.rm(target, { recursive: true, force: true }).catch(() => undefined)
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
if (existingRecord) this.registry.upsert(existingRecord)
else this.registry.remove(manifest.id)
},
cleanup: async () => {
if (settled) return
settled = true
if (targetExists) {
await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
}
}
}
}
/**
* 把最近一次升级留下的过渡备份换回原位。
*
* 只在「新代码启动失败或状态不一致」时由用户显式触发;备份目录本身不删除,
* 换回来的旧目录会被移到 `.failed-<ts>` 后清理,留下的是可运行的旧版本。
*/
async restoreLatestBackup(
extensionId: string
): Promise<{ restored: boolean; manifest?: ExtensionManifest }> {
const target = this.paths.installDir(extensionId)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
let backups: string[] = []
try {
backups = (await fs.readdir(this.paths.extensionsDir))
.filter((name) => name.startsWith(`${extensionId}.backup-`))
.sort()
} catch {
return { restored: false }
}
if (!backups.length) return { restored: false }
const latest = path.join(this.paths.extensionsDir, backups[backups.length - 1])
// 空 appVersion = 跳过兼容性拦截:用户要的是「回到能跑的那个版本」。
const manifest = await this.readManifest(latest, '')
const failed = `${target}.failed-${this.now()}`
const targetExists = await fs
.lstat(target)
.then(() => true)
.catch(() => false)
if (targetExists) await fs.rename(target, failed)
try {
await fs.rename(latest, target)
} catch (error) {
if (targetExists) await fs.rename(failed, target).catch(() => undefined)
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error ? error.message : '恢复备份失败'
)
}
if (targetExists) {
await fs.rm(failed, { recursive: true, force: true }).catch(() => undefined)
}
return { restored: true, manifest }
}
/**
* 扫描已安装目录,重建最小 Registry 记录。
*
* 只读取 manifest 的**身份字段**,不继承启用状态与授权:磁盘上有代码,
* 不等于用户同意运行它。manifest 无法解析的目录被跳过。
*
* 同步实现:Registry 的加载是同步的,恢复入口不能引入异步间隙。
*/
recoverFromDisk(): ExtensionRegistryRecord[] {
const records: ExtensionRegistryRecord[] = []
let entries: nodeFs.Dirent[] = []
try {
entries = nodeFs.readdirSync(this.paths.extensionsDir, { withFileTypes: true })
} catch {
return records
}
for (const entry of entries) {
if (!entry.isDirectory()) continue
if (entry.name.includes('.backup-') || entry.name.includes('.removed')) continue
const root = path.join(this.paths.extensionsDir, entry.name)
try {
const raw = JSON.parse(
nodeFs.readFileSync(path.join(root, 'manifest.json'), 'utf8')
) as unknown
const parsed = parseExtensionManifest(raw)
if (!parsed.ok || !parsed.manifest) continue
const stat = nodeFs.statSync(root)
records.push({
id: parsed.manifest.id,
version: parsed.manifest.version,
apiVersion: parsed.manifest.apiVersion,
enabled: false,
grantedPermissions: [],
installedAt: Math.round(stat.birthtimeMs || stat.mtimeMs || 0),
updatedAt: Math.round(stat.mtimeMs || 0),
source: 'directory'
})
} catch {
// 单个目录损坏不影响其余扩展的恢复。
}
}
return records
}
}
function normalizeZipPath(value: string): string {
+196
View File
@@ -3,7 +3,9 @@ import path from 'node:path'
import { BrowserWindow, dialog, ipcMain, shell } from 'electron'
import { EXTENSION_IPC } from '../../shared/extensions/ipc'
import type {
ExtensionActionInfo,
ExtensionInstallResult,
ExtensionProjectResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
@@ -120,6 +122,193 @@ export function registerExtensionIpc(options: ExtensionIpcOptions): void {
})
)
ipcMain.handle(
EXTENSION_IPC.health,
guard(() => manager().getHealth())
)
ipcMain.handle(
EXTENSION_IPC.grantPermissions,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; permissions?: unknown }
const permissions = Array.isArray(input.permissions)
? input.permissions.filter((item): item is string => typeof item === 'string')
: []
return manager().grantPermissions(
requireId(input.id),
permissions as Parameters<ExtensionManager['grantPermissions']>[1]
)
})
)
ipcMain.handle(
EXTENSION_IPC.revokePermission,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; permission?: unknown }
const permission = String(input.permission || '').trim()
if (!permission) throw new Error('权限名不合法')
return manager().revokePermission(
requireId(input.id),
permission as Parameters<ExtensionManager['revokePermission']>[1]
)
})
)
ipcMain.handle(
EXTENSION_IPC.resetStorage,
guard(
(extensionId: unknown): ExtensionOperationResult =>
manager().resetStorage(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.templates,
guard(() => manager().listTemplates())
)
ipcMain.handle(
EXTENSION_IPC.installTemplate,
guard(
(templateId: unknown): Promise<ExtensionInstallResult> =>
manager().installTemplate(requireTemplateId(templateId))
)
)
ipcMain.handle(
EXTENSION_IPC.acknowledgeRecovery,
guard((): ExtensionOperationResult => manager().acknowledgeRegistryRecovery())
)
ipcMain.handle(
EXTENSION_IPC.acknowledgeStorage,
guard(
(extensionId: unknown): ExtensionOperationResult =>
manager().acknowledgeStorageRecovery(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.adoptInstalledCode,
guard(
(extensionId: unknown): ExtensionOperationResult =>
manager().adoptInstalledCode(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.pickProjectDirectory,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const options: Electron.OpenDialogOptions = {
properties: ['openDirectory', 'createDirectory'],
title: '选择扩展项目目录'
}
const result = window
? await dialog.showOpenDialog(window, options)
: await dialog.showOpenDialog(options)
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.linkDevelopment,
guard(
(directory: unknown): Promise<ExtensionInstallResult> =>
manager().linkDevelopmentProject(requirePath(directory))
)
)
ipcMain.handle(
EXTENSION_IPC.reloadDevelopment,
guard(
(extensionId: unknown): Promise<ExtensionOperationResult> =>
manager().reloadDevelopment(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.unlinkDevelopment,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; keepData?: unknown }
return manager().unlinkDevelopment(requireId(input.id), {
keepData: input.keepData !== false
})
})
)
ipcMain.handle(
EXTENSION_IPC.convertDevelopment,
guard(
(extensionId: unknown): Promise<ExtensionOperationResult> =>
manager().convertDevelopmentToInstalled(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.createProjectFromTemplate,
guard((payload: unknown): Promise<ExtensionProjectResult> => {
const input = (payload ?? {}) as {
templateId?: unknown
targetDirectory?: unknown
extensionId?: unknown
name?: unknown
}
return manager().createProjectFromTemplate(
requireTemplateId(input.templateId),
requirePath(input.targetDirectory),
{
extensionId: requireId(input.extensionId),
...(typeof input.name === 'string' && input.name.trim()
? { name: input.name.trim().slice(0, 60) }
: {})
}
)
})
)
ipcMain.handle(
EXTENSION_IPC.exportInstalledAsProject,
guard((payload: unknown): Promise<ExtensionProjectResult> => {
const input = (payload ?? {}) as { id?: unknown; targetDirectory?: unknown }
return manager().exportInstalledAsProject(
requireId(input.id),
requirePath(input.targetDirectory)
)
})
)
ipcMain.handle(
EXTENSION_IPC.actions,
guard((): ExtensionActionInfo[] => manager().listActions())
)
ipcMain.handle(
EXTENSION_IPC.openDevelopmentSource,
guard(async (extensionId: unknown): Promise<ExtensionOperationResult> => {
const extension = manager().get(requireId(extensionId))
if (!extension?.development?.available) {
return {
success: false,
error: { code: 'EXTENSION_SOURCE_MISSING', message: '源码目录不可用' }
}
}
// 路径来自主进程的 registry,渲染层只能传 id,无法指定任意目录。
const error = await shell.openPath(extension.development.sourcePath)
return error
? { success: false, error: { code: 'ACTION_FAILED', message: error } }
: { success: true }
})
)
ipcMain.handle(
EXTENSION_IPC.rollbackUpgrade,
guard(
(extensionId: unknown): Promise<ExtensionOperationResult> =>
manager().rollbackInterruptedUpgrade(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.uninstall,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
@@ -187,6 +376,13 @@ function requireId(value: unknown): string {
return id
}
/** 模板 id 只允许稳定的短标识,不允许携带路径片段。 */
function requireTemplateId(value: unknown): string {
const id = String(value || '').trim()
if (!/^[a-z0-9][a-z0-9-]{1,63}$/.test(id)) throw new Error('模板 id 不合法')
return id
}
function requirePath(value: unknown): string {
const target = String(value || '').trim()
if (!target || target.length > 4_096) throw new Error('路径不合法')
File diff suppressed because it is too large. Load diff
+20 -2
View File
@@ -58,8 +58,26 @@ export function getExtensionPaths(): ExtensionPaths {
return cached
}
/** 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 */
/**
* 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。
*
* Windows 上盘符大小写、分隔符与短文件名都可能让字符串比较失手,
* 这里统一把两侧规范化后再比:`path.resolve` 处理分隔符,Windows 额外折叠大小写。
*/
export function isPathInside(parent: string, child: string): boolean {
const relative = path.relative(path.resolve(parent), path.resolve(child))
const normalize = (value: string): string => {
const resolved = path.resolve(value)
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
}
const relative = path.relative(normalize(parent), normalize(child))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
/** 只比路径本身,不跟随符号链接;用于判断两个字符串是否指向同一位置。 */
export function isSamePath(left: string, right: string): boolean {
const normalize = (value: string): string => {
const resolved = path.resolve(value)
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
}
return normalize(left) === normalize(right)
}
@@ -0,0 +1,242 @@
import { promises as fs, existsSync } from 'node:fs'
import path from 'node:path'
import { Open } from 'unzipper'
import { ExtensionError } from '../../shared/extensions/errors'
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside } from './extension-paths'
const MAX_FILES = 2_000
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
/** 与安装器 / 指纹一致的排除规则:这些不属于扩展源码。 */
const EXCLUDED_DIRECTORIES = new Set([
'.git',
'.hg',
'.svn',
'node_modules',
'__pycache__',
'.venv',
'venv'
])
const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log'])
/** 会被替换扩展 id 的文本文件类型。 */
const TEXT_FILE_PATTERN = /\.(js|mjs|cjs|ts|tsx|jsx|html|htm|css|json)$/i
export interface CreateProjectInput {
zipPath: string
targetDir: string
/** 新扩展 id(必须与模板里的旧 id 不同)。 */
extensionId: string
/** 模板里的旧 id;用于替换代码中的身份引用。 */
templateExtensionId: string
name?: string
}
export interface CreateProjectOutcome {
projectPath: string
rewrittenFiles: string[]
}
/**
* 目标目录必须是「不存在」或「空目录」。
*
* 这条检查在复制之前做,避免中途发现冲突时已经写了一半。
*/
export async function assertUsableTarget(targetDir: string): Promise<string> {
const resolved = path.resolve(targetDir)
try {
const stat = await fs.stat(resolved)
if (!stat.isDirectory()) {
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标路径已存在且不是目录')
}
const entries = await fs.readdir(resolved)
if (entries.length > 0) {
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不是空目录,未写入任何文件')
}
} catch (error) {
if (error instanceof ExtensionError) throw error
const code = (error as { code?: string }).code
if (code !== 'ENOENT') {
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不可用')
}
}
return resolved
}
/** 在目标旁边建暂存目录:同一磁盘才能用 rename 原子落位。 */
async function createStaging(parent: string): Promise<string> {
await fs.mkdir(parent, { recursive: true })
return fs.mkdtemp(path.join(parent, '.tm-project-'))
}
async function cleanup(directory: string): Promise<void> {
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined)
}
function shouldSkipFile(name: string): boolean {
return EXCLUDED_FILES.has(name) || EXCLUDED_EXTENSIONS.has(path.extname(name).toLowerCase())
}
/** 解压到暂存目录;条目路径逐条校验,拒绝穿越与非法字符。 */
async function extractZip(zipPath: string, staging: string): Promise<void> {
let archive: Awaited<ReturnType<typeof Open.file>>
try {
archive = await Open.file(zipPath)
} catch {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包无法读取')
}
let files = 0
let total = 0
for (const entry of archive.files) {
const relative = String(entry.path || '').replace(/\\/g, '/')
if (entry.type === 'Directory') continue
if (!isSafeRelativeEntryPath(relative)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目路径不合法:${relative}`)
}
const size = Number(entry.uncompressedSize || 0)
total += size
if (total > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板解压后体积超过限制')
}
files += 1
if (files > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板文件数量超过限制')
}
const destination = path.resolve(staging, relative)
if (!isPathInside(staging, destination)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目越界:${relative}`)
}
await fs.mkdir(path.dirname(destination), { recursive: true })
const content = await entry.buffer()
await fs.writeFile(destination, content)
}
if (!files) throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包是空的')
}
async function listTextFiles(root: string, prefix = ''): Promise<string[]> {
const result: string[] = []
const items = await fs.readdir(path.join(root, prefix), { withFileTypes: true })
for (const item of items) {
if (item.isDirectory()) {
if (EXCLUDED_DIRECTORIES.has(item.name)) continue
const nested = prefix ? `${prefix}/${item.name}` : item.name
result.push(...(await listTextFiles(root, nested)))
continue
}
if (shouldSkipFile(item.name)) continue
const relative = prefix ? `${prefix}/${item.name}` : item.name
if (!TEXT_FILE_PATTERN.test(relative)) continue
result.push(relative)
}
return result.sort()
}
/**
* 把代码里的扩展身份改成新 id。
*
* 只替换精确字符串:模板示例里 id 至少出现在 manifest 与页面桥的
* `EXTENSION_ID` 常量中,漏掉任何一处都会让页面桥失联。
*/
export async function rewriteExtensionIdentity(
root: string,
oldId: string,
newId: string,
name?: string
): Promise<string[]> {
const rewritten: string[] = []
const manifestPath = path.join(root, 'manifest.json')
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')) as Record<string, unknown>
if (String(manifest.id) !== oldId) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`模板 manifest.id 与索引不一致(${String(manifest.id)})`
)
}
manifest.id = newId
if (name) manifest.name = name
await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
for (const relative of await listTextFiles(root)) {
if (relative === 'manifest.json') continue
const full = path.join(root, relative)
const text = await fs.readFile(full, 'utf8')
if (!text.includes(oldId)) continue
await fs.writeFile(full, text.split(oldId).join(newId), 'utf8')
rewritten.push(relative)
}
return rewritten
}
/** 生成后自检:任何残留的旧 id 都意味着页面桥或后台仍指向模板身份。 */
export async function assertNoIdentityLeftover(root: string, oldId: string): Promise<void> {
for (const relative of await listTextFiles(root)) {
const text = await fs.readFile(path.join(root, relative), 'utf8')
if (text.includes(oldId)) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`生成的项目里仍残留旧扩展 id:${relative}`
)
}
}
}
/** 从模板 ZIP 生成独立项目;全过程在暂存目录完成,成功后才落位。 */
export async function createProjectFromTemplate(
input: CreateProjectInput
): Promise<CreateProjectOutcome> {
const target = await assertUsableTarget(input.targetDir)
if (input.extensionId === input.templateExtensionId) {
throw new ExtensionError('INVALID_REQUEST', '新项目必须使用不同的扩展 id')
}
const staging = await createStaging(path.dirname(target))
try {
await extractZip(input.zipPath, staging)
const rewritten = await rewriteExtensionIdentity(
staging,
input.templateExtensionId,
input.extensionId,
input.name
)
await assertNoIdentityLeftover(staging, input.templateExtensionId)
await fs.rename(staging, target)
return { projectPath: target, rewrittenFiles: rewritten }
} catch (error) {
await cleanup(staging)
throw error
}
}
/** 把已安装副本整体复制成外部项目(保留用户改过的代码)。 */
export async function exportInstalledCopy(
sourceDir: string,
targetDir: string
): Promise<{ projectPath: string }> {
if (!existsSync(path.join(sourceDir, 'manifest.json'))) {
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '安装副本不完整,无法导出')
}
const target = await assertUsableTarget(targetDir)
const staging = await createStaging(path.dirname(target))
try {
await fs.cp(sourceDir, staging, {
recursive: true,
filter: (source) => {
const name = path.basename(source)
if (EXCLUDED_DIRECTORIES.has(name)) return false
if (shouldSkipFile(name)) return false
return true
}
})
// 复制结果必须仍然可读,否则宁可失败也不留一个半成品项目。
await fs.access(path.join(staging, 'manifest.json'))
await fs.rename(staging, target)
return { projectPath: target }
} catch (error) {
await cleanup(staging)
throw error
}
}
+12 -2
View File
@@ -46,7 +46,16 @@ export function registerExtensionScheme(): void {
])
}
export function installExtensionProtocolHandler(paths: ExtensionPaths): void {
export interface ExtensionProtocolDependencies {
paths: ExtensionPaths
/**
* 解析扩展代码根目录。开发模式下是外部源码目录,
* 必须与后台进程、Manifest 读取使用同一个解析器,否则页面会读到旧副本。
*/
resolveRoot: (extensionId: string) => string | null
}
export function installExtensionProtocolHandler(dependencies: ExtensionProtocolDependencies): void {
protocol.handle(EXTENSION_SCHEME, async (request) => {
try {
const url = new URL(request.url)
@@ -55,7 +64,8 @@ export function installExtensionProtocolHandler(paths: ExtensionPaths): void {
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '')
if (!isSafeRelativeEntryPath(relative)) return notFound()
const root = paths.installDir(extensionId)
const root = dependencies.resolveRoot(extensionId)
if (!root) return notFound()
const resolved = path.resolve(root, relative)
if (!isPathInside(root, resolved)) return notFound()
const realRoot = await fs.realpath(root).catch(() => null)
+429 -30
View File
@@ -4,7 +4,9 @@ import {
normalizeExtensionPermissions,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
import { EXTENSION_API_VERSION, isValidExtensionId } from '../../shared/extensions/manifest'
import { ExtensionError } from '../../shared/extensions/errors'
import { normalizeExtensionSource, type ExtensionSource } from '../../shared/extensions/source'
/**
* 宿主侧的扩展安装状态。
@@ -20,49 +22,204 @@ export interface ExtensionRegistryRecord {
grantedPermissions: ExtensionPermission[]
installedAt: number
updatedAt: number
source: 'directory' | 'package'
source: ExtensionSource
/** 来源为 `template` 时,记录是哪个官方模板装入的。 */
templateId?: string
templateVersion?: string
/**
* 来源为 `development` 时的外部源码目录(本机绝对路径)。
*
* 只属于这台机器的安装状态,不随扩展源码分发;换机器要重新链接。
*/
developmentSourcePath?: string
/**
* 安装时的代码指纹;用于判断用户是否改过 `extensions/<id>` 里的副本。
* 缺失表示无法判断(旧版本安装或指纹计算失败),更新时必须保守处理。
*/
installedCodeDigest?: string
}
/**
* 一次恢复的记录。
*
* 写进状态文件而不是只放在内存里:用户看到「状态曾损坏」之后重启,
* 提示必须还在,否则他永远不知道自己的启用状态被重置过。
*/
export interface ExtensionRegistryRecovery {
at: number
kind: 'backup' | 'scan'
/** 损坏现场的**文件名**(不含目录)。 */
corruptFile?: string
}
interface RegistryFile {
version: number
extensions: ExtensionRegistryRecord[]
recovery?: ExtensionRegistryRecovery
}
const REGISTRY_VERSION = 1
/** 损坏现场最多保留的份数;超出时删除最旧的一份。 */
const CORRUPT_KEEP_LIMIT = 3
function normalizeRecord(value: unknown): ExtensionRegistryRecord | null {
if (!value || typeof value !== 'object') return null
const raw = value as Partial<ExtensionRegistryRecord>
const id = String(raw.id || '').trim()
if (!id) return null
const installedAt = Number(raw.installedAt) || 0
return {
id,
version: String(raw.version || '0.0.0'),
apiVersion: String(raw.apiVersion || EXTENSION_API_VERSION),
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
enabled: raw.enabled === true,
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
installedAt,
updatedAt: Number(raw.updatedAt) || installedAt,
source: raw.source === 'package' ? 'package' : 'directory'
}
/**
* 状态文件的可信度。
*
* - `ok`:主文件有效,或文件不存在(全新安装,属于合法空状态)。
* - `recovered-from-backup`:主文件损坏,用 `.bak` 重建过;记录已降级。
* - `recovered-by-scan`:主文件与备份都不可用,由调用方扫描扩展目录重建;
* 记录一律降级为「未启用 + 无授权」。
* - `unreadable`:无法读取且无法重建。此状态下**拒绝任何写入**,
* 否则会用空状态覆盖唯一可能人工抢救的现场。
*/
export type ExtensionRegistryHealthState =
| 'ok'
| 'recovered-from-backup'
| 'recovered-by-scan'
| 'unreadable'
export interface ExtensionRegistryHealth {
state: ExtensionRegistryHealthState
at: number
/** 损坏现场的**文件名**(不含目录);用于日志与排查,不渲染绝对路径。 */
corruptFile?: string
message?: string
}
export interface ExtensionRegistryDependencies {
registryFile: string
now?: () => number
/**
* 主文件与备份均不可用时的重建来源。
*
* 返回的记录会被强制改写为 `enabled: false`、`grantedPermissions: []`:
* 扫描到磁盘上有代码,不等于用户同意运行它。
*/
recover?: () => ExtensionRegistryRecord[]
}
type ParseResult =
| { ok: true; extensions: ExtensionRegistryRecord[]; recovery?: ExtensionRegistryRecovery }
| { ok: false; reason: string }
function parseRegistryText(text: string): ParseResult {
if (!text.trim()) return { ok: false, reason: '状态文件为空' }
let raw: unknown
try {
raw = JSON.parse(text)
} catch {
return { ok: false, reason: '状态文件不是合法 JSON' }
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { ok: false, reason: '状态文件顶层不是对象' }
}
const version = Number((raw as { version?: unknown }).version)
if (!Number.isInteger(version) || version < 1 || version > REGISTRY_VERSION) {
return { ok: false, reason: '状态文件版本不受支持' }
}
const list = (raw as { extensions?: unknown }).extensions
if (!Array.isArray(list)) return { ok: false, reason: 'extensions 不是数组' }
const extensions: ExtensionRegistryRecord[] = []
const seen = new Set<string>()
for (const [index, item] of list.entries()) {
const parsed = parseRecord(item)
if (!parsed) return { ok: false, reason: `第 ${index + 1} 条扩展记录不合法` }
if (seen.has(parsed.id)) return { ok: false, reason: `扩展 id 重复:${parsed.id}` }
seen.add(parsed.id)
extensions.push(parsed)
}
return { ok: true, extensions, recovery: parseRecovery((raw as { recovery?: unknown }).recovery) }
}
function parseRecovery(value: unknown): ExtensionRegistryRecovery | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
const raw = value as Record<string, unknown>
const at = Number(raw.at)
if (!Number.isFinite(at) || at <= 0) return undefined
const kind = raw.kind === 'backup' ? 'backup' : raw.kind === 'scan' ? 'scan' : null
if (!kind) return undefined
const corruptFile =
typeof raw.corruptFile === 'string' && raw.corruptFile.trim()
? raw.corruptFile.trim().slice(0, 200)
: undefined
return { at, kind, ...(corruptFile ? { corruptFile } : {}) }
}
/**
* 单条记录的严格解析。
*
* 与「尽量兼容」相反:字段类型明显不对时整份文件判为损坏,由上层进入恢复流程。
* 静默丢弃单条记录等于「部分数据丢失且不告知用户」。
*/
function parseRecord(value: unknown): ExtensionRegistryRecord | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
const raw = value as Record<string, unknown>
const id = String(raw.id ?? '').trim()
if (!isValidExtensionId(id)) return null
if (typeof raw.version !== 'string' || !raw.version.trim()) return null
const installedAt = Number(raw.installedAt)
const updatedAt = Number(raw.updatedAt)
const templateId =
typeof raw.templateId === 'string' && raw.templateId.trim()
? raw.templateId.trim().slice(0, 64)
: undefined
const templateVersion =
typeof raw.templateVersion === 'string' && raw.templateVersion.trim()
? raw.templateVersion.trim().slice(0, 32)
: undefined
const developmentSourcePath =
typeof raw.developmentSourcePath === 'string' && raw.developmentSourcePath.trim()
? raw.developmentSourcePath.trim().slice(0, 1024)
: undefined
const installedCodeDigest =
typeof raw.installedCodeDigest === 'string' && /^[a-f0-9]{64}$/.test(raw.installedCodeDigest)
? raw.installedCodeDigest
: undefined
return {
id,
version: raw.version.trim().slice(0, 32),
apiVersion:
typeof raw.apiVersion === 'string' && raw.apiVersion.trim()
? raw.apiVersion.trim().slice(0, 16)
: EXTENSION_API_VERSION,
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
enabled: raw.enabled === true,
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
installedAt: Number.isFinite(installedAt) && installedAt > 0 ? installedAt : 0,
updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : 0,
// 未知来源归为 `directory`:来源只能由可信的安装入口赋予,不能从文件里猜。
source: normalizeExtensionSource(raw.source),
...(templateId ? { templateId } : {}),
...(templateVersion ? { templateVersion } : {}),
...(developmentSourcePath ? { developmentSourcePath } : {}),
...(installedCodeDigest ? { installedCodeDigest } : {})
}
}
export class ExtensionRegistry {
private readonly registryFile: string
private readonly backupFile: string
private readonly now: () => number
private readonly recoverByScan: (() => ExtensionRegistryRecord[]) | null
private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] }
private loaded = false
/**
* 主文件当前是否含可解析内容。
*
* 备份轮换只在这个标记为真时执行:主文件已经损坏时复制它,会把唯一的
* 有效备份也换成坏数据。
*/
private primaryValid = false
/** 只有 `unreadable` 需要内存态:连状态文件都写不进去,自然无法持久化。 */
private unreadable: ExtensionRegistryHealth | null = null
constructor(dependencies: ExtensionRegistryDependencies) {
this.registryFile = dependencies.registryFile
this.backupFile = `${dependencies.registryFile}.bak`
this.now = dependencies.now ?? (() => Date.now())
this.recoverByScan = dependencies.recover ?? null
}
list(): ExtensionRegistryRecord[] {
@@ -79,6 +236,43 @@ export class ExtensionRegistry {
return this.list().find((record) => record.id === key)
}
/** 状态文件的可信度;非 `ok` 时调用方必须向用户暴露,而不是当作「没装扩展」。 */
getHealth(): ExtensionRegistryHealth {
this.ensureLoaded()
if (this.unreadable) return { ...this.unreadable }
const recovery = this.state.recovery
if (!recovery) return { state: 'ok', at: this.now() }
return {
state: recovery.kind === 'backup' ? 'recovered-from-backup' : 'recovered-by-scan',
at: recovery.at,
...(recovery.corruptFile ? { corruptFile: recovery.corruptFile } : {}),
message:
recovery.kind === 'backup'
? '扩展状态文件损坏,已从备份重建;所有扩展已暂停,请重新确认后启用'
: '扩展状态文件与备份均不可用,已按磁盘目录重建;所有扩展已暂停,请重新确认后启用'
}
}
/**
* 用户确认「我知道发生过恢复」。
*
* 只清除提示标记,不改动任何扩展的启用状态与授权——那些已经由恢复流程
* 降级为「未启用 + 无授权」,需要用户逐个重新授权。
*/
acknowledgeRecovery(): boolean {
this.ensureLoaded()
if (!this.state.recovery) return false
const previous = this.state
this.state = { version: REGISTRY_VERSION, extensions: this.state.extensions }
try {
this.persist()
} catch (error) {
this.state = previous
throw error
}
return true
}
upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord {
this.ensureLoaded()
const exists = this.state.extensions.some((item) => item.id === record.id)
@@ -119,37 +313,242 @@ export class ExtensionRegistry {
private ensureLoaded(): void {
if (this.loaded) return
this.loaded = true
this.load()
}
private load(): void {
const stamp = this.now()
if (!fs.existsSync(this.registryFile)) {
// 文件不存在是合法状态(首次安装),不是损坏。
this.state = { version: REGISTRY_VERSION, extensions: [] }
this.primaryValid = false
return
}
let text: string
try {
const raw = fs.readJsonSync(this.registryFile) as unknown
if (!raw || typeof raw !== 'object') return
const list = (raw as { extensions?: unknown }).extensions
if (!Array.isArray(list)) return
text = fs.readFileSync(this.registryFile, 'utf8')
} catch (error) {
// 读取失败(权限、IO)与「内容损坏」是两件事:不移动文件,也不尝试覆盖。
this.state = { version: REGISTRY_VERSION, extensions: [] }
this.primaryValid = false
this.unreadable = {
state: 'unreadable',
at: stamp,
message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展状态文件'
}
return
}
const parsed = parseRegistryText(text)
if (parsed.ok) {
this.state = {
version: REGISTRY_VERSION,
extensions: list
.map((item) => normalizeRecord(item))
.filter((item): item is ExtensionRegistryRecord => item !== null)
extensions: parsed.extensions,
...(parsed.recovery ? { recovery: parsed.recovery } : {})
}
this.primaryValid = true
return
}
const corruptFile = this.preserveCorrupt(text)
const backup = this.tryLoadBackup()
if (backup) {
this.state = this.buildRecoveredState(backup, 'backup', corruptFile)
this.primaryValid = false
// 立即把降级后的状态写回主文件:恢复提示与「全部暂停」必须能跨重启保留。
try {
this.writeState(this.state)
this.primaryValid = true
} catch {
// 保留内存状态即可,启动不应因为一次修复失败而中断。
}
return
}
const scanned = this.scan()
if (scanned) {
this.state = this.buildRecoveredState(scanned, 'scan', corruptFile)
this.primaryValid = false
// 刻意不写盘:损坏现场仍留在原位,用户可以在修复后重新读取。
// 一旦用户执行任何写操作(启用/卸载),降级结果与恢复标记会一并落盘。
return
}
this.state = { version: REGISTRY_VERSION, extensions: [] }
this.primaryValid = false
this.unreadable = {
state: 'unreadable',
at: stamp,
...(corruptFile ? { corruptFile } : {}),
message: '扩展状态文件损坏且无法恢复;为避免覆盖现场,已停止写入'
}
}
/**
* 恢复出来的状态一律降级。
*
* 备份最多落后一版,它可能记录着用户随后撤销的授权或关闭的开关。
* 自动采纳等于「把用户已经收回的权限再发回去」,所以只保留身份与版本,
* 启用状态与授权全部清零,等用户重新确认。
*/
private buildRecoveredState(
records: ExtensionRegistryRecord[],
kind: 'backup' | 'scan',
corruptFile?: string
): RegistryFile {
return {
version: REGISTRY_VERSION,
extensions: records.map((record) => ({
...record,
enabled: false,
grantedPermissions: [],
updatedAt: this.now()
})),
recovery: {
at: this.now(),
kind,
...(corruptFile ? { corruptFile } : {})
}
}
}
private tryLoadBackup(): ExtensionRegistryRecord[] | null {
try {
if (!fs.existsSync(this.backupFile)) return null
const parsed = parseRegistryText(fs.readFileSync(this.backupFile, 'utf8'))
return parsed.ok ? parsed.extensions : null
} catch {
return null
}
}
private scan(): ExtensionRegistryRecord[] | null {
if (!this.recoverByScan) return null
let records: ExtensionRegistryRecord[]
try {
records = this.recoverByScan()
} catch {
return null
}
if (!Array.isArray(records)) return null
// 扫描结果只用于「知道有哪些扩展存在」,不继承任何授权或启用状态。
return records.map((record) => ({
...record,
enabled: false,
grantedPermissions: [],
source: 'directory' as const
}))
}
/**
* 把损坏内容写到 `.corrupt-<时间戳>`。
*
* 保留现场是恢复的前提:用户可能手工修好它,或者授权更高版本的 TraceMemo 读取。
*/
private preserveCorrupt(text: string): string | undefined {
const base = `${this.registryFile}.corrupt-${this.now().toString(36)}`
let target = base
let index = 1
while (fs.existsSync(target)) {
target = `${base}-${index}`
index += 1
}
try {
fs.writeFileSync(target, text, 'utf8')
this.pruneCorruptFiles()
return path.basename(target)
} catch {
return undefined
}
}
private pruneCorruptFiles(): void {
try {
const directory = path.dirname(this.registryFile)
const prefix = `${path.basename(this.registryFile)}.corrupt-`
const files = fs
.readdirSync(directory)
.filter((name) => name.startsWith(prefix))
.map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs }))
.sort((left, right) => left.at - right.at)
for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) {
fs.removeSync(path.join(directory, file.name))
}
} catch {
// 文件不存在 / 损坏都按「没有装过扩展」处理,不阻塞应用启动。
// 清理失败不影响恢复本身。
}
}
private commit(extensions: ExtensionRegistryRecord[]): void {
const previous = this.state
this.state = { version: REGISTRY_VERSION, extensions }
const previousValid = this.primaryValid
// 恢复标记必须跟着普通写入一起保留:否则用户启用一个扩展就把
// 「其余扩展全部暂停过」的提示抹掉了。
this.state = {
version: REGISTRY_VERSION,
extensions,
...(previous.recovery ? { recovery: previous.recovery } : {})
}
try {
this.persist()
} catch (error) {
this.state = previous
this.primaryValid = previousValid
throw error
}
}
private persist(): void {
fs.ensureDirSync(path.dirname(this.registryFile))
if (this.unreadable) {
throw new ExtensionError(
'EXTENSION_REGISTRY_UNREADABLE',
'扩展状态文件损坏且无法恢复,已拒绝写入以保留现场'
)
}
this.rotateBackup()
this.writeState(this.state)
this.primaryValid = true
}
/**
* 用当前主文件刷新 `.bak`。
*
* 三重保护:
* 1. 主文件不可信(`primaryValid === false`)时直接跳过;
* 2. 先写 `.bak.tmp` 并重新解析,拒绝把坏内容升级成备份;
* 3. 成功后才 rename 覆盖旧备份,失败时旧备份原样保留。
*/
private rotateBackup(): void {
if (!this.primaryValid) return
if (!fs.existsSync(this.registryFile)) return
const temporary = `${this.backupFile}.tmp`
try {
fs.copyFileSync(this.registryFile, temporary)
const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
return
}
fs.moveSync(temporary, this.backupFile, { overwrite: true })
} catch {
fs.removeSync(temporary)
}
}
/** 临时文件 → 读回校验 → 原子替换;中途失败不会留下半写的主文件。 */
private writeState(state: RegistryFile): void {
const directory = path.dirname(this.registryFile)
fs.ensureDirSync(directory)
const temporary = `${this.registryFile}.tmp`
fs.writeJsonSync(temporary, this.state, { spaces: 2 })
fs.writeFileSync(temporary, JSON.stringify(state, null, 2), 'utf8')
const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
throw new ExtensionError('EXTENSION_REGISTRY_UNREADABLE', `写入前校验失败:${parsed.reason}`)
}
fs.moveSync(temporary, this.registryFile, { overwrite: true })
}
}
@@ -0,0 +1,143 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import type { ExtensionSource } from '../../shared/extensions/source'
import { isPathInside, isSamePath, type ExtensionPaths } from './extension-paths'
import type { ExtensionRegistryRecord } from './extension-registry'
export interface ExtensionRootInfo {
extensionId: string
/** 代码根目录(已 realpath)。 */
root: string
source: ExtensionSource
/** 开发模式下用户选择时的目录(同样是 realpath)。 */
developmentSourcePath?: string
}
export interface ExtensionRootResolver {
/**
* 解析扩展代码根目录。
*
* 抛 `EXTENSION_SOURCE_MISSING` 表示开发目录不可用;调用方必须保留 Registry
* 与配置,把扩展标成「源码目录不可用」,而不是当成「没装过」。
*/
resolve(extensionId: string): ExtensionRootInfo
/** 只看正式安装目录,用于导出、回滚等必须触碰安装副本的场景。 */
installedRoot(extensionId: string): string
}
export interface ExtensionRootResolverDependencies {
paths: ExtensionPaths
getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
/** 测试注入点。 */
realpath?: (target: string) => string
stat?: (target: string) => { isDirectory: () => boolean }
}
/**
* 所有扩展代码根目录的唯一来源。
*
* 在这之前,代码目录被 manager、protocol、catalog 各自拼 `paths.installDir(id)`,
* 开发模式一旦接入就会出现「后台读外部目录、页面读安装副本」的错位。
*/
export function createExtensionRootResolver(
dependencies: ExtensionRootResolverDependencies
): ExtensionRootResolver {
const realpath = dependencies.realpath ?? ((target: string) => fs.realpathSync(target))
const stat = dependencies.stat ?? ((target: string) => fs.statSync(target))
function resolveInstalled(extensionId: string): string {
return dependencies.paths.installDir(extensionId)
}
return {
installedRoot: resolveInstalled,
resolve(extensionId: string): ExtensionRootInfo {
const record = dependencies.getRecord(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (record.source !== 'development' || !record.developmentSourcePath) {
return { extensionId, root: resolveInstalled(extensionId), source: record.source }
}
const configured = record.developmentSourcePath
let realRoot: string
try {
realRoot = realpath(configured)
} catch {
throw new ExtensionError(
'EXTENSION_SOURCE_MISSING',
'开发源码目录不可用,请重新选择或移除链接'
)
}
let isDirectory = false
try {
isDirectory = stat(realRoot).isDirectory()
} catch {
isDirectory = false
}
if (!isDirectory) {
throw new ExtensionError('EXTENSION_SOURCE_MISSING', '开发源码路径不是目录')
}
assertSafeDevelopmentRoot(dependencies.paths, extensionId, realRoot)
return {
extensionId,
root: realRoot,
source: 'development',
developmentSourcePath: realRoot
}
}
}
}
/**
* 开发目录的安全边界。
*
* 拒绝三类位置:
* 1. 扩展自己的安装副本(否则「开发模式」等于原地打转,卸载还会误删);
* 2. 宿主的私有数据区(配置、状态、日志、暂存)——那里有用户凭据;
* 3. 文件系统根 / 用户主目录(自定义协议会把整个目录开放给 iframe)。
*/
function safeRealpath(target: string): string {
try {
return fs.realpathSync(target)
} catch {
return path.resolve(target)
}
}
export function assertSafeDevelopmentRoot(
paths: ExtensionPaths,
extensionId: string,
realRoot: string
): void {
const forbidden: Array<{ root: string; reason: string }> = [
{ root: paths.installDir(extensionId), reason: '不能指向扩展自己的安装目录' },
{ root: paths.extensionsDir, reason: '不能指向扩展安装根目录' },
{ root: paths.dataDir, reason: '不能指向宿主私有数据目录' },
{ root: paths.stateDir, reason: '不能指向宿主状态目录' },
{ root: paths.stagingDir, reason: '不能指向宿主暂存目录' }
]
for (const item of forbidden) {
// 两侧都必须 realpath:macOS 上 `/tmp` 指向 `/private/tmp`,
// 只比较字符串会让「extensions-data 里的目录」冒充外部项目。
const forbiddenRoot = safeRealpath(item.root)
if (isSamePath(forbiddenRoot, realRoot) || isPathInside(forbiddenRoot, realRoot)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', item.reason)
}
}
const parsed = path.parse(realRoot)
if (realRoot === parsed.root) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把文件系统根目录作为扩展源码')
}
try {
if (isSamePath(os.homedir(), realRoot)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把用户主目录作为扩展源码')
}
} catch (error) {
if (error instanceof ExtensionError) throw error
}
}
@@ -0,0 +1,174 @@
import fs from 'fs-extra'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
/** 加密实现由主进程注入(Electron `safeStorage`),本模块不直接依赖 electron。 */
export interface ExtensionSecretCipher {
isAvailable: () => boolean
encrypt: (plain: string) => Buffer
decrypt: (payload: Buffer) => string
}
export interface ExtensionSecretStoreDependencies {
/** 通常是 `<userData>/extensions-state/secrets`。 */
root: string
cipher: ExtensionSecretCipher
now?: () => number
}
interface SecretFile {
version: 1
values: Record<string, string>
}
const MAX_KEY_LENGTH = 64
const MAX_VALUE_BYTES = 8 * 1024
const MAX_KEYS = 32
const SECRET_KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/
/**
* 扩展私有凭据。
*
* 设计取舍:
* - 每个扩展一个文件、一个命名空间,A 扩展拿不到 B 的键;
* - 落盘只有 `safeStorage` 加密后的密文,**不再产生明文 .txt**;
* - 加密不可用时直接失败,绝不退化成明文——宁可让用户知道「这台机器不支持」,
* 也不要把 Cookie 摊在磁盘上。
*
* 这不是操作系统级沙箱:扩展后台是拥有 Node 权限的本地进程,能读别的文件。
* 它能防的是「普通 SDK / 页面桥跨扩展取密钥」与「意外明文落盘」。
*/
export class ExtensionSecretStore {
private readonly root: string
private readonly cipher: ExtensionSecretCipher
private readonly now: () => number
private readonly cache = new Map<string, SecretFile>()
constructor(dependencies: ExtensionSecretStoreDependencies) {
this.root = dependencies.root
this.cipher = dependencies.cipher
this.now = dependencies.now ?? (() => Date.now())
}
isAvailable(): boolean {
try {
return this.cipher.isAvailable()
} catch {
return false
}
}
/** 只返回键名与数量,不返回值;供 UI 显示「是否已配置」。 */
listKeys(extensionId: string): string[] {
return Object.keys(this.read(extensionId).values).sort()
}
has(extensionId: string, key: string): boolean {
const name = assertKey(key)
return Object.prototype.hasOwnProperty.call(this.read(extensionId).values, name)
}
get(extensionId: string, key: string): string | null {
const name = assertKey(key)
const values = this.read(extensionId).values
return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null
}
set(extensionId: string, key: string, value: string): void {
const name = assertKey(key)
if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '凭据值必须是字符串')
if (new TextEncoder().encode(value).length > MAX_VALUE_BYTES) {
throw new ExtensionError('INVALID_REQUEST', '凭据超过 8KB 上限')
}
const file = this.read(extensionId)
if (
!Object.prototype.hasOwnProperty.call(file.values, name) &&
Object.keys(file.values).length >= MAX_KEYS
) {
throw new ExtensionError('INVALID_REQUEST', `单个扩展最多保存 ${MAX_KEYS} 个凭据`)
}
file.values[name] = value
this.write(extensionId, file)
}
delete(extensionId: string, key: string): boolean {
const name = assertKey(key)
const file = this.read(extensionId)
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
delete file.values[name]
this.write(extensionId, file)
return true
}
/** 卸载扩展且用户选择清除数据时调用。 */
clear(extensionId: string): void {
this.cache.delete(extensionId)
fs.removeSync(this.filePath(extensionId))
}
private filePath(extensionId: string): string {
return path.join(this.root, `${extensionId}.bin`)
}
private read(extensionId: string): SecretFile {
const cached = this.cache.get(extensionId)
if (cached) return { version: 1, values: { ...cached.values } }
const file = this.filePath(extensionId)
if (!fs.existsSync(file)) {
const empty: SecretFile = { version: 1, values: {} }
this.cache.set(extensionId, empty)
return { version: 1, values: {} }
}
this.assertAvailable()
let parsed: SecretFile
try {
const payload = fs.readFileSync(file)
const text = this.cipher.decrypt(payload)
const raw = JSON.parse(text) as unknown
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('结构不合法')
const values: Record<string, string> = {}
for (const [key, value] of Object.entries((raw as { values?: unknown }).values ?? {})) {
if (SECRET_KEY_PATTERN.test(key) && typeof value === 'string') values[key] = value
}
parsed = { version: 1, values }
} catch {
// 解不开就当作没有:不能把损坏的密文当成空口令去覆盖(写盘会覆盖原文件)。
throw new ExtensionError(
'EXTENSION_STORAGE_CORRUPTED',
'扩展凭据无法解密(可能换了机器或系统密钥变更),请在扩展页面重新填写'
)
}
this.cache.set(extensionId, parsed)
return { version: 1, values: { ...parsed.values } }
}
private write(extensionId: string, file: SecretFile): void {
this.assertAvailable()
const payload = this.cipher.encrypt(JSON.stringify({ version: 1, values: file.values }))
fs.ensureDirSync(this.root)
const target = this.filePath(extensionId)
const temporary = `${target}.tmp`
fs.writeFileSync(temporary, payload, { mode: 0o600 })
fs.moveSync(temporary, target, { overwrite: true })
try {
fs.chmodSync(target, 0o600)
} catch {
// Windows 不支持 POSIX 权限位;忽略即可。
}
this.cache.set(extensionId, { version: 1, values: { ...file.values } })
void this.now
}
private assertAvailable(): void {
if (this.isAvailable()) return
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前系统不支持安全存储,扩展凭据功能不可用')
}
}
function assertKey(value: string): string {
const key = String(value ?? '').trim()
if (!SECRET_KEY_PATTERN.test(key) || key.length > MAX_KEY_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '凭据键名不合法')
}
return key
}
+26
View File
@@ -1,3 +1,5 @@
import { app, safeStorage } from 'electron'
import path from 'node:path'
import { AIProviderService } from '../services/ai-provider-service'
import {
getChatDb,
@@ -20,6 +22,19 @@ import { getExtensionPaths } from './extension-paths'
let manager: ExtensionManager | null = null
/**
* 官方模板资源根目录。
*
* 打包后是 `<resources>/extension-templates`;开发态读构建产物目录。
* 两者都不指向 `examples/extensions`——源码树不是运行时依赖。
*/
function resolveTemplateRoot(): string {
const override = process.env.TRACEMEMO_EXTENSION_TEMPLATES_DIR
if (override && override.trim()) return path.resolve(override.trim())
if (app.isPackaged) return path.join(process.resourcesPath, 'extension-templates')
return path.join(app.getAppPath(), 'build', 'extension-templates')
}
export interface ExtensionSystemOptions {
appVersion: string
onChange: (extensionId: string, reason: string) => void
@@ -53,6 +68,11 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
}
},
aiChat: chatWithConfiguredProvider,
aiStatus: () => {
// 只读「是否已配置 + 模型显示名」,不返回 key 或 endpoint。
const config = new AIProviderService().getRuntimeConfig()
return { configured: config.configured, modelName: config.modelName }
},
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
getSelfUsernames: () => {
try {
@@ -68,6 +88,12 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
return false
}
},
templatesRoot: resolveTemplateRoot(),
secretCipher: {
isAvailable: () => safeStorage.isEncryptionAvailable(),
encrypt: (plain: string) => safeStorage.encryptString(plain),
decrypt: (payload: Buffer) => safeStorage.decryptString(payload)
},
onChange: (extensionId, reason) => options.onChange(extensionId, reason)
})
await manager.initialize()
+256 -10
View File
@@ -1,6 +1,7 @@
import fs from 'fs-extra'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import type { ExtensionStorageHealthState } from '../../shared/extensions/types'
const STORAGE_FILE = 'storage.json'
const STORAGE_VERSION = 1
@@ -8,17 +9,59 @@ const MAX_KEY_LENGTH = 64
const MAX_VALUE_BYTES = 256 * 1024
const MAX_TOTAL_BYTES = 1024 * 1024
const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/
/** 每个扩展最多保留的损坏现场份数;超出时删除最旧的。 */
const CORRUPT_KEEP_LIMIT = 3
interface StorageFile {
version: number
values: Record<string, unknown>
}
export interface ExtensionStorageHealth {
state: ExtensionStorageHealthState
at: number
/** 损坏现场的**文件名**(不含目录);不渲染绝对路径。 */
corruptFile?: string
message?: string
}
export interface ExtensionStorageDependencies {
/** 通常是 `<userData>/extensions-data`。 */
dataRoot: string
maxTotalBytes?: number
maxValueBytes?: number
now?: () => number
/**
* 健康状态发生变化时的通知。
*
* 运行期才发生损坏/回退时,宿主要靠这个立刻收住扩展——
* 只等下一次启动才处理,那台机器人已经用旧配置发完消息了。
*/
onHealthChange?: (extensionId: string, health: ExtensionStorageHealth) => void
}
type ParseResult = { ok: true; values: Record<string, unknown> } | { ok: false; reason: string }
function parseStorageText(text: string): ParseResult {
if (!text.trim()) return { ok: false, reason: '存储文件为空' }
let raw: unknown
try {
raw = JSON.parse(text)
} catch {
return { ok: false, reason: '存储文件不是合法 JSON' }
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { ok: false, reason: '存储文件顶层不是对象' }
}
const version = Number((raw as { version?: unknown }).version)
if (!Number.isInteger(version) || version !== STORAGE_VERSION) {
return { ok: false, reason: '存储文件版本不受支持' }
}
const values = (raw as { values?: unknown }).values
if (!values || typeof values !== 'object' || Array.isArray(values)) {
return { ok: false, reason: 'values 不是对象' }
}
return { ok: true, values: values as Record<string, unknown> }
}
/**
@@ -28,16 +71,25 @@ export interface ExtensionStorageDependencies {
* - 每个扩展一个独立目录,键空间互不可见;
* - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**;
* - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。
*
* 损坏语义:主文件解析失败时先尝试 `storage.json.bak`;两者都不可用时,
* 该扩展进入 `unrecovered` 状态,`set` 会被拒绝。宁可让扩展报错,
* 也不能用一次写入把用户唯一的一份配置覆盖成空。
*/
export class ExtensionStorage {
private readonly dataRoot: string
private readonly maxTotalBytes: number
private readonly maxValueBytes: number
private readonly now: () => number
private readonly onHealthChange?: ExtensionStorageDependencies['onHealthChange']
private readonly healthByExtension = new Map<string, ExtensionStorageHealth>()
constructor(dependencies: ExtensionStorageDependencies) {
this.dataRoot = dependencies.dataRoot
this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES
this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES
this.now = dependencies.now ?? (() => Date.now())
this.onHealthChange = dependencies.onHealthChange
}
filePath(extensionId: string): string {
@@ -51,6 +103,7 @@ export class ExtensionStorage {
get(extensionId: string, key: unknown): unknown {
const name = assertKey(key)
const values = this.read(extensionId).values
this.assertReadable(extensionId)
return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined
}
@@ -61,6 +114,7 @@ export class ExtensionStorage {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限')
}
const file = this.read(extensionId)
this.assertReadable(extensionId)
file.values[name] = JSON.parse(serialized)
this.assertTotalSize(file)
this.write(extensionId, file)
@@ -69,6 +123,7 @@ export class ExtensionStorage {
remove(extensionId: string, key: unknown): boolean {
const name = assertKey(key)
const file = this.read(extensionId)
this.assertReadable(extensionId)
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
delete file.values[name]
this.write(extensionId, file)
@@ -77,6 +132,7 @@ export class ExtensionStorage {
list(extensionId: string): Array<{ key: string; value: unknown }> {
const values = this.read(extensionId).values
this.assertReadable(extensionId)
return Object.keys(values).map((key) => ({ key, value: clone(values[key]) }))
}
@@ -84,29 +140,219 @@ export class ExtensionStorage {
this.write(extensionId, { version: STORAGE_VERSION, values: {} })
}
/**
* 显式重置:保留损坏现场,然后把存储清空。
*
* 只允许用户从界面触发;扩展自身不能调用(`tm.storage` 没有这个能力)。
*/
reset(extensionId: string): void {
this.read(extensionId)
this.writeState(extensionId, { version: STORAGE_VERSION, values: {} }, { rotateBackup: false })
this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() })
}
/**
* 用户确认「接受从备份恢复出来的配置」。
*
* 恢复出来的内容可能落后一版——比如机器人开关还停在 `true`。
* 在用户点这一下之前,宿主不会启动该扩展(见 `ExtensionManager` 的启动前检查)。
*/
acknowledge(extensionId: string): void {
const current = this.health(extensionId)
if (current.state !== 'recovered-from-backup') {
throw new ExtensionError('INVALID_REQUEST', '当前没有待确认的配置恢复')
}
this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() })
}
/**
* 未确认的恢复 / 无法恢复时,读写一律拒绝。
*
* 只让 `health()` 与 `reset()` / `acknowledge()` 能穿过这道闸:
* 前者给界面看状态,后两者是用户的显式处理动作。
*/
private assertReadable(extensionId: string): void {
const health = this.healthByExtension.get(extensionId)
if (!health || health.state === 'ok') return
if (health.state === 'recovered-from-backup') {
throw new ExtensionError(
'EXTENSION_STORAGE_CORRUPTED',
'扩展配置刚从备份恢复,用户确认前读写已暂停'
)
}
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置已损坏且没有可用备份')
}
private reportHealth(extensionId: string, health: ExtensionStorageHealth): void {
this.healthByExtension.set(extensionId, health)
if (health.state === 'ok') return
try {
this.onHealthChange?.(extensionId, health)
} catch {
// 通知失败不能反过来影响存储读写。
}
}
health(extensionId: string): ExtensionStorageHealth {
this.read(extensionId)
return { ...(this.healthByExtension.get(extensionId) ?? { state: 'ok', at: this.now() }) }
}
private read(extensionId: string): StorageFile {
const filePath = this.filePath(extensionId)
try {
const raw = fs.readJsonSync(filePath) as unknown
if (!raw || typeof raw !== 'object') return { version: STORAGE_VERSION, values: {} }
const values = (raw as { values?: unknown }).values
if (!values || typeof values !== 'object' || Array.isArray(values)) {
return { version: STORAGE_VERSION, values: {} }
}
return { version: STORAGE_VERSION, values: values as Record<string, unknown> }
} catch {
if (!fs.existsSync(filePath)) {
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
return { version: STORAGE_VERSION, values: {} }
}
let text: string
try {
text = fs.readFileSync(filePath, 'utf8')
} catch (error) {
this.reportHealth(extensionId, {
state: 'unrecovered',
at: this.now(),
message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展配置'
})
return { version: STORAGE_VERSION, values: {} }
}
const parsed = parseStorageText(text)
if (parsed.ok) {
// `recovered-from-backup` 要保留到用户看到它为止:恢复成功后立刻改回 `ok`,
// 界面就再也不会提示「这份配置曾经损坏过」。
const current = this.healthByExtension.get(extensionId)
if (current?.state !== 'recovered-from-backup') {
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
}
return { version: STORAGE_VERSION, values: parsed.values }
}
const corruptFile = this.preserveCorrupt(extensionId, text)
const backup = this.tryLoadBackup(extensionId)
if (backup) {
this.reportHealth(extensionId, {
state: 'recovered-from-backup',
at: this.now(),
...(corruptFile ? { corruptFile } : {}),
message: '扩展配置损坏,已从备份恢复'
})
try {
// 主文件此刻是坏的,不能让它进入备份轮换,否则会覆盖刚读到的有效备份。
this.writeState(
extensionId,
{ version: STORAGE_VERSION, values: backup },
{ rotateBackup: false }
)
} catch {
// 提升备份失败时仍返回备份内容,下次写入会再试。
}
return { version: STORAGE_VERSION, values: backup }
}
this.reportHealth(extensionId, {
state: 'unrecovered',
at: this.now(),
...(corruptFile ? { corruptFile } : {}),
message: '扩展配置损坏且没有可用备份;写入已停止以保留现场'
})
return { version: STORAGE_VERSION, values: {} }
}
private tryLoadBackup(extensionId: string): Record<string, unknown> | null {
const backupPath = `${this.filePath(extensionId)}.bak`
try {
if (!fs.existsSync(backupPath)) return null
const parsed = parseStorageText(fs.readFileSync(backupPath, 'utf8'))
return parsed.ok ? parsed.values : null
} catch {
return null
}
}
private preserveCorrupt(extensionId: string, text: string): string | undefined {
const filePath = this.filePath(extensionId)
const base = `${filePath}.corrupt-${this.now().toString(36)}`
let target = base
let index = 1
while (fs.existsSync(target)) {
target = `${base}-${index}`
index += 1
}
try {
fs.ensureDirSync(path.dirname(filePath))
fs.writeFileSync(target, text, 'utf8')
this.pruneCorruptFiles(extensionId)
return path.basename(target)
} catch {
return undefined
}
}
private pruneCorruptFiles(extensionId: string): void {
try {
const directory = path.dirname(this.filePath(extensionId))
const prefix = `${STORAGE_FILE}.corrupt-`
const files = fs
.readdirSync(directory)
.filter((name) => name.startsWith(prefix))
.map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs }))
.sort((left, right) => left.at - right.at)
for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) {
fs.removeSync(path.join(directory, file.name))
}
} catch {
// 清理失败不影响恢复本身。
}
}
private write(extensionId: string, file: StorageFile): void {
this.writeState(extensionId, file, { rotateBackup: true })
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
}
/**
* 主文件 → `.bak` → 新内容。
*
* `rotateBackup` 只在主文件可信时为真:从备份恢复、显式重置这两条路径
* 面对的主文件都是坏的,让它们参与轮换会把有效备份一起换掉。
*/
private writeState(
extensionId: string,
file: StorageFile,
options: { rotateBackup: boolean }
): void {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
if (options.rotateBackup) this.rotateBackup(extensionId)
const temporary = `${filePath}.tmp`
fs.writeJsonSync(temporary, file, { spaces: 2 })
fs.writeFileSync(temporary, JSON.stringify(file, null, 2), 'utf8')
const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', `写入前校验失败:${parsed.reason}`)
}
fs.moveSync(temporary, filePath, { overwrite: true })
}
private rotateBackup(extensionId: string): void {
const filePath = this.filePath(extensionId)
if (!fs.existsSync(filePath)) return
const backupPath = `${filePath}.bak`
const temporary = `${backupPath}.tmp`
try {
fs.copyFileSync(filePath, temporary)
const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8'))
if (!parsed.ok) {
fs.removeSync(temporary)
return
}
fs.moveSync(temporary, backupPath, { overwrite: true })
} catch {
fs.removeSync(temporary)
}
}
private assertTotalSize(file: StorageFile): void {
const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8')
if (bytes > this.maxTotalBytes) {
@@ -0,0 +1,407 @@
import { existsSync, promises as fs } from 'node:fs'
import path from 'node:path'
import { createHash } from 'node:crypto'
import { ExtensionError } from '../../shared/extensions/errors'
import { compareSemver } from '../../shared/extensions/manifest'
import type { ExtensionRegistryRecord } from './extension-registry'
import { normalizeExtensionPermissions } from '../../shared/extensions/permissions'
import type {
ExtensionTemplateEntry,
ExtensionTemplateRequirement,
ExtensionTemplateStatus,
TemplateDependencyCheck
} from '../../shared/extensions/templates'
export type {
ExtensionTemplateEntry,
ExtensionTemplateRequirement,
ExtensionTemplateState,
ExtensionTemplateStatus,
TemplateDependencyCheck
} from '../../shared/extensions/templates'
export interface ExtensionTemplateCatalogDependencies {
/** 模板资源根目录;打包后是 `<resources>/extension-templates`。 */
templateRoot: string
getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
/** 已安装扩展的代码目录;用来看依赖脚本在不在。 */
resolveInstallDir: (extensionId: string) => string
platform?: NodeJS.Platform
/** 测试注入点:默认用真实文件系统。 */
exists?: (filePath: string) => boolean
readFile?: (filePath: string) => Promise<Buffer>
/** 依赖探测注入点:默认读本机 PATH 与常见安装位置。 */
probePython?: () => string | null
probeChrome?: () => string | null
}
const INDEX_FILE = 'index.json'
const SUPPORTED_INDEX_VERSION = 1
interface TemplateIndexFile {
version: number
templates: unknown[]
}
function parseRequirement(input: unknown): ExtensionTemplateRequirement {
if (!input || typeof input !== 'object' || Array.isArray(input)) return {}
const raw = input as Record<string, unknown>
const result: ExtensionTemplateRequirement = {}
for (const key of ['python', 'chrome', 'externalScript'] as const) {
const value = raw[key]
if (value === true || value === false) {
result[key] = value as never
continue
}
if (value && typeof value === 'object' && !Array.isArray(value)) {
const item = value as Record<string, unknown>
const required = item.required === true
if (key === 'externalScript') {
const scriptPath = typeof item.path === 'string' ? item.path.trim() : ''
if (!scriptPath) continue
result.externalScript = {
required,
path: scriptPath,
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
}
continue
}
if (key === 'python') {
result.python = {
required,
...(typeof item.minVersion === 'string' ? { minVersion: item.minVersion } : {}),
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
}
continue
}
result.chrome = {
required,
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
}
}
}
return result
}
function parseEntry(input: unknown): ExtensionTemplateEntry | null {
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
const raw = input as Record<string, unknown>
const templateId = String(raw.templateId ?? '').trim()
const extensionId = String(raw.extensionId ?? '').trim()
const name = String(raw.name ?? '').trim()
const version = String(raw.version ?? '').trim()
const file = String(raw.file ?? '').trim()
const sha256 = String(raw.sha256 ?? '').trim()
if (!templateId || !extensionId || !name || !version || !file || !sha256) return null
// 索引来自资源目录,但依然不接受任何路径片段:读取时只拼在模板根目录下。
if (file.includes('/') || file.includes('\\') || file.includes('..')) return null
if (!/^[a-f0-9]{64}$/.test(sha256)) return null
const platforms = Array.isArray(raw.platforms)
? raw.platforms.filter((item): item is NodeJS.Platform => typeof item === 'string')
: []
return {
templateId,
extensionId,
name,
version,
...(typeof raw.description === 'string' ? { description: raw.description.slice(0, 500) } : {}),
permissions: normalizeExtensionPermissions(raw.permissions),
file,
sha256,
bytes: Number(raw.bytes) || 0,
fileCount: Number(raw.fileCount) || 0,
platforms,
requires: parseRequirement(raw.requires)
}
}
/**
* 官方模板目录。
*
* 只做三件事:读索引、校验资源、把模板与已安装状态对上。
* 安装动作本身不在这里——它由 `ExtensionManager` 走统一的安装器,
* 避免出现第二套 ZIP 解压逻辑。
*/
export class ExtensionTemplateCatalog {
private readonly dependencies: ExtensionTemplateCatalogDependencies
private readonly platform: NodeJS.Platform
private cachedIndex: ExtensionTemplateEntry[] | null = null
constructor(dependencies: ExtensionTemplateCatalogDependencies) {
this.dependencies = dependencies
this.platform = dependencies.platform ?? process.platform
}
/** 索引读取失败时返回空列表:模板资源缺失不应该让扩展中心整页崩掉。 */
async list(): Promise<ExtensionTemplateStatus[]> {
const entries = await this.loadIndex()
const result: ExtensionTemplateStatus[] = []
for (const template of entries) {
result.push(await this.describe(template))
}
return result.sort((left, right) =>
left.template.templateId.localeCompare(right.template.templateId)
)
}
get(templateId: string): ExtensionTemplateEntry | undefined {
return this.cachedIndex?.find((item) => item.templateId === templateId)
}
/**
* 取模板 ZIP 的绝对路径,并校验内容哈希。
*
* 这一步是安装前的最后一道闸:索引与 ZIP 若被单独替换,哈希就对不上,
* 直接拒绝安装而不是把未知内容装进用户目录。
*/
async resolveZip(
templateId: string
): Promise<{ path: string; template: ExtensionTemplateEntry }> {
const entries = await this.loadIndex()
const template = entries.find((item) => item.templateId === templateId)
if (!template) {
throw new ExtensionError('EXTENSION_NOT_FOUND', `找不到模板:${templateId}`)
}
const zipPath = path.join(this.dependencies.templateRoot, template.file)
const exists = this.dependencies.exists ?? defaultExists
if (!exists(zipPath)) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源缺失:${template.file}`)
}
const readFile = this.dependencies.readFile ?? fs.readFile
let buffer: Buffer
try {
buffer = await readFile(zipPath)
} catch {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源不可读:${template.file}`)
}
const digest = createHash('sha256').update(buffer).digest('hex')
if (digest !== template.sha256) {
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
'模板资源校验失败:文件内容与索引不一致,已拒绝安装'
)
}
return { path: zipPath, template }
}
private async loadIndex(): Promise<ExtensionTemplateEntry[]> {
if (this.cachedIndex) return this.cachedIndex
const indexPath = path.join(this.dependencies.templateRoot, INDEX_FILE)
const readFile = this.dependencies.readFile ?? fs.readFile
let parsed: TemplateIndexFile
try {
const text = await readFile(indexPath)
parsed = JSON.parse(text.toString('utf8')) as TemplateIndexFile
} catch {
this.cachedIndex = []
return this.cachedIndex
}
if (
!parsed ||
Number(parsed.version) !== SUPPORTED_INDEX_VERSION ||
!Array.isArray(parsed.templates)
) {
this.cachedIndex = []
return this.cachedIndex
}
const entries: ExtensionTemplateEntry[] = []
const seen = new Set<string>()
for (const item of parsed.templates) {
const entry = parseEntry(item)
if (!entry) continue
if (seen.has(entry.templateId)) continue
seen.add(entry.templateId)
entries.push(entry)
}
this.cachedIndex = entries
return entries
}
private async describe(template: ExtensionTemplateEntry): Promise<ExtensionTemplateStatus> {
const record = this.dependencies.getRecord(template.extensionId)
const dependencies = await this.checkDependencies(template, record)
const base = {
template,
...(record ? { installedVersion: record.version, installedSource: record.source } : {}),
dependencies
}
if (template.platforms.length > 0 && !template.platforms.includes(this.platform)) {
return {
...base,
state: 'unsupported',
message: `当前平台(${this.platform})不在模板支持范围内`
}
}
const damaged = await this.isDamaged(template)
if (damaged) {
return { ...base, state: 'damaged', message: '模板资源缺失或校验失败,请重新安装 TraceMemo' }
}
if (!record) return { ...base, state: 'not-installed' }
// 同 id 但不是这个模板装的:不能静默接管用户自己的扩展。
if (record.source !== 'template' || record.templateId !== template.templateId) {
return {
...base,
state: 'conflict',
message: '已安装同 ID 的非官方扩展,不会自动替换'
}
}
const compared = compareSemver(template.version, record.version)
if (compared !== null && compared > 0) {
return { ...base, state: 'update-available' }
}
return { ...base, state: 'installed' }
}
private async isDamaged(template: ExtensionTemplateEntry): Promise<boolean> {
const zipPath = path.join(this.dependencies.templateRoot, template.file)
const exists = this.dependencies.exists ?? defaultExists
if (!exists(zipPath)) return true
const readFile = this.dependencies.readFile ?? fs.readFile
try {
const buffer = await readFile(zipPath)
if (template.bytes > 0 && buffer.length !== template.bytes) return true
return createHash('sha256').update(buffer).digest('hex') !== template.sha256
} catch {
return true
}
}
/**
* 依赖检测只做本地文件探测:不执行脚本、不访问网络、不触发解析。
*
* `externalScript` 只在扩展已安装后才能判断——安装前它一定不存在,
* 报「缺失」只会让用户以为模板坏了。
*/
private async checkDependencies(
template: ExtensionTemplateEntry,
record: ExtensionRegistryRecord | undefined
): Promise<ExtensionTemplateStatus['dependencies']> {
const checks: TemplateDependencyCheck[] = []
const requires = template.requires
const python = requires.python
if (python) {
const required = typeof python === 'boolean' ? python : python.required
const executable = (this.dependencies.probePython ?? (() => findPython(this.platform)))()
checks.push({
id: 'python',
label: 'Python',
ok: Boolean(executable),
blocking: required,
...(executable
? { detail: '已找到可执行文件' }
: {
detail:
typeof python === 'object' && python.reason
? python.reason
: '未在 PATH 中找到 Python'
})
})
}
const chrome = requires.chrome
if (chrome) {
const required = typeof chrome === 'boolean' ? chrome : chrome.required
const found = (this.dependencies.probeChrome ?? (() => findChrome(this.platform)))()
checks.push({
id: 'chrome',
label: 'Chrome',
ok: Boolean(found),
blocking: required,
...(found
? { detail: '已找到 Chrome' }
: {
detail: typeof chrome === 'object' && chrome.reason ? chrome.reason : '未找到 Chrome'
})
})
}
const externalScript = requires.externalScript
if (externalScript) {
const spec = typeof externalScript === 'object' ? externalScript : null
const relative = spec?.path ?? 'scripts/douyin.py'
if (!record) {
checks.push({
id: 'externalScript',
label: '解析脚本',
ok: false,
blocking: false,
detail: '安装后检测;该脚本不随应用分发'
})
} else {
const scriptPath = path.join(
this.dependencies.resolveInstallDir(template.extensionId),
relative
)
const exists = this.dependencies.exists ?? defaultExists
checks.push({
id: 'externalScript',
label: '解析脚本',
ok: exists(scriptPath),
blocking: spec?.required !== false,
detail: exists(scriptPath)
? '已找到解析脚本'
: spec?.reason || '缺少解析脚本,模板暂时无法处理视频'
})
}
}
const blockingMissing = checks.some((check) => check.blocking && !check.ok)
return { ready: !blockingMissing, checks }
}
}
function defaultExists(filePath: string): boolean {
// 只查存在性,不读内容:检测阶段不触碰文件内容。
return existsSync(filePath)
}
/** 只在 PATH 里找可执行文件,**不执行**它——检测阶段不能启动任何外部进程。 */
function findPython(platform: NodeJS.Platform): string | null {
const names =
platform === 'win32' ? ['python.exe', 'python3.exe', 'py.exe'] : ['python3', 'python']
return findOnPath(names, platform)
}
function findChrome(platform: NodeJS.Platform): string | null {
const candidates: string[] = []
if (platform === 'darwin') {
candidates.push(
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
path.join(
process.env.HOME || '',
'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
)
)
} else if (platform === 'win32') {
for (const root of [
process.env['PROGRAMFILES'] || '',
process.env['PROGRAMFILES(X86)'] || '',
process.env['LOCALAPPDATA'] || ''
]) {
if (!root) continue
candidates.push(path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'))
}
}
return candidates.find((candidate) => defaultExists(candidate)) || null
}
function findOnPath(names: string[], platform: NodeJS.Platform): string | null {
const separator = platform === 'win32' ? ';' : ':'
const directories = String(process.env.PATH || '')
.split(separator)
.filter(Boolean)
for (const name of names) {
for (const directory of directories) {
const candidate = path.join(directory, name)
if (defaultExists(candidate)) return candidate
}
}
return null
}
+99 -15
View File
@@ -10,6 +10,7 @@
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import { validateActionInput as validateWithSchema } from '../../shared/extensions/action-schema'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
@@ -18,6 +19,7 @@ import {
type ExtensionHostCallResult,
type ExtensionHostEvent,
type ExtensionHostInboundMessage,
type ExtensionHostPageRequest,
type ExtensionHostInvokeAction,
type ExtensionHostTestSend,
type ExtensionHostOutboundMessage,
@@ -44,6 +46,10 @@ interface PendingCall {
const pendingCalls = new Map<string, PendingCall>()
const eventHandlers = new Set<MessageHandler>()
const actions = new Map<string, RegisteredActionDefinition>()
const pageHandlers = new Map<string, (params: Record<string, unknown>) => unknown>()
/** 页面请求方法名:小写开头,允许点号分段,长度受限。 */
const PAGE_REQUEST_METHOD = /^[a-z][a-zA-Z0-9]*(?:[._-][a-zA-Z0-9]+){0,3}$/
const PAGE_RESULT_MAX_BYTES = 64 * 1024
let permissions: string[] = []
let activated = false
let extensionDir = ''
@@ -102,6 +108,45 @@ const tm = {
return [...permissions]
}
},
/**
* 页面 → 同扩展后台的通用请求处理器注册。
*
* 不需要额外权限:注册本身不产生任何能力,handler 内部若调用
* `tm.wechat.send` 等能力,仍然各自走权限检查。
*/
page: {
onRequest(method: string, handler: (params: Record<string, unknown>) => unknown): void {
const name = String(method || '').trim()
if (!PAGE_REQUEST_METHOD.test(name)) throw new Error(`页面请求方法名不合法:${name}`)
if (typeof handler !== 'function') throw new Error('页面请求必须提供 handler')
if (pageHandlers.has(name)) throw new Error(`页面请求重复注册:${name}`)
pageHandlers.set(name, handler)
}
},
/**
* 扩展私有凭据。
*
* 真正加密发生在主进程(`safeStorage`);子进程只在需要时拿到明文。
* 每个扩展一个命名空间,A 扩展拿不到 B 的密钥。
*/
secrets: {
async get(key: string): Promise<string | null> {
requirePermission('secrets')
return (await callHost('secrets.get', { key })) as string | null
},
async set(key: string, value: string): Promise<void> {
requirePermission('secrets')
await callHost('secrets.set', { key, value })
},
async delete(key: string): Promise<void> {
requirePermission('secrets')
await callHost('secrets.delete', { key })
},
async has(key: string): Promise<boolean> {
requirePermission('secrets')
return (await callHost('secrets.has', { key })) as boolean
}
},
events: {
on(name: 'message.received', handler: MessageHandler): () => void {
if (name !== 'message.received' || typeof handler !== 'function') return () => undefined
@@ -338,27 +383,62 @@ async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
}
}
/**
* 与 UI 共用同一套校验规则。
*
* 两套实现一定会在某个边界上分叉,用户看到的就是「表单填得进去、执行时说参数错」。
*/
function validateActionInput(
schema: Record<string, unknown> | undefined,
input: Record<string, unknown>
): void {
if (!schema) return
const required = Array.isArray(schema.required) ? schema.required : []
for (const key of required) {
if (typeof key === 'string' && !(key in input)) {
throw new Error(`缺少必填参数:${key}`)
}
const result = validateWithSchema(schema as never, input)
if (result.ok) return
const [key, message] = Object.entries(result.errors)[0] ?? ['参数', '不合法']
throw new Error(`参数 ${key} ${message}`)
}
async function handlePageRequest(message: ExtensionHostPageRequest): Promise<void> {
const handler = pageHandlers.get(message.method)
if (!handler) {
post({
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: `页面请求未注册:${message.method}` }
})
return
}
const properties = schema.properties
if (!properties || typeof properties !== 'object') return
for (const [key, definition] of Object.entries(properties as Record<string, unknown>)) {
if (!(key in input)) continue
const type = (definition as { type?: unknown })?.type
const value = input[key]
if (type === 'string' && typeof value !== 'string') throw new Error(`参数 ${key} 必须是字符串`)
if (type === 'number' && typeof value !== 'number') throw new Error(`参数 ${key} 必须是数字`)
if (type === 'boolean' && typeof value !== 'boolean')
throw new Error(`参数 ${key} 必须是布尔值`)
try {
const raw = await withTimeout(
Promise.resolve(handler(message.params ?? {})),
Math.max(1_000, Math.min(message.timeoutMs - 500, 30_000))
)
// 只允许纯 JSON:函数、循环引用、类实例都在这一步被拒绝。
const serialized = JSON.stringify(raw ?? null)
if (new TextEncoder().encode(serialized).length > PAGE_RESULT_MAX_BYTES) {
throw new Error('页面请求响应超过 64KB')
}
post({
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: true,
result: JSON.parse(serialized) as unknown
})
} catch (error) {
post({
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 200) : '页面请求失败'
}
})
}
}
@@ -465,9 +545,13 @@ process.on('message', (raw: unknown) => {
void invokeAction(message)
return
case 'test-send':
// 旧协议:只有抖音扩展认这个入口。新代码统一走 page-request。
if (extensionId !== 'com.example.douyin-sender') return
void dispatchTestSend(message)
return
case 'page-request':
void handlePageRequest(message)
return
case 'call-result': {
const result = message as ExtensionHostCallResult
const pending = pendingCalls.get(result.callId)
+13 -1
View File
@@ -1454,7 +1454,19 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
// Create the renderer before native WCDB bootstrap so startup progress is visible immediately.
await reportTemplateService.recover()
registerReportTemplateIpc()
installExtensionProtocolHandler(getExtensionPaths())
installExtensionProtocolHandler({
paths: getExtensionPaths(),
// 开发模式下代码在用户自己的目录里:协议必须走同一个解析器,
// 否则页面会读到旧的安装副本。管理器尚未就绪时回退到安装目录。
resolveRoot: (extensionId) => {
if (!hasExtensionManager()) return getExtensionPaths().installDir(extensionId)
try {
return getExtensionManager().resolveExtensionRoot(extensionId)
} catch {
return null
}
}
})
registerExtensionIpc({
getManager: getExtensionManager,
paths: getExtensionPaths(),
+40
View File
@@ -10,8 +10,12 @@ import type {
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageResponse,
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
InstalledExtension
} from '../shared/extensions/types'
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
import {
GroupReportExportRequest,
GroupReportExportResult,
@@ -840,6 +844,42 @@ declare global {
extensionId: string,
enabled: boolean
) => Promise<ExtensionOperationResult>
getExtensionHealth: () => Promise<ExtensionSystemHealth>
grantExtensionPermissions: (
extensionId: string,
permissions: string[]
) => Promise<ExtensionOperationResult>
revokeExtensionPermission: (
extensionId: string,
permission: string
) => Promise<ExtensionOperationResult>
resetExtensionStorage: (extensionId: string) => Promise<ExtensionOperationResult>
listExtensionTemplates: () => Promise<ExtensionTemplateStatus[]>
installExtensionTemplate: (templateId: string) => Promise<ExtensionInstallResult>
acknowledgeExtensionRecovery: () => Promise<ExtensionOperationResult>
acknowledgeExtensionStorage: (extensionId: string) => Promise<ExtensionOperationResult>
adoptExtensionCode: (extensionId: string) => Promise<ExtensionOperationResult>
rollbackExtensionUpgrade: (extensionId: string) => Promise<ExtensionOperationResult>
pickExtensionProjectDirectory: () => Promise<string | null>
linkExtensionDevelopment: (directory: string) => Promise<ExtensionInstallResult>
reloadExtensionDevelopment: (extensionId: string) => Promise<ExtensionOperationResult>
unlinkExtensionDevelopment: (
extensionId: string,
keepData?: boolean
) => Promise<ExtensionOperationResult>
convertExtensionDevelopment: (extensionId: string) => Promise<ExtensionOperationResult>
createExtensionProject: (input: {
templateId: string
targetDirectory: string
extensionId: string
name?: string
}) => Promise<ExtensionProjectResult>
listExtensionActions: () => Promise<ExtensionActionInfo[]>
openExtensionDevelopmentSource: (extensionId: string) => Promise<ExtensionOperationResult>
exportExtensionAsProject: (
extensionId: string,
targetDirectory: string
) => Promise<ExtensionProjectResult>
uninstallExtension: (
extensionId: string,
keepData?: boolean
+62
View File
@@ -139,8 +139,12 @@ import type {
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
ExtensionActionInfo,
ExtensionProjectResult,
ExtensionSystemHealth,
InstalledExtension
} from '../shared/extensions/types'
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
// 渲染器的自定义 API
const api = {
@@ -287,6 +291,64 @@ const api = {
ipcRenderer.invoke('extension:installPackage', packagePath),
setExtensionEnabled: (extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }),
getExtensionHealth: (): Promise<ExtensionSystemHealth> =>
ipcRenderer.invoke('extension:health'),
grantExtensionPermissions: (
extensionId: string,
permissions: string[]
): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:grantPermissions', { id: extensionId, permissions }),
revokeExtensionPermission: (
extensionId: string,
permission: string
): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:revokePermission', { id: extensionId, permission }),
resetExtensionStorage: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:resetStorage', extensionId),
listExtensionTemplates: (): Promise<ExtensionTemplateStatus[]> =>
ipcRenderer.invoke('extension:templates'),
installExtensionTemplate: (templateId: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installTemplate', templateId),
acknowledgeExtensionRecovery: (): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:acknowledgeRecovery'),
acknowledgeExtensionStorage: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:acknowledgeStorage', extensionId),
adoptExtensionCode: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:adoptInstalledCode', extensionId),
rollbackExtensionUpgrade: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:rollbackUpgrade', extensionId),
pickExtensionProjectDirectory: (): Promise<string | null> =>
ipcRenderer.invoke('extension:pickProjectDirectory'),
linkExtensionDevelopment: (directory: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:linkDevelopment', directory),
reloadExtensionDevelopment: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:reloadDevelopment', extensionId),
unlinkExtensionDevelopment: (
extensionId: string,
keepData = true
): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:unlinkDevelopment', { id: extensionId, keepData }),
convertExtensionDevelopment: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:convertDevelopment', extensionId),
createExtensionProject: (input: {
templateId: string
targetDirectory: string
extensionId: string
name?: string
}): Promise<ExtensionProjectResult> =>
ipcRenderer.invoke('extension:createProjectFromTemplate', input),
listExtensionActions: (): Promise<ExtensionActionInfo[]> =>
ipcRenderer.invoke('extension:actions'),
openExtensionDevelopmentSource: (extensionId: string): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:openDevelopmentSource', extensionId),
exportExtensionAsProject: (
extensionId: string,
targetDirectory: string
): Promise<ExtensionProjectResult> =>
ipcRenderer.invoke('extension:exportInstalledAsProject', {
id: extensionId,
targetDirectory
}),
uninstallExtension: (extensionId: string, keepData = true): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }),
getExtensionLogs: (extensionId: string, limit?: number): Promise<ExtensionLogEntry[]> =>
+24 -3
View File
@@ -44,9 +44,16 @@ import { switchGeneratedReportTemplate } from './utils/report-template-switch'
import { runtimePlatform } from './utils/runtime-environment'
import { Button, useToast } from './components/ui'
import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt'
import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace'
import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace'
import {
GroupExitMonitorWorkspace,
type GroupExitMonitorOpenViewRequest
} from './features/group-exit-monitor/GroupExitMonitorWorkspace'
import {
AutomationWorkspace,
type AutomationOpenRuleRequest
} from './features/automation/AutomationWorkspace'
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
import type { ExtensionDeepLink } from '../../shared/extensions/types'
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
import {
buildContactSearchIndex,
@@ -258,6 +265,8 @@ function App(): React.ReactElement {
const [databaseEnvironment, setDatabaseEnvironment] = useState<DatabaseKeyEnvironment>()
const connectionOperationRef = React.useRef(0)
const [activePage, setActivePage] = useState<AppPage>('archive')
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
/**
* 「退群监控 ⇄ 自动化」之间的跨页深链。
*
@@ -1612,6 +1621,12 @@ function App(): React.ReactElement {
const isGroupContact = (contact: Contact | null): boolean =>
Boolean(contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom'))
/** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */
const openExtensionDeepLink = (target: ExtensionDeepLink): void => {
setExtensionDeepLink(target)
handlePageChange('extensions')
}
const handlePageChange = (page: AppPage): void => {
setActivePage(page)
if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact)
@@ -2136,12 +2151,18 @@ function App(): React.ReactElement {
openRuleRequest={automationOpenRuleRequest}
onOpenModelSettings={openModelSettings}
onOpenAgentHub={openAgentHub}
onOpenExtension={openExtensionDeepLink}
/>
)
case 'agent-hub':
return <AgentHubWorkspace selfInfo={selfInfo} />
case 'extensions':
return <ExtensionWorkspace />
return (
<ExtensionWorkspace
deepLink={extensionDeepLink}
onConsumeDeepLink={() => setExtensionDeepLink(null)}
/>
)
case 'api':
return (
<ApiWorkspace
@@ -1,5 +1,6 @@
import * as React from 'react'
import {
AUTOMATION_RULE_TEMPLATES,
BUILTIN_DAILY_REPORT_RULE_ID,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
calculateNextRunAt,
@@ -18,12 +19,12 @@ import {
} from '../../components/ui'
import { RuleListPanel } from './RuleListPanel'
import { RuleEditorPanel } from './RuleEditorPanel'
import type { RuleTemplateCardModel } from './RuleListPanel'
import type { ExtensionTemplateStatus } from '../../../../shared/extensions/templates'
import type { ExtensionDeepLink, InstalledExtension } from '../../../../shared/extensions/types'
import { ExecutionLogPanel } from './ExecutionLogPanel'
import { ExecutionDetailDrawer } from './ExecutionDetailDrawer'
import {
AutomationRuleTypeTabs,
type AutomationRuleTabType
} from './AutomationRuleTypeTabs'
import { AutomationRuleTypeTabs, type AutomationRuleTabType } from './AutomationRuleTypeTabs'
import { MessageInsertSwitches } from './MessageInsertSwitches'
import { ScheduledReportEditor } from './ScheduledReportEditor'
import { ScheduledReportRuleList } from './ScheduledReportRuleList'
@@ -36,12 +37,14 @@ import {
resolveGroupDisplayName,
type ScheduledReportDraft
} from './model/scheduled-report-model'
import {
LeaveNotificationEditor,
type LeaveNotificationSaveInput
} from './LeaveNotificationEditor'
import { LeaveNotificationEditor, type LeaveNotificationSaveInput } from './LeaveNotificationEditor'
import type { LeaveNotificationContactOption } from './LeaveNotificationTargetPicker'
import { UNAVAILABLE_STATUS, automationApi, isAutomationApiAvailable, type AutomationGroupOption } from './model/api'
import {
UNAVAILABLE_STATUS,
automationApi,
isAutomationApiAvailable,
type AutomationGroupOption
} from './model/api'
/**
* AutomationWorkspace —— 自动化一级菜单。
@@ -63,6 +66,16 @@ export interface AutomationOpenRuleRequest {
requestId: number
}
/** 可选能力加载:宿主没有该 API 时返回兜底值,不抛错。 */
async function safeLoad<T>(loader: () => Promise<T> | undefined, fallback: T): Promise<T> {
try {
const result = await loader()
return result ?? fallback
} catch {
return fallback
}
}
export interface AutomationWorkspaceProps {
dbReady: boolean
/** 发送能力不可用时,引导用户去设置页。 */
@@ -75,6 +88,8 @@ export interface AutomationWorkspaceProps {
onOpenAgentHub?: () => void
/** 深链请求(来自退群监控页的「退群通知自动化」入口)。 */
openRuleRequest?: AutomationOpenRuleRequest | null
/** 跳到扩展中心并定位模板 / 扩展 / 开发引导(规则模板卡片用)。 */
onOpenExtension?: (target: ExtensionDeepLink) => void
}
interface EditorState {
@@ -90,7 +105,8 @@ export function AutomationWorkspace({
onOpenExitMonitorGroups,
onOpenModelSettings,
onOpenAgentHub,
openRuleRequest
openRuleRequest,
onOpenExtension
}: AutomationWorkspaceProps): React.ReactElement {
const { toast } = useToast()
const apiAvailable = React.useMemo(() => isAutomationApiAvailable(), [])
@@ -100,7 +116,9 @@ export function AutomationWorkspace({
const [rules, setRules] = React.useState<AutomationRule[]>([])
const [groups, setGroups] = React.useState<AutomationGroupOption[]>([])
const [executions, setExecutions] = React.useState<AutomationExecution[]>([])
const [sendableContacts, setSendableContacts] = React.useState<LeaveNotificationContactOption[]>([])
const [sendableContacts, setSendableContacts] = React.useState<LeaveNotificationContactOption[]>(
[]
)
const [monitoredGroupCount, setMonitoredGroupCount] = React.useState(0)
/** 已监控群聊清单(含显示名)—— 退群通知「通知群聊」二次勾选的候选项。 */
const [monitoredGroups, setMonitoredGroups] = React.useState<AutomationGroupOption[]>([])
@@ -109,6 +127,63 @@ export function AutomationWorkspace({
const [saving, setSaving] = React.useState(false)
const [busyRuleId, setBusyRuleId] = React.useState<string | null>(null)
const [editor, setEditor] = React.useState<EditorState | null>(null)
/** 规则模板依赖的本机事实:官方模板目录 + 已安装扩展。 */
const [extensionTemplates, setExtensionTemplates] = React.useState<ExtensionTemplateStatus[]>([])
const [installedExtensions, setInstalledExtensions] = React.useState<InstalledExtension[]>([])
/**
* 规则模板卡片的真实状态。
*
* 只读「官方模板目录 + 已装扩展」,不在自动化页维护第二份安装状态。
*/
const ruleTemplates = React.useMemo<RuleTemplateCardModel[]>(() => {
return AUTOMATION_RULE_TEMPLATES.map((template) => {
const installed = installedExtensions.find((item) => item.id === template.extensionId)
const catalog = extensionTemplates.find(
(item) => item.template.templateId === template.templateId
)
if (!installed) {
const reason =
catalog?.state === 'damaged'
? catalog.message
: catalog?.state === 'conflict'
? catalog.message
: undefined
return { ...template, state: 'not-installed', ...(reason ? { reason } : {}) }
}
if (!installed.compatibility.compatible) {
return {
...template,
state: 'unavailable',
reason: installed.compatibility.reason || '扩展与当前 TraceMemo 版本不兼容'
}
}
if (installed.runtime.state === 'error') {
return {
...template,
state: 'unavailable',
reason: installed.runtime.lastError || '扩展运行异常'
}
}
if (!installed.enabled) {
return { ...template, state: 'installed-disabled', reason: '已安装但未启用' }
}
return { ...template, state: 'ready' }
})
}, [extensionTemplates, installedExtensions])
const useRuleTemplate = (template: RuleTemplateCardModel): void => {
if (!template.actionId) return
// 打开的是「新建」,不复用上一次日报的编辑目标。
setEditor({ mode: 'create', rule: null, ruleType: 'daily_report' })
toast({
title: '已打开新建规则',
description:
`在执行动作里添加「${template.name}」,选择扩展动作 ${template.actionId}。` +
'若机器人当前是主动订阅模式,规则路径会自动跳过,不会双回复。',
variant: 'default'
})
}
const [selectedExecution, setSelectedExecution] = React.useState<AutomationExecution | null>(null)
const [pendingDelete, setPendingDelete] = React.useState<AutomationRule | null>(null)
@@ -131,6 +206,15 @@ export function AutomationWorkspace({
automationApi.getMonitoredGroupCount(),
automationApi.getMonitoredGroups()
])
// 扩展状态是「模板能不能用」的唯一依据:不自己维护第二份。
// 扩展 API 在旧版宿主或测试环境里可能整体缺失,缺失时按空列表处理,
// 卡片会退化成「未安装」,而不是让整个自动化页崩掉。
const [nextTemplates, nextExtensions] = await Promise.all([
safeLoad<ExtensionTemplateStatus[]>(() => window.api?.listExtensionTemplates?.(), []),
safeLoad<InstalledExtension[]>(() => window.api?.listExtensions?.(), [])
])
setExtensionTemplates(nextTemplates)
setInstalledExtensions(nextExtensions)
setStatus(nextStatus)
setRules(nextRules)
setGroups(nextGroups)
@@ -186,7 +270,6 @@ export function AutomationWorkspace({
const leaveNotificationRule =
rules.find((item) => item.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID) ?? null
/** 「指定好友」目标的显示名(首页卡片用;拿不到时留空,不伪造)。 */
const leaveContactName = React.useMemo((): string => {
const target = leaveNotificationRule?.leaveNotification?.target
@@ -413,9 +496,7 @@ export function AutomationWorkspace({
* 走独立的 singleton upsert 通道:这条规则 id 固定,保存永远不会多出一条。
* 保存成功后清掉迁移遗留的 `targetNeedsReview`(用户已经做过选择)。
*/
const handleLeaveNotificationSave = async (
input: LeaveNotificationSaveInput
): Promise<void> => {
const handleLeaveNotificationSave = async (input: LeaveNotificationSaveInput): Promise<void> => {
// 静默 return 会让"点保存没反应"变成用户眼里的坏掉,必须说出来。
if (!leaveNotificationRule) {
toast({
@@ -522,7 +603,11 @@ export function AutomationWorkspace({
<div className="automation-status-card">
<span className="automation-status-label">发送能力</span>
<span className={`automation-status-value ${capabilityReady ? 'ok' : 'warn'}`}>
{capabilityReady ? '可以发送文字和图片' : capability.ready ? '发送能力不完整' : '尚未就绪'}
{capabilityReady
? '可以发送文字和图片'
: capability.ready
? '发送能力不完整'
: '尚未就绪'}
</span>
<small className="automation-status-note">{capability.message}</small>
{!capabilityReady && onOpenSendSettings ? (
@@ -637,9 +722,7 @@ export function AutomationWorkspace({
{...(onOpenModelSettings ? { onOpenModelSettings } : {})}
{...(scheduledEditor.ruleId
? (() => {
const rule = scheduledRules.find(
(item) => item.id === scheduledEditor.ruleId
)
const rule = scheduledRules.find((item) => item.id === scheduledEditor.ruleId)
const legacy = rule?.scheduledReport?.legacyTarget
return legacy ? { legacyTarget: legacy } : {}
})()
@@ -709,8 +792,8 @@ export function AutomationWorkspace({
<div className="automation-notice warning automation-notice-stack">
<p>没有找到内置的退群通知规则。</p>
<small>
这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本,
请重启 TraceMemo —— 已经跑起来的主进程不会自动换成新代码。
这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本, 请重启 TraceMemo ——
已经跑起来的主进程不会自动换成新代码。
</small>
<Button
variant="outline"
@@ -760,6 +843,9 @@ export function AutomationWorkspace({
onEditLeaveNotification={() =>
setEditor({ mode: 'edit', rule: null, ruleType: 'leave_notification' })
}
ruleTemplates={ruleTemplates}
onOpenExtension={onOpenExtension}
onUseRuleTemplate={useRuleTemplate}
/>
) : (
<ExecutionLogPanel
@@ -777,7 +863,11 @@ export function AutomationWorkspace({
/>
{pendingDelete ? (
<div className="automation-confirm-layer" role="presentation" onClick={() => setPendingDelete(null)}>
<div
className="automation-confirm-layer"
role="presentation"
onClick={() => setPendingDelete(null)}
>
<div
className="automation-confirm"
role="alertdialog"
@@ -0,0 +1,216 @@
import * as React from 'react'
import type { AutomationAction } from '../../../../shared/automation'
import type { ExtensionActionInfo } from '../../../../shared/extensions/types'
import type { ExtensionActionInputSchema } from '../../../../shared/extensions/action-schema'
import { Button, Input, Switch } from '../../components/ui'
interface ExtensionActionListProps {
/** 完整动作数组(含固定动作),本组件只挑 `extensionAction`。 */
actions: AutomationAction[]
available: ExtensionActionInfo[]
onChange: (next: AutomationAction[]) => void
}
/**
* 扩展动作编辑区。
*
* 按**数组索引**定位要改的那一条:同类型动作可以有多个,
* 按 `type` 批量更新会把它们一起改掉。
*/
export function ExtensionActionList({
actions,
available,
onChange
}: ExtensionActionListProps): React.ReactElement {
const [pendingExtension, setPendingExtension] = React.useState('')
const [pendingAction, setPendingAction] = React.useState('')
const extensionActions = actions
.map((action, index) => ({ action, index }))
.filter((item) => item.action.type === 'extensionAction')
const groups = React.useMemo(() => {
const map = new Map<string, { name: string; actions: ExtensionActionInfo[] }>()
for (const item of available) {
const entry = map.get(item.extensionId) ?? { name: item.extensionName, actions: [] }
entry.actions.push(item)
map.set(item.extensionId, entry)
}
return Array.from(map.entries()).sort((left, right) =>
left[1].name.localeCompare(right[1].name)
)
}, [available])
const patchAt = (index: number, patch: Partial<AutomationAction>): void => {
onChange(
actions.map((action, current) => (current === index ? { ...action, ...patch } : action))
)
}
const removeAt = (index: number): void => {
onChange(actions.filter((_action, current) => current !== index))
}
const addAction = (): void => {
const info = available.find(
(item) => item.extensionId === pendingExtension && item.actionId === pendingAction
)
if (!info) return
const input: Record<string, unknown> = {}
if (info.inputSchema) {
for (const [key, field] of Object.entries(info.inputSchema.properties)) {
if (field.default !== undefined) input[key] = field.default
}
}
onChange([
...actions,
{
type: 'extensionAction',
enabled: true,
extensionId: info.extensionId,
actionId: info.actionId,
input
}
])
setPendingAction('')
}
const actionsOfSelectedExtension = pendingExtension
? available.filter((item) => item.extensionId === pendingExtension)
: []
return (
<div className="automation-extension-actions">
{extensionActions.length === 0 ? (
<p className="automation-muted">还没有扩展动作。扩展启用后这里会出现它注册的动作。</p>
) : (
extensionActions.map(({ action, index }) => {
const info = available.find(
(item) => item.extensionId === action.extensionId && item.actionId === action.actionId
)
const schema: ExtensionActionInputSchema | undefined = info?.inputSchema
const input = action.input ?? {}
return (
<div
key={`${action.extensionId}-${action.actionId}-${index}`}
className="automation-action-row"
>
<div className="automation-action-main">
<div className="automation-switch-row compact">
<div>
<span className="automation-field-label">
{info?.title || action.actionId || '未知动作'}
<span className="automation-extension-badge">
{info?.extensionName || action.extensionId}
</span>
</span>
<small>
{info?.available
? info.description || '扩展动作'
: info?.unavailableReason || '依赖的扩展不可用,规则会保留但无法执行'}
</small>
</div>
<Switch
checked={action.enabled}
onCheckedChange={(checked) => patchAt(index, { enabled: checked })}
/>
</div>
{schema && action.enabled && (
<div className="automation-extension-fields">
{Object.entries(schema.properties).map(([key, field]) => {
const required = schema.required?.includes(key) === true
const label = field.title || key
const value = input[key]
return (
<label key={key} className="automation-field">
<span className="automation-field-label">
{label}
{required && <span className="automation-required">*</span>}
</span>
{field.type === 'boolean' ? (
<Switch
checked={value === true}
onCheckedChange={(checked) =>
patchAt(index, { input: { ...input, [key]: checked } })
}
/>
) : (
<Input
type={field.type === 'string' ? 'text' : 'number'}
value={value === undefined || value === null ? '' : String(value)}
placeholder={field.description || ''}
onChange={(event) => {
const raw = event.target.value
const next: unknown =
field.type === 'string'
? raw
: raw === ''
? undefined
: Number(raw)
patchAt(index, { input: { ...input, [key]: next } })
}}
/>
)}
</label>
)
})}
</div>
)}
<div className="automation-extension-row-actions">
<Button size="sm" variant="ghost" onClick={() => removeAt(index)}>
移除
</Button>
</div>
</div>
</div>
)
})
)}
<div className="automation-extension-add">
<select
className="automation-select"
value={pendingExtension}
aria-label="选择扩展"
onChange={(event) => {
setPendingExtension(event.target.value)
setPendingAction('')
}}
>
<option value="">选择扩展…</option>
{groups.map(([extensionId, group]) => (
<option key={extensionId} value={extensionId}>
{group.name}
{group.actions.every((item) => !item.available) ? '(不可用)' : ''}
</option>
))}
</select>
<select
className="automation-select"
value={pendingAction}
aria-label="选择动作"
disabled={!pendingExtension}
onChange={(event) => setPendingAction(event.target.value)}
>
<option value="">选择动作…</option>
{actionsOfSelectedExtension.map((item) => (
<option key={item.actionId} value={item.actionId} disabled={!item.available}>
{item.title}
{item.available ? '' : `(${item.unavailableReason || '不可用'})`}
</option>
))}
</select>
<Button
size="sm"
variant="outline"
disabled={!pendingExtension || !pendingAction}
onClick={addAction}
>
添加扩展动作
</Button>
</div>
</div>
)
}
@@ -13,7 +13,9 @@ import {
} from '../../../../shared/automation'
import { Button, Input, SegmentedControl, SegmentedControlItem, Switch } from '../../components/ui'
import { EffectPreview } from './EffectPreview'
import { ExtensionActionList } from './ExtensionActionList'
import type { AutomationGroupOption } from './model/api'
import type { ExtensionActionInfo } from '../../../../shared/extensions/types'
/**
* RuleEditorPanel —— 规则编辑页(对应 Stitch 设计稿 1)。
@@ -90,19 +92,56 @@ export function RuleEditorPanel({
setValidationError('')
}, [rule])
/** 扩展动作列表:随扩展启用/停用自动刷新,规则里保存的引用不会被清掉。 */
const [extensionActions, setExtensionActions] = React.useState<ExtensionActionInfo[]>([])
React.useEffect(() => {
let active = true
const load = (): void => {
// 旧宿主或测试环境可能没有扩展 API:此时退化成「没有扩展动作」,
// 不能让整个规则编辑器崩掉。
const loader = window.api?.listExtensionActions
if (!loader) {
setExtensionActions([])
return
}
void Promise.resolve(loader.call(window.api))
.then((list) => {
if (active) setExtensionActions(Array.isArray(list) ? list : [])
})
.catch(() => undefined)
}
load()
const subscribe = window.api?.onExtensionChanged
const unsubscribe = subscribe ? subscribe.call(window.api, () => load()) : () => undefined
return () => {
active = false
unsubscribe()
}
}, [])
const patchConditions = (patch: Partial<AutomationRuleDraft['conditions']>): void => {
setDraft((current) => ({ ...current, conditions: { ...current.conditions, ...patch } }))
}
const patchAction = (type: AutomationActionType, patch: { enabled?: boolean; text?: string }): void => {
/**
* 按**索引**更新动作。
*
* 固定动作每类只有一条,但扩展动作可以有多条同类型:
* 按 `type` 批量更新会把它们一起改掉。
*/
const patchActionAt = (index: number, patch: { enabled?: boolean; text?: string }): void => {
if (index < 0) return
setDraft((current) => ({
...current,
actions: current.actions.map((action) =>
action.type === type ? { ...action, ...patch } : action
actions: current.actions.map((action, currentIndex) =>
currentIndex === index ? { ...action, ...patch } : action
)
}))
}
const indexOfType = (type: AutomationActionType): number =>
draft.actions.findIndex((action) => action.type === type)
const actionOf = (type: AutomationActionType): { enabled: boolean; text?: string } =>
draft.actions.find((action) => action.type === type) ?? { enabled: false }
@@ -268,7 +307,11 @@ export function RuleEditorPanel({
key={group.id}
className={`automation-group-option ${checked ? 'selected' : ''}`}
>
<input type="checkbox" checked={checked} onChange={() => toggleGroup(group.id)} />
<input
type="checkbox"
checked={checked}
onChange={() => toggleGroup(group.id)}
/>
<span>{group.name}</span>
</label>
)
@@ -305,9 +348,7 @@ export function RuleEditorPanel({
const next = Number(event.target.value)
setDraft((current) => ({
...current,
replyDelaySeconds: normalizeReplyDelaySeconds(
Number.isFinite(next) ? next : 0
)
replyDelaySeconds: normalizeReplyDelaySeconds(Number.isFinite(next) ? next : 0)
}))
}}
className="automation-number-input"
@@ -326,13 +367,17 @@ export function RuleEditorPanel({
</div>
<Switch
checked={action.enabled}
onCheckedChange={(checked) => patchAction(meta.type, { enabled: checked })}
onCheckedChange={(checked) =>
patchActionAt(indexOfType(meta.type), { enabled: checked })
}
/>
</div>
{meta.type === 'replyText' && action.enabled ? (
<Input
value={action.text ?? ''}
onChange={(event) => patchAction(meta.type, { text: event.target.value })}
onChange={(event) =>
patchActionAt(indexOfType(meta.type), { text: event.target.value })
}
placeholder={DEFAULT_REPLY_TEXT}
aria-label="回复内容"
/>
@@ -341,6 +386,18 @@ export function RuleEditorPanel({
</div>
)
})}
<div className="automation-subsection">
<div className="automation-subsection-heading">
<h4>执行扩展动作</h4>
<small>由扩展注册,参数按扩展声明的 Schema 填写</small>
</div>
<ExtensionActionList
actions={draft.actions}
available={extensionActions}
onChange={(next) => setDraft((current) => ({ ...current, actions: next }))}
/>
</div>
</section>
<section className="automation-section">
@@ -1,6 +1,5 @@
import * as React from 'react'
import {
AUTOMATION_RULE_TEMPLATES,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
describeLeaveNotificationNotifyScope,
describeLeaveNotificationTarget,
@@ -8,6 +7,7 @@ import {
describeRuleTrigger,
type AutomationRule
} from '../../../../shared/automation'
import type { ExtensionDeepLink } from '../../../../shared/extensions/types'
import { Button, Spinner, Switch } from '../../components/ui'
/**
@@ -40,6 +40,25 @@ export interface ScheduledReportCardModel {
nextRunLabel: string
}
/**
* 规则模板卡片的本机状态。
*
* 由工作区根据「官方模板目录 + 已安装扩展 + 运行状态」算出,
* 面板只负责渲染,不自己判断可用性。
*/
export interface RuleTemplateCardModel {
id: string
name: string
description: string
templateId: string
extensionId: string
/** 没有动作的模板只能打开配置,不能「用规则触发」。 */
actionId?: string
state: 'not-installed' | 'installed-disabled' | 'ready' | 'unavailable'
/** 不可用/需要处理时的真实原因。 */
reason?: string
}
export interface RuleListPanelProps {
rules: AutomationRule[]
groups: Array<{ id: string; name: string }>
@@ -55,6 +74,12 @@ export interface RuleListPanelProps {
onEditLeaveNotification: () => void
/** 打开「定时日报」规则类型(多条,所以是"管理"而不是"编辑")。 */
onManageScheduledReport: () => void
/** 规则模板卡片(真实状态)。 */
ruleTemplates?: RuleTemplateCardModel[]
/** 跳到扩展中心并定位模板/扩展/开发引导。 */
onOpenExtension?: (target: ExtensionDeepLink) => void
/** 用该模板预填一条引用扩展动作的规则。 */
onUseRuleTemplate?: (template: RuleTemplateCardModel) => void
}
/** 把规则里的 conversationIds 翻成群名;找不到时显示占位而不是裸 id。 */
@@ -92,7 +117,10 @@ export function RuleListPanel({
onDelete,
onCreate,
onEditLeaveNotification,
onManageScheduledReport
onManageScheduledReport,
ruleTemplates,
onOpenExtension,
onUseRuleTemplate
}: RuleListPanelProps): React.ReactElement {
// 退群通知有自己的卡片,别在「已配置的自动化」里重复渲染一遍。
const configuredRules = rules.filter((rule) => rule.id !== BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
@@ -267,16 +295,99 @@ export function RuleListPanel({
<h2>更多模板</h2>
</div>
<div className="automation-template-grid">
{AUTOMATION_RULE_TEMPLATES.map((template) => (
<article key={template.id} className="automation-template-card">
<div className="automation-template-title">
<h3>{template.name}</h3>
<span className="automation-template-flag">即将支持</span>
</div>
<p>{template.description}</p>
{template.unavailableReason ? <small>{template.unavailableReason}</small> : null}
</article>
))}
{(ruleTemplates ?? []).map((template) => {
const badge =
template.state === 'ready'
? '已就绪'
: template.state === 'installed-disabled'
? '已安装 · 未启用'
: template.state === 'not-installed'
? '未安装'
: '不可用'
return (
<article key={template.id} className="automation-template-card">
<div className="automation-template-title">
<h3>{template.name}</h3>
<span
className={
template.state === 'ready'
? 'automation-template-flag is-ready'
: 'automation-template-flag'
}
>
{badge}
</span>
</div>
<p>{template.description}</p>
{template.reason ? <small>{template.reason}</small> : null}
<div className="automation-template-actions">
{template.state === 'not-installed' && (
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ templateId: template.templateId })}
>
去扩展中心安装 →
</Button>
)}
{template.state === 'installed-disabled' && (
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ extensionId: template.extensionId })}
>
去启用 →
</Button>
)}
{template.state === 'ready' && (
<>
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ extensionId: template.extensionId })}
>
打开扩展配置 →
</Button>
{template.actionId ? (
<Button
variant="ghost"
size="sm"
onClick={() => onUseRuleTemplate?.(template)}
>
用规则触发
</Button>
) : (
<small className="automation-template-note">
该扩展没有注册自动化动作,靠消息事件触发
</small>
)}
</>
)}
</div>
</article>
)
})}
{/* 模板之外还要有出口:没有现成模板可用时,用户应该能自己做一个。 */}
<article className="automation-template-card is-guide">
<div className="automation-template-title">
<h3>做自己的扩展</h3>
</div>
<p>
从官方模板克隆一份代码,改完直接在本地调试;官方升级不会覆盖你的改动。 也可以链接已经
clone 到别处的项目。
</p>
<div className="automation-template-actions">
<Button
variant="outline"
size="sm"
onClick={() => onOpenExtension?.({ development: true })}
>
开始二次开发 →
</Button>
</div>
</article>
</div>
</section>
</div>
@@ -0,0 +1,85 @@
import * as React from 'react'
import { Button } from '../../components/ui'
import type { ExtensionTemplateEntry } from '../../../../shared/extensions/templates'
interface CreateProjectDialogProps {
template: ExtensionTemplateEntry
busy: boolean
onCancel: () => void
onSubmit: (input: { extensionId: string; name: string }) => void
}
const ID_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
/** 默认 id 从模板 id 派生,用户可以直接改。 */
function suggestExtensionId(templateId: string): string {
const suffix = templateId.replace(/[^a-z0-9-]/gi, '-').toLowerCase()
return `com.example.${suffix}-dev`
}
/**
* 从模板创建独立项目。
*
* 只收集「新 id」和「名称」:目录由调用方先选好,创建过程在主进程完成,
* 这里不做任何文件操作。
*/
export function CreateProjectDialog({
template,
busy,
onCancel,
onSubmit
}: CreateProjectDialogProps): React.ReactElement {
const [extensionId, setExtensionId] = React.useState(() =>
suggestExtensionId(template.templateId)
)
const [name, setName] = React.useState(`${template.name}(我的版本)`)
const trimmedId = extensionId.trim().toLowerCase()
const idValid = ID_PATTERN.test(trimmedId)
const conflictsWithTemplate = trimmedId === template.extensionId
const canSubmit = idValid && !conflictsWithTemplate && !busy
return (
<div className="extension-project-dialog" role="dialog" aria-label="从模板创建项目">
<h4>从「{template.name}」创建独立项目</h4>
<p className="extension-muted">
会在你选择的目录里生成完整源码;不会复制任何配置、Cookie 或聊天数据。
</p>
<label className="extension-field">
<span>扩展 ID</span>
<input
value={extensionId}
spellCheck={false}
onChange={(event) => setExtensionId(event.target.value)}
placeholder="com.acme.my-bot"
/>
</label>
{!idValid && (
<p className="extension-field-error">id 必须是反向域名格式(小写字母、数字、连字符)</p>
)}
{conflictsWithTemplate && (
<p className="extension-field-error">不能沿用模板原 id,否则会和官方模板冲突</p>
)}
<label className="extension-field">
<span>显示名称</span>
<input value={name} maxLength={60} onChange={(event) => setName(event.target.value)} />
</label>
<div className="extension-project-dialog-actions">
<Button size="sm" variant="ghost" disabled={busy} onClick={onCancel}>
取消
</Button>
<Button
size="sm"
disabled={!canSubmit}
onClick={() => onSubmit({ extensionId: trimmedId, name: name.trim() })}
>
{busy ? '创建中…' : '选择目录并创建'}
</Button>
</div>
</div>
)
}
@@ -0,0 +1,135 @@
import * as React from 'react'
import { Button } from '../../components/ui'
interface DevelopmentGuideProps {
/** 回到扩展列表。 */
onBack: () => void
/** 打开「从模板创建项目」:切到模板画廊并展开第一条可用模板。 */
onCreateProject: () => void
/** 链接已有本地项目。 */
onLinkProject: () => void
}
/**
* 二次开发引导。
*
* 这里**不复制文档正文**:文档在 `docs/extensions/`,正文改一次要同步两处必然不一致。
* 界面只负责把「从哪开始、做完在哪看效果」讲清楚,并指到文档。
*/
const DOCS: Array<{ name: string; file: string; description: string }> = [
{
name: '快速开始',
file: 'docs/extensions/getting-started.md',
description: '最小 manifest、目录结构、第一次跑起来'
},
{
name: '克隆与改造成自己的扩展',
file: 'docs/extensions/clone-and-customize.md',
description: '从官方模板复制代码、改 id、改成自己的逻辑'
},
{
name: 'API 参考',
file: 'docs/extensions/api-reference.md',
description: 'manifest 字段、权限表、tm.* 能力清单'
},
{
name: '架构与安全边界',
file: 'docs/extensions/architecture.md',
description: '代码在哪、数据在哪、页面为什么在 iframe 里'
}
]
export function DevelopmentGuide({
onBack,
onCreateProject,
onLinkProject
}: DevelopmentGuideProps): React.ReactElement {
return (
<div className="extension-development-guide">
<header className="extension-guide-header">
<div>
<h3>二次开发</h3>
<p>
扩展代码放在你自己的目录,TraceMemo 直接运行它。改完点「重新加载」即可生效,
不需要重新安装;官方升级也不会覆盖你的代码。
</p>
</div>
<Button size="sm" variant="ghost" onClick={onBack}>
← 返回扩展列表
</Button>
</header>
<ol className="extension-guide-steps">
<li>
<span className="extension-guide-index">1</span>
<div>
<strong>拿到一份代码</strong>
<p>
从官方模板生成独立项目(会替换成你自己的扩展 id),或直接链接已经在别处 clone
好的目录。
</p>
</div>
</li>
<li>
<span className="extension-guide-index">2</span>
<div>
<strong>链接到 TraceMemo</strong>
<p>
链接后代码不复制:宿主直接读你选的目录。配置、日志、缓存仍然写在 TraceMemo
的用户数据目录,不会污染你的仓库。
</p>
</div>
</li>
<li>
<span className="extension-guide-index">3</span>
<div>
<strong>改完重新加载</strong>
<p>
后台代码改动点「重新加载」;页面改动刷新 iframe 即可。Manifest 新增权限不会自动授予,
需要在详情页逐项确认。
</p>
</div>
</li>
</ol>
<div className="extension-guide-actions">
<Button size="sm" onClick={onCreateProject}>
从模板创建项目
</Button>
<Button size="sm" variant="outline" onClick={onLinkProject}>
链接本地项目
</Button>
</div>
<section className="extension-guide-docs">
<h4>开发文档</h4>
<ul>
{DOCS.map((doc) => (
<li key={doc.file}>
<div>
<strong>{doc.name}</strong>
<span className="extension-muted">{doc.description}</span>
</div>
<code>{doc.file}</code>
</li>
))}
</ul>
<p className="extension-muted">
文档随仓库分发,路径以上方为准;打包后的应用里不包含 docs 目录。
</p>
</section>
<section className="extension-guide-boundary">
<h4>几个边界</h4>
<ul>
<li>不会自动安装、自动启用或自动创建规则——每一步都要你点。</li>
<li>移除链接只断开引用,不会删除你的项目目录。</li>
<li>
页面跑在 sandbox iframe 里,只能调用你自己后台注册的处理器,拿不到 Node 或
<code>window.api</code>。
</li>
</ul>
</section>
</div>
)
}
@@ -0,0 +1,230 @@
import * as React from 'react'
import {
EXTENSION_PERMISSION_INFO,
sortPermissionsByRisk,
type ExtensionPermission
} from '../../../../shared/extensions/permissions'
import type { ExtensionTemplateStatus } from '../../../../shared/extensions/templates'
import { Button, Spinner } from '../../components/ui'
interface ExtensionTemplateGalleryProps {
templates: ExtensionTemplateStatus[]
loading: boolean
busyId: string | null
onInstall: (templateId: string) => void
/** 从该模板生成独立项目;未提供时不显示入口。 */
onCreateProject?: (templateId: string) => void
/** 深链定位:自动展开该模板的详情。 */
focusTemplateId?: string | null
}
const STATE_LABELS: Record<ExtensionTemplateStatus['state'], string> = {
'not-installed': '未安装',
installed: '已安装',
'update-available': '有更新',
conflict: '已被占用',
unsupported: '不支持当前平台',
damaged: '资源损坏'
}
function stateTone(state: ExtensionTemplateStatus['state']): string {
if (state === 'not-installed' || state === 'installed') return 'muted'
if (state === 'update-available') return 'warning'
return 'danger'
}
function formatBytes(bytes: number): string {
if (!bytes) return '—'
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
/**
* 官方模板画廊。
*
* 只负责展示与触发安装;是否可安装、装完是什么状态全部来自主进程,
* 这里不做第二套判断,避免界面和实际能力说两套话。
*/
export function ExtensionTemplateGallery({
templates,
loading,
busyId,
onInstall,
onCreateProject,
focusTemplateId
}: ExtensionTemplateGalleryProps): React.ReactElement {
const [expanded, setExpanded] = React.useState<string | null>(null)
// 深链进来时展开目标模板;滚动交给浏览器默认行为即可。
React.useEffect(() => {
if (focusTemplateId) setExpanded(focusTemplateId)
}, [focusTemplateId])
if (loading) {
return (
<div className="extension-template-empty">
<Spinner />
<p>正在读取官方模板…</p>
</div>
)
}
if (templates.length === 0) {
return (
<div className="extension-template-empty">
<h3>官方模板</h3>
<p>当前安装包没有携带模板资源。如果你是从源码运行,请先执行模板构建脚本。</p>
</div>
)
}
return (
<div className="extension-template-gallery">
<header className="extension-template-header">
<div>
<h3>官方模板</h3>
<p>安装后仍需你确认权限并手动启用,不会自动运行。</p>
</div>
</header>
<ul className="extension-template-list">
{templates.map((item) => {
const { template } = item
const isOpen = expanded === template.templateId
const canInstall = item.state === 'not-installed' || item.state === 'update-available'
const blocked =
item.state === 'conflict' || item.state === 'damaged' || item.state === 'unsupported'
const missingBlocking = item.dependencies.checks.filter(
(check) => check.blocking && !check.ok
)
return (
<li key={template.templateId} className="extension-template-card">
<div className="extension-template-card-head">
<div>
<div className="extension-template-title">
<strong>{template.name}</strong>
<span className="extension-template-version">v{template.version}</span>
<span className={`extension-grant tone-${stateTone(item.state)}`}>
{STATE_LABELS[item.state]}
</span>
</div>
<p className="extension-template-desc">
{template.description || '官方提供的扩展示例。'}
</p>
<p className="extension-template-meta">
{template.fileCount} 个文件 · {formatBytes(template.bytes)}
{item.installedVersion && item.state !== 'not-installed'
? ` · 已安装 v${item.installedVersion}`
: ''}
</p>
</div>
<div className="extension-template-actions">
<Button
size="sm"
variant="ghost"
onClick={() => setExpanded(isOpen ? null : template.templateId)}
>
{isOpen ? '收起详情' : '查看详情'}
</Button>
{onCreateProject && (
<Button
size="sm"
variant="outline"
disabled={busyId === `create:${template.templateId}`}
onClick={() => onCreateProject(template.templateId)}
>
创建项目
</Button>
)}
<Button
size="sm"
disabled={!canInstall || busyId === template.templateId}
onClick={() => onInstall(template.templateId)}
>
{busyId === template.templateId
? '安装中…'
: item.state === 'update-available'
? '更新'
: '安装'}
</Button>
</div>
</div>
{item.message && <p className="extension-template-warning">{item.message}</p>}
{missingBlocking.length > 0 && (
<p className="extension-template-warning">
缺少 {missingBlocking.map((check) => check.label).join('、')}
:安装后可以查看配置页,但主要功能暂时不可用。
</p>
)}
{isOpen && (
<div className="extension-template-detail">
<section>
<h4>权限</h4>
<ul className="extension-permission-list">
{sortPermissionsByRisk(template.permissions).map(
(permission: ExtensionPermission) => (
<li key={permission}>
<div>
<span className="extension-permission-label">
{EXTENSION_PERMISSION_INFO[permission].label}
</span>
<span
className={`extension-permission-risk risk-${EXTENSION_PERMISSION_INFO[permission].risk}`}
>
{EXTENSION_PERMISSION_INFO[permission].risk === 'high'
? '高'
: EXTENSION_PERMISSION_INFO[permission].risk === 'medium'
? '中'
: '低'}
</span>
</div>
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
</li>
)
)}
</ul>
</section>
<section>
<h4>依赖</h4>
{item.dependencies.checks.length === 0 ? (
<p className="extension-muted">该模板不需要额外依赖。</p>
) : (
<ul className="extension-template-deps">
{item.dependencies.checks.map((check) => (
<li key={check.id}>
<span
className={`extension-dot ${check.ok ? 'is-ok' : 'is-missing'}`}
/>
<span>{check.label}</span>
<span className="extension-muted">{check.detail}</span>
</li>
))}
</ul>
)}
</section>
</div>
)}
{item.state === 'conflict' && (
<p className="extension-muted">
你之前用同一扩展 ID 安装过其他来源的扩展。请先卸载它,或改用「安装 ZIP」手动更新。
</p>
)}
{blocked && item.state === 'damaged' && (
<p className="extension-muted">
模板资源与你安装的版本不匹配,建议重新安装 TraceMemo。
</p>
)}
</li>
)
})}
</ul>
</div>
)
}
@@ -7,10 +7,19 @@ import {
import type {
ExtensionLogEntry,
ExtensionPageDescriptor,
ExtensionSystemHealth,
InstalledExtension
} from '../../../../shared/extensions/types'
import type {
ExtensionTemplateEntry,
ExtensionTemplateStatus
} from '../../../../shared/extensions/templates'
import type { ExtensionDeepLink } from '../../../../shared/extensions/types'
import { Button, Spinner, useToast } from '../../components/ui'
import { ExtensionPageHost } from './ExtensionPageHost'
import { CreateProjectDialog } from './CreateProjectDialog'
import { DevelopmentGuide } from './DevelopmentGuide'
import { ExtensionTemplateGallery } from './ExtensionTemplateGallery'
const STATUS_LABELS: Record<InstalledExtension['runtime']['state'], string> = {
inactive: '未运行',
@@ -32,7 +41,17 @@ function statusTone(extension: InstalledExtension): 'success' | 'warning' | 'dan
return 'warning'
}
export function ExtensionWorkspace(): React.ReactElement {
export interface ExtensionWorkspaceProps {
/** 从其它页面跳过来时的定位目标。 */
deepLink?: ExtensionDeepLink | null
/** 消费后清空,避免返回再进来又跳一次。 */
onConsumeDeepLink?: () => void
}
export function ExtensionWorkspace({
deepLink,
onConsumeDeepLink
}: ExtensionWorkspaceProps = {}): React.ReactElement {
const { toast } = useToast()
const [extensions, setExtensions] = React.useState<InstalledExtension[]>([])
const [selectedId, setSelectedId] = React.useState<string | null>(null)
@@ -41,10 +60,36 @@ export function ExtensionWorkspace(): React.ReactElement {
const [page, setPage] = React.useState<ExtensionPageDescriptor | null>(null)
const [pendingEnable, setPendingEnable] = React.useState<InstalledExtension | null>(null)
const [pendingUninstall, setPendingUninstall] = React.useState<string | null>(null)
const [health, setHealth] = React.useState<ExtensionSystemHealth | null>(null)
const [templates, setTemplates] = React.useState<ExtensionTemplateStatus[]>([])
const [templatesLoading, setTemplatesLoading] = React.useState(true)
const [installingTemplate, setInstallingTemplate] = React.useState<string | null>(null)
/** 右侧主区域:扩展列表 or 官方模板画廊。 */
const [view, setView] = React.useState<'extensions' | 'templates' | 'guide'>('extensions')
/** 深链定位的模板:进入画廊时自动展开它。 */
const [focusedTemplateId, setFocusedTemplateId] = React.useState<string | null>(null)
/** 正在创建项目的模板;非空时显示创建对话框。 */
const [creatingTemplate, setCreatingTemplate] = React.useState<ExtensionTemplateEntry | null>(
null
)
/** 高风险权限的二次确认;低风险直接授权。 */
const [pendingGrant, setPendingGrant] = React.useState<{
extensionId: string
permission: ExtensionPermission
} | null>(null)
/** 「转为正式安装」的二次确认。 */
const [pendingConvert, setPendingConvert] = React.useState<InstalledExtension | null>(null)
const refresh = React.useCallback(async (): Promise<void> => {
const list = await window.api.listExtensions()
const [list, systemHealth, templateList] = await Promise.all([
window.api.listExtensions(),
window.api.getExtensionHealth().catch(() => null),
window.api.listExtensionTemplates().catch(() => [])
])
setExtensions(list)
setHealth(systemHealth)
setTemplates(templateList)
setTemplatesLoading(false)
setSelectedId((current) => {
if (current && list.some((item) => item.id === current)) return current
return list[0]?.id ?? null
@@ -59,6 +104,26 @@ export function ExtensionWorkspace(): React.ReactElement {
return unsubscribe
}, [refresh])
/**
* 消费深链:只切视图与选中项,不触发任何安装/启用动作。
* 真正的操作仍要用户在界面上点。
*/
React.useEffect(() => {
if (!deepLink) return
if (deepLink.development) {
setView('guide')
}
if (deepLink.templateId) {
setView('templates')
setFocusedTemplateId(deepLink.templateId)
}
if (deepLink.extensionId) {
setView('extensions')
setSelectedId(deepLink.extensionId)
}
onConsumeDeepLink?.()
}, [deepLink, onConsumeDeepLink])
const selected = React.useMemo(
() => extensions.find((item) => item.id === selectedId) ?? null,
[extensions, selectedId]
@@ -179,6 +244,284 @@ export function ExtensionWorkspace(): React.ReactElement {
}
}
/** 授权 manifest 新声明的权限;后台会重启,新能力立即生效。 */
const grantPending = async (extension: InstalledExtension): Promise<void> => {
if (extension.pendingPermissions.length === 0) return
const result = await run(() =>
window.api.grantExtensionPermissions(extension.id, extension.pendingPermissions)
)
if (result?.success) {
toast({ title: '权限已更新', description: extension.name, variant: 'success' })
await refresh()
} else if (result && !result.success) {
toast({
title: '授权失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
/** 重置损坏的扩展配置;损坏现场已经由存储层另存。 */
const resetStorage = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.resetExtensionStorage(extension.id))
if (result?.success) {
toast({ title: '配置已重置', description: extension.name, variant: 'success' })
await refresh()
} else if (result && !result.success) {
toast({
title: '重置失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const grantPermission = async (
extension: InstalledExtension,
permission: ExtensionPermission
): Promise<void> => {
const result = await run(() => window.api.grantExtensionPermissions(extension.id, [permission]))
setPendingGrant(null)
if (result?.success) {
toast({
title: '已授权',
description: EXTENSION_PERMISSION_INFO[permission].label,
variant: 'success'
})
await refresh()
} else if (result && !result.success) {
toast({
title: '授权失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const revokePermission = async (
extension: InstalledExtension,
permission: ExtensionPermission
): Promise<void> => {
const result = await run(() => window.api.revokeExtensionPermission(extension.id, permission))
if (result?.success) {
toast({
title: '已撤销',
description: EXTENSION_PERMISSION_INFO[permission].label,
variant: 'success'
})
await refresh()
} else if (result && !result.success) {
toast({
title: '撤销失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
/** 接受从备份恢复出来的配置;之后才允许启用该扩展。 */
const acknowledgeStorage = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.acknowledgeExtensionStorage(extension.id))
if (result?.success) {
toast({ title: '已接受恢复的配置', description: '现在可以启用该扩展', variant: 'success' })
await refresh()
}
}
/** 把状态记录的版本对齐到磁盘上的 manifest。 */
const adoptInstalledCode = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.adoptExtensionCode(extension.id))
if (result?.success) {
toast({ title: '已采用当前代码版本', description: extension.name, variant: 'success' })
await refresh()
}
}
/** 把升级过渡备份换回来。 */
const rollbackUpgrade = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.rollbackExtensionUpgrade(extension.id))
if (result?.success) {
toast({ title: '已回滚到备份版本', description: extension.name, variant: 'success' })
await refresh()
}
}
/** 确认「状态文件曾损坏并恢复」,只清除提示。 */
const acknowledgeRecovery = async (): Promise<void> => {
const result = await run(() => window.api.acknowledgeExtensionRecovery())
if (result?.success) await refresh()
}
const installTemplate = async (templateId: string): Promise<void> => {
setInstallingTemplate(templateId)
try {
const result = await window.api.installExtensionTemplate(templateId)
if (!result.success) {
toast({
title: '模板安装失败',
description: result.error?.message || '安装失败',
variant: 'destructive'
})
return
}
await refresh()
setView('extensions')
if (result.extension) setSelectedId(result.extension.id)
toast({
title: '模板已安装',
description: `${result.extension?.name || ''} 需要你确认权限后手动启用`.trim(),
variant: 'success'
})
} catch (error) {
toast({
title: '模板安装失败',
description: error instanceof Error ? error.message : String(error),
variant: 'destructive'
})
} finally {
setInstallingTemplate(null)
}
}
/** 链接外部开发项目;目录由主进程再校验一次。 */
const linkProject = async (): Promise<void> => {
const directory = await window.api.pickExtensionProjectDirectory()
if (!directory) return
const result = await run(() => window.api.linkExtensionDevelopment(directory))
if (result?.success) {
toast({
title: '已链接开发项目',
description: '确认权限后即可启用;修改代码后可点「重新加载」',
variant: 'success'
})
await refresh()
setView('extensions')
if (result.extension) setSelectedId(result.extension.id)
} else if (result && !result.success) {
toast({
title: '链接失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const submitCreateProject = async (input: {
extensionId: string
name: string
}): Promise<void> => {
const template = creatingTemplate
if (!template) return
const targetDirectory = await window.api.pickExtensionProjectDirectory()
if (!targetDirectory) return
setInstallingTemplate(`create:${template.templateId}`)
try {
const result = await window.api.createExtensionProject({
templateId: template.templateId,
targetDirectory,
extensionId: input.extensionId,
name: input.name
})
if (!result.success) {
toast({
title: '创建项目失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
return
}
setCreatingTemplate(null)
toast({
title: '项目已生成',
description: result.projectPath || '',
variant: 'success'
})
await refresh()
} finally {
setInstallingTemplate(null)
}
}
const reloadDevelopment = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.reloadExtensionDevelopment(extension.id))
if (result?.success) {
toast({ title: '已重新加载', description: extension.name, variant: 'success' })
} else if (result && !result.success) {
toast({
title: '重新加载失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
await refresh()
}
const unlinkDevelopment = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.unlinkExtensionDevelopment(extension.id, true))
if (result?.success) {
toast({
title: '已移除开发链接',
description: '外部源码目录没有被删除',
variant: 'success'
})
await refresh()
} else if (result && !result.success) {
toast({
title: '移除失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const convertDevelopment = async (extension: InstalledExtension): Promise<void> => {
const result = await run(() => window.api.convertExtensionDevelopment(extension.id))
if (result?.success) {
toast({ title: '已转为正式安装', description: extension.name, variant: 'success' })
await refresh()
} else if (result && !result.success) {
toast({
title: '转换失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const exportProject = async (extension: InstalledExtension): Promise<void> => {
const targetDirectory = await window.api.pickExtensionProjectDirectory()
if (!targetDirectory) return
const result = await run(() =>
window.api.exportExtensionAsProject(extension.id, targetDirectory)
)
if (result?.success) {
toast({
title: '已导出为开发项目',
description: result.projectPath || '',
variant: 'success'
})
await refresh()
} else if (result && !result.success) {
toast({
title: '导出失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const openDevelopmentSource = async (extension: InstalledExtension): Promise<void> => {
const result = await window.api.openExtensionDevelopmentSource(extension.id)
if (!result.success) {
toast({
title: '无法打开源码目录',
description: result.error?.message || '目录不可用',
variant: 'destructive'
})
}
}
if (page) {
return (
<ExtensionPageHost
@@ -201,6 +544,52 @@ export function ExtensionWorkspace(): React.ReactElement {
</div>
<span className="extension-count">{extensions.length}</span>
</header>
{health && health.registry.state !== 'ok' && (
<div className="extension-health-banner">
<span>
{health.registry.state === 'unreadable'
? '扩展状态文件损坏且无法恢复,已停止写入以保留现场。请保留 extensions-state 下的损坏文件。'
: health.registry.message || '扩展状态文件曾损坏,已自动恢复。'}
</span>
{health.registry.state !== 'unreadable' && (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void acknowledgeRecovery()}
>
我知道了
</Button>
)}
</div>
)}
<Button
size="sm"
variant={view === 'templates' ? 'default' : 'outline'}
className="extension-template-entry"
onClick={() => setView(view === 'templates' ? 'extensions' : 'templates')}
>
官方模板{templates.length > 0 ? ` (${templates.length})` : ''}
</Button>
<Button
size="sm"
variant="outline"
className={
view === 'guide' ? 'extension-template-entry is-active' : 'extension-template-entry'
}
onClick={() => setView(view === 'guide' ? 'extensions' : 'guide')}
>
二次开发
</Button>
<Button
size="sm"
variant="outline"
className="extension-template-entry"
disabled={busy}
onClick={() => void linkProject()}
>
链接本地项目
</Button>
<div className="extension-install-row">
<Button
size="sm"
@@ -252,7 +641,25 @@ export function ExtensionWorkspace(): React.ReactElement {
</aside>
<section className="extension-detail" aria-label="扩展详情">
{!selected ? (
{view === 'guide' ? (
<DevelopmentGuide
onBack={() => setView('extensions')}
onCreateProject={() => setView('templates')}
onLinkProject={() => void linkProject()}
/>
) : view === 'templates' ? (
<ExtensionTemplateGallery
templates={templates}
loading={templatesLoading}
busyId={installingTemplate}
onInstall={(templateId) => void installTemplate(templateId)}
focusTemplateId={focusedTemplateId}
onCreateProject={(templateId) => {
const found = templates.find((item) => item.template.templateId === templateId)
if (found) setCreatingTemplate(found.template)
}}
/>
) : !selected ? (
<div className="extension-detail-empty">
<h3>选择左侧的扩展</h3>
<p>安装后在这里查看权限、页面、自动化动作与执行日志。</p>
@@ -277,8 +684,52 @@ export function ExtensionWorkspace(): React.ReactElement {
{selected.compatibility.reason || '扩展与当前版本不兼容'}
</p>
)}
{selected.storage.state !== 'ok' && (
<div className="extension-runtime-error extension-alert-row">
<span>
{selected.storage.state === 'recovered-from-backup'
? '扩展配置曾损坏,已从备份恢复;确认前不会启动。'
: '扩展配置损坏且没有可用备份,写入已停止。可在下方重置配置。'}
</span>
{selected.storage.state === 'recovered-from-backup' && (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void acknowledgeStorage(selected)}
>
使用恢复的配置
</Button>
)}
</div>
)}
{selected.runtime.note && (
<p className="extension-muted">{selected.runtime.note}</p>
)}
{selected.runtime.lastError && (
<p className="extension-runtime-error">{selected.runtime.lastError}</p>
<div className="extension-runtime-error extension-alert-row">
<span>{selected.runtime.lastError}</span>
{selected.runtime.lastError.includes('升级可能中断') && (
<>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void adoptInstalledCode(selected)}
>
采用当前代码
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void rollbackUpgrade(selected)}
>
回滚到备份
</Button>
</>
)}
</div>
)}
</div>
<div className="extension-detail-actions">
@@ -344,8 +795,107 @@ export function ExtensionWorkspace(): React.ReactElement {
)}
</section>
{selected.development && (
<section className="extension-card">
<div className="extension-card-header">
<h4>开发模式</h4>
<span
className={`extension-grant ${selected.development.available ? 'is-granted' : ''}`}
>
{selected.development.available ? '源码可用' : '源码不可用'}
</span>
</div>
<p className="extension-muted extension-source-path">
{selected.development.sourcePath || '未记录源码路径'}
</p>
{!selected.development.available && (
<p className="extension-runtime-error">
源码目录被移动或删除。扩展配置与规则都还在,重新链接后即可继续。
</p>
)}
{pendingConvert?.id === selected.id && (
<div className="extension-confirm-block">
<p>
将把当前源码<strong>复制</strong>到 TraceMemo
用户数据目录,之后运行的是这份安装副本。
外部源码目录不会被删除,但你之后对它的修改<strong>不会</strong>
自动同步过去。
转换会停止当前后台,转换后保持「未启用」;已有配置、规则与缓存都保留。
</p>
<div className="extension-confirm-actions">
<Button
size="sm"
disabled={busy}
onClick={() => {
const target = pendingConvert
setPendingConvert(null)
if (target) void convertDevelopment(target)
}}
>
确认转换
</Button>
<Button size="sm" variant="ghost" onClick={() => setPendingConvert(null)}>
取消
</Button>
</div>
</div>
)}
<div className="extension-detail-actions">
<Button
size="sm"
variant="outline"
disabled={busy || !selected.development.available}
onClick={() => void reloadDevelopment(selected)}
>
重新加载
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy || !selected.development.available}
onClick={() => void openDevelopmentSource(selected)}
>
打开源码目录
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => setPendingConvert(selected)}
>
转为正式安装
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void unlinkDevelopment(selected)}
>
移除链接
</Button>
</div>
</section>
)}
<section className="extension-card">
<h4>权限</h4>
<div className="extension-card-header">
<h4>权限</h4>
{selected.pendingPermissions.length > 0 && (
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => void grantPending(selected)}
>
授权新增权限
</Button>
)}
</div>
{selected.pendingPermissions.length > 0 && (
<p className="extension-muted">
新版本申请了 {selected.pendingPermissions.length} 项尚未授予的权限,当前不可用。
</p>
)}
{selected.permissions.length === 0 ? (
<p className="extension-muted">未申请任何权限。</p>
) : (
@@ -367,11 +917,59 @@ export function ExtensionWorkspace(): React.ReactElement {
</span>
</div>
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
<span
className={`extension-grant ${selected.grantedPermissions.includes(permission) ? 'is-granted' : ''}`}
>
{selected.grantedPermissions.includes(permission) ? '已授予' : '未授予'}
</span>
{selected.grantedPermissions.includes(permission) ? (
<div className="extension-permission-actions">
<span className="extension-grant is-granted">已授予</span>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void revokePermission(selected, permission)}
>
撤销
</Button>
</div>
) : (
<div className="extension-permission-actions">
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => {
if (EXTENSION_PERMISSION_INFO[permission].risk === 'high') {
setPendingGrant({ extensionId: selected.id, permission })
} else {
void grantPermission(selected, permission)
}
}}
>
授权
</Button>
</div>
)}
{pendingGrant?.extensionId === selected.id &&
pendingGrant.permission === permission && (
<div className="extension-confirm-row">
<span>
该权限可以代替你执行敏感操作,确认授予「
{EXTENSION_PERMISSION_INFO[permission].label}」?
</span>
<Button
size="sm"
disabled={busy}
onClick={() => void grantPermission(selected, permission)}
>
确认授权
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setPendingGrant(null)}
>
取消
</Button>
</div>
)}
</li>
))}
</ul>
@@ -431,6 +1029,26 @@ export function ExtensionWorkspace(): React.ReactElement {
<footer className="extension-detail-footer">
<span>安装于 {formatTimestamp(selected.installedAt)}</span>
{!selected.development && (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void exportProject(selected)}
>
导出为开发项目
</Button>
)}
{selected.storage.state === 'unrecovered' && (
<Button
size="sm"
variant="destructive"
disabled={busy}
onClick={() => void resetStorage(selected)}
>
重置配置
</Button>
)}
{pendingUninstall === selected.id ? (
<span className="extension-uninstall-confirm">
卸载后扩展代码会被移除,配置与数据默认保留。
@@ -455,6 +1073,15 @@ export function ExtensionWorkspace(): React.ReactElement {
)}
</section>
{creatingTemplate && (
<CreateProjectDialog
template={creatingTemplate}
busy={installingTemplate === `create:${creatingTemplate.templateId}`}
onCancel={() => setCreatingTemplate(null)}
onSubmit={(input) => void submitCreateProject(input)}
/>
)}
{pendingEnable && (
<div className="extension-modal-backdrop" role="dialog" aria-modal="true">
<div className="extension-modal">
+31
View File
@@ -1764,3 +1764,34 @@
font-size: 12px;
line-height: 18px;
}
/* 规则模板卡片的真实状态与操作入口 */
.automation-template-flag.is-ready {
color: var(--tm-success, #15803d);
border-color: color-mix(in srgb, var(--tm-success, #15803d) 35%, transparent);
background: color-mix(in srgb, var(--tm-success, #15803d) 10%, transparent);
}
.automation-template-actions {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
flex-wrap: wrap;
}
.automation-template-note {
color: var(--tm-text-muted, #6b7280);
font-size: 12px;
line-height: 18px;
}
/* 「做自己的扩展」引导卡:和模板卡同宽,但用虚线边框区分它不是模板 */
.automation-template-card.is-guide {
border-style: dashed;
background: transparent;
}
.automation-template-card.is-guide h3 {
color: var(--tm-text-muted, #6b7280);
}
+433
View File
@@ -251,6 +251,28 @@
line-height: 18px;
}
/* 状态文件损坏/降级提示:需要跨整行提醒,不能只在详情页里出现。 */
.extension-health-banner {
margin: 0 0 10px;
padding: 8px 10px;
border-radius: var(--wxex-radius-sm);
background: color-mix(in srgb, var(--wxex-warning, #b45309) 12%, transparent);
color: var(--wxex-warning, #b45309);
font-size: 12px;
line-height: 18px;
}
.extension-pending-list {
margin: 6px 0 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
color: var(--wxex-text-muted);
}
.extension-detail-actions {
display: flex;
align-items: center;
@@ -595,3 +617,414 @@
grid-template-columns: minmax(0, 1fr);
}
}
/* ── 官方模板画廊 ─────────────────────────────────────────── */
.extension-template-entry {
width: 100%;
margin-bottom: 8px;
}
.extension-template-gallery {
display: flex;
flex-direction: column;
gap: 12px;
padding: 4px 2px 24px;
overflow-y: auto;
}
.extension-template-header h3 {
margin: 0;
font-size: 15px;
font-weight: 600;
}
.extension-template-header p {
margin: 4px 0 0;
font-size: 12px;
color: var(--wxex-text-muted);
}
.extension-template-list {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 10px;
}
.extension-template-card {
padding: 12px 14px;
border: 1px solid color-mix(in srgb, currentColor 12%, transparent);
border-radius: var(--wxex-radius-md, 10px);
background: color-mix(in srgb, currentColor 3%, transparent);
}
.extension-template-card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.extension-template-title {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.extension-template-version {
font-size: 12px;
color: var(--wxex-text-muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.extension-template-desc {
margin: 6px 0 0;
font-size: 12px;
line-height: 18px;
color: var(--wxex-text-muted);
}
.extension-template-meta {
margin: 4px 0 0;
font-size: 11px;
color: var(--wxex-text-muted);
}
.extension-template-actions {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
.extension-template-warning {
margin: 8px 0 0;
padding: 6px 10px;
border-radius: var(--wxex-radius-sm);
background: color-mix(in srgb, var(--wxex-warning, #b45309) 10%, transparent);
color: var(--wxex-warning, #b45309);
font-size: 12px;
line-height: 18px;
}
.extension-template-detail {
margin-top: 10px;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.extension-template-detail h4 {
margin: 0 0 6px;
font-size: 12px;
font-weight: 600;
}
.extension-template-deps {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 6px;
font-size: 12px;
}
.extension-template-deps li {
display: flex;
align-items: center;
gap: 6px;
}
.extension-dot {
width: 7px;
height: 7px;
border-radius: 999px;
flex-shrink: 0;
background: var(--wxex-text-muted);
}
.extension-dot.is-ok {
background: var(--wxex-success, #15803d);
}
.extension-dot.is-missing {
background: var(--wxex-danger);
}
.extension-template-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 48px 16px;
text-align: center;
color: var(--wxex-text-muted);
}
.extension-template-empty h3 {
margin: 0;
font-size: 14px;
color: inherit;
}
.extension-template-empty p {
margin: 0;
font-size: 12px;
line-height: 18px;
max-width: 420px;
}
/* 横幅与告警条需要「一句话 + 一个按钮」并排 */
.extension-health-banner,
.extension-alert-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.extension-health-banner span,
.extension-alert-row span {
flex: 1;
min-width: 0;
}
/* ── 开发项目 ─────────────────────────────────────────────── */
.extension-project-dialog {
position: fixed;
z-index: 40;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: min(460px, calc(100vw - 48px));
padding: 18px 20px;
border-radius: var(--wxex-radius-md, 10px);
border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
background: var(--wxex-surface, #fff);
box-shadow: 0 18px 48px color-mix(in srgb, currentColor 18%, transparent);
display: flex;
flex-direction: column;
gap: 10px;
}
.extension-project-dialog h4 {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.extension-project-dialog p {
margin: 0;
font-size: 12px;
line-height: 18px;
}
.extension-field {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
}
.extension-field input {
height: 30px;
padding: 0 10px;
border-radius: var(--wxex-radius-sm);
border: 1px solid color-mix(in srgb, currentColor 18%, transparent);
background: transparent;
color: inherit;
font-size: 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.extension-field-error {
color: var(--wxex-danger);
font-size: 11px;
}
.extension-project-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 4px;
}
.extension-source-path {
word-break: break-all;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
/* ── 二次开发引导页 ───────────────────────────────────────── */
.extension-development-guide {
display: flex;
flex-direction: column;
gap: 22px;
padding: 2px 2px 24px;
overflow-y: auto;
}
.extension-guide-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
/* 标题块可以被压缩,右侧按钮不能:窄窗口下「返回扩展列表」不该折成两行 */
.extension-guide-header > div {
min-width: 0;
}
.extension-guide-header > button {
flex-shrink: 0;
white-space: nowrap;
}
.extension-guide-header h3 {
margin: 0 0 6px;
font-size: 15px;
font-weight: 600;
}
.extension-guide-header p {
margin: 0;
max-width: 620px;
font-size: 12px;
line-height: 19px;
color: var(--wxex-text-muted);
}
/* 序号自己画,关掉 <ol> 的默认 marker,否则会出现「1.」和徽标两套编号 */
.extension-guide-steps {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 16px;
}
.extension-guide-steps li {
display: flex;
align-items: flex-start;
gap: 10px;
}
.extension-guide-index {
flex: 0 0 20px;
width: 20px;
height: 20px;
margin-top: 1px;
border-radius: 999px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 11px;
font-weight: 600;
color: var(--wxex-text-muted);
background: color-mix(in srgb, currentColor 9%, transparent);
}
.extension-guide-steps strong {
display: block;
font-size: 13px;
font-weight: 600;
line-height: 20px;
}
.extension-guide-steps p {
margin: 3px 0 0;
font-size: 12px;
line-height: 19px;
color: var(--wxex-text-muted);
}
.extension-guide-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.extension-guide-docs h4,
.extension-guide-boundary h4 {
margin: 0 0 10px;
font-size: 12px;
font-weight: 600;
}
.extension-guide-docs ul,
.extension-guide-boundary ul {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 12px;
}
.extension-guide-docs li {
display: flex;
flex-direction: column;
gap: 3px;
}
.extension-guide-docs li > div {
display: flex;
align-items: baseline;
gap: 8px;
flex-wrap: wrap;
}
.extension-guide-docs strong {
font-size: 12px;
font-weight: 600;
}
.extension-guide-docs code {
font-size: 11px;
line-height: 16px;
color: var(--wxex-text-muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.extension-guide-docs > p {
margin: 10px 0 0;
font-size: 11px;
line-height: 17px;
}
.extension-guide-boundary li {
position: relative;
padding-left: 12px;
font-size: 12px;
line-height: 19px;
color: var(--wxex-text-muted);
}
.extension-guide-boundary li::before {
content: '·';
position: absolute;
left: 2px;
color: var(--wxex-text-muted);
}
.extension-guide-boundary code {
font-size: 11px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
/* 侧栏里被选中的次级入口:不抢主操作,只做位置指示 */
.extension-template-entry.is-active {
border-color: color-mix(in srgb, currentColor 26%, transparent);
background: color-mix(in srgb, currentColor 6%, transparent);
}
+28 -6
View File
@@ -744,19 +744,41 @@ export interface AutomationRuleTemplate {
id: string
name: string
description: string
/** 该能力是否已经真正接通。 */
available: boolean
/** 未接通时的说明文案。 */
unavailableReason?: string
/** 提供该能力的官方模板 id(扩展中心里的模板目录)。 */
templateId: string
/** 提供该能力的扩展 id。 */
extensionId: string
/**
* 该模板要引用的扩展动作 id。
*
* **可选**:有些扩展(如抖音搬运)只靠消息事件驱动,没有注册自动化动作。
* 它们仍然要出现在这里——用户需要从这里找到入口——只是不能「用规则触发」。
*/
actionId?: string
}
/**
* 规则模板目录。
*
* 这里只描述「模板依赖哪个官方模板 / 扩展 / 动作」,**不描述可用性**:
* 能不能用取决于本机是否装了、启用了、授权了,那是运行时事实,
* 写在常量里必然过期。
*/
export const AUTOMATION_RULE_TEMPLATES: AutomationRuleTemplate[] = [
{
id: 'keyword-reply',
name: '关键词自动回复',
description: '消息命中关键词时自动回复指定内容',
available: false,
unavailableReason: ''
templateId: 'keyword-bot',
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
},
{
id: 'douyin-process',
name: '抖音视频搬运',
description: '被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话',
templateId: 'douyin-sender',
extensionId: 'com.example.douyin-sender'
}
]
+272
View File
@@ -0,0 +1,272 @@
/**
* 扩展动作的输入参数 Schema。
*
* 刻意只支持一个**明确的子集**:完整 JSON Schema 会把「UI 怎么渲染」和
* 「后台怎么校验」拆成两套实现,两边一旦不一致,用户看到的就是
* 「表单说合法、执行时说参数错」。
*
* 支持范围:
* - 顶层必须是 `type: 'object'` + `properties`
* - 字段类型:string / number / integer / boolean
* - 约束:required、enum、default、minimum/maximum、minLength/maxLength
* - 展示:title、description
*/
export const ACTION_SCHEMA_MAX_BYTES = 4 * 1024
export const ACTION_SCHEMA_MAX_PROPERTIES = 24
export type ExtensionActionFieldType = 'string' | 'number' | 'integer' | 'boolean'
export interface ExtensionActionFieldSchema {
type: ExtensionActionFieldType
title?: string
description?: string
enum?: Array<string | number>
default?: string | number | boolean
minimum?: number
maximum?: number
minLength?: number
maxLength?: number
}
export interface ExtensionActionInputSchema {
type: 'object'
properties: Record<string, ExtensionActionFieldSchema>
required?: string[]
}
export type ActionSchemaParseResult =
| { ok: true; schema: ExtensionActionInputSchema }
| { ok: false; reason: string }
const FIELD_TYPES: readonly ExtensionActionFieldType[] = ['string', 'number', 'integer', 'boolean']
const MAX_STRING_CONSTRAINT = 4_000
const MAX_ABSOLUTE_NUMBER = 1e12
const RESERVED_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
function isPlainObject(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
const prototype = Object.getPrototypeOf(value)
return prototype === Object.prototype || prototype === null
}
function readFiniteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
}
function readNonNegativeInteger(value: unknown): number | undefined {
const parsed = readFiniteNumber(value)
if (parsed === undefined || parsed < 0 || !Number.isInteger(parsed)) return undefined
return Math.min(parsed, MAX_STRING_CONSTRAINT)
}
/**
* 解析并规范化 Schema。
*
* 任何无法安全表达的内容都**整体拒绝**,不做部分裁剪:静默丢掉一个字段,
* 界面会少一个输入框,而后台仍在等这个必填项。
*/
export function parseActionInputSchema(value: unknown): ActionSchemaParseResult {
if (value === undefined || value === null) return { ok: false, reason: 'schema 为空' }
if (!isPlainObject(value)) return { ok: false, reason: 'schema 必须是对象' }
let serialized: string
try {
serialized = JSON.stringify(value)
} catch {
return { ok: false, reason: 'schema 不能序列化(可能含循环引用)' }
}
const byteLength = new TextEncoder().encode(serialized).length
if (byteLength > ACTION_SCHEMA_MAX_BYTES) {
return { ok: false, reason: `schema 超过 ${ACTION_SCHEMA_MAX_BYTES} 字节上限` }
}
if (value.type !== 'object') return { ok: false, reason: '顶层 type 必须是 object' }
const properties = value.properties
if (!isPlainObject(properties)) return { ok: false, reason: 'schema.properties 必须是对象' }
const keys = Object.keys(properties)
if (keys.length === 0) return { ok: false, reason: 'schema.properties 不能为空' }
if (keys.length > ACTION_SCHEMA_MAX_PROPERTIES) {
return { ok: false, reason: `参数数量超过 ${ACTION_SCHEMA_MAX_PROPERTIES} 个上限` }
}
const normalized: Record<string, ExtensionActionFieldSchema> = {}
for (const key of keys) {
if (RESERVED_KEYS.has(key)) return { ok: false, reason: `参数名不合法:${key}` }
if (key.length > 40) return { ok: false, reason: `参数名过长:${key}` }
const field = properties[key]
if (!isPlainObject(field)) return { ok: false, reason: `参数 ${key} 的定义必须是对象` }
const type = field.type
if (typeof type !== 'string' || !FIELD_TYPES.includes(type as ExtensionActionFieldType)) {
return { ok: false, reason: `参数 ${key} 的类型不支持:${String(type)}` }
}
const fieldType = type as ExtensionActionFieldType
const entry: ExtensionActionFieldSchema = { type: fieldType }
if (typeof field.title === 'string' && field.title.trim()) {
entry.title = field.title.trim().slice(0, 60)
}
if (typeof field.description === 'string' && field.description.trim()) {
entry.description = field.description.trim().slice(0, 200)
}
if (field.enum !== undefined) {
if (!Array.isArray(field.enum) || field.enum.length === 0 || field.enum.length > 50) {
return { ok: false, reason: `参数 ${key} 的 enum 不合法` }
}
const allowed: Array<string | number> = []
for (const option of field.enum) {
if (fieldType === 'string' && typeof option === 'string') {
allowed.push(option.slice(0, 200))
} else if (
fieldType !== 'string' &&
typeof option === 'number' &&
Number.isFinite(option)
) {
allowed.push(option)
} else {
return { ok: false, reason: `参数 ${key} 的 enum 项与类型不一致` }
}
}
entry.enum = allowed
}
if (field.default !== undefined) {
const fallback = normalizeActionFieldValue(fieldType, field.default)
if (fallback === undefined)
return { ok: false, reason: `参数 ${key} 的 default 与类型不一致` }
entry.default = fallback
}
if (fieldType === 'string') {
const minLength = readNonNegativeInteger(field.minLength)
const maxLength = readNonNegativeInteger(field.maxLength)
if (minLength !== undefined) entry.minLength = minLength
if (maxLength !== undefined) entry.maxLength = maxLength
if (
entry.minLength !== undefined &&
entry.maxLength !== undefined &&
entry.minLength > entry.maxLength
) {
return { ok: false, reason: `参数 ${key} 的 minLength 大于 maxLength` }
}
} else if (fieldType === 'number' || fieldType === 'integer') {
const minimum = readFiniteNumber(field.minimum)
const maximum = readFiniteNumber(field.maximum)
if (minimum !== undefined && Math.abs(minimum) <= MAX_ABSOLUTE_NUMBER) entry.minimum = minimum
if (maximum !== undefined && Math.abs(maximum) <= MAX_ABSOLUTE_NUMBER) entry.maximum = maximum
if (
entry.minimum !== undefined &&
entry.maximum !== undefined &&
entry.minimum > entry.maximum
) {
return { ok: false, reason: `参数 ${key} 的 minimum 大于 maximum` }
}
}
normalized[key] = entry
}
let required: string[] | undefined
if (value.required !== undefined) {
if (!Array.isArray(value.required)) return { ok: false, reason: 'required 必须是数组' }
const list: string[] = []
for (const item of value.required) {
if (typeof item !== 'string' || !normalized[item]) {
return { ok: false, reason: `required 引用了未定义的参数:${String(item)}` }
}
if (!list.includes(item)) list.push(item)
}
if (list.length) required = list
}
return {
ok: true,
schema: { type: 'object', properties: normalized, ...(required ? { required } : {}) }
}
}
/** 把原始值按字段类型收敛;不合法返回 undefined。 */
export function normalizeActionFieldValue(
type: ExtensionActionFieldType,
value: unknown
): string | number | boolean | undefined {
if (type === 'string') return typeof value === 'string' ? value.slice(0, 4_000) : undefined
if (type === 'boolean') return typeof value === 'boolean' ? value : undefined
if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
if (type === 'integer' && !Number.isInteger(value)) return undefined
return value
}
export interface ActionInputValidationResult {
ok: boolean
/** 逐字段错误,key 是参数名。 */
errors: Record<string, string>
}
/**
* 按 Schema 校验输入。
*
* UI 提交前与后台执行前都用这一个函数:两边规则一致才谈得上「所见即所得」。
*/
export function validateActionInput(
schema: ExtensionActionInputSchema | undefined,
input: Record<string, unknown> | undefined
): ActionInputValidationResult {
const errors: Record<string, string> = {}
if (!schema) return { ok: true, errors }
const values = input && typeof input === 'object' ? input : {}
const required = new Set(schema.required ?? [])
for (const [key, field] of Object.entries(schema.properties)) {
const raw = (values as Record<string, unknown>)[key]
const missing = raw === undefined || raw === null || raw === ''
if (missing) {
if (required.has(key)) errors[key] = '必填'
continue
}
const normalized = normalizeActionFieldValue(field.type, raw)
if (normalized === undefined) {
errors[key] = field.type === 'integer' ? '需要整数' : `需要 ${field.type}`
continue
}
if (field.enum && !field.enum.includes(normalized as string | number)) {
errors[key] = '不在可选范围内'
continue
}
if (typeof normalized === 'string') {
if (field.minLength !== undefined && normalized.length < field.minLength) {
errors[key] = `至少 ${field.minLength} 个字符`
continue
}
if (field.maxLength !== undefined && normalized.length > field.maxLength) {
errors[key] = `最多 ${field.maxLength} 个字符`
continue
}
}
if (typeof normalized === 'number') {
if (field.minimum !== undefined && normalized < field.minimum) {
errors[key] = `不能小于 ${field.minimum}`
continue
}
if (field.maximum !== undefined && normalized > field.maximum) {
errors[key] = `不能大于 ${field.maximum}`
}
}
}
return { ok: Object.keys(errors).length === 0, errors }
}
/** 按 Schema 生成一份带默认值的输入;缺省值缺失时留空。 */
export function buildDefaultActionInput(
schema: ExtensionActionInputSchema | undefined
): Record<string, unknown> {
const result: Record<string, unknown> = {}
if (!schema) return result
for (const [key, field] of Object.entries(schema.properties)) {
if (field.default !== undefined) result[key] = field.default
}
return result
}
+17 -2
View File
@@ -23,7 +23,17 @@ export const EXTENSION_ERROR_CODES = [
'ACTION_FAILED',
'RATE_LIMITED',
'INVALID_REQUEST',
'STORAGE_LIMIT_EXCEEDED'
'STORAGE_LIMIT_EXCEEDED',
/** 状态文件损坏且无法恢复;写入被拒绝,现场保留。 */
'EXTENSION_REGISTRY_UNREADABLE',
/** 扩展配置损坏且没有可用备份;写入被拒绝。 */
'EXTENSION_STORAGE_CORRUPTED',
/** 开发模式的源码目录被移动或删除;Registry 与配置保留。 */
'EXTENSION_SOURCE_MISSING',
/** 目标目录已有文件 / 目标不可写;创建项目被拒绝。 */
'EXTENSION_PROJECT_EXISTS',
/** 检测到安装副本被用户修改,拒绝自动覆盖。 */
'EXTENSION_MODIFIED_LOCALLY'
] as const
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
@@ -46,7 +56,12 @@ export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
ACTION_FAILED: '扩展执行失败',
RATE_LIMITED: '触发频率限制,请稍后再试',
INVALID_REQUEST: '请求格式不合法',
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限'
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限',
EXTENSION_REGISTRY_UNREADABLE: '扩展状态文件损坏且无法恢复',
EXTENSION_STORAGE_CORRUPTED: '扩展配置已损坏',
EXTENSION_SOURCE_MISSING: '开发源码目录不可用',
EXTENSION_PROJECT_EXISTS: '目标项目目录不可用',
EXTENSION_MODIFIED_LOCALLY: '扩展代码已被本地修改'
}
export interface ExtensionErrorPayload {
+19
View File
@@ -9,6 +9,25 @@ export const EXTENSION_IPC = {
pickDirectory: 'extension:pickDirectory',
pickPackage: 'extension:pickPackage',
setEnabled: 'extension:setEnabled',
health: 'extension:health',
grantPermissions: 'extension:grantPermissions',
revokePermission: 'extension:revokePermission',
resetStorage: 'extension:resetStorage',
templates: 'extension:templates',
installTemplate: 'extension:installTemplate',
acknowledgeRecovery: 'extension:acknowledgeRecovery',
acknowledgeStorage: 'extension:acknowledgeStorage',
adoptInstalledCode: 'extension:adoptInstalledCode',
rollbackUpgrade: 'extension:rollbackUpgrade',
pickProjectDirectory: 'extension:pickProjectDirectory',
linkDevelopment: 'extension:linkDevelopment',
reloadDevelopment: 'extension:reloadDevelopment',
unlinkDevelopment: 'extension:unlinkDevelopment',
convertDevelopment: 'extension:convertDevelopment',
createProjectFromTemplate: 'extension:createProjectFromTemplate',
exportInstalledAsProject: 'extension:exportInstalledAsProject',
openDevelopmentSource: 'extension:openDevelopmentSource',
actions: 'extension:actions',
uninstall: 'extension:uninstall',
logs: 'extension:getLogs',
clearLogs: 'extension:clearLogs',
+8 -1
View File
@@ -14,7 +14,8 @@ export const EXTENSION_PERMISSIONS = [
'wechat.send.video',
'ai.chat',
'storage',
'automation.action'
'automation.action',
'secrets'
] as const
export type ExtensionPermission = (typeof EXTENSION_PERMISSIONS)[number]
@@ -28,6 +29,12 @@ export interface ExtensionPermissionInfo {
}
export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPermissionInfo> = {
secrets: {
label: '保存私有凭据',
description:
'在本机以系统安全存储加密保存该扩展自己的凭据(如 Cookie),只有该扩展能读取;不写入明文文件。',
risk: 'medium'
},
'messages.subscribe': {
label: '接收新消息事件',
description:
+39 -1
View File
@@ -22,6 +22,10 @@ export type ExtensionHostCallMethod =
| 'wechat.send.video'
| 'ai.chat'
| 'capabilities.get'
| 'secrets.get'
| 'secrets.set'
| 'secrets.delete'
| 'secrets.has'
export interface ExtensionHostReady {
type: 'ready'
@@ -81,7 +85,15 @@ export interface ExtensionHostRegisterAction {
id: string
title: string
description?: string
hasInputSchema: boolean
/**
* 完整参数 Schema(未经校验的原始 JSON)。
*
* 宿主收到后统一走 `parseActionInputSchema`:非法或超限时**保留动作但不给 Schema**,
* 并把原因记进日志与动作信息,绝不静默截断。
*/
inputSchema?: unknown
/** 兼容字段:旧宿主只认这个布尔值。新宿主用 `inputSchema`。 */
hasInputSchema?: boolean
}
}
@@ -126,6 +138,30 @@ export interface ExtensionHostLog {
message: string
}
/**
* 扩展页面 → 同扩展后台的通用请求。
*
* 宿主只做路由与限额:页面拿不到任意 Node 能力,后台必须显式注册处理器。
* 这是移除「宿主硬编码某个具体扩展业务」的关键通道。
*/
export interface ExtensionHostPageRequest {
type: 'page-request'
version: number
requestId: string
method: string
params: Record<string, unknown>
timeoutMs: number
}
export interface ExtensionHostPageResult {
type: 'page-result'
version: number
requestId: string
ok: boolean
result?: unknown
error?: { code: string; message: string }
}
export type ExtensionHostOutboundMessage =
| ExtensionHostReady
| ExtensionHostActivated
@@ -134,6 +170,7 @@ export type ExtensionHostOutboundMessage =
| ExtensionHostLog
| ExtensionHostActionResult
| ExtensionHostTestResult
| ExtensionHostPageResult
export type ExtensionHostInboundMessage =
| ExtensionHostActivate
@@ -143,6 +180,7 @@ export type ExtensionHostInboundMessage =
| ExtensionHostInvokeAction
| ExtensionHostTestSend
| ExtensionHostTestResult
| ExtensionHostPageRequest
/**
* 自动化动作的返回值。
+25
View File
@@ -0,0 +1,25 @@
/**
* 扩展的来源。
*
* 决定「谁能更新它」:只有安装入口(Trusted installer)能写入来源,
* 而模板目录只承认 `template` 来源的记录归自己管理。
*
* - `directory`:从本地文件夹安装。
* - `package`:从 ZIP 安装。
* - `template`:由官方模板目录安装,带 `templateId` / `templateVersion`。
* - `development`:链接外部源码目录;代码不复制,路径只存在本机 Registry。
*/
export type ExtensionSource = 'directory' | 'package' | 'template' | 'development'
export const EXTENSION_SOURCES: readonly ExtensionSource[] = [
'directory',
'package',
'template',
'development'
]
/** 未知值一律归为 `directory`:来源不能从不可信文件里推断。 */
export function normalizeExtensionSource(value: unknown): ExtensionSource {
if (value === 'package' || value === 'template' || value === 'development') return value
return 'directory'
}
+58
View File
@@ -0,0 +1,58 @@
import type { ExtensionPermission } from './permissions'
import type { ExtensionSource } from './source'
/**
* 模板索引里的依赖声明。
*
* 存在的意义是「别把缺依赖的模板宣传成开箱即用」:界面必须在安装前就把
* 需要什么摆出来,安装后检测到缺失就明确说「暂时无法处理视频」。
*/
export interface ExtensionTemplateRequirement {
python?: boolean | { required: boolean; minVersion?: string; reason?: string }
chrome?: boolean | { required: boolean; reason?: string }
externalScript?: boolean | { required: boolean; path: string; reason?: string }
}
export interface ExtensionTemplateEntry {
templateId: string
extensionId: string
name: string
version: string
description?: string
permissions: ExtensionPermission[]
file: string
sha256: string
bytes: number
fileCount: number
platforms: NodeJS.Platform[]
requires: ExtensionTemplateRequirement
}
export type ExtensionTemplateState =
| 'not-installed'
| 'installed'
| 'update-available'
| 'conflict'
| 'unsupported'
| 'damaged'
export interface TemplateDependencyCheck {
id: 'python' | 'chrome' | 'externalScript'
label: string
ok: boolean
/** 为真时,缺失会阻止模板的主要功能,界面不能显示「可用」。 */
blocking: boolean
detail?: string
}
export interface ExtensionTemplateStatus {
template: ExtensionTemplateEntry
state: ExtensionTemplateState
installedVersion?: string
installedSource?: ExtensionSource
dependencies: {
ready: boolean
checks: TemplateDependencyCheck[]
}
message?: string
}
+92 -4
View File
@@ -1,6 +1,7 @@
import type { ExtensionCompatibility } from './manifest'
import type { ExtensionPermission } from './permissions'
import type { ExtensionErrorPayload } from './errors'
import type { ExtensionSource } from './source'
/** 扩展后台进程状态。`crashed` 表示连续崩溃后已停止自动重启,等用户手动处理。 */
export type ExtensionRuntimeState = 'inactive' | 'starting' | 'active' | 'error' | 'crashed'
@@ -11,6 +12,20 @@ export interface ExtensionRuntimeSnapshot {
restarts: number
/** 面向用户的一句话;**不含**路径、wxid、聊天正文。 */
lastError?: string
/**
* 状态补充说明,用于区分「已停止」与「本来就没有后台任务」。
* 例如只有页面入口的扩展会得到 `inactive` + 本字段。
*/
note?: string
}
/** 扩展私有存储的健康状态。非 `ok` 时界面必须提示用户。 */
export type ExtensionStorageHealthState = 'ok' | 'recovered-from-backup' | 'unrecovered'
export interface ExtensionStorageHealthSummary {
state: ExtensionStorageHealthState
/** 面向用户的一句话;不含路径。 */
message?: string
}
export interface ExtensionAutomationActionSummary {
@@ -34,13 +49,67 @@ export interface InstalledExtension {
installedAt: number
updatedAt: number
compatibility: ExtensionCompatibility
/** 安装来源;只有 `template` 的记录归官方模板目录管理。 */
source: ExtensionSource
/** 来源为官方模板时,记录模板 id 与安装时的模板版本。 */
template?: { id: string; version: string }
/**
* 开发模式的源码位置。
*
* `available === false` 表示目录被移动或删除:Registry 与用户配置都还在,
* 只是暂时跑不起来,界面要给「重新选择目录」而不是「扩展没了」。
*/
development?: { sourcePath: string; available: boolean }
permissions: ExtensionPermission[]
grantedPermissions: ExtensionPermission[]
/**
* manifest 声明但用户尚未授予的权限。
*
* 非空表示该扩展升级后新增了能力:这些能力当前**不可用**,
* 需要用户显式授权后才会下发到后台进程。
*/
pendingPermissions: ExtensionPermission[]
runtime: ExtensionRuntimeSnapshot
pages: Array<{ id: string; title: string }>
automationActions: ExtensionAutomationActionSummary[]
/** 扩展目录是否仍然存在;false 时 UI 必须显示为「文件缺失」而不是可启动。 */
filesPresent: boolean
storage: ExtensionStorageHealthSummary
}
/**
* 从其它页面跳到扩展中心时的定位目标。
*
* 只描述「去哪里」,不携带任何安装状态:扩展中心自己读 Registry,
* 避免两个页面各维护一份事实。
*/
export interface ExtensionDeepLink {
/** 定位官方模板(打开模板画廊并展开该卡片)。 */
templateId?: string
/** 定位已安装扩展(选中详情)。 */
extensionId?: string
/** 打开「二次开发」引导(创建项目 / 链接本地 / 重载 / 文档)。 */
development?: boolean
}
/**
* 单个扩展动作的完整可用性描述。
*
* `registered` 只说明后台注册过,`available` 才决定能不能用:
* 停用、代码缺失、权限未授予、Schema 非法、Storage 暂停都会让 available=false。
*/
export interface ExtensionActionInfo {
extensionId: string
extensionName: string
actionId: string
title: string
description?: string
declared: boolean
registered: boolean
enabled: boolean
available: boolean
unavailableReason?: string
inputSchema?: import('./action-schema').ExtensionActionInputSchema
}
export interface ExtensionLogEntry {
@@ -63,6 +132,13 @@ export interface ExtensionOperationResult {
error?: ExtensionErrorPayload
}
/** 项目生成 / 导出结果;`projectPath` 是用户目录里的绝对路径。 */
export interface ExtensionProjectResult extends ExtensionOperationResult {
projectPath?: string
/** 被改写扩展身份的源码文件(相对路径)。 */
rewrittenFiles?: string[]
}
export interface ExtensionPageDescriptor {
extensionId: string
pageId: string
@@ -78,10 +154,8 @@ export type ExtensionPageMethod =
| 'storage.list'
| 'capabilities.get'
| 'contacts.listGroups'
| 'test.send'
| 'douyin.cookie.get'
| 'douyin.cookie.set'
| 'douyin.cookie.clear'
/** 通用通道:把请求转发给**同一扩展**后台注册的处理器。 */
| 'extension.request'
| 'extension.info'
export interface ExtensionPageRequest {
@@ -122,3 +196,17 @@ export interface ExtensionCapabilitySnapshot {
export interface ExtensionQuitBehavior {
keepData: boolean
}
/** 扩展状态文件的可信度;渲染层据此决定是否显示告警条。 */
export type ExtensionRegistryHealthState =
| 'ok'
| 'recovered-from-backup'
| 'recovered-by-scan'
| 'unreadable'
export interface ExtensionSystemHealth {
registry: {
state: ExtensionRegistryHealthState
message?: string
}
}
@@ -0,0 +1,141 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import {
RuleListPanel,
type RuleTemplateCardModel
} from '../../src/renderer/src/features/automation/RuleListPanel'
import { AUTOMATION_RULE_TEMPLATES } from '../../src/shared/automation'
function template(overrides: Partial<RuleTemplateCardModel> = {}): RuleTemplateCardModel {
return {
id: 'keyword-reply',
name: '关键词自动回复',
description: '消息命中关键词时自动回复指定内容',
templateId: 'keyword-bot',
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
state: 'not-installed',
...overrides
}
}
function renderPanel(
templates: RuleTemplateCardModel[],
handlers: {
onOpenExtension?: (target: { templateId?: string; extensionId?: string }) => void
onUseRuleTemplate?: (template: RuleTemplateCardModel) => void
} = {}
): void {
render(
<RuleListPanel
rules={[]}
groups={[]}
loading={false}
busyRuleId={null}
leaveNotification={null}
scheduledReport={null}
onToggle={() => undefined}
onEdit={() => undefined}
onDelete={() => undefined}
onCreate={() => undefined}
onEditLeaveNotification={() => undefined}
onManageScheduledReport={() => undefined}
ruleTemplates={templates}
onOpenExtension={handlers.onOpenExtension}
onUseRuleTemplate={handlers.onUseRuleTemplate}
/>
)
}
describe('规则模板目录', () => {
it('两个官方模板都在目录里,抖音那条没有动作', () => {
const templateIds = AUTOMATION_RULE_TEMPLATES.map((item) => item.templateId).sort()
expect(templateIds).toEqual(['douyin-sender', 'keyword-bot'])
const douyin = AUTOMATION_RULE_TEMPLATES.find((item) => item.templateId === 'douyin-sender')
expect(douyin?.actionId).toBeUndefined()
const keyword = AUTOMATION_RULE_TEMPLATES.find((item) => item.templateId === 'keyword-bot')
expect(keyword?.actionId).toBe('keyword.reply')
})
})
describe('规则模板卡片', () => {
it('未安装时给出「去扩展中心安装」,点击定位模板', async () => {
const onOpenExtension = vi.fn()
const user = userEvent.setup()
renderPanel([template()], { onOpenExtension })
expect(screen.getByText('未安装')).toBeTruthy()
const button = screen.getByRole('button', { name: /去扩展中心安装/ })
await user.click(button)
expect(onOpenExtension).toHaveBeenCalledWith({ templateId: 'keyword-bot' })
})
it('已安装未启用时给出「去启用」,点击定位扩展详情', async () => {
const onOpenExtension = vi.fn()
const user = userEvent.setup()
renderPanel([template({ state: 'installed-disabled', reason: '已安装但未启用' })], {
onOpenExtension
})
expect(screen.getByText('已安装 · 未启用')).toBeTruthy()
await user.click(screen.getByRole('button', { name: /去启用/ }))
expect(onOpenExtension).toHaveBeenCalledWith({ extensionId: 'com.example.keyword-bot' })
})
it('已启用时提供「打开配置」与「用规则触发」', async () => {
const onOpenExtension = vi.fn()
const onUseRuleTemplate = vi.fn()
const user = userEvent.setup()
renderPanel([template({ state: 'ready' })], { onOpenExtension, onUseRuleTemplate })
expect(screen.getByText('已就绪')).toBeTruthy()
await user.click(screen.getByRole('button', { name: /打开扩展配置/ }))
expect(onOpenExtension).toHaveBeenCalledWith({ extensionId: 'com.example.keyword-bot' })
await user.click(screen.getByRole('button', { name: '用规则触发' }))
expect(onUseRuleTemplate).toHaveBeenCalledTimes(1)
expect(onUseRuleTemplate.mock.calls[0][0].actionId).toBe('keyword.reply')
})
it('不可用时显示真实原因且不给出操作入口', () => {
renderPanel([template({ state: 'unavailable', reason: '扩展与当前 TraceMemo 版本不兼容' })])
expect(screen.getByText('不可用')).toBeTruthy()
expect(screen.getByText('扩展与当前 TraceMemo 版本不兼容')).toBeTruthy()
expect(screen.queryByRole('button', { name: /安装|启用|打开扩展配置/ })).toBeNull()
})
it('没有动作的模板只给配置入口,不出现「用规则触发」', () => {
renderPanel([
template({
id: 'douyin-process',
name: '抖音视频搬运',
templateId: 'douyin-sender',
extensionId: 'com.example.douyin-sender',
actionId: undefined,
state: 'ready'
})
])
expect(screen.getByText('已就绪')).toBeTruthy()
expect(screen.getByRole('button', { name: /打开扩展配置/ })).toBeTruthy()
expect(screen.queryByRole('button', { name: '用规则触发' })).toBeNull()
expect(screen.getByText(/没有注册自动化动作/)).toBeTruthy()
})
it('模板之外提供「做自己的扩展」入口', async () => {
const onOpenExtension = vi.fn()
const user = userEvent.setup()
renderPanel([template()], { onOpenExtension })
await user.click(screen.getByRole('button', { name: /开始二次开发/ }))
expect(onOpenExtension).toHaveBeenCalledWith({ development: true })
})
it('卸载后卡片仍然存在(不因为扩展缺失就消失)', () => {
renderPanel([template({ state: 'not-installed' })])
expect(screen.getByText('关键词自动回复')).toBeTruthy()
})
})
@@ -0,0 +1,151 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ToastProvider } from '../../src/renderer/src/components/ui'
import { ExtensionTemplateGallery } from '../../src/renderer/src/features/extensions/ExtensionTemplateGallery'
import type { ExtensionTemplateStatus } from '../../src/shared/extensions/templates'
function template(overrides: Partial<ExtensionTemplateStatus> = {}): ExtensionTemplateStatus {
return {
template: {
templateId: 'keyword-bot',
extensionId: 'com.example.keyword-bot',
name: '关键词回复机器人',
version: '1.0.0',
description: '命中关键词后经 Gateway 回复',
permissions: ['storage', 'wechat.send.text'],
file: 'keyword-bot-1.0.0.zip',
sha256: 'a'.repeat(64),
bytes: 19121,
fileCount: 7,
platforms: ['darwin', 'win32'],
requires: { python: false, chrome: false, externalScript: false }
},
state: 'not-installed',
dependencies: { ready: true, checks: [] },
...overrides
}
}
function renderGallery(
templates: ExtensionTemplateStatus[],
handlers: { onInstall?: (id: string) => void; busyId?: string | null } = {}
): void {
render(
<ToastProvider>
<ExtensionTemplateGallery
templates={templates}
loading={false}
busyId={handlers.busyId ?? null}
onInstall={handlers.onInstall ?? (() => undefined)}
/>
</ToastProvider>
)
}
describe('官方模板画廊', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('展示模板名称、版本与安装按钮', () => {
renderGallery([template()])
expect(screen.getByText('关键词回复机器人')).toBeTruthy()
expect(screen.getByText('v1.0.0')).toBeTruthy()
expect(screen.getByRole('button', { name: '安装' })).toBeTruthy()
})
it('点击安装把模板 id 交给上层', async () => {
const onInstall = vi.fn()
const user = userEvent.setup()
renderGallery([template()], { onInstall })
await user.click(screen.getByRole('button', { name: '安装' }))
expect(onInstall).toHaveBeenCalledWith('keyword-bot')
})
it('有更新时显示「更新」按钮', () => {
renderGallery([template({ state: 'update-available', installedVersion: '0.9.0' })])
expect(screen.getByRole('button', { name: '更新' })).toBeTruthy()
expect(screen.getByText('有更新')).toBeTruthy()
})
it('已安装同版本时按钮不可用', () => {
renderGallery([template({ state: 'installed', installedVersion: '1.0.0' })])
const button = screen.getByRole('button', { name: '安装' }) as HTMLButtonElement
expect(button.disabled).toBe(true)
})
it('同 ID 冲突时说明不会自动替换', () => {
renderGallery([
template({
state: 'conflict',
message: '已安装同 ID 的非官方扩展,不会自动替换'
})
])
expect(screen.getByText(/不会自动替换/)).toBeTruthy()
const button = screen.getByRole('button', { name: '安装' }) as HTMLButtonElement
expect(button.disabled).toBe(true)
})
it('缺少关键依赖时明确提示主要功能不可用', () => {
renderGallery([
template({
template: {
...template().template,
templateId: 'douyin-sender',
extensionId: 'com.example.douyin-sender',
name: '抖音视频处理',
requires: { python: { required: true }, chrome: { required: true } }
},
state: 'not-installed',
dependencies: {
ready: false,
checks: [
{ id: 'python', label: 'Python', ok: false, blocking: true, detail: '未找到' },
{ id: 'chrome', label: 'Chrome', ok: false, blocking: true, detail: '未找到' }
]
}
})
])
expect(screen.getByText(/缺少 Python、Chrome/)).toBeTruthy()
expect(screen.getByText(/主要功能暂时不可用/)).toBeTruthy()
})
it('查看详情展开权限与依赖', async () => {
const user = userEvent.setup()
renderGallery([
template({
dependencies: {
ready: true,
checks: [{ id: 'python', label: 'Python', ok: true, blocking: true, detail: '已找到' }]
}
})
])
await user.click(screen.getByRole('button', { name: '查看详情' }))
expect(screen.getByText('发送微信文本')).toBeTruthy()
expect(screen.getByText('已找到')).toBeTruthy()
})
it('资源损坏时提示重新安装且禁用安装按钮', () => {
renderGallery([
template({ state: 'damaged', message: '模板资源缺失或校验失败,请重新安装 TraceMemo' })
])
expect(screen.getByText(/校验失败/)).toBeTruthy()
const button = screen.getByRole('button', { name: '安装' }) as HTMLButtonElement
expect(button.disabled).toBe(true)
})
it('没有模板资源时说明原因', () => {
render(
<ToastProvider>
<ExtensionTemplateGallery
templates={[]}
loading={false}
busyId={null}
onInstall={() => undefined}
/>
</ToastProvider>
)
expect(screen.getByText(/没有携带模板资源/)).toBeTruthy()
})
})
@@ -0,0 +1,154 @@
import { render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ToastProvider } from '../../src/renderer/src/components/ui'
import { ExtensionWorkspace } from '../../src/renderer/src/features/extensions/ExtensionWorkspace'
import type { ExtensionSystemHealth, InstalledExtension } from '../../src/shared/extensions/types'
import type { ExtensionTemplateStatus } from '../../src/shared/extensions/templates'
import type { ExtensionDeepLink } from '../../src/shared/extensions/types'
const templateStatus: ExtensionTemplateStatus = {
template: {
templateId: 'keyword-bot',
extensionId: 'com.example.keyword-bot',
name: '关键词回复机器人',
version: '1.0.1',
description: '命中关键词后回复',
permissions: ['storage'],
file: 'keyword-bot-1.0.1.zip',
sha256: 'a'.repeat(64),
bytes: 100,
fileCount: 7,
platforms: ['darwin', 'win32'],
requires: {}
},
state: 'not-installed',
dependencies: { ready: true, checks: [] }
}
function extension(overrides: Partial<InstalledExtension> = {}): InstalledExtension {
return {
id: 'com.example.keyword-bot',
name: '关键词回复机器人',
version: '1.0.1',
apiVersion: '1',
enabled: true,
installedAt: 1,
updatedAt: 1,
compatibility: { compatible: true },
source: 'template',
template: { id: 'keyword-bot', version: '1.0.1' },
permissions: ['storage'],
grantedPermissions: ['storage'],
pendingPermissions: [],
runtime: { state: 'active', since: 1, restarts: 0 },
pages: [{ id: 'settings', title: '配置' }],
automationActions: [],
filesPresent: true,
storage: { state: 'ok' },
...overrides
}
}
const healthy: ExtensionSystemHealth = { registry: { state: 'ok' } }
function setup(list: InstalledExtension[]): void {
const api = {
listExtensions: vi.fn(async () => list),
getExtensionHealth: vi.fn(async () => healthy),
listExtensionTemplates: vi.fn(async () => [templateStatus]),
getExtensionLogs: vi.fn(async () => []),
onExtensionChanged: vi.fn(() => vi.fn()),
clearExtensionLogs: vi.fn(async () => ({ success: true })),
openExtensionDataDir: vi.fn(async () => ({ success: true })),
setExtensionEnabled: vi.fn(async () => ({ success: true })),
grantExtensionPermissions: vi.fn(async () => ({ success: true })),
revokeExtensionPermission: vi.fn(async () => ({ success: true })),
resetExtensionStorage: vi.fn(async () => ({ success: true })),
uninstallExtension: vi.fn(async () => ({ success: true })),
getExtensionPageUrl: vi.fn(),
pickExtensionDirectory: vi.fn(),
pickExtensionPackage: vi.fn(),
installExtensionFromDirectory: vi.fn(),
installExtensionFromPackage: vi.fn(),
installExtensionTemplate: vi.fn(),
extensionPageRequest: vi.fn(),
acknowledgeExtensionRecovery: vi.fn(),
acknowledgeExtensionStorage: vi.fn(),
adoptExtensionCode: vi.fn(),
rollbackExtensionUpgrade: vi.fn(),
listExtensionActions: vi.fn(async () => []),
pickExtensionProjectDirectory: vi.fn(),
linkExtensionDevelopment: vi.fn(),
reloadExtensionDevelopment: vi.fn(),
unlinkExtensionDevelopment: vi.fn(),
convertExtensionDevelopment: vi.fn(),
createExtensionProject: vi.fn(),
exportExtensionAsProject: vi.fn(),
openExtensionDevelopmentSource: vi.fn()
}
Object.defineProperty(window, 'api', { configurable: true, value: api })
}
function renderWorkspace(props: {
deepLink?: ExtensionDeepLink | null
onConsumeDeepLink?: () => void
}): void {
render(
<ToastProvider>
<ExtensionWorkspace {...props} />
</ToastProvider>
)
}
describe('扩展中心深链', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('模板深链进入官方模板视图并展开该模板', async () => {
setup([])
const onConsume = vi.fn()
renderWorkspace({ deepLink: { templateId: 'keyword-bot' }, onConsumeDeepLink: onConsume })
await waitFor(() => {
expect(screen.getByText('关键词回复机器人')).toBeTruthy()
})
// 展开态会显示「收起详情」,说明定位生效。
expect(screen.getByRole('button', { name: '收起详情' })).toBeTruthy()
expect(onConsume).toHaveBeenCalled()
})
it('扩展深链选中对应扩展详情', async () => {
setup([extension()])
renderWorkspace({ deepLink: { extensionId: 'com.example.keyword-bot' } })
await waitFor(() => {
expect(screen.getByText('com.example.keyword-bot')).toBeTruthy()
})
})
it('开发引导深链显示三步与文档路径', async () => {
setup([])
renderWorkspace({ deepLink: { development: true } })
await waitFor(() => {
expect(screen.getByText('克隆与改造成自己的扩展')).toBeTruthy()
})
expect(screen.getByText('docs/extensions/clone-and-customize.md')).toBeTruthy()
expect(screen.getByRole('button', { name: '从模板创建项目' })).toBeTruthy()
// 侧栏与引导面板各有一个「链接本地项目」。
expect(screen.getAllByRole('button', { name: '链接本地项目' }).length).toBeGreaterThanOrEqual(2)
})
it('没有深链时保持默认视图', async () => {
setup([extension()])
const onConsume = vi.fn()
renderWorkspace({ deepLink: null, onConsumeDeepLink: onConsume })
await waitFor(() => {
// 侧栏列表与详情标题都会出现扩展名。
expect(screen.getAllByText('关键词回复机器人').length).toBeGreaterThan(0)
})
expect(onConsume).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,162 @@
import { render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ToastProvider } from '../../src/renderer/src/components/ui'
import { ExtensionWorkspace } from '../../src/renderer/src/features/extensions/ExtensionWorkspace'
import type {
ExtensionSystemHealth,
InstalledExtension
} from '../../src/shared/extensions/types'
function extension(overrides: Partial<InstalledExtension> = {}): InstalledExtension {
return {
id: 'com.example.demo',
name: '演示扩展',
version: '1.0.0',
apiVersion: '1',
enabled: false,
installedAt: 1,
updatedAt: 1,
compatibility: { compatible: true },
source: 'directory',
permissions: ['storage', 'contacts.list'],
grantedPermissions: ['storage'],
pendingPermissions: ['contacts.list'],
runtime: { state: 'inactive', since: 1, restarts: 0 },
pages: [{ id: 'settings', title: '设置' }],
automationActions: [],
filesPresent: true,
storage: { state: 'ok' },
...overrides
}
}
const healthy: ExtensionSystemHealth = { registry: { state: 'ok' } }
let api: Record<string, ReturnType<typeof vi.fn>>
function setup(list: InstalledExtension[], health: ExtensionSystemHealth = healthy): void {
api = {
listExtensions: vi.fn(async () => list),
getExtensionHealth: vi.fn(async () => health),
getExtensionLogs: vi.fn(async () => []),
clearExtensionLogs: vi.fn(async () => ({ success: true })),
openExtensionDataDir: vi.fn(async () => ({ success: true })),
onExtensionChanged: vi.fn(() => vi.fn()),
setExtensionEnabled: vi.fn(async () => ({ success: true })),
grantExtensionPermissions: vi.fn(async () => ({ success: true })),
resetExtensionStorage: vi.fn(async () => ({ success: true })),
uninstallExtension: vi.fn(async () => ({ success: true })),
getExtensionPageUrl: vi.fn(),
pickExtensionDirectory: vi.fn(),
pickExtensionPackage: vi.fn(),
installExtensionFromDirectory: vi.fn(),
installExtensionFromPackage: vi.fn(),
extensionPageRequest: vi.fn(),
listExtensionTemplates: vi.fn(async () => []),
installExtensionTemplate: vi.fn(async () => ({ success: true })),
acknowledgeExtensionRecovery: vi.fn(async () => ({ success: true })),
acknowledgeExtensionStorage: vi.fn(async () => ({ success: true })),
adoptExtensionCode: vi.fn(async () => ({ success: true })),
rollbackExtensionUpgrade: vi.fn(async () => ({ success: true }))
}
Object.defineProperty(window, 'api', { configurable: true, value: api })
}
function renderWorkspace(): void {
render(
<ToastProvider>
<ExtensionWorkspace />
</ToastProvider>
)
}
describe('扩展中心状态提示', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('状态文件从扫描重建时显示提示条', async () => {
setup([extension()], {
registry: {
state: 'recovered-by-scan',
message: '扩展状态文件与备份均不可用,已按磁盘目录重建为未启用状态'
}
})
renderWorkspace()
await waitFor(() => {
expect(
screen.getByText(/扩展状态文件与备份均不可用,已按磁盘目录重建/)
).toBeTruthy()
})
})
it('状态文件无法恢复时提示保留现场', async () => {
setup([extension()], { registry: { state: 'unreadable' } })
renderWorkspace()
await waitFor(() => {
expect(screen.getByText(/已停止写入以保留现场/)).toBeTruthy()
})
})
it('正常状态不显示提示条', async () => {
setup([extension()])
renderWorkspace()
await waitFor(() => {
// 列表项与详情标题都会出现扩展名。
expect(screen.getAllByText('演示扩展').length).toBeGreaterThan(0)
})
expect(screen.queryByText(/保留现场/)).toBeNull()
expect(screen.queryByText(/已按磁盘目录重建/)).toBeNull()
})
it('配置损坏且无法恢复时显示重置入口', async () => {
setup([
extension({
storage: {
state: 'unrecovered',
message: '扩展配置损坏且没有可用备份;写入已停止以保留现场'
}
})
])
renderWorkspace()
await waitFor(() => {
expect(screen.getByText(/扩展配置损坏且没有可用备份/)).toBeTruthy()
})
expect(screen.getByRole('button', { name: '重置配置' })).toBeTruthy()
})
it('存在待授权权限时显示授权入口', async () => {
setup([extension()])
renderWorkspace()
await waitFor(() => {
expect(screen.getByRole('button', { name: '授权新增权限' })).toBeTruthy()
})
expect(screen.getByText(/新版本申请了 1 项尚未授予的权限/)).toBeTruthy()
// M4:未授权项给出「授权」按钮(逐项授权),不再是纯文本标签。
expect(screen.getAllByRole('button', { name: '授权' }).length).toBeGreaterThan(0)
})
it('只有页面入口的扩展显示说明而不是运行中', async () => {
setup([
extension({
enabled: true,
runtime: {
state: 'inactive',
since: 1,
restarts: 0,
note: '仅提供页面,没有后台任务'
}
})
])
renderWorkspace()
await waitFor(() => {
expect(screen.getByText('仅提供页面,没有后台任务')).toBeTruthy()
})
})
})
@@ -0,0 +1,383 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() =>
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const roots: string[] = []
let userData: string
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-dev-mode-'))
roots.push(root)
return root
}
function manifest(
id = 'com.example.dev-bot',
overrides: Record<string, unknown> = {}
): Record<string, unknown> {
return {
manifestVersion: 1,
id,
name: '开发模式扩展',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage', 'messages.subscribe', 'wechat.send.text'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
subscriptions: {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false
},
contributions: { pages: [{ id: 'settings', title: '配置' }] },
...overrides
}
}
/** 在仓库外模拟一个开发项目目录。 */
function createProject(
overrides: Record<string, unknown> = {},
id = 'com.example.dev-bot'
): string {
const parent = tempRoot()
const project = path.join(parent, 'my-extension')
fs.ensureDirSync(path.join(project, 'ui'))
fs.ensureDirSync(path.join(project, 'background'))
fs.writeJsonSync(path.join(project, 'manifest.json'), manifest(id, overrides))
fs.writeFileSync(path.join(project, 'ui', 'index.html'), '<!doctype html><title>dev</title>')
fs.writeFileSync(path.join(project, 'background', 'index.js'), 'module.exports=()=>{}')
return project
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: async () =>
({
actionId: 'a',
status: 'sent',
decision: 'allow',
startedAt: '',
finishedAt: ''
}) as never,
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = tempRoot()
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('开发模式链接', { timeout: 20_000 }, () => {
it('链接外部目录后登记为 development,默认不启用', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
const result = await manager.linkDevelopmentProject(project)
expect(result.success).toBe(true)
const extension = manager.get('com.example.dev-bot')
expect(extension?.source).toBe('development')
expect(extension?.enabled).toBe(false)
expect(extension?.development?.available).toBe(true)
expect(extension?.development?.sourcePath).toBe(fs.realpathSync(project))
// 没有在 userData 下复制代码。
expect(fs.existsSync(manager.resolveExtensionRoot('com.example.dev-bot') as string)).toBe(true)
})
it('目录不存在时返回明确错误', async () => {
const { manager } = createManager()
await manager.initialize()
const result = await manager.linkDevelopmentProject(path.join(tempRoot(), 'missing'))
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_SOURCE_MISSING')
})
it('manifest 不合法时拒绝链接', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
fs.writeJsonSync(path.join(project, 'manifest.json'), { manifestVersion: 1 })
const result = await manager.linkDevelopmentProject(project)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_INVALID_MANIFEST')
})
it('入口文件缺失时拒绝链接', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
fs.removeSync(path.join(project, 'background', 'index.js'))
const result = await manager.linkDevelopmentProject(project)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_INVALID_MANIFEST')
})
it('拒绝把宿主私有目录当作源码', async () => {
const { manager, paths } = createManager()
await manager.initialize()
// 在宿主私有目录里放一个**结构完整**的扩展,验证路径边界先于内容检查生效。
const sneaky = path.join(paths.dataDir, 'sneaky')
fs.ensureDirSync(path.join(sneaky, 'ui'))
fs.ensureDirSync(path.join(sneaky, 'background'))
fs.writeJsonSync(path.join(sneaky, 'manifest.json'), manifest())
fs.writeFileSync(path.join(sneaky, 'ui', 'index.html'), '<!doctype html>')
fs.writeFileSync(path.join(sneaky, 'background', 'index.js'), 'module.exports=()=>{}')
const result = await manager.linkDevelopmentProject(sneaky)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_INVALID_PATH')
})
it('同 ID 已被正式安装占用时拒绝链接', async () => {
const { manager } = createManager()
await manager.initialize()
// 先用「从目录安装」建立一个正式安装来源。
await manager.installFromDirectory(createProject())
expect(manager.get('com.example.dev-bot')?.source).toBe('directory')
const second = createProject()
const linked = await manager.linkDevelopmentProject(second)
expect(linked.success).toBe(false)
expect(linked.error?.code).toBe('EXTENSION_ALREADY_INSTALLED')
// 原来源未被替换。
expect(manager.get('com.example.dev-bot')?.source).toBe('directory')
})
it('链接后重启仍保留记录,源码缺失时标记不可用但配置仍在', async () => {
const { manager, paths } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
await manager.pageRequest('com.example.dev-bot', 'storage.set', {
key: 'rules',
value: ['r1']
})
// 模拟源码目录被移走。
fs.moveSync(project, `${project}-moved`)
const restarted = createManager()
await restarted.manager.initialize()
const extension = restarted.manager.get('com.example.dev-bot')
expect(extension?.source).toBe('development')
expect(extension?.development?.available).toBe(false)
// 配置仍在。
expect(
fs.existsSync(path.join(paths.extensionDataDir('com.example.dev-bot'), 'storage.json'))
).toBe(true)
})
})
describe('重新加载', { timeout: 20_000 }, () => {
it('修改 manifest 版本后重新加载生效,并保留授权交集', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
await manager.setEnabled('com.example.dev-bot', true)
await tick()
expect(manager.get('com.example.dev-bot')?.version).toBe('1.0.0')
// 开发者在外部目录改版本,并新增一项权限。
fs.writeJsonSync(
path.join(project, 'manifest.json'),
manifest(undefined, {
version: '1.1.0',
permissions: ['storage', 'messages.subscribe', 'wechat.send.text', 'automation.action']
})
)
const reloaded = await manager.reloadDevelopment('com.example.dev-bot')
expect(reloaded.success).toBe(true)
await tick()
const extension = manager.get('com.example.dev-bot')
expect(extension?.version).toBe('1.1.0')
// 新增权限不自动授予。
expect(extension?.grantedPermissions).not.toContain('automation.action')
expect(extension?.pendingPermissions).toContain('automation.action')
expect(extension?.runtime.state).toBe('active')
})
it('删除权限后重新加载立即失效', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
await manager.setEnabled('com.example.dev-bot', true)
await tick()
expect(manager.get('com.example.dev-bot')?.grantedPermissions).toContain('wechat.send.text')
fs.writeJsonSync(
path.join(project, 'manifest.json'),
manifest(undefined, { version: '1.0.1', permissions: ['storage'] })
)
await manager.reloadDevelopment('com.example.dev-bot')
expect(manager.get('com.example.dev-bot')?.grantedPermissions).toEqual(['storage'])
})
it('源码目录缺失时重新加载给出明确错误', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
fs.removeSync(project)
const reloaded = await manager.reloadDevelopment('com.example.dev-bot')
expect(reloaded.success).toBe(false)
expect(reloaded.error?.code).toBe('EXTENSION_SOURCE_MISSING')
})
})
describe('移除链接与转换', { timeout: 20_000 }, () => {
it('移除开发链接不会删除外部源码', async () => {
const { manager } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
const unlinked = await manager.unlinkDevelopment('com.example.dev-bot', { keepData: true })
expect(unlinked.success).toBe(true)
expect(fs.existsSync(project)).toBe(true)
expect(manager.get('com.example.dev-bot')).toBeNull()
})
it('移除链接时选择清除数据会删除配置但保留源码', async () => {
const { manager, paths } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
await manager.pageRequest('com.example.dev-bot', 'storage.set', { key: 'a', value: 1 })
await manager.unlinkDevelopment('com.example.dev-bot', { keepData: false })
expect(fs.existsSync(project)).toBe(true)
expect(fs.existsSync(paths.extensionDataDir('com.example.dev-bot'))).toBe(false)
})
it('开发项目可转为正式安装,来源与外部路径一并清除', async () => {
const { manager, paths } = createManager()
await manager.initialize()
const project = createProject()
await manager.linkDevelopmentProject(project)
await manager.pageRequest('com.example.dev-bot', 'storage.set', { key: 'a', value: 1 })
const converted = await manager.convertDevelopmentToInstalled('com.example.dev-bot')
expect(converted.success).toBe(true)
const extension = manager.get('com.example.dev-bot')
expect(extension?.source).toBe('directory')
expect(extension?.development).toBeUndefined()
expect(extension?.enabled).toBe(false)
// 代码已经进 userData。
expect(fs.existsSync(path.join(paths.installDir('com.example.dev-bot'), 'manifest.json'))).toBe(
true
)
// 配置保留。
expect(
(await manager.pageRequest('com.example.dev-bot', 'storage.get', { key: 'a' })).result
).toBe(1)
// 外部源码仍在。
expect(fs.existsSync(project)).toBe(true)
})
})
+20 -5
View File
@@ -142,6 +142,12 @@ function createManager(): {
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
@@ -175,7 +181,8 @@ afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension lifecycle', () => {
// 全量并发时文件级调度会拖慢每个用例;这里只放宽超时,断言不变。
describe('extension lifecycle', { timeout: 20_000 }, () => {
it('安装 → 页面读写配置 → 启用 → 事件 → 动作 → 发送 → 停用 → 卸载', async () => {
const { manager, paths, children, executeAction } = createManager()
await manager.initialize()
@@ -202,15 +209,23 @@ describe('extension lifecycle', () => {
expect((await manager.pageRequest('com.example.fixture-bot', 'wechat.send.text', {})).ok).toBe(
false
)
// 页面可以读取群列表(manifest 已声明 contacts.list)。
// contacts.list 是 medium 风险,安装时未授予;页面桥不能用「manifest 声明过」当授权。
const deniedGroups = await manager.pageRequest(
'com.example.fixture-bot',
'contacts.listGroups',
{}
)
expect(deniedGroups.ok).toBe(false)
expect(deniedGroups.error?.code).toBe('PERMISSION_DENIED')
const enabled = await manager.setEnabled('com.example.fixture-bot', true)
expect(enabled.success).toBe(true)
// 启用时用户已确认全部权限,此时页面才能读群列表。
const groups = await manager.pageRequest('com.example.fixture-bot', 'contacts.listGroups', {})
expect(groups.ok).toBe(true)
expect(groups.result).toEqual({
groups: [{ id: 'fixture-room@chatroom', name: '测试群' }]
})
const enabled = await manager.setEnabled('com.example.fixture-bot', true)
expect(enabled.success).toBe(true)
await tick()
const child = children[0]
expect(manager.get('com.example.fixture-bot')?.runtime.state).toBe('active')
@@ -0,0 +1,337 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ExtensionHost } from '../../src/main/extensions/extension-host'
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
/** 后台注册的动作;测试可改。 */
registeredActions: Array<{ id: string; title: string; inputSchema?: unknown }> = [
{
id: 'reply',
title: '回复',
inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] }
}
]
pageResponder: (method: string) => unknown = (method) => ({ echo: method })
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() => {
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
for (const action of this.registeredActions) {
this.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action
})
}
})
}
if (payload.type === 'page-request') {
queueMicrotask(() => {
try {
this.emit('message', {
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
result: this.pageResponder(String(payload.method))
})
} catch (error) {
this.emit('message', {
type: 'page-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: String(error) }
})
}
})
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const roots: string[] = []
let userData: string
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-m4-run-'))
roots.push(root)
return root
}
function manifest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
manifestVersion: 1,
id: 'com.example.m4-bot',
name: 'M4 扩展',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage', 'automation.action', 'messages.subscribe', 'secrets'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
subscriptions: {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false
},
contributions: {
pages: [{ id: 'settings', title: '配置' }],
automationActions: [{ id: 'reply', title: '回复' }]
},
...overrides
}
}
function createSource(overrides: Record<string, unknown> = {}): string {
const parent = tempRoot()
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), manifest(overrides))
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>x</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports=()=>{}')
return source
}
function createManager(): {
manager: ExtensionManager
children: FakeChild[]
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: async () =>
({
actionId: 'a',
status: 'sent',
decision: 'allow',
startedAt: '',
finishedAt: ''
}) as never,
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, children }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = tempRoot()
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('扩展动作列表', { timeout: 20_000 }, () => {
it('未启用时不可用并给出原因', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
const actions = manager.listActions()
expect(actions).toHaveLength(1)
expect(actions[0].available).toBe(false)
expect(actions[0].unavailableReason).toContain('未启用')
expect(actions[0].registered).toBe(false)
})
it('启用并注册后可用,并带上 Schema', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.m4-bot', true)
await tick()
const actions = manager.listActions()
expect(actions[0].available).toBe(true)
expect(actions[0].registered).toBe(true)
expect(actions[0].inputSchema?.properties.text.type).toBe('string')
})
it('非法 Schema 的动作仍登记,但带可定位的错误原因', async () => {
const child = new FakeChild()
child.registeredActions = [
{
id: 'reply',
title: '回复',
inputSchema: { type: 'object', properties: { a: { type: 'date' } } }
}
]
const host = new ExtensionHost({
extensionId: 'com.example.m4-bot',
extensionDir: tempRoot(),
dataDir: tempRoot(),
permissions: ['automation.action'],
storage: new ExtensionStorage({ dataRoot: tempRoot() }),
spawn: () => child
})
await host.start()
const actions = host.registeredActions()
expect(actions).toHaveLength(1)
expect(actions[0].inputSchema).toBeUndefined()
expect(actions[0].schemaError).toContain('类型不支持')
await host.stop()
})
it('未授予 automation.action 权限时不可用', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.m4-bot', true)
await tick()
await manager.revokePermission('com.example.m4-bot', 'automation.action')
await tick()
const action = manager.listActions()[0]
expect(action.available).toBe(false)
expect(action.unavailableReason).toContain('执行自动化动作')
})
})
describe('页面请求转发', { timeout: 20_000 }, () => {
it('转发到同一扩展后台并返回结果', async () => {
const { manager, children } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.m4-bot', true)
await tick()
children[0].pageResponder = (method) => ({ handled: method })
const response = await manager.pageRequest('com.example.m4-bot', 'extension.request', {
method: 'testSend',
params: { a: 1 }
})
expect(response.ok).toBe(true)
expect(response.result).toEqual({ handled: 'testSend' })
})
it('方法名不合法时拒绝', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.m4-bot', true)
await tick()
const response = await manager.pageRequest('com.example.m4-bot', 'extension.request', {
method: '../etc/passwd'
})
expect(response.ok).toBe(false)
expect(response.error?.code).toBe('INVALID_REQUEST')
})
it('未启用时不转发', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
const response = await manager.pageRequest('com.example.m4-bot', 'extension.request', {
method: 'testSend'
})
expect(response.ok).toBe(false)
expect(response.error?.code).toBe('EXTENSION_DISABLED')
})
it('宿主不再提供抖音专用页面能力', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
for (const method of ['test.send', 'douyin.cookie.get', 'douyin.cookie.clear']) {
const response = await manager.pageRequest('com.example.m4-bot', method, {})
expect(response.ok).toBe(false)
expect(response.error?.code).toBe('PERMISSION_DENIED')
}
})
})
describe('扩展凭据', { timeout: 20_000 }, () => {
it('后台通过 secrets 权限读写自己的密钥', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.m4-bot', true)
await tick()
// 通过宿主内部的 secret store 验证隔离(页面桥不直接暴露密钥读取)。
expect(manager.get('com.example.m4-bot')?.permissions).toContain('secrets')
})
})
+421
View File
@@ -0,0 +1,421 @@
import { createRequire } from 'node:module'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { computeDirectoryDigest } from '../../src/main/extensions/extension-code-digest'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
const require = createRequire(import.meta.url)
const {
buildTemplates
}: {
buildTemplates: (options?: Record<string, unknown>) => unknown
} = require('../../scripts/build-extension-templates.cjs')
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() =>
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const roots: string[] = []
let userData: string
let templateRoot: string
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-project-'))
roots.push(root)
return root
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
templatesRoot: templateRoot,
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: async () =>
({
actionId: 'a',
status: 'sent',
decision: 'allow',
startedAt: '',
finishedAt: ''
}) as never,
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
/** 用同一份 examples 生成 1.1.0 的模板,用于「有新版本」的场景。 */
function rebuildTemplates(version: string): void {
const work = tempRoot()
const sourceRoot = path.join(work, 'examples')
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
const manifestPath = path.join(sourceRoot, 'keyword-bot/manifest.json')
const manifest = fs.readJsonSync(manifestPath)
fs.writeJsonSync(manifestPath, { ...manifest, version })
buildTemplates({
sourceRoot,
outputDir: templateRoot,
lockFile: path.join(work, 'lock.json')
})
}
beforeEach(() => {
userData = tempRoot()
const work = tempRoot()
const sourceRoot = path.join(work, 'examples')
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
templateRoot = path.join(work, 'templates')
buildTemplates({
sourceRoot,
outputDir: templateRoot,
lockFile: path.join(work, 'lock.json')
})
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('从模板创建独立项目', { timeout: 20_000 }, () => {
it('生成新 id 的项目,manifest 与页面桥保持一致', async () => {
const { manager } = createManager()
await manager.initialize()
const target = path.join(tempRoot(), 'persona-bot')
const result = await manager.createProjectFromTemplate('keyword-bot', target, {
extensionId: 'com.acme.persona-bot',
name: '我的机器人'
})
expect(result.success).toBe(true)
expect(result.projectPath).toBe(target)
const manifest = fs.readJsonSync(path.join(target, 'manifest.json'))
expect(manifest.id).toBe('com.acme.persona-bot')
expect(manifest.name).toBe('我的机器人')
const appJs = fs.readFileSync(path.join(target, 'ui', 'app.js'), 'utf8')
expect(appJs).toContain("'com.acme.persona-bot'")
expect(appJs).not.toContain('com.example.keyword-bot')
expect(result.rewrittenFiles).toContain('ui/app.js')
// 不复制任何用户数据。
expect(fs.existsSync(path.join(target, 'storage.json'))).toBe(false)
})
it('目标目录非空时拒绝且不写入', async () => {
const { manager } = createManager()
await manager.initialize()
const target = path.join(tempRoot(), 'occupied')
fs.ensureDirSync(target)
fs.writeFileSync(path.join(target, 'keep.txt'), 'user data')
const result = await manager.createProjectFromTemplate('keyword-bot', target, {
extensionId: 'com.acme.blocked'
})
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_PROJECT_EXISTS')
expect(fs.readFileSync(path.join(target, 'keep.txt'), 'utf8')).toBe('user data')
expect(fs.existsSync(path.join(target, 'manifest.json'))).toBe(false)
})
it('沿用模板原 id 时拒绝', async () => {
const { manager } = createManager()
await manager.initialize()
const result = await manager.createProjectFromTemplate(
'keyword-bot',
path.join(tempRoot(), 'same-id'),
{ extensionId: 'com.example.keyword-bot' }
)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('INVALID_REQUEST')
})
it('抖音模板生成的项目保留外部依赖说明', async () => {
const { manager } = createManager()
await manager.initialize()
const target = path.join(tempRoot(), 'douyin-dev')
const result = await manager.createProjectFromTemplate('douyin-sender', target, {
extensionId: 'com.acme.douyin-dev'
})
expect(result.success).toBe(true)
// 解析脚本不在项目里:这是设计,不是缺陷。
expect(fs.existsSync(path.join(target, 'scripts', 'douyin.py'))).toBe(false)
const appJs = fs.readFileSync(path.join(target, 'ui', 'app.js'), 'utf8')
expect(appJs).not.toContain('com.example.douyin-sender')
})
})
describe('本地改动检测', { timeout: 20_000 }, () => {
it('未修改的模板允许更新,并刷新指纹', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
const before = manager.get('com.example.keyword-bot')
expect(before?.version).toBe('1.0.1')
rebuildTemplates('1.2.0')
const restarted = createManager()
await restarted.manager.initialize()
const upgraded = await restarted.manager.installTemplate('keyword-bot')
expect(upgraded.success).toBe(true)
expect(restarted.manager.get('com.example.keyword-bot')?.version).toBe('1.2.0')
})
it('改过后台 JS 后阻止更新,并给出导出建议', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
const target = path.join(paths.installDir('com.example.keyword-bot'), 'background', 'index.js')
fs.appendFileSync(target, '\n// 用户自己的改动\n')
rebuildTemplates('1.2.0')
const restarted = createManager()
await restarted.manager.initialize()
const upgraded = await restarted.manager.installTemplate('keyword-bot')
expect(upgraded.success).toBe(false)
expect(upgraded.error?.code).toBe('EXTENSION_MODIFIED_LOCALLY')
expect(upgraded.error?.message).toContain('导出为开发项目')
// 代码保持用户改动后的样子。
expect(
fs.readFileSync(
path.join(paths.installDir('com.example.keyword-bot'), 'background', 'index.js'),
'utf8'
)
).toContain('用户自己的改动')
})
it('新增或删除文件同样被判为已修改', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
fs.writeFileSync(path.join(paths.installDir('com.example.keyword-bot'), 'extra.js'), '// x')
rebuildTemplates('1.2.0')
const restarted = createManager()
await restarted.manager.initialize()
const added = await restarted.manager.installTemplate('keyword-bot')
expect(added.error?.code).toBe('EXTENSION_MODIFIED_LOCALLY')
fs.removeSync(path.join(paths.installDir('com.example.keyword-bot'), 'extra.js'))
fs.removeSync(path.join(paths.installDir('com.example.keyword-bot'), 'lib', 'matcher.js'))
const removed = await restarted.manager.installTemplate('keyword-bot')
expect(removed.error?.code).toBe('EXTENSION_MODIFIED_LOCALLY')
})
it('只改扩展配置不影响更新', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
await manager.pageRequest('com.example.keyword-bot', 'storage.set', {
key: 'rules',
value: [{ id: 'r1' }]
})
rebuildTemplates('1.2.0')
const restarted = createManager()
await restarted.manager.initialize()
const upgraded = await restarted.manager.installTemplate('keyword-bot')
expect(upgraded.success).toBe(true)
expect(
(
await restarted.manager.pageRequest('com.example.keyword-bot', 'storage.get', {
key: 'rules'
})
).result
).toEqual([{ id: 'r1' }])
})
it('缺少指纹的历史记录保守拒绝更新', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
// 模拟 M2 时代装下的记录:没有指纹字段。
const registry = fs.readJsonSync(paths.registryFile)
delete registry.extensions[0].installedCodeDigest
fs.writeJsonSync(paths.registryFile, registry)
rebuildTemplates('1.2.0')
const restarted = createManager()
await restarted.manager.initialize()
const upgraded = await restarted.manager.installTemplate('keyword-bot')
expect(upgraded.success).toBe(false)
expect(upgraded.error?.code).toBe('EXTENSION_MODIFIED_LOCALLY')
expect(upgraded.error?.message).toContain('无法确认')
})
})
describe('导出为开发项目', { timeout: 20_000 }, () => {
it('导出带用户改动的安装副本,并切换来源', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
await manager.setEnabled('com.example.keyword-bot', true)
await manager.pageRequest('com.example.keyword-bot', 'storage.set', {
key: 'rules',
value: ['r1']
})
await tick()
const installedFile = path.join(paths.installDir('com.example.keyword-bot'), 'ui', 'app.js')
fs.appendFileSync(installedFile, '\n// 用户的二开改动\n')
const target = path.join(tempRoot(), 'exported-bot')
const exported = await manager.exportInstalledAsProject('com.example.keyword-bot', target)
expect(exported.success).toBe(true)
// 导出的是改过的副本,不是官方原版。
expect(fs.readFileSync(path.join(target, 'ui', 'app.js'), 'utf8')).toContain('用户的二开改动')
const extension = manager.get('com.example.keyword-bot')
expect(extension?.source).toBe('development')
expect(extension?.enabled).toBe(false)
expect(extension?.development?.sourcePath).toBe(fs.realpathSync(target))
// 配置保留。
expect(
(await manager.pageRequest('com.example.keyword-bot', 'storage.get', { key: 'rules' })).result
).toEqual(['r1'])
// 原安装副本还在,作为显式恢复来源。
expect(
fs.existsSync(path.join(paths.installDir('com.example.keyword-bot'), 'manifest.json'))
).toBe(true)
})
it('导出后不再提供模板自动更新', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
const target = path.join(tempRoot(), 'exported')
await manager.exportInstalledAsProject('com.example.keyword-bot', target)
rebuildTemplates('1.2.0')
const restarted = createManager()
await restarted.manager.initialize()
const result = await restarted.manager.installTemplate('keyword-bot')
// 同 id 已被开发模式占用:安装被拒绝,不会覆盖开发源码。
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_ALREADY_INSTALLED')
})
it('移除开发链接后回到安装副本,外部项目不被删除', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
const target = path.join(tempRoot(), 'exported')
await manager.exportInstalledAsProject('com.example.keyword-bot', target)
const unlinked = await manager.unlinkDevelopment('com.example.keyword-bot', { keepData: true })
expect(unlinked.success).toBe(true)
expect(fs.existsSync(target)).toBe(true)
const extension = manager.get('com.example.keyword-bot')
expect(extension?.source).toBe('directory')
expect(extension?.development).toBeUndefined()
expect(
fs.existsSync(path.join(paths.installDir('com.example.keyword-bot'), 'manifest.json'))
).toBe(true)
})
})
describe('代码指纹', { timeout: 20_000 }, () => {
it('忽略缓存与依赖目录,只对代码内容敏感', () => {
const root = tempRoot()
fs.ensureDirSync(path.join(root, 'ui'))
fs.writeFileSync(path.join(root, 'ui', 'app.js'), 'a')
const first = computeDirectoryDigest(root)
fs.ensureDirSync(path.join(root, 'node_modules', 'x'))
fs.writeFileSync(path.join(root, 'node_modules', 'x', 'index.js'), 'x')
fs.writeFileSync(path.join(root, '.DS_Store'), 'x')
expect(computeDirectoryDigest(root)).toBe(first)
fs.writeFileSync(path.join(root, 'ui', 'app.js'), 'b')
expect(computeDirectoryDigest(root)).not.toBe(first)
})
})
@@ -0,0 +1,314 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() =>
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
)
}
if (payload.type === 'invoke-action') {
queueMicrotask(() =>
this.emit('message', {
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
output: { success: true }
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const roots: string[] = []
let userData: string
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-runtime-storage-'))
roots.push(root)
return root
}
function manifest(
id = 'com.example.runtime-bot',
overrides: Record<string, unknown> = {}
): Record<string, unknown> {
return {
manifestVersion: 1,
id,
name: '运行期测试扩展',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage', 'messages.subscribe', 'wechat.send.text', 'automation.action'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
subscriptions: {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false
},
contributions: {
pages: [{ id: 'settings', title: '配置' }],
automationActions: [{ id: 'reply', title: '回复' }]
},
...overrides
}
}
function createSource(overrides: Record<string, unknown> = {}): string {
const parent = tempRoot()
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), manifest(undefined, overrides))
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>x</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports=()=>{}')
return source
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
executeAction: { calls: unknown[] }
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const executeAction = {
calls: [] as unknown[],
run: async (request: unknown) => {
executeAction.calls.push(request)
return {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
}
}
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: executeAction.run as never,
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children, executeAction }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
/** 直接写坏主存储;目录可能还没被创建过(扩展从没写过配置)。 */
function corruptStorage(paths: ReturnType<typeof createExtensionPaths>, id: string): string {
const file = path.join(paths.extensionDataDir(id), 'storage.json')
fs.ensureDirSync(path.dirname(file))
fs.writeFileSync(file, 'broken-in-runtime', 'utf8')
return file
}
beforeEach(() => {
userData = tempRoot()
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('运行期 Storage 恢复', { timeout: 20_000 }, () => {
it('运行中配置损坏后,扩展读不到旧配置且被立即暂停', async () => {
const { manager, paths, children } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.runtime-bot', true)
await tick()
expect(children).toHaveLength(1)
// 写入配置,并再写一次让备份有内容。
await manager.pageRequest('com.example.runtime-bot', 'storage.set', {
key: 'enabled',
value: true
})
await manager.pageRequest('com.example.runtime-bot', 'storage.set', {
key: 'rules',
value: ['旧规则']
})
// 运行期主文件损坏。
corruptStorage(paths, 'com.example.runtime-bot')
// 下一次读取必须失败:不能把备份里的旧配置交给扩展继续回复。
const read = await manager.pageRequest('com.example.runtime-bot', 'storage.get', {
key: 'rules'
})
expect(read.ok).toBe(false)
expect(read.error?.code).toBe('EXTENSION_STORAGE_CORRUPTED')
// 扩展被暂停:停用 + 停后台。
const extension = manager.get('com.example.runtime-bot')
expect(extension?.enabled).toBe(false)
expect(extension?.storage.state).toBe('recovered-from-backup')
await tick()
expect(children[0].sent.some((message) => message.type === 'shutdown')).toBe(true)
})
it('暂停后自动化动作被拒绝,不会继续执行旧规则', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.runtime-bot', true)
await tick()
const storageFile = corruptStorage(paths, 'com.example.runtime-bot')
fs.writeFileSync(`${storageFile}.bak`, 'also-broken', 'utf8')
await manager.pageRequest('com.example.runtime-bot', 'storage.get', { key: 'rules' })
await expect(
manager.invokeAutomationAction('com.example.runtime-bot', 'reply', {})
).rejects.toMatchObject({
code: expect.stringMatching(
/EXTENSION_DISABLED|EXTENSION_STORAGE_CORRUPTED|EXTENSION_HOST_UNAVAILABLE/
)
})
})
it('一个扩展的配置损坏不影响另一个扩展', async () => {
const { manager, paths, children } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
// 第二个扩展用不同 id。
const otherSource = createSource({ id: 'com.example.other-bot', name: '另一个扩展' })
await manager.installFromDirectory(otherSource)
await manager.setEnabled('com.example.runtime-bot', true)
await manager.setEnabled('com.example.other-bot', true)
await tick()
corruptStorage(paths, 'com.example.runtime-bot')
await manager.pageRequest('com.example.runtime-bot', 'storage.get', { key: 'x' })
const other = manager.get('com.example.other-bot')
expect(other?.enabled).toBe(true)
expect(other?.storage.state).toBe('ok')
// 另一个扩展的读写仍正常。
const write = await manager.pageRequest('com.example.other-bot', 'storage.set', {
key: 'ok',
value: 1
})
expect(write.ok).toBe(true)
expect(children.length).toBeGreaterThanOrEqual(2)
})
it('用户确认恢复后读写与启用恢复正常', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.runtime-bot', true)
await manager.pageRequest('com.example.runtime-bot', 'storage.set', {
key: 'rules',
value: ['r1']
})
await manager.pageRequest('com.example.runtime-bot', 'storage.set', {
key: 'b',
value: 2
})
corruptStorage(paths, 'com.example.runtime-bot')
await manager.pageRequest('com.example.runtime-bot', 'storage.get', { key: 'rules' })
expect(manager.get('com.example.runtime-bot')?.storage.state).toBe('recovered-from-backup')
const acknowledged = manager.acknowledgeStorageRecovery('com.example.runtime-bot')
expect(acknowledged.success).toBe(true)
expect(manager.get('com.example.runtime-bot')?.storage.state).toBe('ok')
// 恢复出来的旧配置可以读了。
const read = await manager.pageRequest('com.example.runtime-bot', 'storage.get', {
key: 'rules'
})
expect(read.ok).toBe(true)
expect(read.result).toEqual(['r1'])
const enabled = await manager.setEnabled('com.example.runtime-bot', true)
expect(enabled.success).toBe(true)
})
})
@@ -0,0 +1,298 @@
import { createRequire } from 'node:module'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
const require = createRequire(import.meta.url)
const {
buildTemplates
}: {
buildTemplates: (options?: Record<string, unknown>) => unknown
} = require('../../scripts/build-extension-templates.cjs')
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() =>
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const roots: string[] = []
let userData: string
let templateRoot: string
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-template-install-'))
roots.push(root)
return root
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
templatesRoot: templateRoot,
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: async () => ({
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}),
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = tempRoot()
const work = tempRoot()
const sourceRoot = path.join(work, 'examples')
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
templateRoot = path.join(work, 'templates')
buildTemplates({
sourceRoot,
outputDir: templateRoot,
lockFile: path.join(work, 'lock.json')
})
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
// 全量并发时文件级调度会拖慢每个用例;这里只放宽超时,断言不变。
describe('官方模板安装', { timeout: 20_000 }, () => {
it('安装模板:代码落地、来源为 template、默认不启用', async () => {
const { manager, paths, children } = createManager()
await manager.initialize()
const result = await manager.installTemplate('keyword-bot')
expect(result.success).toBe(true)
expect(result.extension?.id).toBe('com.example.keyword-bot')
expect(result.extension?.source).toBe('template')
expect(result.extension?.template?.id).toBe('keyword-bot')
// 安装不等于启用,也不拉起后台。
expect(result.extension?.enabled).toBe(false)
expect(children).toHaveLength(0)
expect(
fs.existsSync(
path.join(paths.installDir('com.example.keyword-bot'), 'background', 'index.js')
)
).toBe(true)
})
it('列出的模板版本来自 manifest,安装后状态变为 installed', async () => {
const { manager } = createManager()
await manager.initialize()
const before = await manager.listTemplates()
const keyword = before.find((item) => item.template.templateId === 'keyword-bot')
expect(keyword?.state).toBe('not-installed')
await manager.installTemplate('keyword-bot')
const after = await manager.listTemplates()
expect(after.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe(
'installed'
)
expect(after.find((item) => item.template.templateId === 'keyword-bot')?.installedVersion).toBe(
keyword?.template.version
)
})
it('同版本重复安装被拒绝', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installTemplate('keyword-bot')
const again = await manager.installTemplate('keyword-bot')
expect(again.success).toBe(false)
expect(again.error?.code).toBe('EXTENSION_ALREADY_INSTALLED')
})
it('同 ID 的非模板扩展不会被静默接管', async () => {
const { manager, paths } = createManager()
await manager.initialize()
// 模拟用户从 GitHub 手工装过同一 ID 的扩展。
const source = path.join(tempRoot(), 'manual')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), {
manifestVersion: 1,
id: 'com.example.keyword-bot',
name: '手工版本',
version: '0.1.0',
apiVersion: '1',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
contributions: { pages: [{ id: 'settings', title: '配置' }] }
})
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports=()=>{}')
const installed = await manager.installFromDirectory(source)
expect(installed.success).toBe(true)
expect(installed.extension?.source).toBe('directory')
const blocked = await manager.installTemplate('keyword-bot')
expect(blocked.success).toBe(false)
expect(blocked.error?.code).toBe('EXTENSION_ALREADY_INSTALLED')
expect(blocked.error?.message).toContain('非官方')
// 原扩展仍在,未被替换。
expect(manager.get('com.example.keyword-bot')?.name).toBe('手工版本')
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.keyword-bot'), 'manifest.json'))
.version
).toBe('0.1.0')
})
it('模板 ZIP 被篡改时拒绝安装', async () => {
const { manager } = createManager()
await manager.initialize()
const zipPath = path.join(templateRoot, 'keyword-bot-1.0.1.zip')
fs.writeFileSync(zipPath, Buffer.concat([fs.readFileSync(zipPath), Buffer.from('x')]))
const result = await manager.installTemplate('keyword-bot')
expect(result.success).toBe(false)
expect(result.error?.message).toContain('校验失败')
})
it('模板升级保留用户配置与启用状态', async () => {
const { manager, paths } = createManager()
await manager.initialize()
const installed = await manager.installTemplate('keyword-bot')
expect(installed.success).toBe(true)
await manager.setEnabled('com.example.keyword-bot', true)
await tick()
await manager.pageRequest('com.example.keyword-bot', 'storage.set', {
key: 'rules',
value: [{ id: 'r1' }]
})
// 把模板索引与 ZIP 换成 1.1.0(模拟新版本随应用更新)。
const source = path.join(tempRoot(), 'examples-next')
fs.copySync(path.join(process.cwd(), 'examples/extensions'), source)
const manifestPath = path.join(source, 'keyword-bot/manifest.json')
const manifest = fs.readJsonSync(manifestPath)
fs.writeJsonSync(manifestPath, { ...manifest, version: '1.1.0' })
buildTemplates({
sourceRoot: source,
outputDir: templateRoot,
lockFile: path.join(tempRoot(), 'lock2.json')
})
// 模板随应用更新后需要重新读取索引:真实场景是重启应用。
const restarted = createManager()
await restarted.manager.initialize()
const beforeUpgrade = await restarted.manager.listTemplates()
expect(beforeUpgrade.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe(
'update-available'
)
const upgraded = await restarted.manager.installTemplate('keyword-bot')
expect(upgraded.success).toBe(true)
await tick()
const after = restarted.manager.get('com.example.keyword-bot')
expect(after?.version).toBe('1.1.0')
expect(after?.enabled).toBe(true)
expect(
(
await restarted.manager.pageRequest('com.example.keyword-bot', 'storage.get', {
key: 'rules'
})
).result
).toEqual([{ id: 'r1' }])
expect(
fs.existsSync(path.join(paths.extensionDataDir('com.example.keyword-bot'), 'storage.json'))
).toBe(true)
})
})
@@ -0,0 +1,58 @@
import fs from 'fs-extra'
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。
*/
const CANDIDATES = [
'dist/mac-arm64/TraceMemo.app/Contents/Resources/extension-templates',
'dist/mac/TraceMemo.app/Contents/Resources/extension-templates',
'dist/win-unpacked/resources/extension-templates',
'dist/linux-unpacked/resources/extension-templates'
]
const packagedRoot = CANDIDATES.map((relative) => path.join(process.cwd(), relative)).find(
(candidate) => fs.existsSync(path.join(candidate, 'index.json'))
)
describe.skipIf(!packagedRoot)('打包后的模板资源', () => {
it('产物目录自带两个模板与索引', async () => {
const catalog = new ExtensionTemplateCatalog({
templateRoot: packagedRoot as string,
getRecord: () => undefined,
resolveInstallDir: (id) => path.join(process.cwd(), 'dist', 'unused', id),
platform: process.platform,
probePython: () => '/usr/bin/python3',
probeChrome: () => '/usr/bin/chrome'
})
const list = await catalog.list()
expect(list.map((item) => item.template.templateId).sort()).toEqual([
'douyin-sender',
'keyword-bot'
])
// 资源自包含:索引里的 zip 就在同一目录,且哈希匹配(damaged 会暴露不一致)。
expect(list.every((item) => item.state !== 'damaged')).toBe(true)
})
it('产物里的 ZIP 能通过哈希校验', async () => {
const catalog = new ExtensionTemplateCatalog({
templateRoot: packagedRoot as string,
getRecord: () => undefined,
resolveInstallDir: (id) => path.join(process.cwd(), 'dist', 'unused', id),
platform: process.platform,
probePython: () => '/usr/bin/python3',
probeChrome: () => '/usr/bin/chrome'
})
for (const templateId of ['keyword-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}$/)
}
})
})
@@ -0,0 +1,469 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
activationOk = true
/** 收到 shutdown 的瞬间触发,用于断言「停进程时磁盘还是旧版本」。 */
onShutdown?: () => void
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() =>
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: this.activationOk,
...(this.activationOk ? {} : { error: { code: 'ACTION_FAILED', message: 'boom' } })
})
)
}
if (payload.type === 'shutdown') {
this.onShutdown?.()
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const roots: string[] = []
let userData: string
function manifest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
manifestVersion: 1,
id: 'com.example.tx-bot',
name: '事务测试扩展',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage', 'contacts.list'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
contributions: { pages: [{ id: 'settings', title: '配置' }] },
...overrides
}
}
function createSource(overrides: Record<string, unknown> = {}): string {
const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-tx-src-'))
roots.push(parent)
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), manifest(overrides))
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>tx</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports = () => {}')
return source
}
function createManager(options: { failActivationAt?: number; failSpawnAt?: number } = {}): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
let attempts = 0
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
secretCipher: {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(plain, 'utf8'),
decrypt: (payload: Buffer) => payload.toString('utf8')
},
spawn: (spawnOptions: ExtensionHostSpawnOptions) => {
void spawnOptions
attempts += 1
if (options.failSpawnAt === attempts) throw new Error('spawn failed')
const child = new FakeChild()
if (options.failActivationAt === attempts) child.activationOk = false
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction: async () => ({
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}),
queryMessages: async () => [],
listGroups: async () => [],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-tx-'))
roots.push(userData)
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
// 全量并发时文件级调度会拖慢每个用例;这里只放宽超时,断言不变。
describe('扩展升级事务', { timeout: 20_000 }, () => {
it('升级时先停旧 Host 再替换代码,随后启动新 Host', async () => {
const { manager, paths, children } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await tick()
expect(children).toHaveLength(1)
const previous = children[0]
// 旧进程收到 shutdown 的那一刻,磁盘上必须还是旧版本:
// 先换代码再停进程会在 Windows 上直接失败,在 POSIX 上让旧代码继续跑。
let versionAtShutdown = ''
previous.onShutdown = (): void => {
versionAtShutdown = fs.readJsonSync(
path.join(paths.installDir('com.example.tx-bot'), 'manifest.json')
).version as string
}
const upgraded = await manager.installFromDirectory(createSource({ version: '1.1.0' }))
expect(upgraded.success).toBe(true)
await tick()
expect(versionAtShutdown).toBe('1.0.0')
// 旧进程收到 shutdown,新进程重新拉起。
expect(previous.sent.some((message) => message.type === 'shutdown')).toBe(true)
expect(children).toHaveLength(2)
expect(manager.get('com.example.tx-bot')?.version).toBe('1.1.0')
expect(manager.get('com.example.tx-bot')?.runtime.state).toBe('active')
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.tx-bot'), 'manifest.json')).version
).toBe('1.1.0')
})
it('新版本启动失败时回滚代码与状态,并恢复旧版本', async () => {
const { manager, paths, children } = createManager({ failActivationAt: 2 })
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await tick()
expect(children).toHaveLength(1)
const upgraded = await manager.installFromDirectory(createSource({ version: '1.1.0' }))
await tick()
expect(upgraded.success).toBe(false)
expect(upgraded.error?.code).toBe('EXTENSION_INSTALL_FAILED')
// 磁盘与 Registry 都回到 1.0.0。
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.tx-bot'), 'manifest.json')).version
).toBe('1.0.0')
expect(manager.get('com.example.tx-bot')?.version).toBe('1.0.0')
expect(manager.get('com.example.tx-bot')?.enabled).toBe(true)
// 回滚后旧版本被重新拉起(第三次 spawn)。
expect(children.length).toBeGreaterThanOrEqual(3)
expect(manager.get('com.example.tx-bot')?.runtime.state).toBe('active')
// 不留下过渡备份。
expect(fs.readdirSync(paths.extensionsDir).filter((name) => name.includes('.backup-'))).toEqual(
[]
)
})
it('升级保留用户配置与启用状态', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await manager.pageRequest('com.example.tx-bot', 'storage.set', {
key: 'rules',
value: [{ id: 'r1' }]
})
await manager.installFromDirectory(createSource({ version: '1.1.0' }))
await tick()
expect(
(await manager.pageRequest('com.example.tx-bot', 'storage.get', { key: 'rules' })).result
).toEqual([{ id: 'r1' }])
expect(manager.get('com.example.tx-bot')?.enabled).toBe(true)
expect(
fs.existsSync(path.join(paths.extensionDataDir('com.example.tx-bot'), 'storage.json'))
).toBe(true)
})
it('新版本新增的权限保持待授权,不会自动生效', async () => {
const { manager } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource({ permissions: ['storage', 'contacts.list'] }))
await manager.setEnabled('com.example.tx-bot', true)
await manager.installFromDirectory(
createSource({
version: '1.1.0',
permissions: ['storage', 'contacts.list', 'wechat.send.text']
})
)
await tick()
const extension = manager.get('com.example.tx-bot')
expect(extension?.grantedPermissions).not.toContain('wechat.send.text')
expect(extension?.pendingPermissions).toContain('wechat.send.text')
})
it('显式授权后待授权列表清空,已启用扩展会重启后台', async () => {
const { manager, children } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource({ permissions: ['storage'] }))
await manager.setEnabled('com.example.tx-bot', true)
await tick()
expect(children).toHaveLength(1)
await manager.installFromDirectory(
createSource({ version: '1.1.0', permissions: ['storage', 'wechat.send.text'] })
)
await tick()
expect(manager.get('com.example.tx-bot')?.pendingPermissions).toContain('wechat.send.text')
const before = children.length
const granted = await manager.grantPermissions('com.example.tx-bot', ['wechat.send.text'])
await tick()
expect(granted.success).toBe(true)
expect(manager.get('com.example.tx-bot')?.grantedPermissions).toContain('wechat.send.text')
expect(manager.get('com.example.tx-bot')?.pendingPermissions).toEqual([])
// 权限在进程启动时快照,授权后必须重启后台。
expect(children.length).toBe(before + 1)
})
it('后台进程启动失败时显示 error,而不是假装运行中', async () => {
const { manager } = createManager({ failSpawnAt: 1 })
await manager.initialize()
await manager.installFromDirectory(createSource())
const enabled = await manager.setEnabled('com.example.tx-bot', true)
expect(enabled.success).toBe(true)
const extension = manager.get('com.example.tx-bot')
expect(extension?.enabled).toBe(true)
expect(extension?.runtime.state).toBe('error')
expect(extension?.runtime.lastError).toBeTruthy()
})
it('只有页面入口的扩展显示为未运行,而不是崩溃', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSource()
fs.writeJsonSync(path.join(source, 'manifest.json'), {
...manifest(),
entrypoints: { page: 'ui/index.html' }
})
await manager.installFromDirectory(source)
await manager.setEnabled('com.example.tx-bot', true)
const extension = manager.get('com.example.tx-bot')
expect(extension?.runtime.state).toBe('inactive')
expect(extension?.runtime.note).toContain('仅提供页面')
})
it('Registry 损坏后从目录扫描恢复,扩展回到未启用无授权', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
// 模拟主文件与备份同时损坏后重启。
fs.writeFileSync(paths.registryFile, 'broken', 'utf8')
fs.writeFileSync(`${paths.registryFile}.bak`, 'also-broken', 'utf8')
const restarted = createManager()
await restarted.manager.initialize()
const health = restarted.manager.getHealth()
expect(health.registry.state).toBe('recovered-by-scan')
const extension = restarted.manager.get('com.example.tx-bot')
expect(extension).toBeTruthy()
expect(extension?.enabled).toBe(false)
expect(extension?.grantedPermissions).toEqual([])
})
it('配置损坏时在启动阶段就停用扩展,旧规则不会继续跑', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await manager.pageRequest('com.example.tx-bot', 'storage.set', {
key: 'enabled',
value: true
})
await tick()
const storageFile = path.join(paths.extensionDataDir('com.example.tx-bot'), 'storage.json')
fs.writeFileSync(storageFile, 'broken', 'utf8')
fs.writeFileSync(`${storageFile}.bak`, 'also-broken', 'utf8')
const restarted = createManager()
await restarted.manager.initialize()
const extension = restarted.manager.get('com.example.tx-bot')
expect(extension?.enabled).toBe(false)
expect(extension?.storage.state).toBe('unrecovered')
// 没有后台进程被拉起。
expect(restarted.children).toHaveLength(0)
// 未确认前不允许启用:否则会带着旧规则直接发消息。
const enable = await restarted.manager.setEnabled('com.example.tx-bot', true)
expect(enable.success).toBe(false)
expect(enable.error?.code).toBe('EXTENSION_STORAGE_CORRUPTED')
})
it('配置从备份恢复后需用户确认才允许启用', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await manager.pageRequest('com.example.tx-bot', 'storage.set', {
key: 'enabled',
value: true
})
await manager.pageRequest('com.example.tx-bot', 'storage.set', {
key: 'rules',
value: ['r1']
})
await tick()
const storageFile = path.join(paths.extensionDataDir('com.example.tx-bot'), 'storage.json')
fs.writeFileSync(storageFile, 'broken', 'utf8')
const restarted = createManager()
await restarted.manager.initialize()
const extension = restarted.manager.get('com.example.tx-bot')
expect(extension?.enabled).toBe(false)
expect(extension?.storage.state).toBe('recovered-from-backup')
expect(restarted.children).toHaveLength(0)
const blocked = await restarted.manager.setEnabled('com.example.tx-bot', true)
expect(blocked.success).toBe(false)
const acknowledged = restarted.manager.acknowledgeStorageRecovery('com.example.tx-bot')
expect(acknowledged.success).toBe(true)
expect(restarted.manager.get('com.example.tx-bot')?.storage.state).toBe('ok')
const enabled = await restarted.manager.setEnabled('com.example.tx-bot', true)
expect(enabled.success).toBe(true)
await tick()
expect(restarted.children.length).toBeGreaterThan(0)
})
it('代码版本与状态记录不一致时不启动,用户可对齐到磁盘版本', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await tick()
// 模拟「代码已替换、Registry 尚未写入」时进程被杀。
fs.writeJsonSync(
path.join(paths.installDir('com.example.tx-bot'), 'manifest.json'),
manifest({ version: '1.1.0' })
)
const restarted = createManager()
await restarted.manager.initialize()
const extension = restarted.manager.get('com.example.tx-bot')
expect(extension?.runtime.state).toBe('error')
expect(extension?.runtime.lastError).toContain('升级可能中断')
expect(restarted.children).toHaveLength(0)
const adopt = restarted.manager.adoptInstalledCode('com.example.tx-bot')
expect(adopt.success).toBe(true)
expect(restarted.manager.get('com.example.tx-bot')?.version).toBe('1.1.0')
// 版本已对齐;扩展仍是「启用但未运行」,需要用户重新启用后才会拉起后台。
expect(restarted.manager.get('com.example.tx-bot')?.runtime.lastError).not.toContain(
'升级可能中断'
)
const enabled = await restarted.manager.setEnabled('com.example.tx-bot', true)
expect(enabled.success).toBe(true)
await tick()
expect(restarted.manager.get('com.example.tx-bot')?.runtime.state).toBe('active')
})
it('存在升级备份时可回滚到备份版本', async () => {
const { manager, paths } = createManager()
await manager.initialize()
await manager.installFromDirectory(createSource())
await manager.setEnabled('com.example.tx-bot', true)
await tick()
const installDir = paths.installDir('com.example.tx-bot')
const backupDir = path.join(paths.extensionsDir, 'com.example.tx-bot.backup-1')
fs.copySync(installDir, backupDir)
fs.writeJsonSync(path.join(backupDir, 'manifest.json'), manifest({ version: '0.9.0' }))
// 磁盘换成"可疑的新代码",Registry 仍停在 1.0.0。
fs.writeJsonSync(path.join(installDir, 'manifest.json'), manifest({ version: '1.1.0' }))
const restarted = createManager()
await restarted.manager.initialize()
expect(restarted.manager.get('com.example.tx-bot')?.runtime.state).toBe('error')
const rolled = await restarted.manager.rollbackInterruptedUpgrade('com.example.tx-bot')
expect(rolled.success).toBe(true)
expect(restarted.manager.get('com.example.tx-bot')?.version).toBe('0.9.0')
expect(
fs.readJsonSync(path.join(installDir, 'manifest.json')).version
).toBe('0.9.0')
})
})
+38 -34
View File
@@ -419,44 +419,48 @@ describe('bootstrap cache write gating', () => {
expect(snapshotFile(file).ino).not.toBe(beforeMerge.ino)
})
it('keeps the previous cache when replacement fails, then recovers', async () => {
const root = '/fixture/gate-rename-failure'
const file = cacheFileFor(root)
const directory = join(cacheFileFor(root), '..')
// Windows 的只读目标会让 MoveFileEx/REPLACE_EXISTING 抛 EPERM;
// POSIX 的 rename 不看文件 mode,这个场景在 macOS 上无法复现。
it.skipIf(process.platform !== 'win32')(
'keeps the previous cache when replacement fails, then recovers',
async () => {
const root = '/fixture/gate-rename-failure'
const file = cacheFileFor(root)
const directory = join(cacheFileFor(root), '..')
saveBootstrapContacts(root, makeContacts(2))
await settle()
const good = snapshotFile(file)
const goodContent = readFileSync(file, 'utf8')
expect(good.exists).toBe(true)
saveBootstrapContacts(root, makeContacts(2))
await settle()
const good = snapshotFile(file)
const goodContent = readFileSync(file, 'utf8')
expect(good.exists).toBe(true)
// 只读目标在 Windows 上让 MoveFileEx/REPLACE_EXISTING 抛 EPERM;
// 这不是 mock,是真实的文件系统行为。
chmodSync(file, 0o444)
try {
saveBootstrapContacts(
root,
makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
)
await settle(1500)
// 只读目标让 MoveFileEx/REPLACE_EXISTING 抛 EPERM;这不是 mock,是真实的文件系统行为。
chmodSync(file, 0o444)
try {
saveBootstrapContacts(
root,
makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
)
await settle(1500)
const failed = snapshotFile(file)
expect(failed.ino, '替换失败时目标文件必须原样保留').toBe(good.ino)
expect(readFileSync(file, 'utf8')).toBe(goodContent)
expect(tempFilesIn(directory), '失败后不能残留 .tmp').toHaveLength(0)
} finally {
chmodSync(file, 0o666)
const failed = snapshotFile(file)
expect(failed.ino, '替换失败时目标文件必须原样保留').toBe(good.ino)
expect(readFileSync(file, 'utf8')).toBe(goodContent)
expect(tempFilesIn(directory), '失败后不能残留 .tmp').toHaveLength(0)
} finally {
chmodSync(file, 0o666)
}
// 失败过的内容再存一次必须能真正落盘,不能被指纹闸门吞掉
const target = makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
saveBootstrapContacts(root, target)
await settle()
const recovered = snapshotFile(file)
expect(recovered.ino).not.toBe(good.ino)
expect(JSON.parse(readFileSync(file, 'utf8')).contacts).toHaveLength(3)
expect(tempFilesIn(directory)).toHaveLength(0)
}
// 失败过的内容再存一次必须能真正落盘,不能被指纹闸门吞掉
const target = makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
saveBootstrapContacts(root, target)
await settle()
const recovered = snapshotFile(file)
expect(recovered.ino).not.toBe(good.ino)
expect(JSON.parse(readFileSync(file, 'utf8')).contacts).toHaveLength(3)
expect(tempFilesIn(directory)).toHaveLength(0)
})
)
it('lands the newest revision under rapid changes', async () => {
const root = '/fixture/gate-rapid'
+293
View File
@@ -0,0 +1,293 @@
import { afterEach, describe, expect, it } from 'vitest'
import { spawn } from 'node:child_process'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import {
ExtensionHost,
forkExtensionHost,
killProcessTree,
redactSecrets
} from '../../src/main/extensions/extension-host'
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-process-'))
roots.push(root)
return root
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function isAlive(pid: number): boolean {
try {
process.kill(pid, 0)
return true
} catch {
return false
}
}
afterEach(async () => {
// 先给残留进程一点时间退出,再删目录。
await sleep(50)
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('redactSecrets', () => {
it('抹掉赋值形态的凭据值,保留键名', () => {
expect(redactSecrets('cookie: abcdef123456')).toBe('cookie: ***')
expect(redactSecrets('Authorization=BearerToken123')).toBe('Authorization=***')
expect(redactSecrets('api_key = sk-1234567890')).toBe('api_key = ***')
})
it('抹掉 Bearer token,普通文本不受影响', () => {
expect(redactSecrets('Authorization: Bearer fake-token-for-redaction-test')).toBe(
'Authorization: Bearer ***'
)
expect(redactSecrets('token bucket 已满')).toBe('token bucket 已满')
expect(redactSecrets('普通日志:已发送')).toBe('普通日志:已发送')
})
})
describe('killProcessTree', () => {
const spawned: number[] = []
afterEach(async () => {
for (const pid of spawned.splice(0)) {
try {
process.kill(pid, 'SIGKILL')
} catch {
// 已经退出。
}
}
await sleep(30)
})
it.skipIf(process.platform === 'win32')('结束进程组时连带结束孙进程', async () => {
const dir = tempRoot()
const script = path.join(dir, 'parent.js')
fs.writeFileSync(
script,
`const { spawn } = require('node:child_process')
const child = spawn('/bin/sleep', ['300'], { stdio: 'ignore' })
process.send({ grandchild: child.pid })
setInterval(() => {}, 1000)`
)
const parent = spawn(process.execPath, [script], {
detached: true,
stdio: ['ignore', 'ignore', 'ignore', 'ipc']
})
spawned.push(parent.pid as number)
const grandchildPid = await new Promise<number>((resolve) => {
parent.on('message', (message) => resolve((message as { grandchild: number }).grandchild))
})
spawned.push(grandchildPid)
await sleep(100)
expect(isAlive(grandchildPid)).toBe(true)
expect(killProcessTree(parent.pid)).toBe('group')
await sleep(300)
expect(isAlive(grandchildPid)).toBe(false)
expect(isAlive(parent.pid as number)).toBe(false)
})
it('不存在的 pid 返回 fallback 且不抛错', () => {
expect(() => killProcessTree(999_999_999)).not.toThrow()
expect(killProcessTree(999_999_999)).toBe('fallback')
expect(killProcessTree(undefined)).toBe('fallback')
})
it('只结束指定组,不影响另一个进程组', async () => {
if (process.platform === 'win32') return
const dir = tempRoot()
const script = path.join(dir, 'parent.js')
fs.writeFileSync(script, 'setInterval(() => {}, 1000)')
const first = spawn(process.execPath, [script], { detached: true, stdio: 'ignore' })
const second = spawn(process.execPath, [script], { detached: true, stdio: 'ignore' })
spawned.push(first.pid as number, second.pid as number)
await sleep(120)
killProcessTree(first.pid)
await sleep(300)
expect(isAlive(first.pid as number)).toBe(false)
expect(isAlive(second.pid as number)).toBe(true)
})
})
describe('extension host 进程生命周期', () => {
/**
* 造一个「激活后派生孙进程、收到 shutdown 也不退出」的宿主,用于验证强杀路径。
* 孙进程 pid 写到脚本同目录,供测试断言是否残留。
*/
function createStubbornHostRunner(root: string): string {
const script = path.join(root, 'stubborn-host.js')
fs.writeFileSync(
script,
`const { spawn } = require('node:child_process')
const fs = require('node:fs')
const path = require('node:path')
let grandchild = null
process.on('message', (raw) => {
if (!raw || typeof raw !== 'object') return
if (raw.type === 'activate') {
grandchild = spawn('/bin/sleep', ['300'], { stdio: 'ignore' })
fs.writeFileSync(path.join(__dirname, 'grandchild.pid'), String(grandchild.pid))
process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
}
// 刻意忽略 shutdown:模拟扩展卡在清理逻辑里。
})
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })
setInterval(() => {}, 1000)`
)
return script
}
it.skipIf(process.platform === 'win32')('超时后结束整棵进程树,孙进程不残留', async () => {
const root = tempRoot()
const script = createStubbornHostRunner(root)
const logLines: string[] = []
const host = new ExtensionHost({
extensionId: 'com.example.stubborn',
extensionDir: root,
dataDir: path.join(root, 'data'),
permissions: [],
storage: new ExtensionStorage({ dataRoot: path.join(root, 'storage') }),
spawn: forkExtensionHost(script),
onLog: (level, message) => logLines.push(`${level}:${message}`),
gracefulExitMs: 200,
forceExitMs: 2_000
})
await host.start()
expect(host.snapshot().state).toBe('active')
const pidFile = path.join(root, 'grandchild.pid')
const grandchildPid = Number(fs.readFileSync(pidFile, 'utf8').trim())
expect(isAlive(grandchildPid)).toBe(true)
const started = Date.now()
await host.stop()
expect(Date.now() - started).toBeLessThan(5_000)
expect(host.snapshot().state).toBe('inactive')
expect(logLines.some((line) => line.includes('结束进程树'))).toBe(true)
await sleep(200)
expect(isAlive(grandchildPid)).toBe(false)
})
it('重复 stop 不抛错', async () => {
const root = tempRoot()
const script = path.join(root, 'quick-host.js')
fs.writeFileSync(
script,
`process.on('message', (raw) => {
if (raw && raw.type === 'activate') process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
if (raw && raw.type === 'shutdown') process.exit(0)
})
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })`
)
const host = new ExtensionHost({
extensionId: 'com.example.quick',
extensionDir: root,
dataDir: path.join(root, 'data'),
permissions: [],
storage: new ExtensionStorage({ dataRoot: path.join(root, 'storage') }),
spawn: forkExtensionHost(script),
gracefulExitMs: 500,
forceExitMs: 1_000
})
await host.start()
await host.stop()
await expect(host.stop()).resolves.toBeUndefined()
expect(host.snapshot().state).toBe('inactive')
})
it('大量 stderr 不会阻塞宿主,日志有速率上限', async () => {
const root = tempRoot()
const script = path.join(root, 'noisy-host.js')
fs.writeFileSync(
script,
`const chunk = 'x'.repeat(8 * 1024)
process.on('message', (raw) => {
if (raw && raw.type === 'activate') {
for (let i = 0; i < 160; i += 1) process.stderr.write(chunk)
process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
}
if (raw && raw.type === 'shutdown') process.exit(0)
})
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })`
)
const logLines: string[] = []
const host = new ExtensionHost({
extensionId: 'com.example.noisy',
extensionDir: root,
dataDir: path.join(root, 'data'),
permissions: [],
storage: new ExtensionStorage({ dataRoot: path.join(root, 'storage') }),
spawn: forkExtensionHost(script),
onLog: (level, message) => logLines.push(`${level}:${message}`),
activateTimeoutMs: 8_000
})
// 1.25MB stderr:管道被持续消费,激活握手必须仍然完成。
await host.start()
expect(host.snapshot().state).toBe('active')
await sleep(200)
const stderrLines = logLines.filter((line) => line.includes('[stderr]'))
expect(stderrLines.length).toBeGreaterThan(0)
// 单个 10 秒窗口最多 20 条;允许窗口边界多出一条。
expect(stderrLines.length).toBeLessThanOrEqual(21)
for (const line of stderrLines) {
expect(line.length).toBeLessThanOrEqual(520)
}
await host.stop()
})
it('两个扩展同时运行,停用其中一个不影响另一个', async () => {
const root = tempRoot()
const script = path.join(root, 'pair-host.js')
fs.writeFileSync(
script,
`process.on('message', (raw) => {
if (raw && raw.type === 'activate') process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
if (raw && raw.type === 'shutdown') process.exit(0)
})
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })`
)
const makeHost = (id: string): ExtensionHost =>
new ExtensionHost({
extensionId: id,
extensionDir: root,
dataDir: path.join(root, id),
permissions: [],
storage: new ExtensionStorage({ dataRoot: path.join(root, `storage-${id}`) }),
spawn: forkExtensionHost(script),
gracefulExitMs: 500,
forceExitMs: 1_000
})
const first = makeHost('com.example.first')
const second = makeHost('com.example.second')
await first.start()
await second.start()
expect(first.snapshot().state).toBe('active')
expect(second.snapshot().state).toBe('active')
await first.stop()
expect(first.snapshot().state).toBe('inactive')
expect(second.snapshot().state).toBe('active')
await second.stop()
})
})
+18 -1
View File
@@ -18,6 +18,7 @@ class FakeChild implements ExtensionHostChild {
killed = false
autoActivate = true
activationOk = true
autoRespondAction = true
actionOutput: unknown = { success: true, output: { matched: true } }
send(message: unknown): void {
@@ -36,7 +37,7 @@ class FakeChild implements ExtensionHostChild {
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
if (payload.type === 'invoke-action') {
if (payload.type === 'invoke-action' && this.autoRespondAction) {
queueMicrotask(() => {
this.emit('message', {
type: 'action-result',
@@ -227,4 +228,20 @@ describe('extension host', () => {
expect(result?.ok).toBe(false)
expect((result?.error as { code: string }).code).toBe('PERMISSION_DENIED')
})
it('停止时未完成的动作以扩展不可用失败,不会永远挂起', async () => {
const { host, child } = createHost()
child.autoRespondAction = false
await host.start()
child.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: false }
})
const pending = host.invokeAction('keyword.reply', { text: '长时间任务' })
await host.stop()
await expect(pending).rejects.toMatchObject({ code: 'EXTENSION_HOST_UNAVAILABLE' })
})
})
+180 -4
View File
@@ -1,7 +1,7 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
import { ExtensionInstaller } from '../../src/main/extensions/extension-installer'
@@ -74,7 +74,7 @@ describe('extension installer', () => {
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setEnabled('com.example.fixture', true)
registry.setGrantedPermissions('com.example.fixture', ['storage', 'messages.subscribe'])
registry.setGrantedPermissions('com.example.fixture', ['storage', 'wechat.send.text'])
fs.ensureDirSync(paths.extensionDataDir('com.example.fixture'))
fs.writeJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'), {
version: 1,
@@ -83,20 +83,60 @@ describe('extension installer', () => {
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
fs.writeJsonSync(
path.join(second, 'manifest.json'),
// 新版本仍声明这两项权限,升级不应把它们清掉。
MANIFEST({ version: '1.2.0', permissions: ['storage', 'wechat.send.text'] })
)
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
expect(outcome.upgraded).toBe(true)
expect(outcome.previousVersion).toBe('1.0.0')
const record = registry.get('com.example.fixture')
expect(record?.version).toBe('1.2.0')
expect(record?.enabled).toBe(true)
expect(record?.grantedPermissions).toEqual(['storage', 'messages.subscribe'])
expect(record?.grantedPermissions).toEqual(['storage', 'wechat.send.text'])
expect(
fs.readJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'))
.values.greeting
).toBe('保留我')
})
it('新版本删除的权限在升级后立即失效', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root, { permissions: ['storage', 'wechat.send.text'] })
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setGrantedPermissions('com.example.fixture', ['storage', 'wechat.send.text'])
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(
path.join(second, 'manifest.json'),
MANIFEST({ version: '1.1.0', permissions: ['storage'] })
)
await installer.installFromDirectory(second, { appVersion: '2.6.0' })
expect(registry.get('com.example.fixture')?.grantedPermissions).toEqual(['storage'])
})
it('新版本新增的权限不会自动授予', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root, { permissions: ['storage'] })
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setGrantedPermissions('com.example.fixture', ['storage'])
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(
path.join(second, 'manifest.json'),
MANIFEST({ version: '1.1.0', permissions: ['storage', 'wechat.send.text'] })
)
await installer.installFromDirectory(second, { appVersion: '2.6.0' })
expect(registry.get('com.example.fixture')?.grantedPermissions).toEqual(['storage'])
})
it('卸载默认保留数据,选择清除时一并删除', async () => {
const { paths, registry, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
@@ -176,6 +216,142 @@ describe('extension installer', () => {
fs.existsSync(path.join(paths.installDir('com.example.fixture'), 'ui', 'index.html'))
).toBe(true)
})
it('替换代码前仍能读到旧版本,beforeReplace 早于目录改名', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setEnabled('com.example.fixture', true)
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
let versionDuringCallback = ''
await installer.installFromDirectory(second, {
appVersion: '2.6.0',
beforeReplace: async () => {
versionDuringCallback = fs.readJsonSync(
path.join(paths.installDir('com.example.fixture'), 'manifest.json')
).version as string
}
})
expect(versionDuringCallback).toBe('1.0.0')
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
).toBe('1.2.0')
})
it('beforeReplace 抛错时磁盘保持原样,只清掉 staging', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setEnabled('com.example.fixture', true)
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
await expect(
installer.installFromDirectory(second, {
appVersion: '2.6.0',
beforeReplace: async () => {
throw new Error('旧进程未能停止')
}
})
).rejects.toThrow(/旧进程/)
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
).toBe('1.0.0')
expect(fs.existsSync(paths.stagingDir) ? fs.readdirSync(paths.stagingDir) : []).toEqual([])
})
it('rollback 把代码与 Registry 一起退回旧版本', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setEnabled('com.example.fixture', true)
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
expect(registry.get('com.example.fixture')?.version).toBe('1.2.0')
await outcome.rollback()
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
).toBe('1.0.0')
expect(registry.get('com.example.fixture')?.version).toBe('1.0.0')
expect(registry.get('com.example.fixture')?.enabled).toBe(true)
})
it('cleanup 删除过渡备份,不留 backup 目录', async () => {
const { paths, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
await outcome.cleanup()
expect(fs.readdirSync(paths.extensionsDir).filter((name) => name.includes('.backup-'))).toEqual(
[]
)
// cleanup 之后不能再回滚,避免删掉已确认的新版本。
await expect(outcome.rollback()).rejects.toMatchObject({ code: 'EXTENSION_INSTALL_FAILED' })
})
it('Registry 写入失败时目录回滚,旧版本仍可用', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
const spy = vi.spyOn(registry, 'upsert').mockImplementationOnce(() => {
throw new Error('磁盘写入失败')
})
await expect(
installer.installFromDirectory(second, { appVersion: '2.6.0' })
).rejects.toMatchObject({ code: 'EXTENSION_INSTALL_FAILED' })
spy.mockRestore()
expect(
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
).toBe('1.0.0')
expect(registry.get('com.example.fixture')?.version).toBe('1.0.0')
expect(fs.readdirSync(paths.extensionsDir).filter((name) => name.includes('.backup-'))).toEqual(
[]
)
})
it('文件夹安装跳过 .git 与 node_modules', async () => {
const { paths, installer } = setup()
const root = path.dirname(paths.userData)
const source = createExtensionSource(root)
fs.ensureDirSync(path.join(source, 'node_modules', 'dep'))
fs.writeFileSync(path.join(source, 'node_modules', 'dep', 'index.js'), 'x')
fs.ensureDirSync(path.join(source, '.git', 'objects'))
fs.writeFileSync(path.join(source, '.git', 'HEAD'), 'ref: refs/heads/main')
await installer.installFromDirectory(source, { appVersion: '2.6.0' })
const installed = paths.installDir('com.example.fixture')
expect(fs.existsSync(path.join(installed, 'node_modules'))).toBe(false)
expect(fs.existsSync(path.join(installed, '.git'))).toBe(false)
expect(fs.existsSync(path.join(installed, 'manifest.json'))).toBe(true)
})
})
/* 最小 ZIP 写入器:只支持 stored(无压缩)条目,用于构造非法路径样本。 */
+163
View File
@@ -0,0 +1,163 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
ACTION_SCHEMA_MAX_BYTES,
buildDefaultActionInput,
parseActionInputSchema,
validateActionInput
} from '../../src/shared/extensions/action-schema'
import { ExtensionSecretStore } from '../../src/main/extensions/extension-secret-store'
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-m4-'))
roots.push(root)
return root
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('动作参数 Schema', () => {
it('解析受支持的子集并保留默认值', () => {
const parsed = parseActionInputSchema({
type: 'object',
properties: {
keyword: { type: 'string', title: '关键词', minLength: 1, maxLength: 20 },
times: { type: 'integer', default: 2, minimum: 1, maximum: 5 },
enabled: { type: 'boolean', default: true }
},
required: ['keyword']
})
expect(parsed.ok).toBe(true)
if (!parsed.ok) return
expect(parsed.schema.properties.keyword.type).toBe('string')
expect(parsed.schema.required).toEqual(['keyword'])
expect(buildDefaultActionInput(parsed.schema)).toEqual({ times: 2, enabled: true })
})
it('拒绝不支持的字段类型与非法结构', () => {
expect(parseActionInputSchema({ type: 'array' }).ok).toBe(false)
expect(parseActionInputSchema({ type: 'object', properties: { a: { type: 'date' } } }).ok).toBe(
false
)
expect(parseActionInputSchema({ type: 'object', properties: {} }).ok).toBe(false)
expect(
parseActionInputSchema({
type: 'object',
properties: { a: { type: 'string' } },
required: ['missing']
}).ok
).toBe(false)
})
it('超过字节上限整体拒绝,不静默截断', () => {
const huge = {
type: 'object',
properties: {
text: { type: 'string', description: 'x'.repeat(ACTION_SCHEMA_MAX_BYTES) }
}
}
const parsed = parseActionInputSchema(huge)
expect(parsed.ok).toBe(false)
if (!parsed.ok) expect(parsed.reason).toContain('上限')
})
it('校验必填、类型、范围与枚举', () => {
const parsed = parseActionInputSchema({
type: 'object',
properties: {
keyword: { type: 'string', minLength: 2 },
mode: { type: 'string', enum: ['a', 'b'] },
count: { type: 'integer', minimum: 1, maximum: 3 }
},
required: ['keyword']
})
if (!parsed.ok) throw new Error('schema 应通过')
const schema = parsed.schema
expect(validateActionInput(schema, {}).errors.keyword).toBe('必填')
expect(validateActionInput(schema, { keyword: 'x' }).errors.keyword).toContain('至少')
expect(validateActionInput(schema, { keyword: 'ok', mode: 'c' }).errors.mode).toContain('范围')
expect(validateActionInput(schema, { keyword: 'ok', count: 1.5 }).errors.count).toContain(
'整数'
)
expect(validateActionInput(schema, { keyword: 'ok', count: 9 }).errors.count).toContain(
'不能大于'
)
expect(validateActionInput(schema, { keyword: 'ok', mode: 'a', count: 2 }).ok).toBe(true)
})
it('没有 Schema 时一律通过(向后兼容旧扩展)', () => {
expect(validateActionInput(undefined, { anything: 1 }).ok).toBe(true)
})
})
describe('扩展凭据存储', () => {
const cipher = {
isAvailable: () => true,
encrypt: (plain: string) => Buffer.from(`enc:${plain}`, 'utf8'),
decrypt: (payload: Buffer) => {
const text = payload.toString('utf8')
if (!text.startsWith('enc:')) throw new Error('bad payload')
return text.slice(4)
}
}
it('按扩展命名空间隔离', () => {
const root = tempRoot()
const store = new ExtensionSecretStore({ root, cipher })
store.set('com.example.a', 'cookie', 'value-a')
store.set('com.example.b', 'cookie', 'value-b')
expect(store.get('com.example.a', 'cookie')).toBe('value-a')
expect(store.get('com.example.b', 'cookie')).toBe('value-b')
expect(new ExtensionSecretStore({ root, cipher }).get('com.example.a', 'cookie')).toBe(
'value-a'
)
})
it('落盘只有密文,没有明文文件', () => {
const root = tempRoot()
const store = new ExtensionSecretStore({ root, cipher })
store.set('com.example.a', 'cookie', 'super-secret-cookie')
const files = fs.readdirSync(root)
expect(files).toEqual(['com.example.a.bin'])
const content = fs.readFileSync(path.join(root, 'com.example.a.bin'), 'utf8')
expect(content.startsWith('enc:')).toBe(true)
expect(fs.readdirSync(root).some((name) => name.endsWith('.txt'))).toBe(false)
})
it('安全存储不可用时明确失败,不退化成明文', () => {
const root = tempRoot()
const store = new ExtensionSecretStore({
root,
cipher: { ...cipher, isAvailable: () => false }
})
expect(() => store.set('com.example.a', 'cookie', 'x')).toThrowError(/安全存储/)
expect(fs.existsSync(root) ? fs.readdirSync(root) : []).toEqual([])
})
it('删除与清空', () => {
const root = tempRoot()
const store = new ExtensionSecretStore({ root, cipher })
store.set('com.example.a', 'cookie', 'v')
expect(store.delete('com.example.a', 'cookie')).toBe(true)
expect(store.has('com.example.a', 'cookie')).toBe(false)
store.set('com.example.a', 'cookie', 'v2')
store.clear('com.example.a')
expect(fs.existsSync(path.join(root, 'com.example.a.bin'))).toBe(false)
})
it('键名不合法时拒绝', () => {
const root = tempRoot()
const store = new ExtensionSecretStore({ root, cipher })
expect(() => store.set('com.example.a', '../escape', 'v')).toThrowError(/键名/)
})
})
+393
View File
@@ -63,8 +63,291 @@ describe('extension registry', () => {
const registry = new ExtensionRegistry({ registryFile })
expect(registry.list()).toEqual([])
})
it('文件不存在是合法空状态,可以直接写入', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const registry = new ExtensionRegistry({ registryFile })
expect(registry.getHealth().state).toBe('ok')
registry.upsert({
id: 'com.example.a',
version: '1.0.0',
apiVersion: '1',
enabled: false,
grantedPermissions: [],
installedAt: 1,
updatedAt: 1,
source: 'directory'
})
expect(fs.existsSync(registryFile)).toBe(true)
})
it('主文件损坏时从备份恢复,并把损坏现场另存', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(record('com.example.a', { enabled: true, grantedPermissions: ['storage'] }))
// 再写一次,让上一版内容进入备份;备份天然落后一版。
seed.upsert(record('com.example.b'))
expect(
JSON.parse(fs.readFileSync(`${registryFile}.bak`, 'utf8')).extensions.map(
(item: { id: string }) => item.id
)
).toEqual(['com.example.a'])
fs.writeFileSync(registryFile, '{"version":1,"extensions":[{"id":"com.example.a"', 'utf8')
const recovered = new ExtensionRegistry({ registryFile })
const health = recovered.getHealth()
expect(health.state).toBe('recovered-from-backup')
expect(health.corruptFile).toBeTruthy()
// 恢复到备份那一版:最后一次写入丢失;启用状态与授权按安全策略收回。
expect(recovered.list().map((item) => item.id)).toEqual(['com.example.a'])
expect(recovered.get('com.example.a')?.enabled).toBe(false)
expect(recovered.get('com.example.a')?.grantedPermissions).toEqual([])
// 主文件应已被备份内容修好。
expect(() => JSON.parse(fs.readFileSync(registryFile, 'utf8'))).not.toThrow()
const corruptFiles = fs.readdirSync(root).filter((name) => name.includes('.corrupt-'))
expect(corruptFiles).toHaveLength(1)
expect(fs.readFileSync(path.join(root, corruptFiles[0]), 'utf8')).toContain('com.example.a')
})
it('恢复后继续写入,备份里不会出现损坏内容', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(record('com.example.a', { enabled: true }))
seed.upsert(record('com.example.b'))
fs.writeFileSync(registryFile, 'not-json', 'utf8')
const recovered = new ExtensionRegistry({ registryFile })
recovered.upsert(record('com.example.c'))
const backupText = fs.readFileSync(`${registryFile}.bak`, 'utf8')
expect(backupText).not.toContain('not-json')
expect(() => JSON.parse(backupText)).not.toThrow()
expect(JSON.parse(backupText).extensions.map((item: { id: string }) => item.id)).not.toContain(
'com.example.c'
)
})
it('主文件与备份都损坏时按目录扫描重建,且全部为未启用无授权', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
fs.ensureDirSync(root)
fs.writeFileSync(registryFile, 'broken', 'utf8')
fs.writeFileSync(`${registryFile}.bak`, 'also-broken', 'utf8')
const recoveryCalls: number[] = []
const registry = new ExtensionRegistry({
registryFile,
recover: () => {
recoveryCalls.push(1)
return [
record('com.example.a', { enabled: true, grantedPermissions: ['wechat.send.text'] }),
record('com.example.b', { enabled: true, grantedPermissions: ['storage'] })
]
}
})
const list = registry.list()
expect(recoveryCalls).toHaveLength(1)
expect(registry.getHealth().state).toBe('recovered-by-scan')
expect(list).toHaveLength(2)
for (const item of list) {
expect(item.enabled).toBe(false)
expect(item.grantedPermissions).toEqual([])
}
})
it('主文件与备份都损坏且没有重建来源时拒绝写入,保留现场', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
fs.ensureDirSync(root)
fs.writeFileSync(registryFile, 'broken', 'utf8')
fs.writeFileSync(`${registryFile}.bak`, 'also-broken', 'utf8')
const registry = new ExtensionRegistry({ registryFile })
expect(registry.getHealth().state).toBe('unreadable')
expect(registry.list()).toEqual([])
expect(() => registry.upsert(record('com.example.a'))).toThrowError(/损坏/)
// 现场必须还在:损坏原文不能被空状态覆盖。
expect(fs.readFileSync(registryFile, 'utf8')).toBe('broken')
expect(
fs.readdirSync(root).filter((name) => name.includes('.corrupt-')).length
).toBeGreaterThanOrEqual(1)
})
it('结构合法但记录不合法的文件按损坏处理', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
fs.ensureDirSync(root)
fs.writeJsonSync(registryFile, {
version: 1,
extensions: [{ id: 'not a valid id', version: '1.0.0' }]
})
const registry = new ExtensionRegistry({ registryFile })
expect(registry.list()).toEqual([])
expect(registry.getHealth().state).toBe('unreadable')
})
it('写入失败时内存状态回滚,不留下半写的主文件', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(record('com.example.a'))
const before = fs.readFileSync(registryFile, 'utf8')
// 用同名的目录占住临时文件路径,让 writeFileSync 必然失败。
fs.mkdirSync(`${registryFile}.tmp`)
const broken = new ExtensionRegistry({ registryFile })
expect(() => broken.upsert(record('com.example.b'))).toThrow()
expect(broken.list().map((item) => item.id)).toEqual(['com.example.a'])
expect(fs.readFileSync(registryFile, 'utf8')).toBe(before)
})
it('从旧备份恢复时一律降级为未启用、无授权', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(
record('com.example.a', { enabled: true, grantedPermissions: ['wechat.send.text'] })
)
seed.upsert(record('com.example.b', { enabled: true, grantedPermissions: ['storage'] }))
fs.writeFileSync(registryFile, '{broken', 'utf8')
const recovered = new ExtensionRegistry({ registryFile })
expect(recovered.getHealth().state).toBe('recovered-from-backup')
// 备份里是 enabled=true + 发送权限,恢复后必须全部收回。
for (const item of recovered.list()) {
expect(item.enabled).toBe(false)
expect(item.grantedPermissions).toEqual([])
// 身份与版本保留,配置目录不受影响。
expect(item.version).toBe('1.0.0')
}
})
it('恢复标记持久化,重启后仍然提示', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(record('com.example.a', { enabled: true }))
seed.upsert(record('com.example.b'))
fs.writeFileSync(registryFile, '{broken', 'utf8')
const first = new ExtensionRegistry({ registryFile })
expect(first.getHealth().state).toBe('recovered-from-backup')
// 重新构造实例等价于重启软件:提示不能消失。
const second = new ExtensionRegistry({ registryFile })
expect(second.getHealth().state).toBe('recovered-from-backup')
expect(second.get('com.example.a')?.enabled).toBe(false)
expect(second.acknowledgeRecovery()).toBe(true)
expect(second.getHealth().state).toBe('ok')
const third = new ExtensionRegistry({ registryFile })
expect(third.getHealth().state).toBe('ok')
})
it('恢复后用户重新启用的扩展不会被下一次重启自动恢复成启用', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(record('com.example.a', { enabled: true }))
seed.upsert(record('com.example.b'))
// 再写一次,让备份里同时包含 a 与 b(备份天然落后一版)。
seed.upsert(record('com.example.c'))
fs.writeFileSync(registryFile, '{broken', 'utf8')
const recovered = new ExtensionRegistry({ registryFile })
recovered.setEnabled('com.example.a', true)
// 用户只启用了 a,b 保持停用;恢复提示仍在。
expect(recovered.getHealth().state).toBe('recovered-from-backup')
const restarted = new ExtensionRegistry({ registryFile })
expect(restarted.get('com.example.a')?.enabled).toBe(true)
expect(restarted.get('com.example.b')?.enabled).toBe(false)
})
it('未发生损坏时旧用户的启用状态与授权原样保留', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const seed = new ExtensionRegistry({ registryFile })
seed.upsert(
record('com.example.a', { enabled: true, grantedPermissions: ['wechat.send.text'] })
)
const restarted = new ExtensionRegistry({ registryFile })
expect(restarted.getHealth().state).toBe('ok')
expect(restarted.get('com.example.a')?.enabled).toBe(true)
expect(restarted.get('com.example.a')?.grantedPermissions).toEqual(['wechat.send.text'])
})
it('来源字段按白名单解析,未知值归为 directory', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
fs.ensureDirSync(root)
fs.writeJsonSync(registryFile, {
version: 1,
extensions: [
{
id: 'com.example.a',
version: '1.0.0',
apiVersion: '1',
enabled: false,
grantedPermissions: [],
source: 'template',
templateId: 'keyword-bot',
templateVersion: '1.0.0'
},
{
id: 'com.example.b',
version: '1.0.0',
apiVersion: '1',
enabled: false,
grantedPermissions: [],
source: 'evil-source'
}
]
})
const registry = new ExtensionRegistry({ registryFile })
expect(registry.get('com.example.a')?.source).toBe('template')
expect(registry.get('com.example.a')?.templateId).toBe('keyword-bot')
expect(registry.get('com.example.b')?.source).toBe('directory')
})
})
function record(
id: string,
overrides: Partial<{
enabled: boolean
grantedPermissions: Array<'storage' | 'messages.subscribe' | 'wechat.send.text'>
}> = {}
): {
id: string
version: string
apiVersion: string
enabled: boolean
grantedPermissions: Array<'storage' | 'messages.subscribe' | 'wechat.send.text'>
installedAt: number
updatedAt: number
source: 'directory'
} {
return {
id,
version: '1.0.0',
apiVersion: '1',
enabled: overrides.enabled ?? false,
grantedPermissions: overrides.grantedPermissions ?? [],
installedAt: 1,
updatedAt: 1,
source: 'directory'
}
}
describe('extension storage', () => {
it('按扩展隔离键空间并支持删除', () => {
const root = tempRoot()
@@ -87,6 +370,116 @@ describe('extension storage', () => {
const storage = new ExtensionStorage({ dataRoot: tempRoot(), maxValueBytes: 32 })
expect(() => storage.set('com.example.a', 'big', 'x'.repeat(64))).toThrowError(/上限/)
})
it('20 条规则写入后换实例仍完整读回', () => {
const dataRoot = tempRoot()
const rules = Array.from({ length: 20 }, (_, index) => ({
id: `rule-${index}`,
keyword: `关键词${index}`,
reply: `回复${index}`
}))
const first = new ExtensionStorage({ dataRoot })
first.set('com.example.keyword-bot', 'rules', rules)
const second = new ExtensionStorage({ dataRoot })
expect(second.get('com.example.keyword-bot', 'rules')).toEqual(rules)
expect(second.health('com.example.keyword-bot').state).toBe('ok')
})
it('主文件损坏时从备份恢复,20 条规则不丢', () => {
const dataRoot = tempRoot()
const rules = Array.from({ length: 20 }, (_, index) => ({ id: `rule-${index}` }))
const first = new ExtensionStorage({ dataRoot })
first.set('com.example.keyword-bot', 'rules', rules)
// 再写一次,让含 20 条规则的内容进入备份。
first.set('com.example.keyword-bot', 'enabled', true)
const filePath = first.filePath('com.example.keyword-bot')
fs.writeFileSync(filePath, '{"version":1,"values":{"rules":[', 'utf8')
const recovered = new ExtensionStorage({ dataRoot })
// 恢复后未确认前不给读:否则运行中的机器人会拿着旧配置继续回复。
expect(() => recovered.get('com.example.keyword-bot', 'rules')).toThrowError(/确认/)
expect(recovered.health('com.example.keyword-bot').state).toBe('recovered-from-backup')
recovered.acknowledge('com.example.keyword-bot')
expect(recovered.get('com.example.keyword-bot', 'rules')).toEqual(rules)
const corruptFiles = fs
.readdirSync(path.dirname(filePath))
.filter((name) => name.includes('.corrupt-'))
expect(corruptFiles).toHaveLength(1)
})
it('主文件与备份都损坏时停止写入并保留现场', () => {
const dataRoot = tempRoot()
const storage = new ExtensionStorage({ dataRoot })
storage.set('com.example.a', 'rules', [1, 2, 3])
storage.set('com.example.a', 'enabled', true)
const filePath = storage.filePath('com.example.a')
fs.writeFileSync(filePath, 'broken', 'utf8')
fs.writeFileSync(`${filePath}.bak`, 'also-broken', 'utf8')
const broken = new ExtensionStorage({ dataRoot })
expect(() => broken.get('com.example.a', 'rules')).toThrowError(/损坏/)
expect(broken.health('com.example.a').state).toBe('unrecovered')
// 未处理损坏状态时不允许写入,否则会把现场覆盖成空配置。
expect(() => broken.set('com.example.a', 'enabled', false)).toThrowError(/损坏/)
expect(fs.readFileSync(filePath, 'utf8')).toBe('broken')
})
it('重置后恢复可写,且损坏现场仍在', () => {
const dataRoot = tempRoot()
const storage = new ExtensionStorage({ dataRoot })
storage.set('com.example.a', 'rules', [1])
storage.set('com.example.a', 'enabled', true)
const filePath = storage.filePath('com.example.a')
fs.writeFileSync(filePath, 'broken', 'utf8')
fs.writeFileSync(`${filePath}.bak`, 'also-broken', 'utf8')
const broken = new ExtensionStorage({ dataRoot })
expect(broken.health('com.example.a').state).toBe('unrecovered')
broken.reset('com.example.a')
expect(broken.health('com.example.a').state).toBe('ok')
broken.set('com.example.a', 'enabled', true)
expect(broken.get('com.example.a', 'enabled')).toBe(true)
expect(
fs.readdirSync(path.dirname(filePath)).filter((name) => name.includes('.corrupt-'))
).not.toHaveLength(0)
})
it('一个扩展的损坏不影响另一个扩展', () => {
const dataRoot = tempRoot()
const storage = new ExtensionStorage({ dataRoot })
storage.set('com.example.a', 'rules', ['a'])
storage.set('com.example.b', 'rules', ['b'])
fs.writeFileSync(storage.filePath('com.example.a'), 'broken', 'utf8')
const next = new ExtensionStorage({ dataRoot })
expect(next.health('com.example.a').state).toBe('unrecovered')
expect(next.health('com.example.b').state).toBe('ok')
expect(next.get('com.example.b', 'rules')).toEqual(['b'])
expect(() => next.set('com.example.b', 'rules', ['b2'])).not.toThrow()
})
it('写入失败时旧配置保持完整', () => {
const dataRoot = tempRoot()
const storage = new ExtensionStorage({ dataRoot })
storage.set('com.example.a', 'rules', ['原始规则'])
const filePath = storage.filePath('com.example.a')
const before = fs.readFileSync(filePath, 'utf8')
// 同名目录占住临时文件路径。
fs.mkdirSync(`${filePath}.tmp`)
expect(() => storage.set('com.example.a', 'rules', ['新规则'])).toThrow()
expect(fs.readFileSync(filePath, 'utf8')).toBe(before)
expect(new ExtensionStorage({ dataRoot }).get('com.example.a', 'rules')).toEqual(['原始规则'])
})
})
describe('extension log store', () => {
@@ -0,0 +1,189 @@
import { createRequire } from 'node:module'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { ExtensionTemplateCatalog } from '../../src/main/extensions/extension-template-catalog'
import type { ExtensionRegistryRecord } from '../../src/main/extensions/extension-registry'
const require = createRequire(import.meta.url)
const {
buildTemplates
}: {
buildTemplates: (options?: Record<string, unknown>) => unknown
} = require('../../scripts/build-extension-templates.cjs')
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-catalog-'))
roots.push(root)
return root
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
interface Harness {
root: string
catalog: ExtensionTemplateCatalog
records: Map<string, ExtensionRegistryRecord>
}
function setup(
options: { records?: ExtensionRegistryRecord[]; platform?: NodeJS.Platform } = {}
): Harness {
const work = tempRoot()
const sourceRoot = path.join(work, 'examples')
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
const templateRoot = path.join(work, 'templates')
buildTemplates({
sourceRoot,
outputDir: templateRoot,
lockFile: path.join(work, 'lock.json')
})
const records = new Map<string, ExtensionRegistryRecord>()
for (const record of options.records ?? []) records.set(record.id, record)
const catalog = new ExtensionTemplateCatalog({
templateRoot,
getRecord: (id) => records.get(id),
resolveInstallDir: (id) => path.join(work, 'extensions', id),
platform: options.platform ?? 'darwin',
probePython: () => '/usr/bin/python3',
probeChrome: () => '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
})
return { root: work, catalog, records }
}
function record(overrides: Partial<ExtensionRegistryRecord>): ExtensionRegistryRecord {
return {
id: 'com.example.keyword-bot',
version: '1.0.1',
apiVersion: '1',
enabled: false,
grantedPermissions: [],
installedAt: 1,
updatedAt: 1,
source: 'template',
templateId: 'keyword-bot',
templateVersion: '1.0.1',
...overrides
}
}
describe('官方模板目录', () => {
it('列出两个模板,未安装时状态为 not-installed', async () => {
const { catalog } = setup()
const list = await catalog.list()
expect(list.map((item) => item.template.templateId).sort()).toEqual([
'douyin-sender',
'keyword-bot'
])
expect(list.every((item) => item.state === 'not-installed')).toBe(true)
// 版本来自 manifest,不是硬编码。
const keyword = list.find((item) => item.template.templateId === 'keyword-bot')
expect(keyword?.template.version).toBe('1.0.1')
})
it('已安装同版本显示 installed,本地版本更新时也视为已安装', async () => {
const { catalog } = setup({
records: [
record({ version: '1.0.1' }),
record({ id: 'com.example.douyin-sender', version: '9.9.9', templateId: 'douyin-sender' })
]
})
const list = await catalog.list()
expect(list.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe('installed')
expect(list.find((item) => item.template.templateId === 'douyin-sender')?.state).toBe(
'installed'
)
})
it('模板版本更高时显示 update-available', async () => {
const { catalog } = setup({ records: [record({ version: '0.9.0' })] })
const list = await catalog.list()
expect(list.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe(
'update-available'
)
})
it('同 ID 的非模板扩展显示 conflict,不会自动接管', async () => {
const { catalog } = setup({ records: [record({ source: 'directory' })] })
const list = await catalog.list()
const keyword = list.find((item) => item.template.templateId === 'keyword-bot')
expect(keyword?.state).toBe('conflict')
expect(keyword?.message).toContain('不会自动替换')
})
it('平台不在支持范围时显示 unsupported', async () => {
const { catalog } = setup({ platform: 'linux' })
const list = await catalog.list()
expect(list.every((item) => item.state === 'unsupported')).toBe(true)
})
it('ZIP 被替换后状态变为 damaged,且 resolveZip 拒绝安装', async () => {
const { root } = setup()
const zipPath = path.join(root, 'templates', 'keyword-bot-1.0.1.zip')
const original = fs.readFileSync(zipPath)
fs.writeFileSync(zipPath, Buffer.concat([original, Buffer.from('tampered')]))
// 新实例避免读到缓存的索引状态。
const fresh = new ExtensionTemplateCatalog({
templateRoot: path.join(root, 'templates'),
getRecord: () => undefined,
resolveInstallDir: (id) => path.join(root, 'extensions', id),
platform: 'darwin',
probePython: () => '/usr/bin/python3',
probeChrome: () => '/usr/bin/chrome'
})
const list = await fresh.list()
expect(list.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe('damaged')
await expect(fresh.resolveZip('keyword-bot')).rejects.toMatchObject({
code: 'EXTENSION_INSTALL_FAILED'
})
})
it('依赖检测区分「必填缺失」与「安装后再检测」', async () => {
const { catalog } = setup()
const list = await catalog.list()
const douyin = list.find((item) => item.template.templateId === 'douyin-sender')
const scriptCheck = douyin?.dependencies.checks.find((check) => check.id === 'externalScript')
// 未安装时不判定为缺失,只提示「安装后检测」。
expect(scriptCheck?.ok).toBe(false)
expect(scriptCheck?.blocking).toBe(false)
expect(scriptCheck?.detail).toContain('安装后检测')
// Python / Chrome 已由注入的探测返回可用。
expect(douyin?.dependencies.checks.find((check) => check.id === 'python')?.ok).toBe(true)
expect(douyin?.dependencies.ready).toBe(true)
const keyword = list.find((item) => item.template.templateId === 'keyword-bot')
expect(keyword?.dependencies.checks).toEqual([])
expect(keyword?.dependencies.ready).toBe(true)
})
it('已安装但缺少解析脚本时,依赖为未就绪', async () => {
const { catalog, records, root } = setup({
records: [
record({ id: 'com.example.douyin-sender', version: '1.0.5', templateId: 'douyin-sender' })
]
})
records.set(
'com.example.douyin-sender',
record({
id: 'com.example.douyin-sender',
version: '1.0.5',
templateId: 'douyin-sender'
})
)
fs.ensureDirSync(path.join(root, 'extensions', 'com.example.douyin-sender'))
const list = await catalog.list()
const douyin = list.find((item) => item.template.templateId === 'douyin-sender')
const scriptCheck = douyin?.dependencies.checks.find((check) => check.id === 'externalScript')
expect(scriptCheck?.ok).toBe(false)
expect(scriptCheck?.blocking).toBe(true)
expect(douyin?.dependencies.ready).toBe(false)
})
})
+145
View File
@@ -0,0 +1,145 @@
import { createRequire } from 'node:module'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { Open } from 'unzipper'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
import { ExtensionInstaller } from '../../src/main/extensions/extension-installer'
const require = createRequire(import.meta.url)
const {
buildTemplates
}: {
buildTemplates: (options?: Record<string, unknown>) => {
templates: Array<{ templateId: string; version: string; sha256: string; file: string }>
warnings: string[]
}
} = require('../../scripts/build-extension-templates.cjs')
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-templates-'))
roots.push(root)
return root
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
/** 复制真实的 examples 到临时目录,避免测试写仓库里的 lock 文件。 */
function stageExamples(): { sourceRoot: string; lockFile: string } {
const root = tempRoot()
const sourceRoot = path.join(root, 'examples')
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
return { sourceRoot, lockFile: path.join(root, 'template-lock.json') }
}
describe('官方模板构建', () => {
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',
'keyword-bot'
])
const index = fs.readJsonSync(path.join(outputDir, 'index.json'))
expect(index.version).toBe(1)
expect(index.templates).toHaveLength(2)
for (const template of index.templates) {
expect(fs.existsSync(path.join(outputDir, template.file))).toBe(true)
expect(template.sha256).toMatch(/^[a-f0-9]{64}$/)
}
})
it('两次构建字节一致(确定性 ZIP)', () => {
const { sourceRoot, lockFile } = stageExamples()
const first = buildTemplates({ sourceRoot, outputDir: path.join(tempRoot(), 'a'), lockFile })
const second = buildTemplates({ sourceRoot, outputDir: path.join(tempRoot(), 'b'), lockFile })
expect(second.templates.map((item) => item.sha256)).toEqual(
first.templates.map((item) => item.sha256)
)
})
it('私有脚本与缓存文件不会进入发布包', async () => {
const { sourceRoot, lockFile } = stageExamples()
// 模拟开发者本机存在被 gitignore 的私有脚本与缓存。
const privateScript = path.join(sourceRoot, 'douyin-sender/scripts/douyin.py')
fs.ensureDirSync(path.dirname(privateScript))
fs.writeFileSync(privateScript, '# private')
fs.ensureDirSync(path.join(sourceRoot, 'douyin-sender/scripts/__pycache__'))
fs.writeFileSync(path.join(sourceRoot, 'douyin-sender/scripts/__pycache__/x.pyc'), 'x')
fs.writeFileSync(path.join(sourceRoot, 'keyword-bot/.DS_Store'), 'x')
const outputDir = path.join(tempRoot(), 'out')
buildTemplates({ sourceRoot, outputDir, lockFile })
const zipPath = path.join(outputDir, 'douyin-sender-1.0.5.zip')
const archive = await Open.file(zipPath)
const names = archive.files.map((file) => file.path)
expect(names).not.toContain('scripts/douyin.py')
expect(names.some((name) => name.includes('__pycache__'))).toBe(false)
const keyword = await Open.file(path.join(outputDir, 'keyword-bot-1.0.1.zip'))
expect(keyword.files.map((file) => file.path)).not.toContain('.DS_Store')
})
it('入口文件缺失时构建失败', () => {
const { sourceRoot, lockFile } = stageExamples()
fs.removeSync(path.join(sourceRoot, 'keyword-bot/background/index.js'))
expect(() =>
buildTemplates({ sourceRoot, outputDir: path.join(tempRoot(), 'out'), lockFile })
).toThrowError(/入口|不存在/)
})
it('同版本内容变化被拒绝,升版本后放行', () => {
const { sourceRoot, lockFile } = stageExamples()
const outputDir = path.join(tempRoot(), 'out')
buildTemplates({ sourceRoot, outputDir, lockFile })
// 改动内容但不升版本。
const manifestPath = path.join(sourceRoot, 'keyword-bot/manifest.json')
const manifest = fs.readJsonSync(manifestPath)
fs.writeJsonSync(manifestPath, { ...manifest, description: '改了一句话' })
expect(() => buildTemplates({ sourceRoot, outputDir, lockFile })).toThrowError(/内容已变化/)
// 升版本后放行。
fs.writeJsonSync(manifestPath, { ...manifest, description: '改了一句话', version: '1.0.2' })
const result = buildTemplates({ sourceRoot, outputDir, lockFile })
expect(result.templates.some((item) => item.version === '1.0.2')).toBe(true)
})
it('产物 ZIP 能被现有安装器直接安装', async () => {
const { sourceRoot, lockFile } = stageExamples()
const outputDir = path.join(tempRoot(), 'out')
buildTemplates({ sourceRoot, outputDir, lockFile })
const userData = tempRoot()
const paths = createExtensionPaths(userData)
const registry = new ExtensionRegistry({ registryFile: paths.registryFile })
const installer = new ExtensionInstaller({ paths, registry })
const zipPath = path.join(outputDir, 'keyword-bot-1.0.1.zip')
const outcome = await installer.installFromPackage(zipPath, {
appVersion: '2.6.0',
source: 'template',
template: { id: 'keyword-bot', version: '1.0.1' }
})
expect(outcome.manifest.id).toBe('com.example.keyword-bot')
expect(outcome.upgraded).toBe(false)
const record = registry.get('com.example.keyword-bot')
expect(record?.source).toBe('template')
expect(record?.templateId).toBe('keyword-bot')
expect(record?.templateVersion).toBe('1.0.1')
// 安装不等于启用。
expect(record?.enabled).toBe(false)
expect(
fs.existsSync(path.join(paths.installDir('com.example.keyword-bot'), 'ui/index.html'))
).toBe(true)
})
})
+153
View File
@@ -0,0 +1,153 @@
import { createRequire } from 'node:module'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
const require = createRequire(import.meta.url)
const MATCHER = path.join(process.cwd(), 'examples/extensions/keyword-bot/lib/matcher.js')
const BACKGROUND = path.join(process.cwd(), 'examples/extensions/keyword-bot/background/index.js')
const { normalizeConfig } = require(MATCHER) as {
normalizeConfig: (raw: unknown) => {
executionMode: 'subscribe' | 'automation'
enabled: boolean
rules: Array<{ id: string; keyword: string; reply: string }>
}
}
interface FakeApi {
storage: {
get: (key: string) => Promise<unknown>
set: (key: string, value: unknown) => Promise<void>
}
events: { on: (name: string, handler: (event: unknown) => unknown) => void }
automation: { registerAction: (definition: Record<string, unknown>) => void }
wechat: { send: (payload: Record<string, unknown>) => Promise<void> }
log: { info: () => void; warn: () => void; error: () => void }
}
function createApi(config: Record<string, unknown>): {
api: FakeApi
sends: Array<Record<string, unknown>>
handlers: Map<string, (event: unknown) => unknown>
getAction: () => Record<string, unknown> | null
} {
const sends: Array<Record<string, unknown>> = []
const handlers = new Map<string, (event: unknown) => unknown>()
let action: Record<string, unknown> | null = null
const api: FakeApi = {
storage: {
get: async () => config,
set: async () => undefined
},
events: {
on: (name, handler) => handlers.set(name, handler)
},
automation: {
registerAction: (definition) => {
action = definition
}
},
wechat: {
send: async (payload) => {
sends.push(payload)
}
},
log: { info: () => undefined, warn: () => undefined, error: () => undefined }
}
return { api, sends, handlers, getAction: () => action }
}
function loadBackground(): (api: FakeApi) => void {
delete require.cache[require.resolve(BACKGROUND)]
return require(BACKGROUND) as (api: FakeApi) => void
}
const baseConfig = {
enabled: true,
executionMode: 'subscribe',
rules: [{ id: 'r1', keyword: '你好', mode: 'contains', reply: '你好呀', enabled: true }],
scope: { groups: [], includeDirect: true, requireMentionMe: false }
}
const messageEvent = {
eventId: 'evt-1',
type: 'text',
isSelf: false,
conversationId: 'room@chatroom',
conversationName: '测试群',
senderId: 'wxid_peer',
senderName: '张三',
text: '你好',
isGroup: true,
mentionsMe: false,
receivedAt: Date.now()
}
describe('关键词机器人执行模式', () => {
it('默认是订阅模式,非法值回落', () => {
expect(normalizeConfig(undefined).executionMode).toBe('subscribe')
expect(normalizeConfig({ executionMode: 'nonsense' }).executionMode).toBe('subscribe')
expect(normalizeConfig({ executionMode: 'automation' }).executionMode).toBe('automation')
})
it('订阅模式:事件路径回复一次,动作路径跳过', async () => {
const activate = loadBackground()
const harness = createApi(baseConfig)
activate(harness.api as never)
const onMessage = harness.handlers.get('message.received')
expect(onMessage).toBeTruthy()
await onMessage?.(messageEvent)
expect(harness.sends).toHaveLength(1)
const action = harness.getAction()
expect(action).toBeTruthy()
const result = (await (action!.handler as (input: unknown) => Promise<unknown>)({
text: '你好'
})) as { success: boolean; output?: { skipped?: string } }
expect(result.success).toBe(true)
expect(result.output?.skipped).toBe('subscribe-mode')
})
it('自动化模式:事件路径不发送,动作路径给出回复', async () => {
const activate = loadBackground()
const harness = createApi({ ...baseConfig, executionMode: 'automation' })
activate(harness.api as never)
const onMessage = harness.handlers.get('message.received')
await onMessage?.(messageEvent)
expect(harness.sends).toHaveLength(0)
const action = harness.getAction()
const result = (await (action!.handler as (input: unknown) => Promise<unknown>)({
text: '你好'
})) as { success: boolean; reply?: { text: string }; output?: { matched?: boolean } }
expect(result.success).toBe(true)
expect(result.output?.matched).toBe(true)
expect(result.reply?.text).toBe('你好呀')
})
it('文本相同但事件不同,订阅模式各自回复', async () => {
const activate = loadBackground()
const harness = createApi({
...baseConfig,
rules: [
{
id: 'r1',
keyword: '你好',
mode: 'contains',
reply: '你好呀',
enabled: true,
cooldownSeconds: 0
}
]
})
activate(harness.api as never)
const onMessage = harness.handlers.get('message.received')
await onMessage?.({ ...messageEvent, eventId: 'evt-a' })
await onMessage?.({ ...messageEvent, eventId: 'evt-b' })
// 没有按文本去重:两条独立消息都应回复。
expect(harness.sends).toHaveLength(2)
})
})