diff --git a/.gitignore b/.gitignore
index 25fd124..6ea0b95 100644
--- a/.gitignore
+++ b/.gitignore
@@ -34,3 +34,6 @@ debug-originals
# 去水印脚本
/examples/extensions/douyin-sender/scripts/douyin.py
+
+# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
+/build/extension-templates/
diff --git a/electron-builder.win.yml b/electron-builder.win.yml
index 2f07f2e..510d4cd 100644
--- a/electron-builder.win.yml
+++ b/electron-builder.win.yml
@@ -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
diff --git a/electron-builder.yml b/electron-builder.yml
index 5e1352f..13481fc 100644
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@ -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
diff --git a/examples/extensions/douyin-sender/background/index.js b/examples/extensions/douyin-sender/background/index.js
index 9562120..7605708 100644
--- a/examples/extensions/douyin-sender/background/index.js
+++ b/examples/extensions/douyin-sender/background/index.js
@@ -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
diff --git a/examples/extensions/douyin-sender/manifest.json b/examples/extensions/douyin-sender/manifest.json
index 59b62ae..fa0bc18 100644
--- a/examples/extensions/douyin-sender/manifest.json
+++ b/examples/extensions/douyin-sender/manifest.json
@@ -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
diff --git a/examples/extensions/douyin-sender/ui/app.js b/examples/extensions/douyin-sender/ui/app.js
index 718aa15..677f55f 100644
--- a/examples/extensions/douyin-sender/ui/app.js
+++ b/examples/extensions/douyin-sender/ui/app.js
@@ -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')
diff --git a/examples/extensions/keyword-bot/background/index.js b/examples/extensions/keyword-bot/background/index.js
index 5134d1d..89f6709 100644
--- a/examples/extensions/keyword-bot/background/index.js
+++ b/examples/extensions/keyword-bot/background/index.js
@@ -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 } }
diff --git a/examples/extensions/keyword-bot/lib/matcher.js b/examples/extensions/keyword-bot/lib/matcher.js
index dd3f4e2..32baee6 100644
--- a/examples/extensions/keyword-bot/lib/matcher.js
+++ b/examples/extensions/keyword-bot/lib/matcher.js
@@ -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,
diff --git a/examples/extensions/keyword-bot/manifest.json b/examples/extensions/keyword-bot/manifest.json
index af423ce..3072042 100644
--- a/examples/extensions/keyword-bot/manifest.json
+++ b/examples/extensions/keyword-bot/manifest.json
@@ -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
diff --git a/examples/extensions/template-lock.json b/examples/extensions/template-lock.json
new file mode 100644
index 0000000..85ff745
--- /dev/null
+++ b/examples/extensions/template-lock.json
@@ -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
+ }
+ }
+}
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..fed8462
--- /dev/null
+++ b/index.html
@@ -0,0 +1,19 @@
+
+
+
+
+ TraceMemo(迹忆)
+
+
+
+
+
+
+
+
+
+
+
diff --git a/package.json b/package.json
index 2091366..4fcdf59 100644
--- a/package.json
+++ b/package.json
@@ -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",
diff --git a/scripts/after-pack.cjs b/scripts/after-pack.cjs
index c63faaa..595e6c4 100644
--- a/scripts/after-pack.cjs
+++ b/scripts/after-pack.cjs
@@ -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(
diff --git a/scripts/build-extension-templates.cjs b/scripts/build-extension-templates.cjs
new file mode 100644
index 0000000..b1369da
--- /dev/null
+++ b/scripts/build-extension-templates.cjs
@@ -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
+}
diff --git a/src/main/extensions/extension-action-registry.ts b/src/main/extensions/extension-action-registry.ts
index b8d6fdf..0bead51 100644
--- a/src/main/extensions/extension-action-registry.ts
+++ b/src/main/extensions/extension-action-registry.ts
@@ -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
+ 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 } : {})
}
}
diff --git a/src/main/extensions/extension-code-digest.ts b/src/main/extensions/extension-code-digest.ts
new file mode 100644
index 0000000..1b1d91a
--- /dev/null
+++ b/src/main/extensions/extension-code-digest.ts
@@ -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
+ ignoreFiles?: Iterable
+}
+
+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
+}
diff --git a/src/main/extensions/extension-host.ts b/src/main/extensions/extension-host.ts
index ce24c84..63da182 100644
--- a/src/main/extensions/extension-host.ts
+++ b/src/main/extensions/extension-host.ts
@@ -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 ` 整体,再按「键=值」处理,
+ // 否则 `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()
+ private readonly pendingPageRequests = new Map<
+ string,
+ {
+ resolve: (value: unknown) => void
+ reject: (error: Error) => void
+ timer: ReturnType
+ }
+ >()
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,
+ timeoutMs = 10_000
+ ): Promise {
+ const child = this.child
+ if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
+ const requestId = randomUUID()
+ return new Promise((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): Promise {
return this.runTestMessage('test-send', params)
}
@@ -204,6 +310,13 @@ export class ExtensionHost {
return this.activation
}
+ /**
+ * 停止后台进程。
+ *
+ * 三段式:先请扩展自行退出,超时后结束整棵进程树,再等真实的 exit 事件。
+ * 只有收到 exit 才算停止完成——只发信号就返回,会让上层在进程仍占用
+ * 文件时去替换扩展目录(Windows 上必然失败,POSIX 上会留下旧代码在跑)。
+ */
async stop(): Promise {
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((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 {
+ return new Promise((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 } : {})
}
}
diff --git a/src/main/extensions/extension-installer.ts b/src/main/extensions/extension-installer.ts
index b1d137d..f5614d3 100644
--- a/src/main/extensions/extension-installer.ts
+++ b/src/main/extensions/extension-installer.ts
@@ -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
}
export interface InstallOutcome {
manifest: ExtensionManifest
installPath: string
previousVersion?: string
+ /** 安装前的 Registry 记录;首次安装时为 undefined。 */
+ previousRecord?: ExtensionRegistryRecord
upgraded: boolean
+ /**
+ * 把磁盘与 Registry 一起恢复到本次安装之前。
+ *
+ * 只在新版本启动失败时调用;调用后 `cleanup` 失效。
+ */
+ rollback: () => Promise
+ /**
+ * 删除旧版本的过渡备份。
+ *
+ * 新版本确认可用后调用;调用后 `rollback` 失效。
+ */
+ cleanup: () => Promise
}
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 => {
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-`,由调用方在新版本确认可用后清理;
+ * 启动失败时用 `rollback()` 换回来。
+ * - Registry 写入失败时当场回滚目录,不把「代码已换、状态未换」留给上层。
+ *
+ * 不保证跨进程的强原子性:如果进程在 rename 之后、Registry 写入之前被杀,
+ * 磁盘上是新代码配旧记录;下次启动会以 manifest 为准做兼容性检查。
+ */
private async finalize(
staging: string,
manifest: ExtensionManifest,
- source: 'directory' | 'package'
+ source: ExtensionSource,
+ options: InstallOptions
): Promise {
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-` 后清理,留下的是可运行的旧版本。
+ */
+ 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 {
diff --git a/src/main/extensions/extension-ipc.ts b/src/main/extensions/extension-ipc.ts
index b97a3be..4010879 100644
--- a/src/main/extensions/extension-ipc.ts
+++ b/src/main/extensions/extension-ipc.ts
@@ -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 => {
+ 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[1]
+ )
+ })
+ )
+
+ ipcMain.handle(
+ EXTENSION_IPC.revokePermission,
+ guard((payload: unknown): Promise => {
+ 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[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 =>
+ 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 => {
+ 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 =>
+ manager().linkDevelopmentProject(requirePath(directory))
+ )
+ )
+
+ ipcMain.handle(
+ EXTENSION_IPC.reloadDevelopment,
+ guard(
+ (extensionId: unknown): Promise =>
+ manager().reloadDevelopment(requireId(extensionId))
+ )
+ )
+
+ ipcMain.handle(
+ EXTENSION_IPC.unlinkDevelopment,
+ guard((payload: unknown): Promise => {
+ 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 =>
+ manager().convertDevelopmentToInstalled(requireId(extensionId))
+ )
+ )
+
+ ipcMain.handle(
+ EXTENSION_IPC.createProjectFromTemplate,
+ guard((payload: unknown): Promise => {
+ 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 => {
+ 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 => {
+ 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 =>
+ manager().rollbackInterruptedUpgrade(requireId(extensionId))
+ )
+ )
+
ipcMain.handle(
EXTENSION_IPC.uninstall,
guard((payload: unknown): Promise => {
@@ -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('路径不合法')
diff --git a/src/main/extensions/extension-manager.ts b/src/main/extensions/extension-manager.ts
index c878b6a..becf1b9 100644
--- a/src/main/extensions/extension-manager.ts
+++ b/src/main/extensions/extension-manager.ts
@@ -1,15 +1,22 @@
import fs from 'fs-extra'
-import os from 'node:os'
import path from 'node:path'
-import { safeStorage } from 'electron'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
+import { isPathInside } from './extension-paths'
+import { computeDirectoryDigest } from './extension-code-digest'
+import { ExtensionSecretStore, type ExtensionSecretCipher } from './extension-secret-store'
+import {
+ createProjectFromTemplate as createProjectFiles,
+ exportInstalledCopy
+} from './extension-project-files'
import {
autoGrantedPermissions,
hasExtensionPermission,
+ normalizeExtensionPermissions,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import {
checkExtensionCompatibility,
+ isValidExtensionId,
parseExtensionManifest,
type ExtensionManifest
} from '../../shared/extensions/manifest'
@@ -21,6 +28,9 @@ import type {
ExtensionPageDescriptor,
ExtensionPageMethod,
ExtensionPageResponse,
+ ExtensionActionInfo,
+ ExtensionProjectResult,
+ ExtensionSystemHealth,
InstalledExtension
} from '../../shared/extensions/types'
import type {
@@ -44,7 +54,16 @@ import {
type ExtensionHostChild,
type ExtensionHostSpawnOptions
} from './extension-host'
-import { ExtensionInstaller } from './extension-installer'
+import { ExtensionInstaller, type InstallOutcome } from './extension-installer'
+import {
+ assertSafeDevelopmentRoot,
+ createExtensionRootResolver,
+ type ExtensionRootResolver
+} from './extension-root-resolver'
+import {
+ ExtensionTemplateCatalog,
+ type ExtensionTemplateStatus
+} from './extension-template-catalog'
import { ExtensionLogStore } from './extension-log'
import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry'
import { ExtensionSendGateway } from './extension-send-gateway'
@@ -63,9 +82,15 @@ export interface ExtensionManagerDependencies {
/** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */
listGroups: () => Promise>
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
+ /** 当前 AI 是否已配置;不暴露 key、endpoint 或任何凭据。 */
+ aiStatus?: () => { configured: boolean; modelName: string }
getAccountId: () => string
getSelfUsernames: () => string[]
isDatabaseReady: () => boolean
+ /** 官方模板资源根目录;未提供时扩展中心只显示「我的扩展」。 */
+ templatesRoot?: string
+ /** 扩展凭据的加密实现;未提供时凭据能力不可用(明确失败,不退化明文)。 */
+ secretCipher: ExtensionSecretCipher
now?: () => number
onChange?: (
extensionId: string,
@@ -73,6 +98,9 @@ export interface ExtensionManagerDependencies {
) => void
}
+/** 页面请求方法名:与 SDK 侧保持同一规则。 */
+const PAGE_REQUEST_METHOD = /^[a-z][a-zA-Z0-9]*(?:[._-][a-zA-Z0-9]+){0,3}$/
+
const PAGE_METHODS: ExtensionPageMethod[] = [
'storage.get',
'storage.set',
@@ -80,10 +108,7 @@ const PAGE_METHODS: ExtensionPageMethod[] = [
'storage.list',
'capabilities.get',
'contacts.listGroups',
- 'test.send',
- 'douyin.cookie.get',
- 'douyin.cookie.set',
- 'douyin.cookie.clear',
+ 'extension.request',
'extension.info'
]
@@ -111,18 +136,51 @@ export class ExtensionManager {
private readonly eventBus: ExtensionEventBus
private readonly now: () => number
private initialized = false
+ /** 代码与 Registry 版本不一致的扩展:值为面向用户的原因,存在即禁止启动。 */
+ private readonly inconsistencies = new Map()
+ /** 配置从旧备份恢复、尚未被用户确认的扩展。 */
+ private readonly storageHolds = new Set()
+ private readonly templates: ExtensionTemplateCatalog | null
+ /** 扩展代码根目录的唯一解析器:安装副本与外部开发目录共用一条路径。 */
+ private readonly roots: ExtensionRootResolver
+ private readonly secrets: ExtensionSecretStore
constructor(dependencies: ExtensionManagerDependencies) {
this.dependencies = dependencies
this.paths = dependencies.paths
this.now = dependencies.now ?? (() => Date.now())
- this.registry = new ExtensionRegistry({ registryFile: this.paths.registryFile, now: this.now })
+ this.registry = new ExtensionRegistry({
+ registryFile: this.paths.registryFile,
+ now: this.now,
+ // 状态文件与备份都不可用时,用磁盘上的目录重建「有哪些扩展」;
+ // 重建结果不带启用状态与授权,用户必须重新确认。
+ recover: () => this.installer.recoverFromDisk()
+ })
this.installer = new ExtensionInstaller({
paths: this.paths,
registry: this.registry,
now: this.now
})
- this.storage = new ExtensionStorage({ dataRoot: this.paths.dataDir })
+ this.templates = dependencies.templatesRoot
+ ? new ExtensionTemplateCatalog({
+ templateRoot: dependencies.templatesRoot,
+ getRecord: (extensionId) => this.registry.get(extensionId),
+ resolveInstallDir: (extensionId) => this.paths.installDir(extensionId),
+ platform: dependencies.platform
+ })
+ : null
+ this.roots = createExtensionRootResolver({
+ paths: this.paths,
+ getRecord: (extensionId) => this.registry.get(extensionId)
+ })
+ this.secrets = new ExtensionSecretStore({
+ root: path.join(this.paths.stateDir, 'secrets'),
+ cipher: dependencies.secretCipher
+ })
+ this.storage = new ExtensionStorage({
+ dataRoot: this.paths.dataDir,
+ onHealthChange: (extensionId, health) => this.handleStorageHealthChange(extensionId, health)
+ })
this.logs = new ExtensionLogStore(this.paths.logsDir)
this.sendGateway = new ExtensionSendGateway({
getCapability: dependencies.getCapability,
@@ -153,6 +211,12 @@ export class ExtensionManager {
fs.ensureDirSync(directory)
}
this.eventBus.setAccountId(this.dependencies.getAccountId())
+ const health = this.registry.getHealth()
+ if (health.state !== 'ok') {
+ // 宿主级事件没有归属扩展,走主进程日志;界面通过 `getHealth()` 展示。
+ console.warn(`[Extension] ${health.message || '扩展状态文件曾损坏,已进入恢复状态'}`)
+ }
+
for (const record of this.registry.list()) {
const manifest = this.readManifest(record.id)
if (!manifest) {
@@ -160,7 +224,39 @@ export class ExtensionManager {
continue
}
this.syncDeclared(record.id, manifest)
+
+ // 代码与状态可能在上次升级中断时分叉:先判一致性,不一致就不启动。
+ const drift = this.checkInstallConsistency(record, manifest)
+ if (drift) {
+ this.inconsistencies.set(record.id, drift)
+ this.logs.append(record.id, 'error', 'core', drift)
+ continue
+ }
+ this.inconsistencies.delete(record.id)
+
if (!record.enabled) continue
+
+ // 配置从旧备份恢复过:先暂停,等用户确认「接受恢复的配置」。
+ const storageHealth = this.storage.health(record.id)
+ if (storageHealth.state !== 'ok') {
+ this.storageHolds.add(record.id)
+ this.logs.append(
+ record.id,
+ 'warn',
+ 'core',
+ storageHealth.state === 'recovered-from-backup'
+ ? '扩展配置曾从备份恢复,已暂停启动;请在详情页确认后再启用'
+ : '扩展配置损坏且无可用备份,已暂停启动;请重置配置后重新启用'
+ )
+ try {
+ this.registry.setEnabled(record.id, false)
+ } catch {
+ // 状态文件不可写时保持内存中的暂停状态即可。
+ }
+ continue
+ }
+ this.storageHolds.delete(record.id)
+
const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
if (!compatibility.compatible) {
this.logs.append(record.id, 'error', 'core', compatibility.reason || '扩展不兼容')
@@ -179,6 +275,28 @@ export class ExtensionManager {
}
}
+ /**
+ * 校验状态记录与磁盘上的 manifest 是否描述同一个版本。
+ *
+ * 升级会在「换代码」与「写状态」之间留下一个窗口;进程在该窗口被杀时,
+ * 磁盘上是新代码、状态里是旧版本。这种扩展不能带着旧授权直接跑。
+ */
+ private checkInstallConsistency(
+ record: ExtensionRegistryRecord,
+ manifest: ExtensionManifest
+ ): string | null {
+ if (record.id !== manifest.id) {
+ return '扩展目录中的 manifest.id 与状态记录不一致'
+ }
+ if (record.version !== manifest.version) {
+ return `代码版本 ${manifest.version} 与状态记录 ${record.version} 不一致,上次升级可能中断`
+ }
+ if (record.apiVersion !== manifest.apiVersion) {
+ return `扩展 API 版本不一致(代码 ${manifest.apiVersion} / 状态 ${record.apiVersion})`
+ }
+ return null
+ }
+
list(): InstalledExtension[] {
return this.registry
.list()
@@ -201,20 +319,649 @@ export class ExtensionManager {
}
async installFromDirectory(directory: string): Promise {
- return this.install(() =>
- this.installer.installFromDirectory(directory, { appVersion: this.dependencies.appVersion })
+ return this.install((beforeReplace) =>
+ this.installer.installFromDirectory(directory, {
+ appVersion: this.dependencies.appVersion,
+ beforeReplace
+ })
)
}
async installFromPackage(packagePath: string): Promise {
- return this.install(() =>
+ return this.install((beforeReplace) =>
this.installer.installFromPackage(packagePath, {
appVersion: this.dependencies.appVersion,
- source: 'package'
+ source: 'package',
+ beforeReplace
})
)
}
+ /** 官方模板列表;模板资源缺失时返回空数组,不影响「我的扩展」。 */
+ async listTemplates(): Promise {
+ if (!this.templates) return []
+ return this.templates.list()
+ }
+
+ /**
+ * 安装官方模板。
+ *
+ * 三条硬约束:
+ * 1. 只接受模板索引里的 id,ZIP 路径由目录服务解析并校验哈希;
+ * 2. 同 id 已被非模板来源占用时拒绝接管;
+ * 3. 安装只落代码,不启用——启用仍需用户确认权限。
+ */
+ async installTemplate(templateId: string): Promise {
+ const templates = this.templates
+ if (!templates) {
+ return {
+ success: false,
+ error: { code: 'CAPABILITY_UNAVAILABLE', message: '模板目录不可用' }
+ }
+ }
+ let resolved: Awaited>
+ try {
+ resolved = await templates.resolveZip(templateId)
+ } catch (error) {
+ return { success: false, error: toExtensionErrorPayload(error) }
+ }
+
+ const existing = this.registry.get(resolved.template.extensionId)
+ if (existing && (existing.source !== 'template' || existing.templateId !== templateId)) {
+ return {
+ success: false,
+ error: {
+ code: 'EXTENSION_ALREADY_INSTALLED',
+ message: '已存在同 ID 的非官方扩展,未自动替换'
+ }
+ }
+ }
+ if (existing && existing.version === resolved.template.version) {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_ALREADY_INSTALLED', message: '该模板版本已安装' }
+ }
+ }
+
+ return this.install((beforeReplace) =>
+ this.installer.installFromPackage(resolved.path, {
+ appVersion: this.dependencies.appVersion,
+ source: 'template',
+ template: { id: resolved.template.templateId, version: resolved.template.version },
+ beforeReplace
+ })
+ )
+ }
+
+ /**
+ * 该扩展当前是否被暂停(配置待确认 / 版本不一致)。
+ *
+ * 这是唯一的判断入口:事件投递、动作调用、发送出口都走它,
+ * 避免出现「某处放行、某处拦截」的不一致状态。
+ */
+ private isSuspended(extensionId: string): boolean {
+ return this.storageHolds.has(extensionId) || this.inconsistencies.has(extensionId)
+ }
+
+ /**
+ * 运行期检测到配置回退:立刻收住这个扩展。
+ *
+ * 顺序很重要:先停后台(切断正在跑的回复循环),再改状态、记日志。
+ * 已经交给 Native Host 的发送请求无法撤回,属于已知边界。
+ */
+ private handleStorageHealthChange(
+ extensionId: string,
+ health: { state: string; message?: string }
+ ): void {
+ if (health.state === 'ok') return
+ if (this.storageHolds.has(extensionId)) return
+ this.storageHolds.add(extensionId)
+ void this.stopHost(extensionId).catch(() => undefined)
+ try {
+ this.registry.setEnabled(extensionId, false)
+ } catch {
+ // 状态文件不可写时保持内存中的暂停状态即可。
+ }
+ this.logs.append(
+ extensionId,
+ 'warn',
+ 'core',
+ health.state === 'recovered-from-backup'
+ ? '扩展配置在运行期间从备份恢复,已暂停该扩展;请确认后再启用'
+ : '扩展配置在运行期间损坏,已暂停该扩展'
+ )
+ this.dependencies.onChange?.(extensionId, 'runtime')
+ }
+
+ /** 供自定义协议解析代码根目录;开发目录不可用时返回 null(页面 404 而不是 500)。 */
+ resolveExtensionRoot(extensionId: string): string | null {
+ try {
+ return this.roots.resolve(extensionId).root
+ } catch {
+ return null
+ }
+ }
+
+ /**
+ * 链接外部开发项目。
+ *
+ * 只读用户显式选择的目录:校验 manifest、入口文件、路径边界与 ID 冲突,
+ * 然后登记为 `development` 来源。**不复制代码**,也不写回源码目录。
+ */
+ async linkDevelopmentProject(directory: string): Promise {
+ const raw = String(directory || '').trim()
+ if (!raw) {
+ return { success: false, error: { code: 'INVALID_REQUEST', message: '请选择项目目录' } }
+ }
+ let realRoot: string
+ try {
+ realRoot = fs.realpathSync(raw)
+ } catch {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_SOURCE_MISSING', message: '目录不存在或无法访问' }
+ }
+ }
+ let isDirectory = false
+ try {
+ isDirectory = fs.statSync(realRoot).isDirectory()
+ } catch {
+ isDirectory = false
+ }
+ if (!isDirectory) {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_INVALID_PATH', message: '所选路径不是目录' }
+ }
+ }
+
+ const manifestPath = path.join(realRoot, 'manifest.json')
+ let parsedManifest: ReturnType
+ try {
+ parsedManifest = parseExtensionManifest(fs.readJsonSync(manifestPath) as unknown)
+ } catch {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_INVALID_MANIFEST', message: '目录里没有可读的 manifest.json' }
+ }
+ }
+ if (!parsedManifest.ok || !parsedManifest.manifest) {
+ return {
+ success: false,
+ error: {
+ code: 'EXTENSION_INVALID_MANIFEST',
+ message: 'manifest.json 不合法'
+ }
+ }
+ }
+ const manifest = parsedManifest.manifest
+
+ // 先判路径边界:指向宿主私有目录时,连入口检查都不该做。
+ try {
+ assertSafeDevelopmentRoot(this.paths, manifest.id, realRoot)
+ } catch (error) {
+ return { success: false, error: toExtensionErrorPayload(error) }
+ }
+
+ for (const [key, value] of Object.entries(manifest.entrypoints)) {
+ if (!value) continue
+ const entryPath = path.join(realRoot, value)
+ if (!this.isFileInside(realRoot, entryPath)) {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_INVALID_MANIFEST', message: `入口 ${key} 无法解析` }
+ }
+ }
+ }
+
+ const existing = this.registry.get(manifest.id)
+ if (existing && existing.source !== 'development') {
+ return {
+ success: false,
+ error: {
+ code: 'EXTENSION_ALREADY_INSTALLED',
+ message: '该扩展 ID 已被正式安装占用;请先「导出为开发项目」切换来源'
+ }
+ }
+ }
+ if (existing && existing.developmentSourcePath === realRoot) {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_ALREADY_INSTALLED', message: '该目录已经链接过' }
+ }
+ }
+
+ const timestamp = this.now()
+ this.registry.upsert({
+ id: manifest.id,
+ version: manifest.version,
+ apiVersion: manifest.apiVersion,
+ // 链接不等于信任:默认停用;只自动授予低风险权限(与安装策略一致),
+ // 高风险能力仍需用户在启用时确认。
+ enabled: false,
+ grantedPermissions: autoGrantedPermissions(manifest.permissions),
+ installedAt: existing?.installedAt ?? timestamp,
+ updatedAt: timestamp,
+ source: 'development',
+ developmentSourcePath: realRoot
+ })
+ this.manifests.set(manifest.id, manifest)
+ this.syncDeclared(manifest.id, manifest)
+ this.logs.append(manifest.id, 'info', 'core', '已链接外部开发项目')
+ this.dependencies.onChange?.(manifest.id, 'installed')
+ const extension = this.get(manifest.id)
+ return { success: true, ...(extension ? { extension } : {}) }
+ }
+
+ /**
+ * 重新加载开发项目。
+ *
+ * 停后台 → 清 manifest 缓存 → 重新解析 → 权限取交集 → 原本启用则重启。
+ * 页面侧由界面刷新 iframe 完成,两者互不依赖。
+ */
+ async reloadDevelopment(extensionId: string): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ if (record.source !== 'development') {
+ return failure(new ExtensionError('INVALID_REQUEST', '该扩展不是开发模式'))
+ }
+
+ await this.stopHost(extensionId)
+ this.manifests.delete(extensionId)
+
+ try {
+ // 先确认源码目录仍然可达;不可达时给出「重新选择目录」而不是「manifest 读不到」。
+ this.roots.resolve(extensionId)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ const manifest = this.readManifest(extensionId)
+ if (!manifest) {
+ return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', 'manifest 无法读取'))
+ }
+ if (manifest.id !== extensionId) {
+ return failure(
+ new ExtensionError(
+ 'EXTENSION_INVALID_MANIFEST',
+ `目录内 manifest.id 为 ${manifest.id},与链接时不一致`
+ )
+ )
+ }
+
+ try {
+ const drift = this.checkInstallConsistency(record, manifest)
+ if (drift && manifest.version !== record.version) {
+ // 开发模式允许版本自由变化:这里把状态对齐到磁盘,而不是拒绝启动。
+ this.registry.upsert({
+ ...record,
+ version: manifest.version,
+ apiVersion: manifest.apiVersion,
+ grantedPermissions: record.grantedPermissions.filter((permission) =>
+ manifest.permissions.includes(permission)
+ ),
+ updatedAt: this.now()
+ })
+ }
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+
+ this.manifests.set(extensionId, manifest)
+ this.syncDeclared(extensionId, manifest)
+ this.inconsistencies.delete(extensionId)
+ this.storageHolds.delete(extensionId)
+
+ let startError: unknown = null
+ if (record.enabled) {
+ try {
+ await this.startHost(extensionId, manifest)
+ } catch (error) {
+ startError = error
+ }
+ }
+ this.logs.append(extensionId, 'info', 'core', '开发项目已重新加载')
+ this.dependencies.onChange?.(extensionId, 'installed')
+ if (startError) {
+ return failure(toExtensionErrorPayload(startError) as unknown as ExtensionError)
+ }
+ return { success: true }
+ }
+
+ /**
+ * 移除开发链接。
+ *
+ * 绝不删除外部源码目录。若安装副本还在,把来源退回安装副本;
+ * 否则移除 Registry 记录。用户数据按 `keepData` 决定。
+ */
+ async unlinkDevelopment(
+ extensionId: string,
+ options: { keepData: boolean }
+ ): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ if (record.source !== 'development') {
+ return failure(new ExtensionError('INVALID_REQUEST', '该扩展不是开发模式'))
+ }
+
+ await this.stopHost(extensionId)
+ this.manifests.delete(extensionId)
+ this.inconsistencies.delete(extensionId)
+ this.storageHolds.delete(extensionId)
+
+ const installedRoot = this.paths.installDir(extensionId)
+ const hasInstalledCopy = fs.existsSync(path.join(installedRoot, 'manifest.json'))
+ try {
+ if (hasInstalledCopy) {
+ // 回到安装副本:不是删除,只是换来源。
+ this.registry.upsert({
+ ...record,
+ source: 'directory',
+ enabled: false,
+ updatedAt: this.now()
+ })
+ const restored = this.readManifest(extensionId)
+ if (restored) {
+ this.manifests.set(extensionId, restored)
+ this.syncDeclared(extensionId, restored)
+ }
+ } else {
+ this.registry.remove(extensionId)
+ }
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+
+ if (!options.keepData) {
+ await fs
+ .rm(this.paths.extensionDataDir(extensionId), { recursive: true, force: true })
+ .catch(() => undefined)
+ }
+ this.logs.append(extensionId, 'info', 'core', '已移除开发链接(外部源码未删除)')
+ this.dependencies.onChange?.(extensionId, hasInstalledCopy ? 'installed' : 'uninstalled')
+ return { success: true }
+ }
+
+ /**
+ * 把开发项目转成正式安装副本。
+ *
+ * 只复制代码;用户配置本来就在 `extensions-data`,不受影响。
+ */
+ async convertDevelopmentToInstalled(extensionId: string): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ if (record.source !== 'development') {
+ return failure(new ExtensionError('INVALID_REQUEST', '该扩展不是开发模式'))
+ }
+ let root: string
+ try {
+ root = this.roots.resolve(extensionId).root
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+
+ await this.stopHost(extensionId)
+ // 转换后不自动运行:先把启用状态落成 false,安装器才会保留它。
+ try {
+ this.registry.setEnabled(extensionId, false)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+
+ try {
+ const outcome = await this.installer.installFromDirectory(root, {
+ appVersion: this.dependencies.appVersion,
+ source: 'directory',
+ beforeReplace: async () => {
+ await this.stopHost(extensionId)
+ }
+ })
+ await outcome.cleanup()
+ this.manifests.delete(extensionId)
+ this.manifests.set(extensionId, outcome.manifest)
+ this.syncDeclared(extensionId, outcome.manifest)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+
+ this.logs.append(extensionId, 'info', 'core', '开发项目已转为正式安装')
+ this.dependencies.onChange?.(extensionId, 'installed')
+ return { success: true }
+ }
+
+ /**
+ * 从官方模板生成一个独立项目(不安装、不启用)。
+ *
+ * ZIP 来自官方模板目录并已校验哈希;生成过程在暂存目录完成,
+ * 目标目录非空时不会写入任何文件。
+ */
+ async createProjectFromTemplate(
+ templateId: string,
+ targetDirectory: string,
+ options: { extensionId: string; name?: string }
+ ): Promise {
+ if (!this.templates) {
+ return {
+ success: false,
+ error: { code: 'CAPABILITY_UNAVAILABLE', message: '模板目录不可用' }
+ }
+ }
+ if (!isValidExtensionId(options.extensionId)) {
+ return {
+ success: false,
+ error: { code: 'INVALID_REQUEST', message: '扩展 id 必须是反向域名格式' }
+ }
+ }
+ if (this.registry.get(options.extensionId)) {
+ return {
+ success: false,
+ error: { code: 'EXTENSION_ALREADY_INSTALLED', message: '该扩展 id 已被占用' }
+ }
+ }
+
+ let resolved: Awaited>
+ try {
+ resolved = await this.templates.resolveZip(templateId)
+ } catch (error) {
+ return { success: false, error: toExtensionErrorPayload(error) }
+ }
+
+ try {
+ const outcome = await createProjectFiles({
+ zipPath: resolved.path,
+ targetDir: targetDirectory,
+ extensionId: options.extensionId,
+ templateExtensionId: resolved.template.extensionId,
+ ...(options.name ? { name: options.name } : {})
+ })
+ this.logs.append(
+ options.extensionId,
+ 'info',
+ 'core',
+ `已从模板 ${resolved.template.templateId} 生成独立项目`
+ )
+ return {
+ success: true,
+ projectPath: outcome.projectPath,
+ rewrittenFiles: outcome.rewrittenFiles
+ }
+ } catch (error) {
+ return { success: false, error: toExtensionErrorPayload(error) }
+ }
+ }
+
+ /**
+ * 把已安装副本导出成外部项目,并把来源切换为 development。
+ *
+ * 导出的必须是**用户改过的安装副本**,不能重新解压官方 ZIP——
+ * 那样会把二开内容换回原版。原安装副本保留,作为显式恢复来源。
+ */
+ async exportInstalledAsProject(
+ extensionId: string,
+ targetDirectory: string
+ ): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return { success: false, error: { code: 'EXTENSION_NOT_FOUND', message: '' } }
+ if (record.source === 'development') {
+ return {
+ success: false,
+ error: { code: 'INVALID_REQUEST', message: '该扩展已经是开发模式' }
+ }
+ }
+ const installRoot = this.paths.installDir(extensionId)
+
+ await this.stopHost(extensionId)
+ let projectPath: string
+ try {
+ const outcome = await exportInstalledCopy(installRoot, targetDirectory)
+ projectPath = fs.realpathSync(outcome.projectPath)
+ } catch (error) {
+ // 导出失败时把旧 Host 拉回来,别让扩展停在半死状态。
+ await this.restoreHostAfterFailure(extensionId)
+ return { success: false, error: toExtensionErrorPayload(error) }
+ }
+
+ const parsed = (() => {
+ try {
+ return parseExtensionManifest(fs.readJsonSync(path.join(projectPath, 'manifest.json')))
+ } catch {
+ return null
+ }
+ })()
+ if (!parsed?.ok || !parsed.manifest || parsed.manifest.id !== extensionId) {
+ return {
+ success: false,
+ error: {
+ code: 'EXTENSION_INVALID_MANIFEST',
+ message: '导出的项目 manifest 与原扩展不一致,未切换来源'
+ }
+ }
+ }
+
+ const next = {
+ ...record,
+ source: 'development' as const,
+ developmentSourcePath: projectPath,
+ // 转换后不自动运行;授权按新 manifest 取交集。
+ enabled: false,
+ grantedPermissions: record.grantedPermissions.filter((permission) =>
+ parsed.manifest!.permissions.includes(permission)
+ ),
+ updatedAt: this.now()
+ }
+ // 模板身份与旧指纹在新来源下没有意义,必须清掉。
+ delete next.templateId
+ delete next.templateVersion
+ delete next.installedCodeDigest
+
+ try {
+ this.registry.upsert(next)
+ } catch {
+ return {
+ success: false,
+ error: {
+ code: 'EXTENSION_REGISTRY_UNREADABLE',
+ message: '项目已导出,但扩展状态写入失败;请用「链接本地项目」重新接入'
+ }
+ }
+ }
+
+ this.manifests.delete(extensionId)
+ this.manifests.set(extensionId, parsed.manifest)
+ this.syncDeclared(extensionId, parsed.manifest)
+ this.logs.append(extensionId, 'info', 'core', '已导出为开发项目并切换来源')
+ this.dependencies.onChange?.(extensionId, 'installed')
+ return { success: true, projectPath }
+ }
+
+ /** 目标文件必须真实落在扩展根目录内(跟随符号链接后仍在内)。 */
+ private isFileInside(root: string, target: string): boolean {
+ try {
+ const realRoot = fs.realpathSync(root)
+ const realTarget = fs.realpathSync(target)
+ return isPathInside(realRoot, realTarget) && fs.statSync(realTarget).isFile()
+ } catch {
+ return false
+ }
+ }
+
+ /** 状态文件的可信度;`unreadable` 时界面必须提示,而不是显示「没有扩展」。 */
+ getHealth(): ExtensionSystemHealth {
+ const health = this.registry.getHealth()
+ return {
+ registry: {
+ state: health.state,
+ ...(health.message ? { message: health.message } : {})
+ }
+ }
+ }
+
+ /**
+ * 授予扩展已声明的权限。
+ *
+ * 只接受 manifest 里出现过的权限:渲染层传来的字符串不能扩大扩展的能力面。
+ * 权限在子进程启动时快照,因此已启用的扩展需要重启后台才会生效。
+ */
+ async grantPermissions(
+ extensionId: string,
+ permissions: ExtensionPermission[]
+ ): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ const manifest = this.readManifest(extensionId)
+ if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失'))
+
+ const granted = normalizeExtensionPermissions([
+ ...record.grantedPermissions,
+ ...permissions.filter((permission) => manifest.permissions.includes(permission))
+ ])
+ try {
+ this.registry.setGrantedPermissions(extensionId, granted)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ if (record.enabled && manifest.entrypoints.background) {
+ await this.startHost(extensionId, manifest).catch(() => undefined)
+ }
+ this.dependencies.onChange?.(extensionId, 'enabled')
+ return { success: true }
+ }
+
+ /** 撤销单项授权;已启用时需要重启后台,正在运行的能力随之失效。 */
+ async revokePermission(
+ extensionId: string,
+ permission: ExtensionPermission
+ ): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ const manifest = this.readManifest(extensionId)
+ try {
+ this.registry.setGrantedPermissions(
+ extensionId,
+ record.grantedPermissions.filter((item) => item !== permission)
+ )
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ if (record.enabled && manifest?.entrypoints.background) {
+ await this.startHost(extensionId, manifest).catch(() => undefined)
+ }
+ this.dependencies.onChange?.(extensionId, 'enabled')
+ return { success: true }
+ }
+
+ /** 重置扩展私有存储;损坏现场已经由存储层另存为 `.corrupt-*`。 */
+ resetStorage(extensionId: string): ExtensionOperationResult {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ try {
+ this.storage.reset(extensionId)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ this.dependencies.onChange?.(extensionId, 'runtime')
+ return { success: true }
+ }
+
async setEnabled(extensionId: string, enabled: boolean): Promise {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
@@ -229,6 +976,27 @@ export class ExtensionManager {
return { success: true }
}
+ const drift = this.checkInstallConsistency(record, manifest)
+ if (drift) {
+ this.inconsistencies.set(extensionId, drift)
+ return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', drift))
+ }
+
+ // 配置还没被用户确认前不允许启动:恢复出来的开关可能还停在旧值上。
+ const storageHealth = this.storage.health(extensionId)
+ if (storageHealth.state !== 'ok') {
+ this.storageHolds.add(extensionId)
+ return failure(
+ new ExtensionError(
+ 'EXTENSION_STORAGE_CORRUPTED',
+ storageHealth.state === 'recovered-from-backup'
+ ? '扩展配置曾从备份恢复,请先在详情页确认后再启用'
+ : '扩展配置已损坏,请先重置配置再启用'
+ )
+ )
+ }
+ this.storageHolds.delete(extensionId)
+
const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
if (!compatibility.compatible) {
return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', compatibility.reason))
@@ -247,6 +1015,93 @@ export class ExtensionManager {
return { success: true }
}
+ /** 清除「状态文件曾恢复」的提示;不改动任何扩展的启用状态。 */
+ acknowledgeRegistryRecovery(): ExtensionOperationResult {
+ try {
+ this.registry.acknowledgeRecovery()
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ this.dependencies.onChange?.('', 'runtime')
+ return { success: true }
+ }
+
+ /** 接受从备份恢复出来的扩展配置,之后才允许启用该扩展。 */
+ acknowledgeStorageRecovery(extensionId: string): ExtensionOperationResult {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ try {
+ this.storage.acknowledge(extensionId)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ this.storageHolds.delete(extensionId)
+ this.dependencies.onChange?.(extensionId, 'runtime')
+ return { success: true }
+ }
+
+ /**
+ * 采用磁盘上的代码版本:把状态记录的版本对齐到 manifest。
+ *
+ * 用于「上次升级中断」后的修复。授权按新 manifest 取交集,不会扩大能力。
+ */
+ adoptInstalledCode(extensionId: string): ExtensionOperationResult {
+ const record = this.registry.get(extensionId)
+ const manifest = this.readManifest(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失'))
+ try {
+ this.registry.upsert({
+ ...record,
+ version: manifest.version,
+ apiVersion: manifest.apiVersion,
+ grantedPermissions: record.grantedPermissions.filter((permission) =>
+ manifest.permissions.includes(permission)
+ ),
+ updatedAt: this.now()
+ })
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ this.inconsistencies.delete(extensionId)
+ this.manifests.delete(extensionId)
+ this.dependencies.onChange?.(extensionId, 'installed')
+ return { success: true }
+ }
+
+ /** 把最近的升级过渡备份换回来,用于「新代码可疑、旧代码还在」的场景。 */
+ async rollbackInterruptedUpgrade(extensionId: string): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
+ await this.stopHost(extensionId)
+ let restored: { restored: boolean; manifest?: ExtensionManifest }
+ try {
+ restored = await this.installer.restoreLatestBackup(extensionId)
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ if (!restored.restored || !restored.manifest) {
+ return failure(new ExtensionError('EXTENSION_INSTALL_FAILED', '没有可用的升级备份'))
+ }
+ try {
+ this.registry.upsert({
+ ...record,
+ version: restored.manifest.version,
+ apiVersion: restored.manifest.apiVersion,
+ grantedPermissions: record.grantedPermissions.filter((permission) =>
+ restored.manifest!.permissions.includes(permission)
+ ),
+ updatedAt: this.now()
+ })
+ } catch (error) {
+ return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
+ }
+ this.inconsistencies.delete(extensionId)
+ this.manifests.delete(extensionId)
+ this.dependencies.onChange?.(extensionId, 'installed')
+ return { success: true }
+ }
+
async uninstall(extensionId: string, keepData: boolean): Promise {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
@@ -297,17 +1152,18 @@ export class ExtensionManager {
if (!PAGE_METHODS.includes(method as ExtensionPageMethod)) {
throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`)
}
- if (method.startsWith('douyin.cookie.') && extensionId !== 'com.example.douyin-sender') {
- throw new ExtensionError('PERMISSION_DENIED', 'Cookie 能力不适用于此扩展')
- }
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
const manifest = this.readManifest(extensionId)
if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')
- if (!manifest.permissions.includes('storage') && method.startsWith('storage.')) {
+ // 页面桥只认「已授予」的权限:manifest 声明只是申请,不代表用户同意。
+ if (!record.grantedPermissions.includes('storage') && method.startsWith('storage.')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 storage 权限')
}
- if (method === 'contacts.listGroups' && !manifest.permissions.includes('contacts.list')) {
+ if (
+ method === 'contacts.listGroups' &&
+ !record.grantedPermissions.includes('contacts.list')
+ ) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 contacts.list 权限')
}
switch (method as ExtensionPageMethod) {
@@ -334,38 +1190,34 @@ export class ExtensionManager {
}
}
}
- case 'test.send': {
- if (extensionId !== 'com.example.douyin-sender') {
- throw new ExtensionError('PERMISSION_DENIED', '测试能力不适用于此扩展')
+ case 'extension.request': {
+ // 通用转发:只进入**同一扩展**的后台,宿主不知道任何具体业务。
+ const inner = String(params.method || '').trim()
+ if (!PAGE_REQUEST_METHOD.test(inner)) {
+ throw new ExtensionError('INVALID_REQUEST', '页面请求方法名不合法')
+ }
+ if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
+ if (this.isSuspended(extensionId)) {
+ throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,页面请求被拒绝')
}
const host = this.hosts.get(extensionId)
- if (!host) throw new ExtensionError('EXTENSION_DISABLED')
- const cookieHeader = String(params.cookieHeader || '') || this.readDouyinCookie()
- try {
- return { ok: true, result: await host.testSend({ ...params, cookieHeader }) }
- } finally {
- params.cookieHeader = ''
+ if (!host) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
+ const rawParams = params.params
+ if (
+ rawParams !== undefined &&
+ (typeof rawParams !== 'object' || Array.isArray(rawParams))
+ ) {
+ throw new ExtensionError('INVALID_REQUEST', 'params 必须是对象')
+ }
+ return {
+ ok: true,
+ result: await host.requestPage(
+ inner,
+ (rawParams as Record | undefined) ?? {},
+ 10_000
+ )
}
}
- case 'douyin.cookie.get':
- return { ok: true, result: { configured: Boolean(this.readDouyinCookie()) } }
- case 'douyin.cookie.set': {
- const value = String(params.cookieHeader || '').trim()
- if (!value) throw new ExtensionError('INVALID_REQUEST', 'Cookie 不能为空')
- if (!safeStorage.isEncryptionAvailable())
- throw new ExtensionError('CAPABILITY_UNAVAILABLE', '系统安全存储不可用')
- fs.writeFileSync(
- path.join(this.paths.userData, 'douyin-cookie.bin'),
- safeStorage.encryptString(value),
- { mode: 0o600 }
- )
- fs.chmodSync(path.join(this.paths.userData, 'douyin-cookie.bin'), 0o600)
- this.syncDouyinCookieToExtensionData(value)
- return { ok: true, result: { configured: true } }
- }
- case 'douyin.cookie.clear':
- this.clearDouyinCookie()
- return { ok: true, result: { configured: false } }
case 'extension.info':
return {
ok: true,
@@ -389,53 +1241,6 @@ export class ExtensionManager {
this.eventBus.handleMessage(message)
}
- private syncDouyinCookieToExtensionData(value: string): void {
- try {
- const dataDir = this.paths.extensionDataDir('com.example.douyin-sender')
- fs.ensureDirSync(dataDir)
- const target = path.join(dataDir, 'douyin-cookie.txt')
- fs.writeFileSync(target, value, { mode: 0o600 })
- fs.chmodSync(target, 0o600)
- } catch {
- // 扩展数据目录同步失败不影响加密主存储。
- }
- }
-
- private readDouyinCookie(): string {
- const file = path.join(this.paths.userData, 'douyin-cookie.bin')
- if (fs.existsSync(file) && safeStorage.isEncryptionAvailable()) {
- try {
- const decrypted = safeStorage.decryptString(fs.readFileSync(file)).trim()
- if (decrypted) {
- this.syncDouyinCookieToExtensionData(decrypted)
- return decrypted
- }
- } catch {
- // 加密文件损坏或不可解密时继续尝试桌面 Cookie 文件。
- }
- }
- const desktopCookie = path.join(os.homedir(), 'Desktop', 'douyin-cookie')
- if (fs.existsSync(desktopCookie)) {
- try {
- return fs.readFileSync(desktopCookie, 'utf8').trim()
- } catch {
- return ''
- }
- }
- return ''
- }
-
- private clearDouyinCookie(): void {
- try {
- fs.removeSync(path.join(this.paths.userData, 'douyin-cookie.bin'))
- fs.removeSync(
- path.join(this.paths.extensionDataDir('com.example.douyin-sender'), 'douyin-cookie.txt')
- )
- } catch {
- throw new ExtensionError('INVALID_REQUEST', '无法清除抖音 Cookie')
- }
- }
-
setAccountId(accountId: string): void {
this.eventBus.setAccountId(accountId)
}
@@ -450,6 +1255,9 @@ export class ExtensionManager {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
+ if (this.isSuspended(extensionId)) {
+ throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置待确认,动作已暂停')
+ }
if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 automation.action 权限')
}
@@ -465,27 +1273,97 @@ export class ExtensionManager {
return this.actions.list()
}
+ /**
+ * 供自动化编辑器使用的动作列表。
+ *
+ * `registered` 只是「后台注册过」,是否可用要逐条判断:停用、代码缺失、
+ * 权限未授予、Storage 暂停、Schema 非法,任一成立都不可执行。
+ */
+ listActions(): ExtensionActionInfo[] {
+ return this.actions.list().map((action) => {
+ const record = this.registry.get(action.extensionId)
+ const manifest = this.manifests.get(action.extensionId)
+ const base: ExtensionActionInfo = {
+ extensionId: action.extensionId,
+ extensionName: action.extensionName,
+ actionId: action.actionId,
+ title: action.title,
+ ...(action.description ? { description: action.description } : {}),
+ declared: action.declared,
+ registered: action.registered,
+ enabled: record?.enabled === true,
+ available: false,
+ ...(action.inputSchema ? { inputSchema: action.inputSchema } : {})
+ }
+ const block = (reason: string): ExtensionActionInfo => ({
+ ...base,
+ unavailableReason: reason
+ })
+
+ if (!record) return block('扩展已卸载')
+ if (!manifest) return block('扩展代码缺失或 manifest 无法读取')
+ const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
+ if (!compatibility.compatible) return block(compatibility.reason || '扩展与当前版本不兼容')
+ if (!record.enabled) return block('扩展未启用')
+ if (this.isSuspended(record.id)) return block('扩展已暂停(配置待确认)')
+ if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) {
+ return block('未授予「执行自动化动作」权限')
+ }
+ if (action.schemaError) return block(`参数 Schema 不可用:${action.schemaError}`)
+ if (!action.registered) {
+ return block(action.declared ? '后台未注册该动作(可能仍在启动或代码报错)' : '动作未注册')
+ }
+ return { ...base, available: true }
+ })
+ }
+
async dispose(): Promise {
const ids = Array.from(this.hosts.keys())
await Promise.all(ids.map((id) => this.stopHost(id)))
}
+ /**
+ * 安装 / 升级的编排。
+ *
+ * 顺序是「停旧进程 → 换代码 → 写状态 → 起新进程」,任何一步失败都要让
+ * 磁盘与 Registry 回到同一个版本。仅靠多次 rename 不构成跨进程事务,
+ * 所以失败时显式回滚,并把错误原样返回给界面,不吞成成功。
+ */
private async install(
- run: () => Promise<{ manifest: ExtensionManifest; upgraded: boolean; previousVersion?: string }>
+ run: (
+ beforeReplace: (
+ manifest: ExtensionManifest,
+ previous: ExtensionRegistryRecord | undefined
+ ) => Promise
+ ) => Promise
): Promise {
- let outcome: Awaited>
+ let upgradingId: string | null = null
+ const beforeReplace = async (
+ manifest: ExtensionManifest,
+ previous: ExtensionRegistryRecord | undefined
+ ): Promise => {
+ upgradingId = manifest.id
+ // 模板来源的代码被用户改过时,不允许任何安装路径静默覆盖。
+ if (previous?.source === 'template') this.assertTemplateCodeUntouched(previous)
+ // manifest 缓存必须先失效:否则后续读到的仍是旧版本的入口与权限。
+ this.manifests.delete(manifest.id)
+ if (previous?.enabled) await this.stopHost(manifest.id)
+ }
+
+ let outcome: InstallOutcome
try {
- outcome = await run()
+ outcome = await run(beforeReplace)
} catch (error) {
+ // 失败可能发生在旧 Host 已停止之后:旧代码仍在磁盘上,尽量把它拉回来。
+ if (upgradingId) await this.restoreHostAfterFailure(upgradingId)
return { success: false, error: toExtensionErrorPayload(error) }
}
- const { manifest } = outcome
- const wasEnabled = this.registry.get(manifest.id)?.enabled === true
- if (wasEnabled) await this.stopHost(manifest.id)
- this.manifests.delete(manifest.id)
+
+ const { manifest, previousRecord } = outcome
+ const wasEnabled = previousRecord?.enabled === true
this.manifests.set(manifest.id, manifest)
this.syncDeclared(manifest.id, manifest)
- // 新安装只自动授予低风险权限;升级保留用户已经授予的集合。
+ // 新安装只自动授予低风险权限;升级保留用户已经授予的集合(已按新 manifest 取交集)。
if (!outcome.upgraded) {
this.registry.setGrantedPermissions(manifest.id, autoGrantedPermissions(manifest.permissions))
}
@@ -498,22 +1376,87 @@ export class ExtensionManager {
: `扩展已安装:${manifest.version}`
)
this.dependencies.onChange?.(manifest.id, 'installed')
+
if (wasEnabled && manifest.entrypoints.background) {
- await this.startHost(manifest.id, manifest).catch(() => undefined)
+ try {
+ await this.startHost(manifest.id, manifest)
+ } catch (error) {
+ // 新版本起不来:代码与状态一起退回旧版本,并把旧版本重新拉起。
+ await this.stopHost(manifest.id)
+ await outcome.rollback().catch(() => undefined)
+ this.manifests.delete(manifest.id)
+ await this.restoreHostAfterFailure(manifest.id)
+ const message = error instanceof Error ? error.message : '新版本启动失败'
+ this.logs.append(manifest.id, 'error', 'core', `新版本启动失败,已回滚:${message}`)
+ this.dependencies.onChange?.(manifest.id, 'installed')
+ return {
+ success: false,
+ error: {
+ code: 'EXTENSION_INSTALL_FAILED',
+ message: `扩展已回滚到上一版本:${message}`
+ }
+ }
+ }
}
+
+ await outcome.cleanup().catch(() => undefined)
const installed = this.get(manifest.id)
return { success: true, ...(installed ? { extension: installed } : {}) }
}
+ /**
+ * 模板来源的「本地改动」检查。
+ *
+ * 只保护 `template` 来源:用户自己装的 ZIP / 目录本来就会被覆盖,
+ * 开发模式根本没有安装副本可覆盖。
+ */
+ private assertTemplateCodeUntouched(record: ExtensionRegistryRecord): void {
+ const root = this.paths.installDir(record.id)
+ if (!fs.existsSync(path.join(root, 'manifest.json'))) return
+ if (!record.installedCodeDigest) {
+ throw new ExtensionError(
+ 'EXTENSION_MODIFIED_LOCALLY',
+ '无法确认该模板的代码是否被修改过;请先「导出为开发项目」再更新'
+ )
+ }
+ const current = computeDirectoryDigest(root)
+ if (current !== record.installedCodeDigest) {
+ throw new ExtensionError(
+ 'EXTENSION_MODIFIED_LOCALLY',
+ '检测到安装代码已被修改,已阻止自动覆盖;请先「导出为开发项目」'
+ )
+ }
+ }
+
+ /** 安装流程中断后,把 Registry 里仍标记为启用的扩展重新拉起来。 */
+ private async restoreHostAfterFailure(extensionId: string): Promise {
+ const record = this.registry.get(extensionId)
+ if (!record?.enabled) return
+ this.manifests.delete(extensionId)
+ const manifest = this.readManifest(extensionId)
+ if (!manifest?.entrypoints.background) return
+ await this.startHost(extensionId, manifest).catch(() => undefined)
+ }
+
private async startHost(extensionId: string, manifest: ExtensionManifest): Promise {
if (!manifest.entrypoints.background) return
+ // 双保险:任何路径(含自动恢复、自动化触发)都不能绕过这两道闸。
+ const drift = this.inconsistencies.get(extensionId)
+ if (drift) {
+ throw new ExtensionError('EXTENSION_INCOMPATIBLE', drift)
+ }
+ if (this.storageHolds.has(extensionId)) {
+ throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置尚未确认恢复,已阻止启动')
+ }
await this.stopHost(extensionId)
+ const resolvedRoot = this.roots.resolve(extensionId)
const host = new ExtensionHost({
extensionId,
- extensionDir: this.paths.installDir(extensionId),
+ extensionDir: resolvedRoot.root,
dataDir: this.paths.extensionDataDir(extensionId),
permissions: this.registry.get(extensionId)?.grantedPermissions ?? [],
storage: this.storage,
+ secrets: this.secrets,
spawn: this.dependencies.spawn ?? this.defaultSpawn(),
onLog: (level, message) => {
this.logs.append(extensionId, level, 'core', message)
@@ -577,6 +1520,8 @@ export class ExtensionManager {
const record = this.registry.get(extensionId)
const manifest = this.manifests.get(extensionId)
if (!record?.enabled || !manifest) continue
+ // 暂停中的扩展不再收事件:否则它仍会用旧规则回复。
+ if (this.isSuspended(extensionId)) continue
if (!hasExtensionPermission(record.grantedPermissions, 'messages.subscribe')) continue
if (host.snapshot().state !== 'active') continue
subscribers.push({
@@ -625,6 +1570,9 @@ export class ExtensionManager {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
+ if (this.isSuspended(extensionId)) {
+ throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝')
+ }
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendText(
{
@@ -643,6 +1591,9 @@ export class ExtensionManager {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
+ if (this.isSuspended(extensionId)) {
+ throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝')
+ }
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendImage(
{
@@ -661,6 +1612,9 @@ export class ExtensionManager {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
+ if (this.isSuspended(extensionId)) {
+ throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝')
+ }
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendVideo(
{
@@ -696,10 +1650,16 @@ export class ExtensionManager {
licensed,
message: capability?.message || '暂时无法获知微信发送能力'
},
- ai: {
- configured: false,
- modelName: ''
- }
+ ai: (() => {
+ try {
+ const status = this.dependencies.aiStatus?.()
+ return status
+ ? { configured: status.configured, modelName: status.modelName }
+ : { configured: false, modelName: '' }
+ } catch {
+ return { configured: false, modelName: '' }
+ }
+ })()
}
}
@@ -709,13 +1669,11 @@ export class ExtensionManager {
? checkExtensionCompatibility(manifest, this.dependencies.appVersion)
: { compatible: false, code: 'manifest' as const, reason: '扩展文件缺失或 manifest 无法读取' }
const host = this.hosts.get(record.id)
- const runtime = host
- ? host.snapshot()
- : {
- state: record.enabled ? ('active' as const) : ('inactive' as const),
- since: record.updatedAt,
- restarts: 0
- }
+ const runtime = host ? host.snapshot() : this.deriveIdleRuntime(record, manifest)
+ const pendingPermissions = manifest
+ ? manifest.permissions.filter((permission) => !record.grantedPermissions.includes(permission))
+ : []
+ const storageHealth = this.storage.health(record.id)
return {
id: record.id,
name: manifest?.name || record.id,
@@ -728,21 +1686,101 @@ export class ExtensionManager {
installedAt: record.installedAt,
updatedAt: record.updatedAt,
compatibility,
+ source: record.source,
+ ...(record.templateId
+ ? {
+ template: {
+ id: record.templateId,
+ version: record.templateVersion || ''
+ }
+ }
+ : {}),
+ ...(record.source === 'development'
+ ? {
+ development: {
+ sourcePath: record.developmentSourcePath || '',
+ available: this.isDevelopmentRootAvailable(record.id)
+ }
+ }
+ : {}),
permissions: manifest?.permissions ?? [],
grantedPermissions: record.grantedPermissions,
+ pendingPermissions,
runtime,
pages: (manifest?.contributions.pages ?? []).map((page) => ({
id: page.id,
title: page.title
})),
automationActions: this.actions.summariesFor(record.id),
- filesPresent: Boolean(manifest)
+ filesPresent: Boolean(manifest),
+ storage: {
+ state: storageHealth.state,
+ ...(storageHealth.message ? { message: storageHealth.message } : {})
+ }
+ }
+ }
+
+ /**
+ * 没有 Host 时的运行状态。
+ *
+ * 只有页面入口的扩展本来就不会有后台进程,必须与「启用但启动失败」区分开:
+ * 前者是 `inactive` 加说明,后者是 `error` 加原因。
+ */
+ private deriveIdleRuntime(
+ record: ExtensionRegistryRecord,
+ manifest: ExtensionManifest | null
+ ): InstalledExtension['runtime'] {
+ const base = { since: record.updatedAt, restarts: 0 }
+ // 版本不一致优先展示:即使扩展已停用,用户也需要知道上一次升级可能中断。
+ const drift = this.inconsistencies.get(record.id)
+ if (drift) return { state: 'error', ...base, lastError: drift }
+ if (this.storageHolds.has(record.id) && record.enabled) {
+ return {
+ state: 'error',
+ ...base,
+ lastError: '扩展配置曾从备份恢复,确认后才能启动'
+ }
+ }
+ if (!record.enabled) return { state: 'inactive', ...base }
+ if (!manifest) {
+ return {
+ state: 'error',
+ ...base,
+ lastError: '扩展文件缺失或 manifest 无法读取'
+ }
+ }
+ if (!manifest.entrypoints.background) {
+ return { state: 'inactive', ...base, note: '仅提供页面,没有后台任务' }
+ }
+ const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
+ if (!compatibility.compatible) {
+ return {
+ state: 'error',
+ ...base,
+ lastError: compatibility.reason || '扩展与当前版本不兼容'
+ }
+ }
+ return { state: 'error', ...base, lastError: '后台进程未启动' }
+ }
+
+ private isDevelopmentRootAvailable(extensionId: string): boolean {
+ try {
+ return Boolean(this.roots.resolve(extensionId).root)
+ } catch {
+ return false
}
}
private readManifest(extensionId: string): ExtensionManifest | null {
if (this.manifests.has(extensionId)) return this.manifests.get(extensionId) ?? null
- const file = path.join(this.paths.installDir(extensionId), 'manifest.json')
+ let root: string
+ try {
+ root = this.roots.resolve(extensionId).root
+ } catch {
+ // 开发目录不可用或扩展不存在:交给调用方按「没有 manifest」处理。
+ return null
+ }
+ const file = path.join(root, 'manifest.json')
let manifest: ExtensionManifest | null = null
try {
const parsed = parseExtensionManifest(fs.readJsonSync(file) as unknown)
diff --git a/src/main/extensions/extension-paths.ts b/src/main/extensions/extension-paths.ts
index 99a4259..a84e147 100644
--- a/src/main/extensions/extension-paths.ts
+++ b/src/main/extensions/extension-paths.ts
@@ -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)
+}
diff --git a/src/main/extensions/extension-project-files.ts b/src/main/extensions/extension-project-files.ts
new file mode 100644
index 0000000..0827584
--- /dev/null
+++ b/src/main/extensions/extension-project-files.ts
@@ -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 {
+ 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 {
+ await fs.mkdir(parent, { recursive: true })
+ return fs.mkdtemp(path.join(parent, '.tm-project-'))
+}
+
+async function cleanup(directory: string): Promise {
+ 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 {
+ let archive: Awaited>
+ 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 {
+ 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 {
+ const rewritten: string[] = []
+ const manifestPath = path.join(root, 'manifest.json')
+ const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')) as Record
+ 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 {
+ 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 {
+ 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
+ }
+}
diff --git a/src/main/extensions/extension-protocol.ts b/src/main/extensions/extension-protocol.ts
index b5025e7..40f8ac9 100644
--- a/src/main/extensions/extension-protocol.ts
+++ b/src/main/extensions/extension-protocol.ts
@@ -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)
diff --git a/src/main/extensions/extension-registry.ts b/src/main/extensions/extension-registry.ts
index 4a6bb99..fe0753a 100644
--- a/src/main/extensions/extension-registry.ts
+++ b/src/main/extensions/extension-registry.ts
@@ -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/` 里的副本。
+ * 缺失表示无法判断(旧版本安装或指纹计算失败),更新时必须保守处理。
+ */
+ 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
- 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()
+ 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
+ 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
+ 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 })
}
}
diff --git a/src/main/extensions/extension-root-resolver.ts b/src/main/extensions/extension-root-resolver.ts
new file mode 100644
index 0000000..5502bdb
--- /dev/null
+++ b/src/main/extensions/extension-root-resolver.ts
@@ -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
+ }
+}
diff --git a/src/main/extensions/extension-secret-store.ts b/src/main/extensions/extension-secret-store.ts
new file mode 100644
index 0000000..358cee1
--- /dev/null
+++ b/src/main/extensions/extension-secret-store.ts
@@ -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 {
+ /** 通常是 `/extensions-state/secrets`。 */
+ root: string
+ cipher: ExtensionSecretCipher
+ now?: () => number
+}
+
+interface SecretFile {
+ version: 1
+ values: Record
+}
+
+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()
+
+ 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 = {}
+ 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
+}
diff --git a/src/main/extensions/extension-service.ts b/src/main/extensions/extension-service.ts
index 67b48ae..d013163 100644
--- a/src/main/extensions/extension-service.ts
+++ b/src/main/extensions/extension-service.ts
@@ -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
+/**
+ * 官方模板资源根目录。
+ *
+ * 打包后是 `/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()
diff --git a/src/main/extensions/extension-storage.ts b/src/main/extensions/extension-storage.ts
index 1919073..00e93e3 100644
--- a/src/main/extensions/extension-storage.ts
+++ b/src/main/extensions/extension-storage.ts
@@ -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
}
+export interface ExtensionStorageHealth {
+ state: ExtensionStorageHealthState
+ at: number
+ /** 损坏现场的**文件名**(不含目录);不渲染绝对路径。 */
+ corruptFile?: string
+ message?: string
+}
+
export interface ExtensionStorageDependencies {
/** 通常是 `/extensions-data`。 */
dataRoot: string
maxTotalBytes?: number
maxValueBytes?: number
+ now?: () => number
+ /**
+ * 健康状态发生变化时的通知。
+ *
+ * 运行期才发生损坏/回退时,宿主要靠这个立刻收住扩展——
+ * 只等下一次启动才处理,那台机器人已经用旧配置发完消息了。
+ */
+ onHealthChange?: (extensionId: string, health: ExtensionStorageHealth) => void
+}
+
+type ParseResult = { ok: true; values: Record } | { 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 }
}
/**
@@ -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()
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 }
- } 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 | 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) {
diff --git a/src/main/extensions/extension-template-catalog.ts b/src/main/extensions/extension-template-catalog.ts
new file mode 100644
index 0000000..6742b5c
--- /dev/null
+++ b/src/main/extensions/extension-template-catalog.ts
@@ -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 {
+ /** 模板资源根目录;打包后是 `/extension-templates`。 */
+ templateRoot: string
+ getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
+ /** 已安装扩展的代码目录;用来看依赖脚本在不在。 */
+ resolveInstallDir: (extensionId: string) => string
+ platform?: NodeJS.Platform
+ /** 测试注入点:默认用真实文件系统。 */
+ exists?: (filePath: string) => boolean
+ readFile?: (filePath: string) => Promise
+ /** 依赖探测注入点:默认读本机 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
+ 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
+ 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
+ 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 {
+ 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 {
+ 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()
+ 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 {
+ 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 {
+ 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 {
+ 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
+}
diff --git a/src/main/extensions/host-runtime.ts b/src/main/extensions/host-runtime.ts
index f3e2b4d..25dbb1c 100644
--- a/src/main/extensions/host-runtime.ts
+++ b/src/main/extensions/host-runtime.ts
@@ -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()
const eventHandlers = new Set()
const actions = new Map()
+const pageHandlers = new Map) => 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) => 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 {
+ requirePermission('secrets')
+ return (await callHost('secrets.get', { key })) as string | null
+ },
+ async set(key: string, value: string): Promise {
+ requirePermission('secrets')
+ await callHost('secrets.set', { key, value })
+ },
+ async delete(key: string): Promise {
+ requirePermission('secrets')
+ await callHost('secrets.delete', { key })
+ },
+ async has(key: string): Promise {
+ 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 {
}
}
+/**
+ * 与 UI 共用同一套校验规则。
+ *
+ * 两套实现一定会在某个边界上分叉,用户看到的就是「表单填得进去、执行时说参数错」。
+ */
function validateActionInput(
schema: Record | undefined,
input: Record
): 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 {
+ 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)) {
- 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)
diff --git a/src/main/index.ts b/src/main/index.ts
index 6a911c9..76998a9 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -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(),
diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts
index 984161f..51e0a3d 100644
--- a/src/preload/index.d.ts
+++ b/src/preload/index.d.ts
@@ -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
+ getExtensionHealth: () => Promise
+ grantExtensionPermissions: (
+ extensionId: string,
+ permissions: string[]
+ ) => Promise
+ revokeExtensionPermission: (
+ extensionId: string,
+ permission: string
+ ) => Promise
+ resetExtensionStorage: (extensionId: string) => Promise
+ listExtensionTemplates: () => Promise
+ installExtensionTemplate: (templateId: string) => Promise
+ acknowledgeExtensionRecovery: () => Promise
+ acknowledgeExtensionStorage: (extensionId: string) => Promise
+ adoptExtensionCode: (extensionId: string) => Promise
+ rollbackExtensionUpgrade: (extensionId: string) => Promise
+ pickExtensionProjectDirectory: () => Promise
+ linkExtensionDevelopment: (directory: string) => Promise
+ reloadExtensionDevelopment: (extensionId: string) => Promise
+ unlinkExtensionDevelopment: (
+ extensionId: string,
+ keepData?: boolean
+ ) => Promise
+ convertExtensionDevelopment: (extensionId: string) => Promise
+ createExtensionProject: (input: {
+ templateId: string
+ targetDirectory: string
+ extensionId: string
+ name?: string
+ }) => Promise
+ listExtensionActions: () => Promise
+ openExtensionDevelopmentSource: (extensionId: string) => Promise
+ exportExtensionAsProject: (
+ extensionId: string,
+ targetDirectory: string
+ ) => Promise
uninstallExtension: (
extensionId: string,
keepData?: boolean
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 553c6c4..71cc670 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -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 =>
ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }),
+ getExtensionHealth: (): Promise =>
+ ipcRenderer.invoke('extension:health'),
+ grantExtensionPermissions: (
+ extensionId: string,
+ permissions: string[]
+ ): Promise =>
+ ipcRenderer.invoke('extension:grantPermissions', { id: extensionId, permissions }),
+ revokeExtensionPermission: (
+ extensionId: string,
+ permission: string
+ ): Promise =>
+ ipcRenderer.invoke('extension:revokePermission', { id: extensionId, permission }),
+ resetExtensionStorage: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:resetStorage', extensionId),
+ listExtensionTemplates: (): Promise =>
+ ipcRenderer.invoke('extension:templates'),
+ installExtensionTemplate: (templateId: string): Promise =>
+ ipcRenderer.invoke('extension:installTemplate', templateId),
+ acknowledgeExtensionRecovery: (): Promise =>
+ ipcRenderer.invoke('extension:acknowledgeRecovery'),
+ acknowledgeExtensionStorage: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:acknowledgeStorage', extensionId),
+ adoptExtensionCode: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:adoptInstalledCode', extensionId),
+ rollbackExtensionUpgrade: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:rollbackUpgrade', extensionId),
+ pickExtensionProjectDirectory: (): Promise =>
+ ipcRenderer.invoke('extension:pickProjectDirectory'),
+ linkExtensionDevelopment: (directory: string): Promise =>
+ ipcRenderer.invoke('extension:linkDevelopment', directory),
+ reloadExtensionDevelopment: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:reloadDevelopment', extensionId),
+ unlinkExtensionDevelopment: (
+ extensionId: string,
+ keepData = true
+ ): Promise =>
+ ipcRenderer.invoke('extension:unlinkDevelopment', { id: extensionId, keepData }),
+ convertExtensionDevelopment: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:convertDevelopment', extensionId),
+ createExtensionProject: (input: {
+ templateId: string
+ targetDirectory: string
+ extensionId: string
+ name?: string
+ }): Promise =>
+ ipcRenderer.invoke('extension:createProjectFromTemplate', input),
+ listExtensionActions: (): Promise =>
+ ipcRenderer.invoke('extension:actions'),
+ openExtensionDevelopmentSource: (extensionId: string): Promise =>
+ ipcRenderer.invoke('extension:openDevelopmentSource', extensionId),
+ exportExtensionAsProject: (
+ extensionId: string,
+ targetDirectory: string
+ ): Promise =>
+ ipcRenderer.invoke('extension:exportInstalledAsProject', {
+ id: extensionId,
+ targetDirectory
+ }),
uninstallExtension: (extensionId: string, keepData = true): Promise =>
ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }),
getExtensionLogs: (extensionId: string, limit?: number): Promise =>
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index d0c52f3..423a2c8 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -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()
const connectionOperationRef = React.useRef(0)
const [activePage, setActivePage] = useState('archive')
+ /** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
+ const [extensionDeepLink, setExtensionDeepLink] = useState(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
case 'extensions':
- return
+ return (
+ setExtensionDeepLink(null)}
+ />
+ )
case 'api':
return (
(loader: () => Promise | undefined, fallback: T): Promise {
+ 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([])
const [groups, setGroups] = React.useState([])
const [executions, setExecutions] = React.useState([])
- const [sendableContacts, setSendableContacts] = React.useState([])
+ const [sendableContacts, setSendableContacts] = React.useState(
+ []
+ )
const [monitoredGroupCount, setMonitoredGroupCount] = React.useState(0)
/** 已监控群聊清单(含显示名)—— 退群通知「通知群聊」二次勾选的候选项。 */
const [monitoredGroups, setMonitoredGroups] = React.useState([])
@@ -109,6 +127,63 @@ export function AutomationWorkspace({
const [saving, setSaving] = React.useState(false)
const [busyRuleId, setBusyRuleId] = React.useState(null)
const [editor, setEditor] = React.useState(null)
+ /** 规则模板依赖的本机事实:官方模板目录 + 已安装扩展。 */
+ const [extensionTemplates, setExtensionTemplates] = React.useState([])
+ const [installedExtensions, setInstalledExtensions] = React.useState([])
+
+ /**
+ * 规则模板卡片的真实状态。
+ *
+ * 只读「官方模板目录 + 已装扩展」,不在自动化页维护第二份安装状态。
+ */
+ const ruleTemplates = React.useMemo(() => {
+ 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(null)
const [pendingDelete, setPendingDelete] = React.useState(null)
@@ -131,6 +206,15 @@ export function AutomationWorkspace({
automationApi.getMonitoredGroupCount(),
automationApi.getMonitoredGroups()
])
+ // 扩展状态是「模板能不能用」的唯一依据:不自己维护第二份。
+ // 扩展 API 在旧版宿主或测试环境里可能整体缺失,缺失时按空列表处理,
+ // 卡片会退化成「未安装」,而不是让整个自动化页崩掉。
+ const [nextTemplates, nextExtensions] = await Promise.all([
+ safeLoad(() => window.api?.listExtensionTemplates?.(), []),
+ safeLoad(() => 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 => {
+ const handleLeaveNotificationSave = async (input: LeaveNotificationSaveInput): Promise => {
// 静默 return 会让"点保存没反应"变成用户眼里的坏掉,必须说出来。
if (!leaveNotificationRule) {
toast({
@@ -522,7 +603,11 @@ export function AutomationWorkspace({
发送能力
- {capabilityReady ? '可以发送文字和图片' : capability.ready ? '发送能力不完整' : '尚未就绪'}
+ {capabilityReady
+ ? '可以发送文字和图片'
+ : capability.ready
+ ? '发送能力不完整'
+ : '尚未就绪'}
{capability.message}
{!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({
没有找到内置的退群通知规则。
- 这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本,
- 请重启 TraceMemo —— 已经跑起来的主进程不会自动换成新代码。
+ 这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本, 请重启 TraceMemo ——
+ 已经跑起来的主进程不会自动换成新代码。
- {AUTOMATION_RULE_TEMPLATES.map((template) => (
-
-
-
{template.name}
- 即将支持
-
- {template.description}
- {template.unavailableReason ? {template.unavailableReason} : null}
-
- ))}
+ {(ruleTemplates ?? []).map((template) => {
+ const badge =
+ template.state === 'ready'
+ ? '已就绪'
+ : template.state === 'installed-disabled'
+ ? '已安装 · 未启用'
+ : template.state === 'not-installed'
+ ? '未安装'
+ : '不可用'
+ return (
+
+
+
{template.name}
+
+ {badge}
+
+
+ {template.description}
+ {template.reason ? {template.reason} : null}
+
+
+ {template.state === 'not-installed' && (
+ onOpenExtension?.({ templateId: template.templateId })}
+ >
+ 去扩展中心安装 →
+
+ )}
+ {template.state === 'installed-disabled' && (
+ onOpenExtension?.({ extensionId: template.extensionId })}
+ >
+ 去启用 →
+
+ )}
+ {template.state === 'ready' && (
+ <>
+ onOpenExtension?.({ extensionId: template.extensionId })}
+ >
+ 打开扩展配置 →
+
+ {template.actionId ? (
+ onUseRuleTemplate?.(template)}
+ >
+ 用规则触发
+
+ ) : (
+
+ 该扩展没有注册自动化动作,靠消息事件触发
+
+ )}
+ >
+ )}
+
+
+ )
+ })}
+
+ {/* 模板之外还要有出口:没有现成模板可用时,用户应该能自己做一个。 */}
+
+
+
做自己的扩展
+
+
+ 从官方模板克隆一份代码,改完直接在本地调试;官方升级不会覆盖你的改动。 也可以链接已经
+ clone 到别处的项目。
+
+
+ onOpenExtension?.({ development: true })}
+ >
+ 开始二次开发 →
+
+
+
diff --git a/src/renderer/src/features/extensions/CreateProjectDialog.tsx b/src/renderer/src/features/extensions/CreateProjectDialog.tsx
new file mode 100644
index 0000000..5099946
--- /dev/null
+++ b/src/renderer/src/features/extensions/CreateProjectDialog.tsx
@@ -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 (
+
+
从「{template.name}」创建独立项目
+
+ 会在你选择的目录里生成完整源码;不会复制任何配置、Cookie 或聊天数据。
+
+
+
+ {!idValid && (
+
id 必须是反向域名格式(小写字母、数字、连字符)
+ )}
+ {conflictsWithTemplate && (
+
不能沿用模板原 id,否则会和官方模板冲突
+ )}
+
+
+
+
+
+ 取消
+
+ onSubmit({ extensionId: trimmedId, name: name.trim() })}
+ >
+ {busy ? '创建中…' : '选择目录并创建'}
+
+
+
+ )
+}
diff --git a/src/renderer/src/features/extensions/DevelopmentGuide.tsx b/src/renderer/src/features/extensions/DevelopmentGuide.tsx
new file mode 100644
index 0000000..33c8302
--- /dev/null
+++ b/src/renderer/src/features/extensions/DevelopmentGuide.tsx
@@ -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 (
+
+
+
+
+ -
+ 1
+
+
拿到一份代码
+
+ 从官方模板生成独立项目(会替换成你自己的扩展 id),或直接链接已经在别处 clone
+ 好的目录。
+
+
+
+ -
+ 2
+
+
链接到 TraceMemo
+
+ 链接后代码不复制:宿主直接读你选的目录。配置、日志、缓存仍然写在 TraceMemo
+ 的用户数据目录,不会污染你的仓库。
+
+
+
+ -
+ 3
+
+
改完重新加载
+
+ 后台代码改动点「重新加载」;页面改动刷新 iframe 即可。Manifest 新增权限不会自动授予,
+ 需要在详情页逐项确认。
+
+
+
+
+
+
+
+ 从模板创建项目
+
+
+ 链接本地项目
+
+
+
+
+ 开发文档
+
+
+ 文档随仓库分发,路径以上方为准;打包后的应用里不包含 docs 目录。
+
+
+
+
+ 几个边界
+
+ - 不会自动安装、自动启用或自动创建规则——每一步都要你点。
+ - 移除链接只断开引用,不会删除你的项目目录。
+ -
+ 页面跑在 sandbox iframe 里,只能调用你自己后台注册的处理器,拿不到 Node 或
+
window.api。
+
+
+
+
+ )
+}
diff --git a/src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx b/src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx
new file mode 100644
index 0000000..a345ac3
--- /dev/null
+++ b/src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx
@@ -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 = {
+ '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(null)
+
+ // 深链进来时展开目标模板;滚动交给浏览器默认行为即可。
+ React.useEffect(() => {
+ if (focusTemplateId) setExpanded(focusTemplateId)
+ }, [focusTemplateId])
+
+ if (loading) {
+ return (
+
+ )
+ }
+
+ if (templates.length === 0) {
+ return (
+
+
官方模板
+
当前安装包没有携带模板资源。如果你是从源码运行,请先执行模板构建脚本。
+
+ )
+ }
+
+ return (
+
+
+
+
官方模板
+
安装后仍需你确认权限并手动启用,不会自动运行。
+
+
+
+
+ {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 (
+ -
+
+
+
+ {template.name}
+ v{template.version}
+
+ {STATE_LABELS[item.state]}
+
+
+
+ {template.description || '官方提供的扩展示例。'}
+
+
+ {template.fileCount} 个文件 · {formatBytes(template.bytes)}
+ {item.installedVersion && item.state !== 'not-installed'
+ ? ` · 已安装 v${item.installedVersion}`
+ : ''}
+
+
+
+ setExpanded(isOpen ? null : template.templateId)}
+ >
+ {isOpen ? '收起详情' : '查看详情'}
+
+ {onCreateProject && (
+ onCreateProject(template.templateId)}
+ >
+ 创建项目
+
+ )}
+ onInstall(template.templateId)}
+ >
+ {busyId === template.templateId
+ ? '安装中…'
+ : item.state === 'update-available'
+ ? '更新'
+ : '安装'}
+
+
+
+
+ {item.message && {item.message}
}
+
+ {missingBlocking.length > 0 && (
+
+ 缺少 {missingBlocking.map((check) => check.label).join('、')}
+ :安装后可以查看配置页,但主要功能暂时不可用。
+
+ )}
+
+ {isOpen && (
+
+
+ 权限
+
+ {sortPermissionsByRisk(template.permissions).map(
+ (permission: ExtensionPermission) => (
+ -
+
+
+ {EXTENSION_PERMISSION_INFO[permission].label}
+
+
+ {EXTENSION_PERMISSION_INFO[permission].risk === 'high'
+ ? '高'
+ : EXTENSION_PERMISSION_INFO[permission].risk === 'medium'
+ ? '中'
+ : '低'}
+
+
+ {EXTENSION_PERMISSION_INFO[permission].description}
+
+ )
+ )}
+
+
+
+
+ 依赖
+ {item.dependencies.checks.length === 0 ? (
+ 该模板不需要额外依赖。
+ ) : (
+
+ {item.dependencies.checks.map((check) => (
+ -
+
+ {check.label}
+ {check.detail}
+
+ ))}
+
+ )}
+
+
+ )}
+
+ {item.state === 'conflict' && (
+
+ 你之前用同一扩展 ID 安装过其他来源的扩展。请先卸载它,或改用「安装 ZIP」手动更新。
+
+ )}
+ {blocked && item.state === 'damaged' && (
+
+ 模板资源与你安装的版本不匹配,建议重新安装 TraceMemo。
+
+ )}
+
+ )
+ })}
+
+
+ )
+}
diff --git a/src/renderer/src/features/extensions/ExtensionWorkspace.tsx b/src/renderer/src/features/extensions/ExtensionWorkspace.tsx
index 19d0c26..9003474 100644
--- a/src/renderer/src/features/extensions/ExtensionWorkspace.tsx
+++ b/src/renderer/src/features/extensions/ExtensionWorkspace.tsx
@@ -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 = {
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([])
const [selectedId, setSelectedId] = React.useState(null)
@@ -41,10 +60,36 @@ export function ExtensionWorkspace(): React.ReactElement {
const [page, setPage] = React.useState(null)
const [pendingEnable, setPendingEnable] = React.useState(null)
const [pendingUninstall, setPendingUninstall] = React.useState(null)
+ const [health, setHealth] = React.useState(null)
+ const [templates, setTemplates] = React.useState([])
+ const [templatesLoading, setTemplatesLoading] = React.useState(true)
+ const [installingTemplate, setInstallingTemplate] = React.useState(null)
+ /** 右侧主区域:扩展列表 or 官方模板画廊。 */
+ const [view, setView] = React.useState<'extensions' | 'templates' | 'guide'>('extensions')
+ /** 深链定位的模板:进入画廊时自动展开它。 */
+ const [focusedTemplateId, setFocusedTemplateId] = React.useState(null)
+ /** 正在创建项目的模板;非空时显示创建对话框。 */
+ const [creatingTemplate, setCreatingTemplate] = React.useState(
+ null
+ )
+ /** 高风险权限的二次确认;低风险直接授权。 */
+ const [pendingGrant, setPendingGrant] = React.useState<{
+ extensionId: string
+ permission: ExtensionPermission
+ } | null>(null)
+ /** 「转为正式安装」的二次确认。 */
+ const [pendingConvert, setPendingConvert] = React.useState(null)
const refresh = React.useCallback(async (): Promise => {
- 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ const result = await run(() => window.api.acknowledgeExtensionRecovery())
+ if (result?.success) await refresh()
+ }
+
+ const installTemplate = async (templateId: string): Promise => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ 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 => {
+ const result = await window.api.openExtensionDevelopmentSource(extension.id)
+ if (!result.success) {
+ toast({
+ title: '无法打开源码目录',
+ description: result.error?.message || '目录不可用',
+ variant: 'destructive'
+ })
+ }
+ }
+
if (page) {
return (
{extensions.length}
+ {health && health.registry.state !== 'ok' && (
+
+
+ {health.registry.state === 'unreadable'
+ ? '扩展状态文件损坏且无法恢复,已停止写入以保留现场。请保留 extensions-state 下的损坏文件。'
+ : health.registry.message || '扩展状态文件曾损坏,已自动恢复。'}
+
+ {health.registry.state !== 'unreadable' && (
+ void acknowledgeRecovery()}
+ >
+ 我知道了
+
+ )}
+
+ )}
+ setView(view === 'templates' ? 'extensions' : 'templates')}
+ >
+ 官方模板{templates.length > 0 ? ` (${templates.length})` : ''}
+
+ setView(view === 'guide' ? 'extensions' : 'guide')}
+ >
+ 二次开发
+
+ void linkProject()}
+ >
+ 链接本地项目
+
- {!selected ? (
+ {view === 'guide' ? (
+ setView('extensions')}
+ onCreateProject={() => setView('templates')}
+ onLinkProject={() => void linkProject()}
+ />
+ ) : view === 'templates' ? (
+ void installTemplate(templateId)}
+ focusTemplateId={focusedTemplateId}
+ onCreateProject={(templateId) => {
+ const found = templates.find((item) => item.template.templateId === templateId)
+ if (found) setCreatingTemplate(found.template)
+ }}
+ />
+ ) : !selected ? (
选择左侧的扩展
安装后在这里查看权限、页面、自动化动作与执行日志。
@@ -277,8 +684,52 @@ export function ExtensionWorkspace(): React.ReactElement {
{selected.compatibility.reason || '扩展与当前版本不兼容'}
)}
+ {selected.storage.state !== 'ok' && (
+
+
+ {selected.storage.state === 'recovered-from-backup'
+ ? '扩展配置曾损坏,已从备份恢复;确认前不会启动。'
+ : '扩展配置损坏且没有可用备份,写入已停止。可在下方重置配置。'}
+
+ {selected.storage.state === 'recovered-from-backup' && (
+ void acknowledgeStorage(selected)}
+ >
+ 使用恢复的配置
+
+ )}
+
+ )}
+ {selected.runtime.note && (
+
{selected.runtime.note}
+ )}
{selected.runtime.lastError && (
-
{selected.runtime.lastError}
+
+ {selected.runtime.lastError}
+ {selected.runtime.lastError.includes('升级可能中断') && (
+ <>
+ void adoptInstalledCode(selected)}
+ >
+ 采用当前代码
+
+ void rollbackUpgrade(selected)}
+ >
+ 回滚到备份
+
+ >
+ )}
+
)}
@@ -344,8 +795,107 @@ export function ExtensionWorkspace(): React.ReactElement {
)}
+ {selected.development && (
+
+
+
开发模式
+
+ {selected.development.available ? '源码可用' : '源码不可用'}
+
+
+
+ {selected.development.sourcePath || '未记录源码路径'}
+
+ {!selected.development.available && (
+
+ 源码目录被移动或删除。扩展配置与规则都还在,重新链接后即可继续。
+
+ )}
+ {pendingConvert?.id === selected.id && (
+
+
+ 将把当前源码复制到 TraceMemo
+ 用户数据目录,之后运行的是这份安装副本。
+ 外部源码目录不会被删除,但你之后对它的修改不会
+ 自动同步过去。
+ 转换会停止当前后台,转换后保持「未启用」;已有配置、规则与缓存都保留。
+
+
+ {
+ const target = pendingConvert
+ setPendingConvert(null)
+ if (target) void convertDevelopment(target)
+ }}
+ >
+ 确认转换
+
+ setPendingConvert(null)}>
+ 取消
+
+
+
+ )}
+
+ void reloadDevelopment(selected)}
+ >
+ 重新加载
+
+ void openDevelopmentSource(selected)}
+ >
+ 打开源码目录
+
+ setPendingConvert(selected)}
+ >
+ 转为正式安装
+
+ void unlinkDevelopment(selected)}
+ >
+ 移除链接
+
+
+
+ )}
+
- 权限
+
+
权限
+ {selected.pendingPermissions.length > 0 && (
+ void grantPending(selected)}
+ >
+ 授权新增权限
+
+ )}
+
+ {selected.pendingPermissions.length > 0 && (
+
+ 新版本申请了 {selected.pendingPermissions.length} 项尚未授予的权限,当前不可用。
+
+ )}
{selected.permissions.length === 0 ? (
未申请任何权限。
) : (
@@ -367,11 +917,59 @@ export function ExtensionWorkspace(): React.ReactElement {
{EXTENSION_PERMISSION_INFO[permission].description}
-
- {selected.grantedPermissions.includes(permission) ? '已授予' : '未授予'}
-
+ {selected.grantedPermissions.includes(permission) ? (
+
+ 已授予
+ void revokePermission(selected, permission)}
+ >
+ 撤销
+
+
+ ) : (
+
+ {
+ if (EXTENSION_PERMISSION_INFO[permission].risk === 'high') {
+ setPendingGrant({ extensionId: selected.id, permission })
+ } else {
+ void grantPermission(selected, permission)
+ }
+ }}
+ >
+ 授权
+
+
+ )}
+ {pendingGrant?.extensionId === selected.id &&
+ pendingGrant.permission === permission && (
+
+
+ 该权限可以代替你执行敏感操作,确认授予「
+ {EXTENSION_PERMISSION_INFO[permission].label}」?
+
+ void grantPermission(selected, permission)}
+ >
+ 确认授权
+
+ setPendingGrant(null)}
+ >
+ 取消
+
+
+ )}
))}
@@ -431,6 +1029,26 @@ export function ExtensionWorkspace(): React.ReactElement {
+ {creatingTemplate && (
+ setCreatingTemplate(null)}
+ onSubmit={(input) => void submitCreateProject(input)}
+ />
+ )}
+
{pendingEnable && (
diff --git a/src/renderer/src/styles/automation.scss b/src/renderer/src/styles/automation.scss
index c29d7f1..bf2afef 100644
--- a/src/renderer/src/styles/automation.scss
+++ b/src/renderer/src/styles/automation.scss
@@ -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);
+}
diff --git a/src/renderer/src/styles/extensions.scss b/src/renderer/src/styles/extensions.scss
index 2c6ce94..ff473dc 100644
--- a/src/renderer/src/styles/extensions.scss
+++ b/src/renderer/src/styles/extensions.scss
@@ -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);
+}
+
+/* 序号自己画,关掉
的默认 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);
+}
diff --git a/src/shared/automation.ts b/src/shared/automation.ts
index be332a5..fa1b029 100644
--- a/src/shared/automation.ts
+++ b/src/shared/automation.ts
@@ -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'
}
]
diff --git a/src/shared/extensions/action-schema.ts b/src/shared/extensions/action-schema.ts
new file mode 100644
index 0000000..a6a4336
--- /dev/null
+++ b/src/shared/extensions/action-schema.ts
@@ -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
+ default?: string | number | boolean
+ minimum?: number
+ maximum?: number
+ minLength?: number
+ maxLength?: number
+}
+
+export interface ExtensionActionInputSchema {
+ type: 'object'
+ properties: Record
+ 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 {
+ 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 = {}
+ 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 = []
+ 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
+}
+
+/**
+ * 按 Schema 校验输入。
+ *
+ * UI 提交前与后台执行前都用这一个函数:两边规则一致才谈得上「所见即所得」。
+ */
+export function validateActionInput(
+ schema: ExtensionActionInputSchema | undefined,
+ input: Record | undefined
+): ActionInputValidationResult {
+ const errors: Record = {}
+ 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)[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 {
+ const result: Record = {}
+ if (!schema) return result
+ for (const [key, field] of Object.entries(schema.properties)) {
+ if (field.default !== undefined) result[key] = field.default
+ }
+ return result
+}
diff --git a/src/shared/extensions/errors.ts b/src/shared/extensions/errors.ts
index 17d96a3..956b296 100644
--- a/src/shared/extensions/errors.ts
+++ b/src/shared/extensions/errors.ts
@@ -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 = {
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 {
diff --git a/src/shared/extensions/ipc.ts b/src/shared/extensions/ipc.ts
index 2c0e635..3f4b531 100644
--- a/src/shared/extensions/ipc.ts
+++ b/src/shared/extensions/ipc.ts
@@ -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',
diff --git a/src/shared/extensions/permissions.ts b/src/shared/extensions/permissions.ts
index cf4e217..108ff60 100644
--- a/src/shared/extensions/permissions.ts
+++ b/src/shared/extensions/permissions.ts
@@ -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 = {
+ secrets: {
+ label: '保存私有凭据',
+ description:
+ '在本机以系统安全存储加密保存该扩展自己的凭据(如 Cookie),只有该扩展能读取;不写入明文文件。',
+ risk: 'medium'
+ },
'messages.subscribe': {
label: '接收新消息事件',
description:
diff --git a/src/shared/extensions/rpc.ts b/src/shared/extensions/rpc.ts
index 4136379..7036b55 100644
--- a/src/shared/extensions/rpc.ts
+++ b/src/shared/extensions/rpc.ts
@@ -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
+ 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
/**
* 自动化动作的返回值。
diff --git a/src/shared/extensions/source.ts b/src/shared/extensions/source.ts
new file mode 100644
index 0000000..b9a9440
--- /dev/null
+++ b/src/shared/extensions/source.ts
@@ -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'
+}
diff --git a/src/shared/extensions/templates.ts b/src/shared/extensions/templates.ts
new file mode 100644
index 0000000..aa2c312
--- /dev/null
+++ b/src/shared/extensions/templates.ts
@@ -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
+}
diff --git a/src/shared/extensions/types.ts b/src/shared/extensions/types.ts
index d7c8458..ab4de44 100644
--- a/src/shared/extensions/types.ts
+++ b/src/shared/extensions/types.ts
@@ -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
+ }
+}
diff --git a/tests/component/automation-rule-templates.test.tsx b/tests/component/automation-rule-templates.test.tsx
new file mode 100644
index 0000000..0d9499c
--- /dev/null
+++ b/tests/component/automation-rule-templates.test.tsx
@@ -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 {
+ 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(
+ 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()
+ })
+})
diff --git a/tests/component/extension-template-gallery.test.tsx b/tests/component/extension-template-gallery.test.tsx
new file mode 100644
index 0000000..ea21a18
--- /dev/null
+++ b/tests/component/extension-template-gallery.test.tsx
@@ -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 {
+ 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(
+
+ undefined)}
+ />
+
+ )
+}
+
+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(
+
+ undefined}
+ />
+
+ )
+ expect(screen.getByText(/没有携带模板资源/)).toBeTruthy()
+ })
+})
diff --git a/tests/component/extension-workspace-deeplink.test.tsx b/tests/component/extension-workspace-deeplink.test.tsx
new file mode 100644
index 0000000..244738f
--- /dev/null
+++ b/tests/component/extension-workspace-deeplink.test.tsx
@@ -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 {
+ 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(
+
+
+
+ )
+}
+
+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()
+ })
+})
diff --git a/tests/component/extension-workspace-health.test.tsx b/tests/component/extension-workspace-health.test.tsx
new file mode 100644
index 0000000..72392d4
--- /dev/null
+++ b/tests/component/extension-workspace-health.test.tsx
@@ -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 {
+ 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>
+
+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(
+
+
+
+ )
+}
+
+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()
+ })
+ })
+})
diff --git a/tests/integration/extension-development.test.ts b/tests/integration/extension-development.test.ts
new file mode 100644
index 0000000..90beb77
--- /dev/null
+++ b/tests/integration/extension-development.test.ts
@@ -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> = []
+ private readonly listeners = new Map()
+
+ send(message: unknown): void {
+ const payload = message as Record
+ 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 = {}
+): Record {
+ 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 = {},
+ 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'), 'dev')
+ fs.writeFileSync(path.join(project, 'background', 'index.js'), 'module.exports=()=>{}')
+ return project
+}
+
+function createManager(): {
+ manager: ExtensionManager
+ paths: ReturnType
+ 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 {
+ 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'), '')
+ 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)
+ })
+})
diff --git a/tests/integration/extension-lifecycle.test.ts b/tests/integration/extension-lifecycle.test.ts
index 7b4bae4..8328709 100644
--- a/tests/integration/extension-lifecycle.test.ts
+++ b/tests/integration/extension-lifecycle.test.ts
@@ -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')
diff --git a/tests/integration/extension-m4-runtime.test.ts b/tests/integration/extension-m4-runtime.test.ts
new file mode 100644
index 0000000..61aa696
--- /dev/null
+++ b/tests/integration/extension-m4-runtime.test.ts
@@ -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> = []
+ private readonly listeners = new Map()
+ /** 后台注册的动作;测试可改。 */
+ 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