mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 拓展中心
This commit is contained in:
1 parent
9ffa1efc26
commit
4eaddc2d75
74 files changed
+11738
-379
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest'
|
||||
import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types'
|
||||
import type { ExtensionActionInputSchema } from '../../shared/extensions/action-schema'
|
||||
|
||||
export interface RegisteredExtensionAction {
|
||||
extensionId: string
|
||||
@@ -11,6 +12,9 @@ export interface RegisteredExtensionAction {
|
||||
registered: boolean
|
||||
/** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */
|
||||
declared: boolean
|
||||
inputSchema?: ExtensionActionInputSchema
|
||||
/** Schema 校验失败的原因;有值时动作不可配置。 */
|
||||
schemaError?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,7 +29,15 @@ export interface RegisteredExtensionAction {
|
||||
export class ExtensionActionRegistry {
|
||||
private readonly registered = new Map<
|
||||
string,
|
||||
Map<string, { title: string; description?: string }>
|
||||
Map<
|
||||
string,
|
||||
{
|
||||
title: string
|
||||
description?: string
|
||||
inputSchema?: ExtensionActionInputSchema
|
||||
schemaError?: string
|
||||
}
|
||||
>
|
||||
>()
|
||||
private readonly declared = new Map<
|
||||
string,
|
||||
@@ -45,7 +57,13 @@ export class ExtensionActionRegistry {
|
||||
setRegistered(
|
||||
extensionId: string,
|
||||
extensionName: string,
|
||||
actions: Array<{ id: string; title: string; description?: string }>
|
||||
actions: Array<{
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
inputSchema?: ExtensionActionInputSchema
|
||||
schemaError?: string
|
||||
}>
|
||||
): void {
|
||||
this.names.set(extensionId, extensionName)
|
||||
this.registered.set(
|
||||
@@ -55,7 +73,9 @@ export class ExtensionActionRegistry {
|
||||
action.id,
|
||||
{
|
||||
title: action.title,
|
||||
...(action.description ? { description: action.description } : {})
|
||||
...(action.description ? { description: action.description } : {}),
|
||||
...(action.inputSchema ? { inputSchema: action.inputSchema } : {}),
|
||||
...(action.schemaError ? { schemaError: action.schemaError } : {})
|
||||
}
|
||||
])
|
||||
)
|
||||
@@ -91,7 +111,9 @@ export class ExtensionActionRegistry {
|
||||
? { description: runtime?.description || declaredAction?.description }
|
||||
: {}),
|
||||
registered: Boolean(runtime),
|
||||
declared: Boolean(declaredAction)
|
||||
declared: Boolean(declaredAction),
|
||||
...(runtime?.inputSchema ? { inputSchema: runtime.inputSchema } : {}),
|
||||
...(runtime?.schemaError ? { schemaError: runtime.schemaError } : {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
/** 与安装器的排除规则保持一致:这些目录不属于扩展产物。 */
|
||||
const DEFAULT_IGNORED_DIRECTORIES = new Set([
|
||||
'.git',
|
||||
'.hg',
|
||||
'.svn',
|
||||
'node_modules',
|
||||
'__pycache__',
|
||||
'.venv',
|
||||
'venv'
|
||||
])
|
||||
|
||||
const DEFAULT_IGNORED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
|
||||
const IGNORED_EXTENSIONS = new Set(['.pyc', '.log'])
|
||||
|
||||
export interface CodeDigestOptions {
|
||||
ignoreDirectories?: Iterable<string>
|
||||
ignoreFiles?: Iterable<string>
|
||||
}
|
||||
|
||||
interface DigestEntry {
|
||||
path: string
|
||||
sha256: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算一个目录的代码指纹。
|
||||
*
|
||||
* 只覆盖**代码与静态资源**:不包含 `extensions-data`、日志或缓存,
|
||||
* 所以用户改配置不会让指纹变化,改一行 JS 就会。
|
||||
*
|
||||
* 细则:
|
||||
* - 相对路径参与哈希,因此改名与改内容都能被发现;
|
||||
* - 文件按路径排序后再累加,结果与遍历顺序无关;
|
||||
* - 符号链接按链接目标字符串参与哈希,不跟随(避免读到宿主私有文件)。
|
||||
*/
|
||||
export function computeDirectoryDigest(root: string, options: CodeDigestOptions = {}): string {
|
||||
const ignoreDirectories = new Set([
|
||||
...DEFAULT_IGNORED_DIRECTORIES,
|
||||
...(options.ignoreDirectories ?? [])
|
||||
])
|
||||
const ignoreFiles = new Set([...DEFAULT_IGNORED_FILES, ...(options.ignoreFiles ?? [])])
|
||||
const entries: DigestEntry[] = []
|
||||
|
||||
const walk = (directory: string, prefix: string): void => {
|
||||
let items: fs.Dirent[]
|
||||
try {
|
||||
items = fs.readdirSync(directory, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.isDirectory()) {
|
||||
if (ignoreDirectories.has(item.name)) continue
|
||||
walk(path.join(directory, item.name), prefix ? `${prefix}/${item.name}` : item.name)
|
||||
continue
|
||||
}
|
||||
if (ignoreFiles.has(item.name)) continue
|
||||
if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue
|
||||
|
||||
const relative = prefix ? `${prefix}/${item.name}` : item.name
|
||||
const absolute = path.join(directory, item.name)
|
||||
if (item.isSymbolicLink()) {
|
||||
try {
|
||||
const target = fs.readlinkSync(absolute)
|
||||
entries.push({
|
||||
path: relative,
|
||||
sha256: createHash('sha256').update(`link:${target}`).digest('hex')
|
||||
})
|
||||
} catch {
|
||||
entries.push({ path: relative, sha256: 'link:unreadable' })
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!item.isFile()) continue
|
||||
try {
|
||||
const content = fs.readFileSync(absolute)
|
||||
entries.push({
|
||||
path: relative,
|
||||
sha256: createHash('sha256').update(content).digest('hex')
|
||||
})
|
||||
} catch {
|
||||
// 读不到的文件不应让整个指纹失效,但必须留下痕迹。
|
||||
entries.push({ path: relative, sha256: 'unreadable' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(root, '')
|
||||
entries.sort((left, right) => left.path.localeCompare(right.path))
|
||||
const hash = createHash('sha256')
|
||||
for (const entry of entries) {
|
||||
hash.update(`${entry.path}\0${entry.sha256}\n`)
|
||||
}
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
/** 列出参与指纹的文件数量;用于诊断「是不是把缓存算进去了」。 */
|
||||
export function countDigestFiles(root: string): number {
|
||||
let count = 0
|
||||
const walk = (directory: string): void => {
|
||||
let items: fs.Dirent[]
|
||||
try {
|
||||
items = fs.readdirSync(directory, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.isDirectory()) {
|
||||
if (DEFAULT_IGNORED_DIRECTORIES.has(item.name)) continue
|
||||
walk(path.join(directory, item.name))
|
||||
continue
|
||||
}
|
||||
if (DEFAULT_IGNORED_FILES.has(item.name)) continue
|
||||
if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
return count
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fork, type ChildProcess } from 'node:child_process'
|
||||
import { fork, spawn, type ChildProcess } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
|
||||
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
|
||||
@@ -23,7 +23,12 @@ import {
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
|
||||
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
|
||||
import {
|
||||
parseActionInputSchema,
|
||||
type ExtensionActionInputSchema
|
||||
} from '../../shared/extensions/action-schema'
|
||||
import type { ExtensionStorage } from './extension-storage'
|
||||
import type { ExtensionSecretStore } from './extension-secret-store'
|
||||
|
||||
const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000
|
||||
const DEFAULT_ACTION_TIMEOUT_MS = 15_000
|
||||
@@ -33,14 +38,52 @@ const RESTART_BASE_DELAY_MS = 1_000
|
||||
const EVENT_BUCKET_CAPACITY = 100
|
||||
const EVENT_REFILL_PER_SECOND = 60
|
||||
|
||||
/** 发出 shutdown 后等待扩展自行退出的时间。 */
|
||||
const GRACEFUL_EXIT_MS = 2_500
|
||||
/** 结束进程树之后等待 exit 事件的时间。 */
|
||||
const FORCE_EXIT_MS = 3_000
|
||||
|
||||
/** stderr 采样窗口:只把有代表性的片段写进日志,避免日志洪水拖住主进程。 */
|
||||
const STDERR_WINDOW_MS = 10_000
|
||||
const STDERR_WINDOW_BYTES = 64 * 1024
|
||||
const STDERR_WINDOW_ENTRIES = 20
|
||||
const STDERR_MAX_CHUNK_CHARS = 400
|
||||
|
||||
/**
|
||||
* stderr 里常见的凭据写法。
|
||||
*
|
||||
* 扩展的 stderr 是任意文本,可能包含用户配置的 Cookie / Token;
|
||||
* 落日志前统一抹掉值,只保留键名。
|
||||
*/
|
||||
const SECRET_ASSIGNMENT =
|
||||
/\b(cookie|token|authorization|password|passwd|secret|api[_-]?key)\b(\s*[:=]\s*)(?!Bearer\b)([^\s,;"']{4,})/gi
|
||||
const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi
|
||||
|
||||
export function redactSecrets(value: string): string {
|
||||
// 顺序不能反:先抹 `Bearer <token>` 整体,再按「键=值」处理,
|
||||
// 否则 `Authorization: Bearer xxx` 会只抹掉 `Bearer`,token 本体留在日志里。
|
||||
return String(value ?? '')
|
||||
.replace(BEARER_TOKEN, 'Bearer ***')
|
||||
.replace(
|
||||
SECRET_ASSIGNMENT,
|
||||
(_match, name: string, separator: string) => `${name}${separator}***`
|
||||
)
|
||||
}
|
||||
|
||||
export interface ExtensionHostChild {
|
||||
send(message: unknown): void
|
||||
/** 终止本扩展的整棵进程树;实现方负责平台差异。 */
|
||||
kill(): void
|
||||
on(event: 'message', listener: (message: unknown) => void): void
|
||||
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
|
||||
on(event: 'error', listener: (error: Error) => void): void
|
||||
once?(event: 'exit', listener: () => void): void
|
||||
readonly pid?: number
|
||||
/**
|
||||
* 子进程的 stderr。必须被消费:管道写满会让子进程在 `write` 上阻塞,
|
||||
* 表现为「扩展还活着但不再响应」。
|
||||
*/
|
||||
readonly stderr?: NodeJS.ReadableStream | null
|
||||
}
|
||||
|
||||
export interface ExtensionHostSpawnOptions {
|
||||
@@ -55,6 +98,7 @@ export interface ExtensionHostDependencies {
|
||||
dataDir: string
|
||||
permissions: ExtensionPermission[]
|
||||
storage: ExtensionStorage
|
||||
secrets?: ExtensionSecretStore
|
||||
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
|
||||
onLog?: (level: 'info' | 'warn' | 'error', message: string) => void
|
||||
onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void
|
||||
@@ -83,6 +127,10 @@ export interface ExtensionHostDependencies {
|
||||
now?: () => number
|
||||
activateTimeoutMs?: number
|
||||
actionTimeoutMs?: number
|
||||
/** 覆盖「等扩展自行退出」的时间;生产默认 2.5s。 */
|
||||
gracefulExitMs?: number
|
||||
/** 覆盖「结束进程树后等 exit」的时间;生产默认 3s。 */
|
||||
forceExitMs?: number
|
||||
}
|
||||
|
||||
interface PendingAction {
|
||||
@@ -95,6 +143,9 @@ interface RegisteredAction {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
/** 已校验的参数 Schema;非法时为 undefined 且 `schemaError` 有值。 */
|
||||
inputSchema?: ExtensionActionInputSchema
|
||||
schemaError?: string
|
||||
}
|
||||
|
||||
interface ActivationWaiter {
|
||||
@@ -133,17 +184,27 @@ export class ExtensionHost {
|
||||
}
|
||||
>()
|
||||
private readonly actions = new Map<string, RegisteredAction>()
|
||||
private readonly pendingPageRequests = new Map<
|
||||
string,
|
||||
{
|
||||
resolve: (value: unknown) => void
|
||||
reject: (error: Error) => void
|
||||
timer: ReturnType<typeof setTimeout>
|
||||
}
|
||||
>()
|
||||
private eventTokens = EVENT_BUCKET_CAPACITY
|
||||
private eventTokensAt: number
|
||||
private droppedEvents = 0
|
||||
private mutedDropLog = false
|
||||
private restartTimestamps: number[] = []
|
||||
private stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: 0 }
|
||||
|
||||
constructor(dependencies: ExtensionHostDependencies) {
|
||||
this.dependencies = dependencies
|
||||
this.storage = dependencies.storage
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
this.eventTokensAt = this.now()
|
||||
this.stderrWindow.at = this.now()
|
||||
this.state = { state: 'inactive', since: this.now(), restarts: 0 }
|
||||
}
|
||||
|
||||
@@ -155,6 +216,51 @@ export class ExtensionHost {
|
||||
return Array.from(this.actions.values()).map((action) => ({ ...action }))
|
||||
}
|
||||
|
||||
/**
|
||||
* 把页面请求转给同扩展的后台处理器。
|
||||
*
|
||||
* 这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。
|
||||
* 响应大小与超时都在这里收口,避免页面被一个坏 handler 拖死。
|
||||
*/
|
||||
async requestPage(
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
timeoutMs = 10_000
|
||||
): Promise<unknown> {
|
||||
const child = this.child
|
||||
if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
|
||||
const requestId = randomUUID()
|
||||
return new Promise<unknown>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => {
|
||||
this.pendingPageRequests.delete(requestId)
|
||||
reject(new ExtensionError('ACTION_TIMEOUT', '页面请求超时'))
|
||||
},
|
||||
Math.max(1_000, timeoutMs)
|
||||
)
|
||||
this.pendingPageRequests.set(requestId, { resolve, reject, timer })
|
||||
try {
|
||||
child.send({
|
||||
type: 'page-request',
|
||||
version: EXTENSION_HOST_PROTOCOL_VERSION,
|
||||
requestId,
|
||||
method,
|
||||
params,
|
||||
timeoutMs
|
||||
})
|
||||
} catch (error) {
|
||||
clearTimeout(timer)
|
||||
this.pendingPageRequests.delete(requestId)
|
||||
reject(
|
||||
new ExtensionError(
|
||||
'EXTENSION_HOST_UNAVAILABLE',
|
||||
error instanceof Error ? error.message : '扩展进程不可用'
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async testSend(params: Record<string, unknown>): Promise<unknown> {
|
||||
return this.runTestMessage('test-send', params)
|
||||
}
|
||||
@@ -204,6 +310,13 @@ export class ExtensionHost {
|
||||
return this.activation
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止后台进程。
|
||||
*
|
||||
* 三段式:先请扩展自行退出,超时后结束整棵进程树,再等真实的 exit 事件。
|
||||
* 只有收到 exit 才算停止完成——只发信号就返回,会让上层在进程仍占用
|
||||
* 文件时去替换扩展目录(Windows 上必然失败,POSIX 上会留下旧代码在跑)。
|
||||
*/
|
||||
async stop(): Promise<void> {
|
||||
this.stopping = true
|
||||
if (this.restartTimer) {
|
||||
@@ -216,26 +329,66 @@ export class ExtensionHost {
|
||||
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
|
||||
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
|
||||
this.actions.clear()
|
||||
this.setState('inactive')
|
||||
if (!child) return
|
||||
if (!child) {
|
||||
this.setState('inactive')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION })
|
||||
} catch {
|
||||
// 进程可能已经断开;kill 兜底。
|
||||
// 进程可能已经断开;后续按「未退出」处理。
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
resolve()
|
||||
}, 1_500)
|
||||
child.once?.('exit', () => {
|
||||
|
||||
if (await this.waitForExit(child, this.dependencies.gracefulExitMs ?? GRACEFUL_EXIT_MS)) {
|
||||
this.setState('inactive')
|
||||
return
|
||||
}
|
||||
|
||||
this.dependencies.onLog?.('warn', '扩展未在预期时间内退出,正在结束进程树')
|
||||
this.killTree(child)
|
||||
if (!(await this.waitForExit(child, this.dependencies.forceExitMs ?? FORCE_EXIT_MS))) {
|
||||
this.dependencies.onLog?.('error', '扩展进程树未能退出,可能有子进程仍在运行')
|
||||
}
|
||||
this.setState('inactive')
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束扩展进程及其派生进程。
|
||||
*
|
||||
* POSIX 依赖 `fork` 时的 `detached` 建立独立进程组,`kill(-pid)` 一次覆盖整组;
|
||||
* 组不存在时退化为只杀直接子进程,并记一条降级日志。
|
||||
*
|
||||
* Windows 用 `taskkill /T /F`,且必须**在父进程仍存活时**执行:
|
||||
* 父进程先退出后,进程树的父子关系消失,`/T` 再也找不到孙进程。
|
||||
*/
|
||||
private killTree(child: ExtensionHostChild): void {
|
||||
const pid = child.pid
|
||||
if (!pid) {
|
||||
try {
|
||||
child.kill()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return
|
||||
}
|
||||
const result = killProcessTree(pid)
|
||||
if (result !== 'group' && process.platform !== 'win32') {
|
||||
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
|
||||
}
|
||||
}
|
||||
|
||||
private waitForExit(child: ExtensionHostChild, timeoutMs: number): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let settled = false
|
||||
const finish = (exited: boolean): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve()
|
||||
})
|
||||
resolve(exited)
|
||||
}
|
||||
const timer = setTimeout(() => finish(false), timeoutMs)
|
||||
child.once?.('exit', () => finish(true))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -398,6 +551,62 @@ export class ExtensionHost {
|
||||
this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`)
|
||||
})
|
||||
child.on('exit', (code) => this.handleExit(child, code))
|
||||
this.consumeStderr(child)
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费子进程 stderr。
|
||||
*
|
||||
* 两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞),
|
||||
* 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。
|
||||
* 凭据形态的字段在落日志前抹掉值。
|
||||
*/
|
||||
private consumeStderr(child: ExtensionHostChild): void {
|
||||
const stream = child.stderr
|
||||
if (!stream || typeof stream.on !== 'function') return
|
||||
|
||||
const onData = (chunk: Buffer | string): void => {
|
||||
try {
|
||||
const now = this.now()
|
||||
if (now - this.stderrWindow.at >= STDERR_WINDOW_MS) {
|
||||
const dropped = this.stderrWindow.dropped
|
||||
this.stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: now }
|
||||
if (dropped > 0) {
|
||||
this.dependencies.onLog?.('warn', `扩展 stderr 有 ${dropped} 字节省略未记录`)
|
||||
}
|
||||
}
|
||||
const text = redactSecrets(String(chunk)).replace(/\s+/g, ' ').trim()
|
||||
if (!text) return
|
||||
const bytes = Buffer.byteLength(text, 'utf8')
|
||||
if (
|
||||
this.stderrWindow.entries >= STDERR_WINDOW_ENTRIES ||
|
||||
this.stderrWindow.bytes + bytes > STDERR_WINDOW_BYTES
|
||||
) {
|
||||
this.stderrWindow.dropped += bytes
|
||||
return
|
||||
}
|
||||
this.stderrWindow.bytes += bytes
|
||||
this.stderrWindow.entries += 1
|
||||
this.dependencies.onLog?.('warn', `[stderr] ${text.slice(0, STDERR_MAX_CHUNK_CHARS)}`)
|
||||
} catch {
|
||||
// stderr 处理失败不能影响扩展运行。
|
||||
}
|
||||
}
|
||||
|
||||
const onEnd = (): void => {
|
||||
if (this.stderrWindow.dropped > 0) {
|
||||
this.dependencies.onLog?.(
|
||||
'warn',
|
||||
`扩展 stderr 有 ${this.stderrWindow.dropped} 字节省略未记录`
|
||||
)
|
||||
this.stderrWindow.dropped = 0
|
||||
}
|
||||
stream.removeListener?.('data', onData)
|
||||
stream.removeListener?.('end', onEnd)
|
||||
}
|
||||
|
||||
stream.on('data', onData)
|
||||
stream.on('end', onEnd)
|
||||
}
|
||||
|
||||
private handleExit(child: ExtensionHostChild, code: number | null): void {
|
||||
@@ -450,14 +659,45 @@ export class ExtensionHost {
|
||||
case 'register-action': {
|
||||
const action = message.action
|
||||
if (!action || typeof action.id !== 'string') return
|
||||
// Schema 不合法的动作仍然登记:界面上要能看到它,并显示具体原因,
|
||||
// 而不是让它凭空消失。
|
||||
let inputSchema: ExtensionActionInputSchema | undefined
|
||||
let schemaError: string | undefined
|
||||
if (action.inputSchema !== undefined) {
|
||||
const parsed = parseActionInputSchema(action.inputSchema)
|
||||
if (parsed.ok) inputSchema = parsed.schema
|
||||
else schemaError = parsed.reason
|
||||
}
|
||||
this.actions.set(action.id, {
|
||||
id: action.id,
|
||||
title: String(action.title || action.id).slice(0, 60),
|
||||
...(action.description ? { description: String(action.description).slice(0, 200) } : {})
|
||||
...(action.description ? { description: String(action.description).slice(0, 200) } : {}),
|
||||
...(inputSchema ? { inputSchema } : {}),
|
||||
...(schemaError ? { schemaError } : {})
|
||||
})
|
||||
if (schemaError) {
|
||||
this.dependencies.onLog?.(
|
||||
'warn',
|
||||
`动作 ${action.id} 的参数 Schema 不可用:${schemaError}`
|
||||
)
|
||||
}
|
||||
this.dependencies.onActionsChanged?.()
|
||||
return
|
||||
}
|
||||
case 'page-result': {
|
||||
const pending = this.pendingPageRequests.get(message.requestId)
|
||||
if (!pending) return
|
||||
clearTimeout(pending.timer)
|
||||
this.pendingPageRequests.delete(message.requestId)
|
||||
if (message.ok) {
|
||||
pending.resolve(message.result)
|
||||
} else {
|
||||
pending.reject(
|
||||
new ExtensionError('ACTION_FAILED', message.error?.message || '扩展页面请求失败')
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'log':
|
||||
this.dependencies.onLog?.(message.level, message.message)
|
||||
return
|
||||
@@ -533,6 +773,31 @@ export class ExtensionHost {
|
||||
case 'storage.list':
|
||||
this.requirePermission('storage')
|
||||
return { entries: this.storage.list(extensionId) }
|
||||
case 'secrets.get': {
|
||||
this.requirePermission('secrets')
|
||||
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.secrets.get(extensionId, String(params.key ?? ''))
|
||||
}
|
||||
case 'secrets.set': {
|
||||
this.requirePermission('secrets')
|
||||
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
this.dependencies.secrets.set(
|
||||
extensionId,
|
||||
String(params.key ?? ''),
|
||||
String(params.value ?? '')
|
||||
)
|
||||
return { ok: true }
|
||||
}
|
||||
case 'secrets.delete': {
|
||||
this.requirePermission('secrets')
|
||||
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return { removed: this.dependencies.secrets.delete(extensionId, String(params.key ?? '')) }
|
||||
}
|
||||
case 'secrets.has': {
|
||||
this.requirePermission('secrets')
|
||||
if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.secrets.has(extensionId, String(params.key ?? ''))
|
||||
}
|
||||
case 'messages.query': {
|
||||
this.requirePermission('messages.query')
|
||||
if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
@@ -642,6 +907,49 @@ export class ExtensionHost {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束 `pid` 对应的进程树。
|
||||
*
|
||||
* 返回值表示实际使用的手段:
|
||||
* - `group`:POSIX 进程组,覆盖扩展派生的全部子进程;
|
||||
* - `taskkill`:Windows 进程树,必须在父进程仍存活时调用;
|
||||
* - `fallback`:只能结束进程本身,调用方应记录降级。
|
||||
*/
|
||||
export function killProcessTree(
|
||||
pid: number | undefined,
|
||||
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {}
|
||||
): 'group' | 'taskkill' | 'fallback' {
|
||||
if (!pid) return 'fallback'
|
||||
const platform = options.platform ?? process.platform
|
||||
const signal = options.signal ?? 'SIGKILL'
|
||||
|
||||
if (platform === 'win32') {
|
||||
try {
|
||||
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
|
||||
windowsHide: true,
|
||||
stdio: 'ignore'
|
||||
})
|
||||
killer.on('error', () => undefined)
|
||||
killer.unref?.()
|
||||
return 'taskkill'
|
||||
} catch {
|
||||
return 'fallback'
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(-pid, signal)
|
||||
return 'group'
|
||||
} catch {
|
||||
try {
|
||||
process.kill(pid, signal)
|
||||
} catch {
|
||||
// 进程已经退出。
|
||||
}
|
||||
return 'fallback'
|
||||
}
|
||||
}
|
||||
|
||||
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
|
||||
export function forkExtensionHost(
|
||||
scriptPath: string
|
||||
@@ -650,6 +958,9 @@ export function forkExtensionHost(
|
||||
const child: ChildProcess = fork(scriptPath, [], {
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
serialization: 'advanced',
|
||||
// POSIX 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。
|
||||
// Windows 用 taskkill /T,不需要(也不支持)detached。
|
||||
detached: process.platform !== 'win32',
|
||||
env: {
|
||||
...process.env,
|
||||
ELECTRON_RUN_AS_NODE: '1',
|
||||
@@ -671,6 +982,7 @@ export function forkExtensionHost(
|
||||
once: (event, listener) => {
|
||||
child.once(event, listener)
|
||||
},
|
||||
stderr: child.stderr,
|
||||
...(child.pid ? { pid: child.pid } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { promises as fs } from 'node:fs'
|
||||
import * as nodeFs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { Open } from 'unzipper'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
@@ -9,23 +10,61 @@ import {
|
||||
} from '../../shared/extensions/manifest'
|
||||
import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry'
|
||||
import { isPathInside, type ExtensionPaths } from './extension-paths'
|
||||
import type { ExtensionSource } from '../../shared/extensions/source'
|
||||
import { computeDirectoryDigest } from './extension-code-digest'
|
||||
|
||||
const MAX_FILES = 2_000
|
||||
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
|
||||
const MAX_FILE_BYTES = 20 * 1024 * 1024
|
||||
const MAX_PACKAGE_BYTES = 100 * 1024 * 1024
|
||||
|
||||
/** 从「文件夹安装」时跳过的目录名;与打包脚本的白名单保持同一套判断。 */
|
||||
const EXCLUDED_SOURCE_DIRECTORIES = new Set([
|
||||
'.git',
|
||||
'.hg',
|
||||
'.svn',
|
||||
'node_modules',
|
||||
'__pycache__',
|
||||
'.venv',
|
||||
'venv'
|
||||
])
|
||||
|
||||
export interface InstallOptions {
|
||||
/** 应用版本,用于 `minAppVersion` 兼容检查。 */
|
||||
appVersion: string
|
||||
source?: 'directory' | 'package'
|
||||
source?: ExtensionSource
|
||||
/** 模板安装时由可信入口填入;普通 ZIP/目录安装不得携带。 */
|
||||
template?: { id: string; version: string }
|
||||
/**
|
||||
* 代码被替换之前的最后一步:用于停止旧的 Host。
|
||||
*
|
||||
* 抛错表示「不能安全替换」,安装整体中止,磁盘保持原样。
|
||||
*/
|
||||
beforeReplace?: (
|
||||
manifest: ExtensionManifest,
|
||||
previous: ExtensionRegistryRecord | undefined
|
||||
) => Promise<void>
|
||||
}
|
||||
|
||||
export interface InstallOutcome {
|
||||
manifest: ExtensionManifest
|
||||
installPath: string
|
||||
previousVersion?: string
|
||||
/** 安装前的 Registry 记录;首次安装时为 undefined。 */
|
||||
previousRecord?: ExtensionRegistryRecord
|
||||
upgraded: boolean
|
||||
/**
|
||||
* 把磁盘与 Registry 一起恢复到本次安装之前。
|
||||
*
|
||||
* 只在新版本启动失败时调用;调用后 `cleanup` 失效。
|
||||
*/
|
||||
rollback: () => Promise<void>
|
||||
/**
|
||||
* 删除旧版本的过渡备份。
|
||||
*
|
||||
* 新版本确认可用后调用;调用后 `rollback` 失效。
|
||||
*/
|
||||
cleanup: () => Promise<void>
|
||||
}
|
||||
|
||||
export interface ExtensionInstallerDependencies {
|
||||
@@ -71,7 +110,7 @@ export class ExtensionInstaller {
|
||||
await fs.mkdir(staging, { recursive: true })
|
||||
try {
|
||||
await copyTree(root, staging, entries)
|
||||
return await this.finalize(staging, manifest, options.source ?? 'directory')
|
||||
return await this.finalize(staging, manifest, options.source ?? 'directory', options)
|
||||
} finally {
|
||||
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
@@ -174,7 +213,7 @@ export class ExtensionInstaller {
|
||||
)
|
||||
}
|
||||
}
|
||||
return await this.finalize(staging, manifest, 'package')
|
||||
return await this.finalize(staging, manifest, options.source ?? 'package', options)
|
||||
} finally {
|
||||
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
@@ -192,13 +231,20 @@ export class ExtensionInstaller {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
|
||||
}
|
||||
const trash = `${target}.removed-${this.now()}`
|
||||
// lstat 不跟随符号链接:目标断链时也要把链接本身清掉,否则会留下悬空目录项。
|
||||
const exists = await fs
|
||||
.stat(target)
|
||||
.lstat(target)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
if (exists) {
|
||||
await fs.rename(target, trash)
|
||||
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
|
||||
const trashStat = await fs.lstat(trash).catch(() => null)
|
||||
if (trashStat?.isSymbolicLink()) {
|
||||
// 只删链接本身;递归删除可能跟随链接进入用户自己的目录。
|
||||
await fs.unlink(trash).catch(() => undefined)
|
||||
} else {
|
||||
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
if (!options.keepData) {
|
||||
await fs
|
||||
@@ -255,6 +301,9 @@ export class ExtensionInstaller {
|
||||
const walk = async (directory: string, prefix: string): Promise<void> => {
|
||||
const items = await fs.readdir(directory, { withFileTypes: true })
|
||||
for (const item of items) {
|
||||
// 版本库与依赖目录不属于扩展产物:复制它们既超体积上限,
|
||||
// 也会把提交历史带进用户数据目录。
|
||||
if (item.isDirectory() && EXCLUDED_SOURCE_DIRECTORIES.has(item.name)) continue
|
||||
const relativePath = prefix ? `${prefix}/${item.name}` : item.name
|
||||
if (!isSafeRelativeEntryPath(relativePath)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`)
|
||||
@@ -292,11 +341,24 @@ export class ExtensionInstaller {
|
||||
return entries
|
||||
}
|
||||
|
||||
/** 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 */
|
||||
/**
|
||||
* 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。
|
||||
*
|
||||
* 事务边界(只覆盖「同一文件系统内的目录改名 + 一次 JSON 写入」):
|
||||
* - 改名前先停旧 Host:Windows 上被进程占用的目录无法改名,且旧进程
|
||||
* 继续运行会读到已被替换的代码。
|
||||
* - 旧目录保留为 `.backup-<ts>`,由调用方在新版本确认可用后清理;
|
||||
* 启动失败时用 `rollback()` 换回来。
|
||||
* - Registry 写入失败时当场回滚目录,不把「代码已换、状态未换」留给上层。
|
||||
*
|
||||
* 不保证跨进程的强原子性:如果进程在 rename 之后、Registry 写入之前被杀,
|
||||
* 磁盘上是新代码配旧记录;下次启动会以 manifest 为准做兼容性检查。
|
||||
*/
|
||||
private async finalize(
|
||||
staging: string,
|
||||
manifest: ExtensionManifest,
|
||||
source: 'directory' | 'package'
|
||||
source: ExtensionSource,
|
||||
options: InstallOptions
|
||||
): Promise<InstallOutcome> {
|
||||
const target = this.paths.installDir(manifest.id)
|
||||
if (!isPathInside(this.paths.extensionsDir, target)) {
|
||||
@@ -311,6 +373,9 @@ export class ExtensionInstaller {
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
|
||||
// 旧 Host 必须在代码被替换之前停下;这一步失败则不触碰磁盘。
|
||||
await options.beforeReplace?.(manifest, existingRecord)
|
||||
|
||||
if (targetExists) await fs.rename(target, backup)
|
||||
try {
|
||||
await fs.rename(staging, target)
|
||||
@@ -321,7 +386,6 @@ export class ExtensionInstaller {
|
||||
error instanceof Error ? error.message : '安装目录替换失败'
|
||||
)
|
||||
}
|
||||
if (targetExists) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
|
||||
|
||||
const timestamp = this.now()
|
||||
const record: ExtensionRegistryRecord = {
|
||||
@@ -330,20 +394,162 @@ export class ExtensionInstaller {
|
||||
apiVersion: manifest.apiVersion,
|
||||
// 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。
|
||||
enabled: existingRecord?.enabled ?? false,
|
||||
grantedPermissions: existingRecord?.grantedPermissions ?? [],
|
||||
// 只保留新 manifest 仍声明的授权:被删掉的权限必须立刻失效。
|
||||
grantedPermissions: (existingRecord?.grantedPermissions ?? []).filter((permission) =>
|
||||
manifest.permissions.includes(permission)
|
||||
),
|
||||
installedAt: existingRecord?.installedAt ?? timestamp,
|
||||
updatedAt: timestamp,
|
||||
source
|
||||
source,
|
||||
// 安装完成后立刻记录基线:之后判断「用户改没改」全靠它。
|
||||
installedCodeDigest: computeDirectoryDigest(target),
|
||||
...(options.template
|
||||
? { templateId: options.template.id, templateVersion: options.template.version }
|
||||
: existingRecord?.templateId
|
||||
? {
|
||||
templateId: existingRecord.templateId,
|
||||
...(existingRecord.templateVersion
|
||||
? { templateVersion: existingRecord.templateVersion }
|
||||
: {})
|
||||
}
|
||||
: {})
|
||||
}
|
||||
this.registry.upsert(record)
|
||||
|
||||
try {
|
||||
this.registry.upsert(record)
|
||||
} catch (error) {
|
||||
// 代码已经换进去了,但状态没写成:必须把磁盘也退回去,否则用户会看到
|
||||
// 「旧版本号 + 新代码」。新目录直接删除,内容仍在安装源里。
|
||||
await fs.rm(target, { recursive: true, force: true }).catch(() => undefined)
|
||||
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
|
||||
if (existingRecord) {
|
||||
await Promise.resolve(this.registry.upsert(existingRecord)).catch(() => undefined)
|
||||
}
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_INSTALL_FAILED',
|
||||
error instanceof Error
|
||||
? `扩展状态写入失败,已回滚:${error.message}`
|
||||
: '扩展状态写入失败,已回滚'
|
||||
)
|
||||
}
|
||||
|
||||
let settled = false
|
||||
return {
|
||||
manifest,
|
||||
installPath: target,
|
||||
previousRecord: existingRecord,
|
||||
...(existingRecord ? { previousVersion: existingRecord.version } : {}),
|
||||
upgraded: Boolean(existingRecord)
|
||||
upgraded: Boolean(existingRecord),
|
||||
rollback: async () => {
|
||||
if (settled) {
|
||||
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '该安装结果已完成清理,无法回滚')
|
||||
}
|
||||
settled = true
|
||||
await fs.rm(target, { recursive: true, force: true }).catch(() => undefined)
|
||||
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
|
||||
if (existingRecord) this.registry.upsert(existingRecord)
|
||||
else this.registry.remove(manifest.id)
|
||||
},
|
||||
cleanup: async () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (targetExists) {
|
||||
await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把最近一次升级留下的过渡备份换回原位。
|
||||
*
|
||||
* 只在「新代码启动失败或状态不一致」时由用户显式触发;备份目录本身不删除,
|
||||
* 换回来的旧目录会被移到 `.failed-<ts>` 后清理,留下的是可运行的旧版本。
|
||||
*/
|
||||
async restoreLatestBackup(
|
||||
extensionId: string
|
||||
): Promise<{ restored: boolean; manifest?: ExtensionManifest }> {
|
||||
const target = this.paths.installDir(extensionId)
|
||||
if (!isPathInside(this.paths.extensionsDir, target)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
|
||||
}
|
||||
let backups: string[] = []
|
||||
try {
|
||||
backups = (await fs.readdir(this.paths.extensionsDir))
|
||||
.filter((name) => name.startsWith(`${extensionId}.backup-`))
|
||||
.sort()
|
||||
} catch {
|
||||
return { restored: false }
|
||||
}
|
||||
if (!backups.length) return { restored: false }
|
||||
|
||||
const latest = path.join(this.paths.extensionsDir, backups[backups.length - 1])
|
||||
// 空 appVersion = 跳过兼容性拦截:用户要的是「回到能跑的那个版本」。
|
||||
const manifest = await this.readManifest(latest, '')
|
||||
const failed = `${target}.failed-${this.now()}`
|
||||
const targetExists = await fs
|
||||
.lstat(target)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
if (targetExists) await fs.rename(target, failed)
|
||||
try {
|
||||
await fs.rename(latest, target)
|
||||
} catch (error) {
|
||||
if (targetExists) await fs.rename(failed, target).catch(() => undefined)
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_INSTALL_FAILED',
|
||||
error instanceof Error ? error.message : '恢复备份失败'
|
||||
)
|
||||
}
|
||||
if (targetExists) {
|
||||
await fs.rm(failed, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
return { restored: true, manifest }
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描已安装目录,重建最小 Registry 记录。
|
||||
*
|
||||
* 只读取 manifest 的**身份字段**,不继承启用状态与授权:磁盘上有代码,
|
||||
* 不等于用户同意运行它。manifest 无法解析的目录被跳过。
|
||||
*
|
||||
* 同步实现:Registry 的加载是同步的,恢复入口不能引入异步间隙。
|
||||
*/
|
||||
recoverFromDisk(): ExtensionRegistryRecord[] {
|
||||
const records: ExtensionRegistryRecord[] = []
|
||||
let entries: nodeFs.Dirent[] = []
|
||||
try {
|
||||
entries = nodeFs.readdirSync(this.paths.extensionsDir, { withFileTypes: true })
|
||||
} catch {
|
||||
return records
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue
|
||||
if (entry.name.includes('.backup-') || entry.name.includes('.removed')) continue
|
||||
const root = path.join(this.paths.extensionsDir, entry.name)
|
||||
try {
|
||||
const raw = JSON.parse(
|
||||
nodeFs.readFileSync(path.join(root, 'manifest.json'), 'utf8')
|
||||
) as unknown
|
||||
const parsed = parseExtensionManifest(raw)
|
||||
if (!parsed.ok || !parsed.manifest) continue
|
||||
const stat = nodeFs.statSync(root)
|
||||
records.push({
|
||||
id: parsed.manifest.id,
|
||||
version: parsed.manifest.version,
|
||||
apiVersion: parsed.manifest.apiVersion,
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
installedAt: Math.round(stat.birthtimeMs || stat.mtimeMs || 0),
|
||||
updatedAt: Math.round(stat.mtimeMs || 0),
|
||||
source: 'directory'
|
||||
})
|
||||
} catch {
|
||||
// 单个目录损坏不影响其余扩展的恢复。
|
||||
}
|
||||
}
|
||||
return records
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeZipPath(value: string): string {
|
||||
|
||||
@@ -3,7 +3,9 @@ import path from 'node:path'
|
||||
import { BrowserWindow, dialog, ipcMain, shell } from 'electron'
|
||||
import { EXTENSION_IPC } from '../../shared/extensions/ipc'
|
||||
import type {
|
||||
ExtensionActionInfo,
|
||||
ExtensionInstallResult,
|
||||
ExtensionProjectResult,
|
||||
ExtensionLogEntry,
|
||||
ExtensionOperationResult,
|
||||
ExtensionPageDescriptor,
|
||||
@@ -120,6 +122,193 @@ export function registerExtensionIpc(options: ExtensionIpcOptions): void {
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.health,
|
||||
guard(() => manager().getHealth())
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.grantPermissions,
|
||||
guard((payload: unknown): Promise<ExtensionOperationResult> => {
|
||||
const input = (payload ?? {}) as { id?: unknown; permissions?: unknown }
|
||||
const permissions = Array.isArray(input.permissions)
|
||||
? input.permissions.filter((item): item is string => typeof item === 'string')
|
||||
: []
|
||||
return manager().grantPermissions(
|
||||
requireId(input.id),
|
||||
permissions as Parameters<ExtensionManager['grantPermissions']>[1]
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.revokePermission,
|
||||
guard((payload: unknown): Promise<ExtensionOperationResult> => {
|
||||
const input = (payload ?? {}) as { id?: unknown; permission?: unknown }
|
||||
const permission = String(input.permission || '').trim()
|
||||
if (!permission) throw new Error('权限名不合法')
|
||||
return manager().revokePermission(
|
||||
requireId(input.id),
|
||||
permission as Parameters<ExtensionManager['revokePermission']>[1]
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.resetStorage,
|
||||
guard(
|
||||
(extensionId: unknown): ExtensionOperationResult =>
|
||||
manager().resetStorage(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.templates,
|
||||
guard(() => manager().listTemplates())
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.installTemplate,
|
||||
guard(
|
||||
(templateId: unknown): Promise<ExtensionInstallResult> =>
|
||||
manager().installTemplate(requireTemplateId(templateId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.acknowledgeRecovery,
|
||||
guard((): ExtensionOperationResult => manager().acknowledgeRegistryRecovery())
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.acknowledgeStorage,
|
||||
guard(
|
||||
(extensionId: unknown): ExtensionOperationResult =>
|
||||
manager().acknowledgeStorageRecovery(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.adoptInstalledCode,
|
||||
guard(
|
||||
(extensionId: unknown): ExtensionOperationResult =>
|
||||
manager().adoptInstalledCode(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.pickProjectDirectory,
|
||||
guard(async (): Promise<string | null> => {
|
||||
const window = BrowserWindow.getFocusedWindow()
|
||||
const options: Electron.OpenDialogOptions = {
|
||||
properties: ['openDirectory', 'createDirectory'],
|
||||
title: '选择扩展项目目录'
|
||||
}
|
||||
const result = window
|
||||
? await dialog.showOpenDialog(window, options)
|
||||
: await dialog.showOpenDialog(options)
|
||||
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.linkDevelopment,
|
||||
guard(
|
||||
(directory: unknown): Promise<ExtensionInstallResult> =>
|
||||
manager().linkDevelopmentProject(requirePath(directory))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.reloadDevelopment,
|
||||
guard(
|
||||
(extensionId: unknown): Promise<ExtensionOperationResult> =>
|
||||
manager().reloadDevelopment(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.unlinkDevelopment,
|
||||
guard((payload: unknown): Promise<ExtensionOperationResult> => {
|
||||
const input = (payload ?? {}) as { id?: unknown; keepData?: unknown }
|
||||
return manager().unlinkDevelopment(requireId(input.id), {
|
||||
keepData: input.keepData !== false
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.convertDevelopment,
|
||||
guard(
|
||||
(extensionId: unknown): Promise<ExtensionOperationResult> =>
|
||||
manager().convertDevelopmentToInstalled(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.createProjectFromTemplate,
|
||||
guard((payload: unknown): Promise<ExtensionProjectResult> => {
|
||||
const input = (payload ?? {}) as {
|
||||
templateId?: unknown
|
||||
targetDirectory?: unknown
|
||||
extensionId?: unknown
|
||||
name?: unknown
|
||||
}
|
||||
return manager().createProjectFromTemplate(
|
||||
requireTemplateId(input.templateId),
|
||||
requirePath(input.targetDirectory),
|
||||
{
|
||||
extensionId: requireId(input.extensionId),
|
||||
...(typeof input.name === 'string' && input.name.trim()
|
||||
? { name: input.name.trim().slice(0, 60) }
|
||||
: {})
|
||||
}
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.exportInstalledAsProject,
|
||||
guard((payload: unknown): Promise<ExtensionProjectResult> => {
|
||||
const input = (payload ?? {}) as { id?: unknown; targetDirectory?: unknown }
|
||||
return manager().exportInstalledAsProject(
|
||||
requireId(input.id),
|
||||
requirePath(input.targetDirectory)
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.actions,
|
||||
guard((): ExtensionActionInfo[] => manager().listActions())
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.openDevelopmentSource,
|
||||
guard(async (extensionId: unknown): Promise<ExtensionOperationResult> => {
|
||||
const extension = manager().get(requireId(extensionId))
|
||||
if (!extension?.development?.available) {
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'EXTENSION_SOURCE_MISSING', message: '源码目录不可用' }
|
||||
}
|
||||
}
|
||||
// 路径来自主进程的 registry,渲染层只能传 id,无法指定任意目录。
|
||||
const error = await shell.openPath(extension.development.sourcePath)
|
||||
return error
|
||||
? { success: false, error: { code: 'ACTION_FAILED', message: error } }
|
||||
: { success: true }
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.rollbackUpgrade,
|
||||
guard(
|
||||
(extensionId: unknown): Promise<ExtensionOperationResult> =>
|
||||
manager().rollbackInterruptedUpgrade(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.uninstall,
|
||||
guard((payload: unknown): Promise<ExtensionOperationResult> => {
|
||||
@@ -187,6 +376,13 @@ function requireId(value: unknown): string {
|
||||
return id
|
||||
}
|
||||
|
||||
/** 模板 id 只允许稳定的短标识,不允许携带路径片段。 */
|
||||
function requireTemplateId(value: unknown): string {
|
||||
const id = String(value || '').trim()
|
||||
if (!/^[a-z0-9][a-z0-9-]{1,63}$/.test(id)) throw new Error('模板 id 不合法')
|
||||
return id
|
||||
}
|
||||
|
||||
function requirePath(value: unknown): string {
|
||||
const target = String(value || '').trim()
|
||||
if (!target || target.length > 4_096) throw new Error('路径不合法')
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -58,8 +58,26 @@ export function getExtensionPaths(): ExtensionPaths {
|
||||
return cached
|
||||
}
|
||||
|
||||
/** 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 */
|
||||
/**
|
||||
* 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。
|
||||
*
|
||||
* Windows 上盘符大小写、分隔符与短文件名都可能让字符串比较失手,
|
||||
* 这里统一把两侧规范化后再比:`path.resolve` 处理分隔符,Windows 额外折叠大小写。
|
||||
*/
|
||||
export function isPathInside(parent: string, child: string): boolean {
|
||||
const relative = path.relative(path.resolve(parent), path.resolve(child))
|
||||
const normalize = (value: string): string => {
|
||||
const resolved = path.resolve(value)
|
||||
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
|
||||
}
|
||||
const relative = path.relative(normalize(parent), normalize(child))
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
/** 只比路径本身,不跟随符号链接;用于判断两个字符串是否指向同一位置。 */
|
||||
export function isSamePath(left: string, right: string): boolean {
|
||||
const normalize = (value: string): string => {
|
||||
const resolved = path.resolve(value)
|
||||
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
|
||||
}
|
||||
return normalize(left) === normalize(right)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { promises as fs, existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { Open } from 'unzipper'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
|
||||
import { isPathInside } from './extension-paths'
|
||||
|
||||
const MAX_FILES = 2_000
|
||||
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
|
||||
|
||||
/** 与安装器 / 指纹一致的排除规则:这些不属于扩展源码。 */
|
||||
const EXCLUDED_DIRECTORIES = new Set([
|
||||
'.git',
|
||||
'.hg',
|
||||
'.svn',
|
||||
'node_modules',
|
||||
'__pycache__',
|
||||
'.venv',
|
||||
'venv'
|
||||
])
|
||||
const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db'])
|
||||
const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log'])
|
||||
|
||||
/** 会被替换扩展 id 的文本文件类型。 */
|
||||
const TEXT_FILE_PATTERN = /\.(js|mjs|cjs|ts|tsx|jsx|html|htm|css|json)$/i
|
||||
|
||||
export interface CreateProjectInput {
|
||||
zipPath: string
|
||||
targetDir: string
|
||||
/** 新扩展 id(必须与模板里的旧 id 不同)。 */
|
||||
extensionId: string
|
||||
/** 模板里的旧 id;用于替换代码中的身份引用。 */
|
||||
templateExtensionId: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
export interface CreateProjectOutcome {
|
||||
projectPath: string
|
||||
rewrittenFiles: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标目录必须是「不存在」或「空目录」。
|
||||
*
|
||||
* 这条检查在复制之前做,避免中途发现冲突时已经写了一半。
|
||||
*/
|
||||
export async function assertUsableTarget(targetDir: string): Promise<string> {
|
||||
const resolved = path.resolve(targetDir)
|
||||
try {
|
||||
const stat = await fs.stat(resolved)
|
||||
if (!stat.isDirectory()) {
|
||||
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标路径已存在且不是目录')
|
||||
}
|
||||
const entries = await fs.readdir(resolved)
|
||||
if (entries.length > 0) {
|
||||
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不是空目录,未写入任何文件')
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ExtensionError) throw error
|
||||
const code = (error as { code?: string }).code
|
||||
if (code !== 'ENOENT') {
|
||||
throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不可用')
|
||||
}
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
/** 在目标旁边建暂存目录:同一磁盘才能用 rename 原子落位。 */
|
||||
async function createStaging(parent: string): Promise<string> {
|
||||
await fs.mkdir(parent, { recursive: true })
|
||||
return fs.mkdtemp(path.join(parent, '.tm-project-'))
|
||||
}
|
||||
|
||||
async function cleanup(directory: string): Promise<void> {
|
||||
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
|
||||
function shouldSkipFile(name: string): boolean {
|
||||
return EXCLUDED_FILES.has(name) || EXCLUDED_EXTENSIONS.has(path.extname(name).toLowerCase())
|
||||
}
|
||||
|
||||
/** 解压到暂存目录;条目路径逐条校验,拒绝穿越与非法字符。 */
|
||||
async function extractZip(zipPath: string, staging: string): Promise<void> {
|
||||
let archive: Awaited<ReturnType<typeof Open.file>>
|
||||
try {
|
||||
archive = await Open.file(zipPath)
|
||||
} catch {
|
||||
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包无法读取')
|
||||
}
|
||||
|
||||
let files = 0
|
||||
let total = 0
|
||||
for (const entry of archive.files) {
|
||||
const relative = String(entry.path || '').replace(/\\/g, '/')
|
||||
if (entry.type === 'Directory') continue
|
||||
if (!isSafeRelativeEntryPath(relative)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目路径不合法:${relative}`)
|
||||
}
|
||||
const size = Number(entry.uncompressedSize || 0)
|
||||
total += size
|
||||
if (total > MAX_TOTAL_BYTES) {
|
||||
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板解压后体积超过限制')
|
||||
}
|
||||
files += 1
|
||||
if (files > MAX_FILES) {
|
||||
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板文件数量超过限制')
|
||||
}
|
||||
|
||||
const destination = path.resolve(staging, relative)
|
||||
if (!isPathInside(staging, destination)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目越界:${relative}`)
|
||||
}
|
||||
await fs.mkdir(path.dirname(destination), { recursive: true })
|
||||
const content = await entry.buffer()
|
||||
await fs.writeFile(destination, content)
|
||||
}
|
||||
if (!files) throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包是空的')
|
||||
}
|
||||
|
||||
async function listTextFiles(root: string, prefix = ''): Promise<string[]> {
|
||||
const result: string[] = []
|
||||
const items = await fs.readdir(path.join(root, prefix), { withFileTypes: true })
|
||||
for (const item of items) {
|
||||
if (item.isDirectory()) {
|
||||
if (EXCLUDED_DIRECTORIES.has(item.name)) continue
|
||||
const nested = prefix ? `${prefix}/${item.name}` : item.name
|
||||
result.push(...(await listTextFiles(root, nested)))
|
||||
continue
|
||||
}
|
||||
if (shouldSkipFile(item.name)) continue
|
||||
const relative = prefix ? `${prefix}/${item.name}` : item.name
|
||||
if (!TEXT_FILE_PATTERN.test(relative)) continue
|
||||
result.push(relative)
|
||||
}
|
||||
return result.sort()
|
||||
}
|
||||
|
||||
/**
|
||||
* 把代码里的扩展身份改成新 id。
|
||||
*
|
||||
* 只替换精确字符串:模板示例里 id 至少出现在 manifest 与页面桥的
|
||||
* `EXTENSION_ID` 常量中,漏掉任何一处都会让页面桥失联。
|
||||
*/
|
||||
export async function rewriteExtensionIdentity(
|
||||
root: string,
|
||||
oldId: string,
|
||||
newId: string,
|
||||
name?: string
|
||||
): Promise<string[]> {
|
||||
const rewritten: string[] = []
|
||||
const manifestPath = path.join(root, 'manifest.json')
|
||||
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')) as Record<string, unknown>
|
||||
if (String(manifest.id) !== oldId) {
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_INVALID_MANIFEST',
|
||||
`模板 manifest.id 与索引不一致(${String(manifest.id)})`
|
||||
)
|
||||
}
|
||||
manifest.id = newId
|
||||
if (name) manifest.name = name
|
||||
await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
|
||||
|
||||
for (const relative of await listTextFiles(root)) {
|
||||
if (relative === 'manifest.json') continue
|
||||
const full = path.join(root, relative)
|
||||
const text = await fs.readFile(full, 'utf8')
|
||||
if (!text.includes(oldId)) continue
|
||||
await fs.writeFile(full, text.split(oldId).join(newId), 'utf8')
|
||||
rewritten.push(relative)
|
||||
}
|
||||
return rewritten
|
||||
}
|
||||
|
||||
/** 生成后自检:任何残留的旧 id 都意味着页面桥或后台仍指向模板身份。 */
|
||||
export async function assertNoIdentityLeftover(root: string, oldId: string): Promise<void> {
|
||||
for (const relative of await listTextFiles(root)) {
|
||||
const text = await fs.readFile(path.join(root, relative), 'utf8')
|
||||
if (text.includes(oldId)) {
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_INVALID_MANIFEST',
|
||||
`生成的项目里仍残留旧扩展 id:${relative}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 从模板 ZIP 生成独立项目;全过程在暂存目录完成,成功后才落位。 */
|
||||
export async function createProjectFromTemplate(
|
||||
input: CreateProjectInput
|
||||
): Promise<CreateProjectOutcome> {
|
||||
const target = await assertUsableTarget(input.targetDir)
|
||||
if (input.extensionId === input.templateExtensionId) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '新项目必须使用不同的扩展 id')
|
||||
}
|
||||
|
||||
const staging = await createStaging(path.dirname(target))
|
||||
try {
|
||||
await extractZip(input.zipPath, staging)
|
||||
const rewritten = await rewriteExtensionIdentity(
|
||||
staging,
|
||||
input.templateExtensionId,
|
||||
input.extensionId,
|
||||
input.name
|
||||
)
|
||||
await assertNoIdentityLeftover(staging, input.templateExtensionId)
|
||||
await fs.rename(staging, target)
|
||||
return { projectPath: target, rewrittenFiles: rewritten }
|
||||
} catch (error) {
|
||||
await cleanup(staging)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** 把已安装副本整体复制成外部项目(保留用户改过的代码)。 */
|
||||
export async function exportInstalledCopy(
|
||||
sourceDir: string,
|
||||
targetDir: string
|
||||
): Promise<{ projectPath: string }> {
|
||||
if (!existsSync(path.join(sourceDir, 'manifest.json'))) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '安装副本不完整,无法导出')
|
||||
}
|
||||
const target = await assertUsableTarget(targetDir)
|
||||
const staging = await createStaging(path.dirname(target))
|
||||
try {
|
||||
await fs.cp(sourceDir, staging, {
|
||||
recursive: true,
|
||||
filter: (source) => {
|
||||
const name = path.basename(source)
|
||||
if (EXCLUDED_DIRECTORIES.has(name)) return false
|
||||
if (shouldSkipFile(name)) return false
|
||||
return true
|
||||
}
|
||||
})
|
||||
// 复制结果必须仍然可读,否则宁可失败也不留一个半成品项目。
|
||||
await fs.access(path.join(staging, 'manifest.json'))
|
||||
await fs.rename(staging, target)
|
||||
return { projectPath: target }
|
||||
} catch (error) {
|
||||
await cleanup(staging)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
normalizeExtensionPermissions,
|
||||
type ExtensionPermission
|
||||
} from '../../shared/extensions/permissions'
|
||||
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
|
||||
import { EXTENSION_API_VERSION, isValidExtensionId } from '../../shared/extensions/manifest'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import { normalizeExtensionSource, type ExtensionSource } from '../../shared/extensions/source'
|
||||
|
||||
/**
|
||||
* 宿主侧的扩展安装状态。
|
||||
@@ -20,49 +22,204 @@ export interface ExtensionRegistryRecord {
|
||||
grantedPermissions: ExtensionPermission[]
|
||||
installedAt: number
|
||||
updatedAt: number
|
||||
source: 'directory' | 'package'
|
||||
source: ExtensionSource
|
||||
/** 来源为 `template` 时,记录是哪个官方模板装入的。 */
|
||||
templateId?: string
|
||||
templateVersion?: string
|
||||
/**
|
||||
* 来源为 `development` 时的外部源码目录(本机绝对路径)。
|
||||
*
|
||||
* 只属于这台机器的安装状态,不随扩展源码分发;换机器要重新链接。
|
||||
*/
|
||||
developmentSourcePath?: string
|
||||
/**
|
||||
* 安装时的代码指纹;用于判断用户是否改过 `extensions/<id>` 里的副本。
|
||||
* 缺失表示无法判断(旧版本安装或指纹计算失败),更新时必须保守处理。
|
||||
*/
|
||||
installedCodeDigest?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次恢复的记录。
|
||||
*
|
||||
* 写进状态文件而不是只放在内存里:用户看到「状态曾损坏」之后重启,
|
||||
* 提示必须还在,否则他永远不知道自己的启用状态被重置过。
|
||||
*/
|
||||
export interface ExtensionRegistryRecovery {
|
||||
at: number
|
||||
kind: 'backup' | 'scan'
|
||||
/** 损坏现场的**文件名**(不含目录)。 */
|
||||
corruptFile?: string
|
||||
}
|
||||
|
||||
interface RegistryFile {
|
||||
version: number
|
||||
extensions: ExtensionRegistryRecord[]
|
||||
recovery?: ExtensionRegistryRecovery
|
||||
}
|
||||
|
||||
const REGISTRY_VERSION = 1
|
||||
/** 损坏现场最多保留的份数;超出时删除最旧的一份。 */
|
||||
const CORRUPT_KEEP_LIMIT = 3
|
||||
|
||||
function normalizeRecord(value: unknown): ExtensionRegistryRecord | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const raw = value as Partial<ExtensionRegistryRecord>
|
||||
const id = String(raw.id || '').trim()
|
||||
if (!id) return null
|
||||
const installedAt = Number(raw.installedAt) || 0
|
||||
return {
|
||||
id,
|
||||
version: String(raw.version || '0.0.0'),
|
||||
apiVersion: String(raw.apiVersion || EXTENSION_API_VERSION),
|
||||
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
|
||||
enabled: raw.enabled === true,
|
||||
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
|
||||
installedAt,
|
||||
updatedAt: Number(raw.updatedAt) || installedAt,
|
||||
source: raw.source === 'package' ? 'package' : 'directory'
|
||||
}
|
||||
/**
|
||||
* 状态文件的可信度。
|
||||
*
|
||||
* - `ok`:主文件有效,或文件不存在(全新安装,属于合法空状态)。
|
||||
* - `recovered-from-backup`:主文件损坏,用 `.bak` 重建过;记录已降级。
|
||||
* - `recovered-by-scan`:主文件与备份都不可用,由调用方扫描扩展目录重建;
|
||||
* 记录一律降级为「未启用 + 无授权」。
|
||||
* - `unreadable`:无法读取且无法重建。此状态下**拒绝任何写入**,
|
||||
* 否则会用空状态覆盖唯一可能人工抢救的现场。
|
||||
*/
|
||||
export type ExtensionRegistryHealthState =
|
||||
| 'ok'
|
||||
| 'recovered-from-backup'
|
||||
| 'recovered-by-scan'
|
||||
| 'unreadable'
|
||||
|
||||
export interface ExtensionRegistryHealth {
|
||||
state: ExtensionRegistryHealthState
|
||||
at: number
|
||||
/** 损坏现场的**文件名**(不含目录);用于日志与排查,不渲染绝对路径。 */
|
||||
corruptFile?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ExtensionRegistryDependencies {
|
||||
registryFile: string
|
||||
now?: () => number
|
||||
/**
|
||||
* 主文件与备份均不可用时的重建来源。
|
||||
*
|
||||
* 返回的记录会被强制改写为 `enabled: false`、`grantedPermissions: []`:
|
||||
* 扫描到磁盘上有代码,不等于用户同意运行它。
|
||||
*/
|
||||
recover?: () => ExtensionRegistryRecord[]
|
||||
}
|
||||
|
||||
type ParseResult =
|
||||
| { ok: true; extensions: ExtensionRegistryRecord[]; recovery?: ExtensionRegistryRecovery }
|
||||
| { ok: false; reason: string }
|
||||
|
||||
function parseRegistryText(text: string): ParseResult {
|
||||
if (!text.trim()) return { ok: false, reason: '状态文件为空' }
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(text)
|
||||
} catch {
|
||||
return { ok: false, reason: '状态文件不是合法 JSON' }
|
||||
}
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return { ok: false, reason: '状态文件顶层不是对象' }
|
||||
}
|
||||
const version = Number((raw as { version?: unknown }).version)
|
||||
if (!Number.isInteger(version) || version < 1 || version > REGISTRY_VERSION) {
|
||||
return { ok: false, reason: '状态文件版本不受支持' }
|
||||
}
|
||||
const list = (raw as { extensions?: unknown }).extensions
|
||||
if (!Array.isArray(list)) return { ok: false, reason: 'extensions 不是数组' }
|
||||
|
||||
const extensions: ExtensionRegistryRecord[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const [index, item] of list.entries()) {
|
||||
const parsed = parseRecord(item)
|
||||
if (!parsed) return { ok: false, reason: `第 ${index + 1} 条扩展记录不合法` }
|
||||
if (seen.has(parsed.id)) return { ok: false, reason: `扩展 id 重复:${parsed.id}` }
|
||||
seen.add(parsed.id)
|
||||
extensions.push(parsed)
|
||||
}
|
||||
return { ok: true, extensions, recovery: parseRecovery((raw as { recovery?: unknown }).recovery) }
|
||||
}
|
||||
|
||||
function parseRecovery(value: unknown): ExtensionRegistryRecovery | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
|
||||
const raw = value as Record<string, unknown>
|
||||
const at = Number(raw.at)
|
||||
if (!Number.isFinite(at) || at <= 0) return undefined
|
||||
const kind = raw.kind === 'backup' ? 'backup' : raw.kind === 'scan' ? 'scan' : null
|
||||
if (!kind) return undefined
|
||||
const corruptFile =
|
||||
typeof raw.corruptFile === 'string' && raw.corruptFile.trim()
|
||||
? raw.corruptFile.trim().slice(0, 200)
|
||||
: undefined
|
||||
return { at, kind, ...(corruptFile ? { corruptFile } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条记录的严格解析。
|
||||
*
|
||||
* 与「尽量兼容」相反:字段类型明显不对时整份文件判为损坏,由上层进入恢复流程。
|
||||
* 静默丢弃单条记录等于「部分数据丢失且不告知用户」。
|
||||
*/
|
||||
function parseRecord(value: unknown): ExtensionRegistryRecord | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
||||
const raw = value as Record<string, unknown>
|
||||
const id = String(raw.id ?? '').trim()
|
||||
if (!isValidExtensionId(id)) return null
|
||||
if (typeof raw.version !== 'string' || !raw.version.trim()) return null
|
||||
|
||||
const installedAt = Number(raw.installedAt)
|
||||
const updatedAt = Number(raw.updatedAt)
|
||||
const templateId =
|
||||
typeof raw.templateId === 'string' && raw.templateId.trim()
|
||||
? raw.templateId.trim().slice(0, 64)
|
||||
: undefined
|
||||
const templateVersion =
|
||||
typeof raw.templateVersion === 'string' && raw.templateVersion.trim()
|
||||
? raw.templateVersion.trim().slice(0, 32)
|
||||
: undefined
|
||||
const developmentSourcePath =
|
||||
typeof raw.developmentSourcePath === 'string' && raw.developmentSourcePath.trim()
|
||||
? raw.developmentSourcePath.trim().slice(0, 1024)
|
||||
: undefined
|
||||
const installedCodeDigest =
|
||||
typeof raw.installedCodeDigest === 'string' && /^[a-f0-9]{64}$/.test(raw.installedCodeDigest)
|
||||
? raw.installedCodeDigest
|
||||
: undefined
|
||||
return {
|
||||
id,
|
||||
version: raw.version.trim().slice(0, 32),
|
||||
apiVersion:
|
||||
typeof raw.apiVersion === 'string' && raw.apiVersion.trim()
|
||||
? raw.apiVersion.trim().slice(0, 16)
|
||||
: EXTENSION_API_VERSION,
|
||||
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
|
||||
enabled: raw.enabled === true,
|
||||
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
|
||||
installedAt: Number.isFinite(installedAt) && installedAt > 0 ? installedAt : 0,
|
||||
updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : 0,
|
||||
// 未知来源归为 `directory`:来源只能由可信的安装入口赋予,不能从文件里猜。
|
||||
source: normalizeExtensionSource(raw.source),
|
||||
...(templateId ? { templateId } : {}),
|
||||
...(templateVersion ? { templateVersion } : {}),
|
||||
...(developmentSourcePath ? { developmentSourcePath } : {}),
|
||||
...(installedCodeDigest ? { installedCodeDigest } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export class ExtensionRegistry {
|
||||
private readonly registryFile: string
|
||||
private readonly backupFile: string
|
||||
private readonly now: () => number
|
||||
private readonly recoverByScan: (() => ExtensionRegistryRecord[]) | null
|
||||
private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] }
|
||||
private loaded = false
|
||||
/**
|
||||
* 主文件当前是否含可解析内容。
|
||||
*
|
||||
* 备份轮换只在这个标记为真时执行:主文件已经损坏时复制它,会把唯一的
|
||||
* 有效备份也换成坏数据。
|
||||
*/
|
||||
private primaryValid = false
|
||||
/** 只有 `unreadable` 需要内存态:连状态文件都写不进去,自然无法持久化。 */
|
||||
private unreadable: ExtensionRegistryHealth | null = null
|
||||
|
||||
constructor(dependencies: ExtensionRegistryDependencies) {
|
||||
this.registryFile = dependencies.registryFile
|
||||
this.backupFile = `${dependencies.registryFile}.bak`
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
this.recoverByScan = dependencies.recover ?? null
|
||||
}
|
||||
|
||||
list(): ExtensionRegistryRecord[] {
|
||||
@@ -79,6 +236,43 @@ export class ExtensionRegistry {
|
||||
return this.list().find((record) => record.id === key)
|
||||
}
|
||||
|
||||
/** 状态文件的可信度;非 `ok` 时调用方必须向用户暴露,而不是当作「没装扩展」。 */
|
||||
getHealth(): ExtensionRegistryHealth {
|
||||
this.ensureLoaded()
|
||||
if (this.unreadable) return { ...this.unreadable }
|
||||
const recovery = this.state.recovery
|
||||
if (!recovery) return { state: 'ok', at: this.now() }
|
||||
return {
|
||||
state: recovery.kind === 'backup' ? 'recovered-from-backup' : 'recovered-by-scan',
|
||||
at: recovery.at,
|
||||
...(recovery.corruptFile ? { corruptFile: recovery.corruptFile } : {}),
|
||||
message:
|
||||
recovery.kind === 'backup'
|
||||
? '扩展状态文件损坏,已从备份重建;所有扩展已暂停,请重新确认后启用'
|
||||
: '扩展状态文件与备份均不可用,已按磁盘目录重建;所有扩展已暂停,请重新确认后启用'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户确认「我知道发生过恢复」。
|
||||
*
|
||||
* 只清除提示标记,不改动任何扩展的启用状态与授权——那些已经由恢复流程
|
||||
* 降级为「未启用 + 无授权」,需要用户逐个重新授权。
|
||||
*/
|
||||
acknowledgeRecovery(): boolean {
|
||||
this.ensureLoaded()
|
||||
if (!this.state.recovery) return false
|
||||
const previous = this.state
|
||||
this.state = { version: REGISTRY_VERSION, extensions: this.state.extensions }
|
||||
try {
|
||||
this.persist()
|
||||
} catch (error) {
|
||||
this.state = previous
|
||||
throw error
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord {
|
||||
this.ensureLoaded()
|
||||
const exists = this.state.extensions.some((item) => item.id === record.id)
|
||||
@@ -119,37 +313,242 @@ export class ExtensionRegistry {
|
||||
private ensureLoaded(): void {
|
||||
if (this.loaded) return
|
||||
this.loaded = true
|
||||
this.load()
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
const stamp = this.now()
|
||||
|
||||
if (!fs.existsSync(this.registryFile)) {
|
||||
// 文件不存在是合法状态(首次安装),不是损坏。
|
||||
this.state = { version: REGISTRY_VERSION, extensions: [] }
|
||||
this.primaryValid = false
|
||||
return
|
||||
}
|
||||
|
||||
let text: string
|
||||
try {
|
||||
const raw = fs.readJsonSync(this.registryFile) as unknown
|
||||
if (!raw || typeof raw !== 'object') return
|
||||
const list = (raw as { extensions?: unknown }).extensions
|
||||
if (!Array.isArray(list)) return
|
||||
text = fs.readFileSync(this.registryFile, 'utf8')
|
||||
} catch (error) {
|
||||
// 读取失败(权限、IO)与「内容损坏」是两件事:不移动文件,也不尝试覆盖。
|
||||
this.state = { version: REGISTRY_VERSION, extensions: [] }
|
||||
this.primaryValid = false
|
||||
this.unreadable = {
|
||||
state: 'unreadable',
|
||||
at: stamp,
|
||||
message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展状态文件'
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const parsed = parseRegistryText(text)
|
||||
if (parsed.ok) {
|
||||
this.state = {
|
||||
version: REGISTRY_VERSION,
|
||||
extensions: list
|
||||
.map((item) => normalizeRecord(item))
|
||||
.filter((item): item is ExtensionRegistryRecord => item !== null)
|
||||
extensions: parsed.extensions,
|
||||
...(parsed.recovery ? { recovery: parsed.recovery } : {})
|
||||
}
|
||||
this.primaryValid = true
|
||||
return
|
||||
}
|
||||
|
||||
const corruptFile = this.preserveCorrupt(text)
|
||||
|
||||
const backup = this.tryLoadBackup()
|
||||
if (backup) {
|
||||
this.state = this.buildRecoveredState(backup, 'backup', corruptFile)
|
||||
this.primaryValid = false
|
||||
// 立即把降级后的状态写回主文件:恢复提示与「全部暂停」必须能跨重启保留。
|
||||
try {
|
||||
this.writeState(this.state)
|
||||
this.primaryValid = true
|
||||
} catch {
|
||||
// 保留内存状态即可,启动不应因为一次修复失败而中断。
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const scanned = this.scan()
|
||||
if (scanned) {
|
||||
this.state = this.buildRecoveredState(scanned, 'scan', corruptFile)
|
||||
this.primaryValid = false
|
||||
// 刻意不写盘:损坏现场仍留在原位,用户可以在修复后重新读取。
|
||||
// 一旦用户执行任何写操作(启用/卸载),降级结果与恢复标记会一并落盘。
|
||||
return
|
||||
}
|
||||
|
||||
this.state = { version: REGISTRY_VERSION, extensions: [] }
|
||||
this.primaryValid = false
|
||||
this.unreadable = {
|
||||
state: 'unreadable',
|
||||
at: stamp,
|
||||
...(corruptFile ? { corruptFile } : {}),
|
||||
message: '扩展状态文件损坏且无法恢复;为避免覆盖现场,已停止写入'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复出来的状态一律降级。
|
||||
*
|
||||
* 备份最多落后一版,它可能记录着用户随后撤销的授权或关闭的开关。
|
||||
* 自动采纳等于「把用户已经收回的权限再发回去」,所以只保留身份与版本,
|
||||
* 启用状态与授权全部清零,等用户重新确认。
|
||||
*/
|
||||
private buildRecoveredState(
|
||||
records: ExtensionRegistryRecord[],
|
||||
kind: 'backup' | 'scan',
|
||||
corruptFile?: string
|
||||
): RegistryFile {
|
||||
return {
|
||||
version: REGISTRY_VERSION,
|
||||
extensions: records.map((record) => ({
|
||||
...record,
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
updatedAt: this.now()
|
||||
})),
|
||||
recovery: {
|
||||
at: this.now(),
|
||||
kind,
|
||||
...(corruptFile ? { corruptFile } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private tryLoadBackup(): ExtensionRegistryRecord[] | null {
|
||||
try {
|
||||
if (!fs.existsSync(this.backupFile)) return null
|
||||
const parsed = parseRegistryText(fs.readFileSync(this.backupFile, 'utf8'))
|
||||
return parsed.ok ? parsed.extensions : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private scan(): ExtensionRegistryRecord[] | null {
|
||||
if (!this.recoverByScan) return null
|
||||
let records: ExtensionRegistryRecord[]
|
||||
try {
|
||||
records = this.recoverByScan()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!Array.isArray(records)) return null
|
||||
// 扫描结果只用于「知道有哪些扩展存在」,不继承任何授权或启用状态。
|
||||
return records.map((record) => ({
|
||||
...record,
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
source: 'directory' as const
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 把损坏内容写到 `.corrupt-<时间戳>`。
|
||||
*
|
||||
* 保留现场是恢复的前提:用户可能手工修好它,或者授权更高版本的 TraceMemo 读取。
|
||||
*/
|
||||
private preserveCorrupt(text: string): string | undefined {
|
||||
const base = `${this.registryFile}.corrupt-${this.now().toString(36)}`
|
||||
let target = base
|
||||
let index = 1
|
||||
while (fs.existsSync(target)) {
|
||||
target = `${base}-${index}`
|
||||
index += 1
|
||||
}
|
||||
try {
|
||||
fs.writeFileSync(target, text, 'utf8')
|
||||
this.pruneCorruptFiles()
|
||||
return path.basename(target)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
private pruneCorruptFiles(): void {
|
||||
try {
|
||||
const directory = path.dirname(this.registryFile)
|
||||
const prefix = `${path.basename(this.registryFile)}.corrupt-`
|
||||
const files = fs
|
||||
.readdirSync(directory)
|
||||
.filter((name) => name.startsWith(prefix))
|
||||
.map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs }))
|
||||
.sort((left, right) => left.at - right.at)
|
||||
for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) {
|
||||
fs.removeSync(path.join(directory, file.name))
|
||||
}
|
||||
} catch {
|
||||
// 文件不存在 / 损坏都按「没有装过扩展」处理,不阻塞应用启动。
|
||||
// 清理失败不影响恢复本身。
|
||||
}
|
||||
}
|
||||
|
||||
private commit(extensions: ExtensionRegistryRecord[]): void {
|
||||
const previous = this.state
|
||||
this.state = { version: REGISTRY_VERSION, extensions }
|
||||
const previousValid = this.primaryValid
|
||||
// 恢复标记必须跟着普通写入一起保留:否则用户启用一个扩展就把
|
||||
// 「其余扩展全部暂停过」的提示抹掉了。
|
||||
this.state = {
|
||||
version: REGISTRY_VERSION,
|
||||
extensions,
|
||||
...(previous.recovery ? { recovery: previous.recovery } : {})
|
||||
}
|
||||
try {
|
||||
this.persist()
|
||||
} catch (error) {
|
||||
this.state = previous
|
||||
this.primaryValid = previousValid
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
fs.ensureDirSync(path.dirname(this.registryFile))
|
||||
if (this.unreadable) {
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_REGISTRY_UNREADABLE',
|
||||
'扩展状态文件损坏且无法恢复,已拒绝写入以保留现场'
|
||||
)
|
||||
}
|
||||
this.rotateBackup()
|
||||
this.writeState(this.state)
|
||||
this.primaryValid = true
|
||||
}
|
||||
|
||||
/**
|
||||
* 用当前主文件刷新 `.bak`。
|
||||
*
|
||||
* 三重保护:
|
||||
* 1. 主文件不可信(`primaryValid === false`)时直接跳过;
|
||||
* 2. 先写 `.bak.tmp` 并重新解析,拒绝把坏内容升级成备份;
|
||||
* 3. 成功后才 rename 覆盖旧备份,失败时旧备份原样保留。
|
||||
*/
|
||||
private rotateBackup(): void {
|
||||
if (!this.primaryValid) return
|
||||
if (!fs.existsSync(this.registryFile)) return
|
||||
const temporary = `${this.backupFile}.tmp`
|
||||
try {
|
||||
fs.copyFileSync(this.registryFile, temporary)
|
||||
const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8'))
|
||||
if (!parsed.ok) {
|
||||
fs.removeSync(temporary)
|
||||
return
|
||||
}
|
||||
fs.moveSync(temporary, this.backupFile, { overwrite: true })
|
||||
} catch {
|
||||
fs.removeSync(temporary)
|
||||
}
|
||||
}
|
||||
|
||||
/** 临时文件 → 读回校验 → 原子替换;中途失败不会留下半写的主文件。 */
|
||||
private writeState(state: RegistryFile): void {
|
||||
const directory = path.dirname(this.registryFile)
|
||||
fs.ensureDirSync(directory)
|
||||
const temporary = `${this.registryFile}.tmp`
|
||||
fs.writeJsonSync(temporary, this.state, { spaces: 2 })
|
||||
fs.writeFileSync(temporary, JSON.stringify(state, null, 2), 'utf8')
|
||||
const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8'))
|
||||
if (!parsed.ok) {
|
||||
fs.removeSync(temporary)
|
||||
throw new ExtensionError('EXTENSION_REGISTRY_UNREADABLE', `写入前校验失败:${parsed.reason}`)
|
||||
}
|
||||
fs.moveSync(temporary, this.registryFile, { overwrite: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import type { ExtensionSource } from '../../shared/extensions/source'
|
||||
import { isPathInside, isSamePath, type ExtensionPaths } from './extension-paths'
|
||||
import type { ExtensionRegistryRecord } from './extension-registry'
|
||||
|
||||
export interface ExtensionRootInfo {
|
||||
extensionId: string
|
||||
/** 代码根目录(已 realpath)。 */
|
||||
root: string
|
||||
source: ExtensionSource
|
||||
/** 开发模式下用户选择时的目录(同样是 realpath)。 */
|
||||
developmentSourcePath?: string
|
||||
}
|
||||
|
||||
export interface ExtensionRootResolver {
|
||||
/**
|
||||
* 解析扩展代码根目录。
|
||||
*
|
||||
* 抛 `EXTENSION_SOURCE_MISSING` 表示开发目录不可用;调用方必须保留 Registry
|
||||
* 与配置,把扩展标成「源码目录不可用」,而不是当成「没装过」。
|
||||
*/
|
||||
resolve(extensionId: string): ExtensionRootInfo
|
||||
/** 只看正式安装目录,用于导出、回滚等必须触碰安装副本的场景。 */
|
||||
installedRoot(extensionId: string): string
|
||||
}
|
||||
|
||||
export interface ExtensionRootResolverDependencies {
|
||||
paths: ExtensionPaths
|
||||
getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
|
||||
/** 测试注入点。 */
|
||||
realpath?: (target: string) => string
|
||||
stat?: (target: string) => { isDirectory: () => boolean }
|
||||
}
|
||||
|
||||
/**
|
||||
* 所有扩展代码根目录的唯一来源。
|
||||
*
|
||||
* 在这之前,代码目录被 manager、protocol、catalog 各自拼 `paths.installDir(id)`,
|
||||
* 开发模式一旦接入就会出现「后台读外部目录、页面读安装副本」的错位。
|
||||
*/
|
||||
export function createExtensionRootResolver(
|
||||
dependencies: ExtensionRootResolverDependencies
|
||||
): ExtensionRootResolver {
|
||||
const realpath = dependencies.realpath ?? ((target: string) => fs.realpathSync(target))
|
||||
const stat = dependencies.stat ?? ((target: string) => fs.statSync(target))
|
||||
|
||||
function resolveInstalled(extensionId: string): string {
|
||||
return dependencies.paths.installDir(extensionId)
|
||||
}
|
||||
|
||||
return {
|
||||
installedRoot: resolveInstalled,
|
||||
|
||||
resolve(extensionId: string): ExtensionRootInfo {
|
||||
const record = dependencies.getRecord(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (record.source !== 'development' || !record.developmentSourcePath) {
|
||||
return { extensionId, root: resolveInstalled(extensionId), source: record.source }
|
||||
}
|
||||
|
||||
const configured = record.developmentSourcePath
|
||||
let realRoot: string
|
||||
try {
|
||||
realRoot = realpath(configured)
|
||||
} catch {
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_SOURCE_MISSING',
|
||||
'开发源码目录不可用,请重新选择或移除链接'
|
||||
)
|
||||
}
|
||||
let isDirectory = false
|
||||
try {
|
||||
isDirectory = stat(realRoot).isDirectory()
|
||||
} catch {
|
||||
isDirectory = false
|
||||
}
|
||||
if (!isDirectory) {
|
||||
throw new ExtensionError('EXTENSION_SOURCE_MISSING', '开发源码路径不是目录')
|
||||
}
|
||||
|
||||
assertSafeDevelopmentRoot(dependencies.paths, extensionId, realRoot)
|
||||
return {
|
||||
extensionId,
|
||||
root: realRoot,
|
||||
source: 'development',
|
||||
developmentSourcePath: realRoot
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 开发目录的安全边界。
|
||||
*
|
||||
* 拒绝三类位置:
|
||||
* 1. 扩展自己的安装副本(否则「开发模式」等于原地打转,卸载还会误删);
|
||||
* 2. 宿主的私有数据区(配置、状态、日志、暂存)——那里有用户凭据;
|
||||
* 3. 文件系统根 / 用户主目录(自定义协议会把整个目录开放给 iframe)。
|
||||
*/
|
||||
function safeRealpath(target: string): string {
|
||||
try {
|
||||
return fs.realpathSync(target)
|
||||
} catch {
|
||||
return path.resolve(target)
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSafeDevelopmentRoot(
|
||||
paths: ExtensionPaths,
|
||||
extensionId: string,
|
||||
realRoot: string
|
||||
): void {
|
||||
const forbidden: Array<{ root: string; reason: string }> = [
|
||||
{ root: paths.installDir(extensionId), reason: '不能指向扩展自己的安装目录' },
|
||||
{ root: paths.extensionsDir, reason: '不能指向扩展安装根目录' },
|
||||
{ root: paths.dataDir, reason: '不能指向宿主私有数据目录' },
|
||||
{ root: paths.stateDir, reason: '不能指向宿主状态目录' },
|
||||
{ root: paths.stagingDir, reason: '不能指向宿主暂存目录' }
|
||||
]
|
||||
for (const item of forbidden) {
|
||||
// 两侧都必须 realpath:macOS 上 `/tmp` 指向 `/private/tmp`,
|
||||
// 只比较字符串会让「extensions-data 里的目录」冒充外部项目。
|
||||
const forbiddenRoot = safeRealpath(item.root)
|
||||
if (isSamePath(forbiddenRoot, realRoot) || isPathInside(forbiddenRoot, realRoot)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', item.reason)
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = path.parse(realRoot)
|
||||
if (realRoot === parsed.root) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把文件系统根目录作为扩展源码')
|
||||
}
|
||||
try {
|
||||
if (isSamePath(os.homedir(), realRoot)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把用户主目录作为扩展源码')
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ExtensionError) throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'node:path'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
|
||||
/** 加密实现由主进程注入(Electron `safeStorage`),本模块不直接依赖 electron。 */
|
||||
export interface ExtensionSecretCipher {
|
||||
isAvailable: () => boolean
|
||||
encrypt: (plain: string) => Buffer
|
||||
decrypt: (payload: Buffer) => string
|
||||
}
|
||||
|
||||
export interface ExtensionSecretStoreDependencies {
|
||||
/** 通常是 `<userData>/extensions-state/secrets`。 */
|
||||
root: string
|
||||
cipher: ExtensionSecretCipher
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface SecretFile {
|
||||
version: 1
|
||||
values: Record<string, string>
|
||||
}
|
||||
|
||||
const MAX_KEY_LENGTH = 64
|
||||
const MAX_VALUE_BYTES = 8 * 1024
|
||||
const MAX_KEYS = 32
|
||||
const SECRET_KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/
|
||||
|
||||
/**
|
||||
* 扩展私有凭据。
|
||||
*
|
||||
* 设计取舍:
|
||||
* - 每个扩展一个文件、一个命名空间,A 扩展拿不到 B 的键;
|
||||
* - 落盘只有 `safeStorage` 加密后的密文,**不再产生明文 .txt**;
|
||||
* - 加密不可用时直接失败,绝不退化成明文——宁可让用户知道「这台机器不支持」,
|
||||
* 也不要把 Cookie 摊在磁盘上。
|
||||
*
|
||||
* 这不是操作系统级沙箱:扩展后台是拥有 Node 权限的本地进程,能读别的文件。
|
||||
* 它能防的是「普通 SDK / 页面桥跨扩展取密钥」与「意外明文落盘」。
|
||||
*/
|
||||
export class ExtensionSecretStore {
|
||||
private readonly root: string
|
||||
private readonly cipher: ExtensionSecretCipher
|
||||
private readonly now: () => number
|
||||
private readonly cache = new Map<string, SecretFile>()
|
||||
|
||||
constructor(dependencies: ExtensionSecretStoreDependencies) {
|
||||
this.root = dependencies.root
|
||||
this.cipher = dependencies.cipher
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
}
|
||||
|
||||
isAvailable(): boolean {
|
||||
try {
|
||||
return this.cipher.isAvailable()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 只返回键名与数量,不返回值;供 UI 显示「是否已配置」。 */
|
||||
listKeys(extensionId: string): string[] {
|
||||
return Object.keys(this.read(extensionId).values).sort()
|
||||
}
|
||||
|
||||
has(extensionId: string, key: string): boolean {
|
||||
const name = assertKey(key)
|
||||
return Object.prototype.hasOwnProperty.call(this.read(extensionId).values, name)
|
||||
}
|
||||
|
||||
get(extensionId: string, key: string): string | null {
|
||||
const name = assertKey(key)
|
||||
const values = this.read(extensionId).values
|
||||
return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null
|
||||
}
|
||||
|
||||
set(extensionId: string, key: string, value: string): void {
|
||||
const name = assertKey(key)
|
||||
if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '凭据值必须是字符串')
|
||||
if (new TextEncoder().encode(value).length > MAX_VALUE_BYTES) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '凭据超过 8KB 上限')
|
||||
}
|
||||
const file = this.read(extensionId)
|
||||
if (
|
||||
!Object.prototype.hasOwnProperty.call(file.values, name) &&
|
||||
Object.keys(file.values).length >= MAX_KEYS
|
||||
) {
|
||||
throw new ExtensionError('INVALID_REQUEST', `单个扩展最多保存 ${MAX_KEYS} 个凭据`)
|
||||
}
|
||||
file.values[name] = value
|
||||
this.write(extensionId, file)
|
||||
}
|
||||
|
||||
delete(extensionId: string, key: string): boolean {
|
||||
const name = assertKey(key)
|
||||
const file = this.read(extensionId)
|
||||
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
|
||||
delete file.values[name]
|
||||
this.write(extensionId, file)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 卸载扩展且用户选择清除数据时调用。 */
|
||||
clear(extensionId: string): void {
|
||||
this.cache.delete(extensionId)
|
||||
fs.removeSync(this.filePath(extensionId))
|
||||
}
|
||||
|
||||
private filePath(extensionId: string): string {
|
||||
return path.join(this.root, `${extensionId}.bin`)
|
||||
}
|
||||
|
||||
private read(extensionId: string): SecretFile {
|
||||
const cached = this.cache.get(extensionId)
|
||||
if (cached) return { version: 1, values: { ...cached.values } }
|
||||
const file = this.filePath(extensionId)
|
||||
if (!fs.existsSync(file)) {
|
||||
const empty: SecretFile = { version: 1, values: {} }
|
||||
this.cache.set(extensionId, empty)
|
||||
return { version: 1, values: {} }
|
||||
}
|
||||
this.assertAvailable()
|
||||
let parsed: SecretFile
|
||||
try {
|
||||
const payload = fs.readFileSync(file)
|
||||
const text = this.cipher.decrypt(payload)
|
||||
const raw = JSON.parse(text) as unknown
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('结构不合法')
|
||||
const values: Record<string, string> = {}
|
||||
for (const [key, value] of Object.entries((raw as { values?: unknown }).values ?? {})) {
|
||||
if (SECRET_KEY_PATTERN.test(key) && typeof value === 'string') values[key] = value
|
||||
}
|
||||
parsed = { version: 1, values }
|
||||
} catch {
|
||||
// 解不开就当作没有:不能把损坏的密文当成空口令去覆盖(写盘会覆盖原文件)。
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_STORAGE_CORRUPTED',
|
||||
'扩展凭据无法解密(可能换了机器或系统密钥变更),请在扩展页面重新填写'
|
||||
)
|
||||
}
|
||||
this.cache.set(extensionId, parsed)
|
||||
return { version: 1, values: { ...parsed.values } }
|
||||
}
|
||||
|
||||
private write(extensionId: string, file: SecretFile): void {
|
||||
this.assertAvailable()
|
||||
const payload = this.cipher.encrypt(JSON.stringify({ version: 1, values: file.values }))
|
||||
fs.ensureDirSync(this.root)
|
||||
const target = this.filePath(extensionId)
|
||||
const temporary = `${target}.tmp`
|
||||
fs.writeFileSync(temporary, payload, { mode: 0o600 })
|
||||
fs.moveSync(temporary, target, { overwrite: true })
|
||||
try {
|
||||
fs.chmodSync(target, 0o600)
|
||||
} catch {
|
||||
// Windows 不支持 POSIX 权限位;忽略即可。
|
||||
}
|
||||
this.cache.set(extensionId, { version: 1, values: { ...file.values } })
|
||||
void this.now
|
||||
}
|
||||
|
||||
private assertAvailable(): void {
|
||||
if (this.isAvailable()) return
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前系统不支持安全存储,扩展凭据功能不可用')
|
||||
}
|
||||
}
|
||||
|
||||
function assertKey(value: string): string {
|
||||
const key = String(value ?? '').trim()
|
||||
if (!SECRET_KEY_PATTERN.test(key) || key.length > MAX_KEY_LENGTH) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '凭据键名不合法')
|
||||
}
|
||||
return key
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { app, safeStorage } from 'electron'
|
||||
import path from 'node:path'
|
||||
import { AIProviderService } from '../services/ai-provider-service'
|
||||
import {
|
||||
getChatDb,
|
||||
@@ -20,6 +22,19 @@ import { getExtensionPaths } from './extension-paths'
|
||||
|
||||
let manager: ExtensionManager | null = null
|
||||
|
||||
/**
|
||||
* 官方模板资源根目录。
|
||||
*
|
||||
* 打包后是 `<resources>/extension-templates`;开发态读构建产物目录。
|
||||
* 两者都不指向 `examples/extensions`——源码树不是运行时依赖。
|
||||
*/
|
||||
function resolveTemplateRoot(): string {
|
||||
const override = process.env.TRACEMEMO_EXTENSION_TEMPLATES_DIR
|
||||
if (override && override.trim()) return path.resolve(override.trim())
|
||||
if (app.isPackaged) return path.join(process.resourcesPath, 'extension-templates')
|
||||
return path.join(app.getAppPath(), 'build', 'extension-templates')
|
||||
}
|
||||
|
||||
export interface ExtensionSystemOptions {
|
||||
appVersion: string
|
||||
onChange: (extensionId: string, reason: string) => void
|
||||
@@ -53,6 +68,11 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
|
||||
}
|
||||
},
|
||||
aiChat: chatWithConfiguredProvider,
|
||||
aiStatus: () => {
|
||||
// 只读「是否已配置 + 模型显示名」,不返回 key 或 endpoint。
|
||||
const config = new AIProviderService().getRuntimeConfig()
|
||||
return { configured: config.configured, modelName: config.modelName }
|
||||
},
|
||||
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
|
||||
getSelfUsernames: () => {
|
||||
try {
|
||||
@@ -68,6 +88,12 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
|
||||
return false
|
||||
}
|
||||
},
|
||||
templatesRoot: resolveTemplateRoot(),
|
||||
secretCipher: {
|
||||
isAvailable: () => safeStorage.isEncryptionAvailable(),
|
||||
encrypt: (plain: string) => safeStorage.encryptString(plain),
|
||||
decrypt: (payload: Buffer) => safeStorage.decryptString(payload)
|
||||
},
|
||||
onChange: (extensionId, reason) => options.onChange(extensionId, reason)
|
||||
})
|
||||
await manager.initialize()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'node:path'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import type { ExtensionStorageHealthState } from '../../shared/extensions/types'
|
||||
|
||||
const STORAGE_FILE = 'storage.json'
|
||||
const STORAGE_VERSION = 1
|
||||
@@ -8,17 +9,59 @@ const MAX_KEY_LENGTH = 64
|
||||
const MAX_VALUE_BYTES = 256 * 1024
|
||||
const MAX_TOTAL_BYTES = 1024 * 1024
|
||||
const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/
|
||||
/** 每个扩展最多保留的损坏现场份数;超出时删除最旧的。 */
|
||||
const CORRUPT_KEEP_LIMIT = 3
|
||||
|
||||
interface StorageFile {
|
||||
version: number
|
||||
values: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExtensionStorageHealth {
|
||||
state: ExtensionStorageHealthState
|
||||
at: number
|
||||
/** 损坏现场的**文件名**(不含目录);不渲染绝对路径。 */
|
||||
corruptFile?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ExtensionStorageDependencies {
|
||||
/** 通常是 `<userData>/extensions-data`。 */
|
||||
dataRoot: string
|
||||
maxTotalBytes?: number
|
||||
maxValueBytes?: number
|
||||
now?: () => number
|
||||
/**
|
||||
* 健康状态发生变化时的通知。
|
||||
*
|
||||
* 运行期才发生损坏/回退时,宿主要靠这个立刻收住扩展——
|
||||
* 只等下一次启动才处理,那台机器人已经用旧配置发完消息了。
|
||||
*/
|
||||
onHealthChange?: (extensionId: string, health: ExtensionStorageHealth) => void
|
||||
}
|
||||
|
||||
type ParseResult = { ok: true; values: Record<string, unknown> } | { ok: false; reason: string }
|
||||
|
||||
function parseStorageText(text: string): ParseResult {
|
||||
if (!text.trim()) return { ok: false, reason: '存储文件为空' }
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(text)
|
||||
} catch {
|
||||
return { ok: false, reason: '存储文件不是合法 JSON' }
|
||||
}
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return { ok: false, reason: '存储文件顶层不是对象' }
|
||||
}
|
||||
const version = Number((raw as { version?: unknown }).version)
|
||||
if (!Number.isInteger(version) || version !== STORAGE_VERSION) {
|
||||
return { ok: false, reason: '存储文件版本不受支持' }
|
||||
}
|
||||
const values = (raw as { values?: unknown }).values
|
||||
if (!values || typeof values !== 'object' || Array.isArray(values)) {
|
||||
return { ok: false, reason: 'values 不是对象' }
|
||||
}
|
||||
return { ok: true, values: values as Record<string, unknown> }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,16 +71,25 @@ export interface ExtensionStorageDependencies {
|
||||
* - 每个扩展一个独立目录,键空间互不可见;
|
||||
* - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**;
|
||||
* - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。
|
||||
*
|
||||
* 损坏语义:主文件解析失败时先尝试 `storage.json.bak`;两者都不可用时,
|
||||
* 该扩展进入 `unrecovered` 状态,`set` 会被拒绝。宁可让扩展报错,
|
||||
* 也不能用一次写入把用户唯一的一份配置覆盖成空。
|
||||
*/
|
||||
export class ExtensionStorage {
|
||||
private readonly dataRoot: string
|
||||
private readonly maxTotalBytes: number
|
||||
private readonly maxValueBytes: number
|
||||
private readonly now: () => number
|
||||
private readonly onHealthChange?: ExtensionStorageDependencies['onHealthChange']
|
||||
private readonly healthByExtension = new Map<string, ExtensionStorageHealth>()
|
||||
|
||||
constructor(dependencies: ExtensionStorageDependencies) {
|
||||
this.dataRoot = dependencies.dataRoot
|
||||
this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES
|
||||
this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
this.onHealthChange = dependencies.onHealthChange
|
||||
}
|
||||
|
||||
filePath(extensionId: string): string {
|
||||
@@ -51,6 +103,7 @@ export class ExtensionStorage {
|
||||
get(extensionId: string, key: unknown): unknown {
|
||||
const name = assertKey(key)
|
||||
const values = this.read(extensionId).values
|
||||
this.assertReadable(extensionId)
|
||||
return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined
|
||||
}
|
||||
|
||||
@@ -61,6 +114,7 @@ export class ExtensionStorage {
|
||||
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限')
|
||||
}
|
||||
const file = this.read(extensionId)
|
||||
this.assertReadable(extensionId)
|
||||
file.values[name] = JSON.parse(serialized)
|
||||
this.assertTotalSize(file)
|
||||
this.write(extensionId, file)
|
||||
@@ -69,6 +123,7 @@ export class ExtensionStorage {
|
||||
remove(extensionId: string, key: unknown): boolean {
|
||||
const name = assertKey(key)
|
||||
const file = this.read(extensionId)
|
||||
this.assertReadable(extensionId)
|
||||
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
|
||||
delete file.values[name]
|
||||
this.write(extensionId, file)
|
||||
@@ -77,6 +132,7 @@ export class ExtensionStorage {
|
||||
|
||||
list(extensionId: string): Array<{ key: string; value: unknown }> {
|
||||
const values = this.read(extensionId).values
|
||||
this.assertReadable(extensionId)
|
||||
return Object.keys(values).map((key) => ({ key, value: clone(values[key]) }))
|
||||
}
|
||||
|
||||
@@ -84,29 +140,219 @@ export class ExtensionStorage {
|
||||
this.write(extensionId, { version: STORAGE_VERSION, values: {} })
|
||||
}
|
||||
|
||||
/**
|
||||
* 显式重置:保留损坏现场,然后把存储清空。
|
||||
*
|
||||
* 只允许用户从界面触发;扩展自身不能调用(`tm.storage` 没有这个能力)。
|
||||
*/
|
||||
reset(extensionId: string): void {
|
||||
this.read(extensionId)
|
||||
this.writeState(extensionId, { version: STORAGE_VERSION, values: {} }, { rotateBackup: false })
|
||||
this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() })
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户确认「接受从备份恢复出来的配置」。
|
||||
*
|
||||
* 恢复出来的内容可能落后一版——比如机器人开关还停在 `true`。
|
||||
* 在用户点这一下之前,宿主不会启动该扩展(见 `ExtensionManager` 的启动前检查)。
|
||||
*/
|
||||
acknowledge(extensionId: string): void {
|
||||
const current = this.health(extensionId)
|
||||
if (current.state !== 'recovered-from-backup') {
|
||||
throw new ExtensionError('INVALID_REQUEST', '当前没有待确认的配置恢复')
|
||||
}
|
||||
this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() })
|
||||
}
|
||||
|
||||
/**
|
||||
* 未确认的恢复 / 无法恢复时,读写一律拒绝。
|
||||
*
|
||||
* 只让 `health()` 与 `reset()` / `acknowledge()` 能穿过这道闸:
|
||||
* 前者给界面看状态,后两者是用户的显式处理动作。
|
||||
*/
|
||||
private assertReadable(extensionId: string): void {
|
||||
const health = this.healthByExtension.get(extensionId)
|
||||
if (!health || health.state === 'ok') return
|
||||
if (health.state === 'recovered-from-backup') {
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_STORAGE_CORRUPTED',
|
||||
'扩展配置刚从备份恢复,用户确认前读写已暂停'
|
||||
)
|
||||
}
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置已损坏且没有可用备份')
|
||||
}
|
||||
|
||||
private reportHealth(extensionId: string, health: ExtensionStorageHealth): void {
|
||||
this.healthByExtension.set(extensionId, health)
|
||||
if (health.state === 'ok') return
|
||||
try {
|
||||
this.onHealthChange?.(extensionId, health)
|
||||
} catch {
|
||||
// 通知失败不能反过来影响存储读写。
|
||||
}
|
||||
}
|
||||
|
||||
health(extensionId: string): ExtensionStorageHealth {
|
||||
this.read(extensionId)
|
||||
return { ...(this.healthByExtension.get(extensionId) ?? { state: 'ok', at: this.now() }) }
|
||||
}
|
||||
|
||||
private read(extensionId: string): StorageFile {
|
||||
const filePath = this.filePath(extensionId)
|
||||
try {
|
||||
const raw = fs.readJsonSync(filePath) as unknown
|
||||
if (!raw || typeof raw !== 'object') return { version: STORAGE_VERSION, values: {} }
|
||||
const values = (raw as { values?: unknown }).values
|
||||
if (!values || typeof values !== 'object' || Array.isArray(values)) {
|
||||
return { version: STORAGE_VERSION, values: {} }
|
||||
}
|
||||
return { version: STORAGE_VERSION, values: values as Record<string, unknown> }
|
||||
} catch {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
|
||||
return { version: STORAGE_VERSION, values: {} }
|
||||
}
|
||||
|
||||
let text: string
|
||||
try {
|
||||
text = fs.readFileSync(filePath, 'utf8')
|
||||
} catch (error) {
|
||||
this.reportHealth(extensionId, {
|
||||
state: 'unrecovered',
|
||||
at: this.now(),
|
||||
message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展配置'
|
||||
})
|
||||
return { version: STORAGE_VERSION, values: {} }
|
||||
}
|
||||
|
||||
const parsed = parseStorageText(text)
|
||||
if (parsed.ok) {
|
||||
// `recovered-from-backup` 要保留到用户看到它为止:恢复成功后立刻改回 `ok`,
|
||||
// 界面就再也不会提示「这份配置曾经损坏过」。
|
||||
const current = this.healthByExtension.get(extensionId)
|
||||
if (current?.state !== 'recovered-from-backup') {
|
||||
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
|
||||
}
|
||||
return { version: STORAGE_VERSION, values: parsed.values }
|
||||
}
|
||||
|
||||
const corruptFile = this.preserveCorrupt(extensionId, text)
|
||||
const backup = this.tryLoadBackup(extensionId)
|
||||
if (backup) {
|
||||
this.reportHealth(extensionId, {
|
||||
state: 'recovered-from-backup',
|
||||
at: this.now(),
|
||||
...(corruptFile ? { corruptFile } : {}),
|
||||
message: '扩展配置损坏,已从备份恢复'
|
||||
})
|
||||
try {
|
||||
// 主文件此刻是坏的,不能让它进入备份轮换,否则会覆盖刚读到的有效备份。
|
||||
this.writeState(
|
||||
extensionId,
|
||||
{ version: STORAGE_VERSION, values: backup },
|
||||
{ rotateBackup: false }
|
||||
)
|
||||
} catch {
|
||||
// 提升备份失败时仍返回备份内容,下次写入会再试。
|
||||
}
|
||||
return { version: STORAGE_VERSION, values: backup }
|
||||
}
|
||||
|
||||
this.reportHealth(extensionId, {
|
||||
state: 'unrecovered',
|
||||
at: this.now(),
|
||||
...(corruptFile ? { corruptFile } : {}),
|
||||
message: '扩展配置损坏且没有可用备份;写入已停止以保留现场'
|
||||
})
|
||||
return { version: STORAGE_VERSION, values: {} }
|
||||
}
|
||||
|
||||
private tryLoadBackup(extensionId: string): Record<string, unknown> | null {
|
||||
const backupPath = `${this.filePath(extensionId)}.bak`
|
||||
try {
|
||||
if (!fs.existsSync(backupPath)) return null
|
||||
const parsed = parseStorageText(fs.readFileSync(backupPath, 'utf8'))
|
||||
return parsed.ok ? parsed.values : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private preserveCorrupt(extensionId: string, text: string): string | undefined {
|
||||
const filePath = this.filePath(extensionId)
|
||||
const base = `${filePath}.corrupt-${this.now().toString(36)}`
|
||||
let target = base
|
||||
let index = 1
|
||||
while (fs.existsSync(target)) {
|
||||
target = `${base}-${index}`
|
||||
index += 1
|
||||
}
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(filePath))
|
||||
fs.writeFileSync(target, text, 'utf8')
|
||||
this.pruneCorruptFiles(extensionId)
|
||||
return path.basename(target)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
private pruneCorruptFiles(extensionId: string): void {
|
||||
try {
|
||||
const directory = path.dirname(this.filePath(extensionId))
|
||||
const prefix = `${STORAGE_FILE}.corrupt-`
|
||||
const files = fs
|
||||
.readdirSync(directory)
|
||||
.filter((name) => name.startsWith(prefix))
|
||||
.map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs }))
|
||||
.sort((left, right) => left.at - right.at)
|
||||
for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) {
|
||||
fs.removeSync(path.join(directory, file.name))
|
||||
}
|
||||
} catch {
|
||||
// 清理失败不影响恢复本身。
|
||||
}
|
||||
}
|
||||
|
||||
private write(extensionId: string, file: StorageFile): void {
|
||||
this.writeState(extensionId, file, { rotateBackup: true })
|
||||
this.reportHealth(extensionId, { state: 'ok', at: this.now() })
|
||||
}
|
||||
|
||||
/**
|
||||
* 主文件 → `.bak` → 新内容。
|
||||
*
|
||||
* `rotateBackup` 只在主文件可信时为真:从备份恢复、显式重置这两条路径
|
||||
* 面对的主文件都是坏的,让它们参与轮换会把有效备份一起换掉。
|
||||
*/
|
||||
private writeState(
|
||||
extensionId: string,
|
||||
file: StorageFile,
|
||||
options: { rotateBackup: boolean }
|
||||
): void {
|
||||
const filePath = this.filePath(extensionId)
|
||||
fs.ensureDirSync(path.dirname(filePath))
|
||||
if (options.rotateBackup) this.rotateBackup(extensionId)
|
||||
const temporary = `${filePath}.tmp`
|
||||
fs.writeJsonSync(temporary, file, { spaces: 2 })
|
||||
fs.writeFileSync(temporary, JSON.stringify(file, null, 2), 'utf8')
|
||||
const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8'))
|
||||
if (!parsed.ok) {
|
||||
fs.removeSync(temporary)
|
||||
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', `写入前校验失败:${parsed.reason}`)
|
||||
}
|
||||
fs.moveSync(temporary, filePath, { overwrite: true })
|
||||
}
|
||||
|
||||
private rotateBackup(extensionId: string): void {
|
||||
const filePath = this.filePath(extensionId)
|
||||
if (!fs.existsSync(filePath)) return
|
||||
const backupPath = `${filePath}.bak`
|
||||
const temporary = `${backupPath}.tmp`
|
||||
try {
|
||||
fs.copyFileSync(filePath, temporary)
|
||||
const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8'))
|
||||
if (!parsed.ok) {
|
||||
fs.removeSync(temporary)
|
||||
return
|
||||
}
|
||||
fs.moveSync(temporary, backupPath, { overwrite: true })
|
||||
} catch {
|
||||
fs.removeSync(temporary)
|
||||
}
|
||||
}
|
||||
|
||||
private assertTotalSize(file: StorageFile): void {
|
||||
const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8')
|
||||
if (bytes > this.maxTotalBytes) {
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
import { existsSync, promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import { compareSemver } from '../../shared/extensions/manifest'
|
||||
import type { ExtensionRegistryRecord } from './extension-registry'
|
||||
import { normalizeExtensionPermissions } from '../../shared/extensions/permissions'
|
||||
|
||||
import type {
|
||||
ExtensionTemplateEntry,
|
||||
ExtensionTemplateRequirement,
|
||||
ExtensionTemplateStatus,
|
||||
TemplateDependencyCheck
|
||||
} from '../../shared/extensions/templates'
|
||||
|
||||
export type {
|
||||
ExtensionTemplateEntry,
|
||||
ExtensionTemplateRequirement,
|
||||
ExtensionTemplateState,
|
||||
ExtensionTemplateStatus,
|
||||
TemplateDependencyCheck
|
||||
} from '../../shared/extensions/templates'
|
||||
|
||||
export interface ExtensionTemplateCatalogDependencies {
|
||||
/** 模板资源根目录;打包后是 `<resources>/extension-templates`。 */
|
||||
templateRoot: string
|
||||
getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined
|
||||
/** 已安装扩展的代码目录;用来看依赖脚本在不在。 */
|
||||
resolveInstallDir: (extensionId: string) => string
|
||||
platform?: NodeJS.Platform
|
||||
/** 测试注入点:默认用真实文件系统。 */
|
||||
exists?: (filePath: string) => boolean
|
||||
readFile?: (filePath: string) => Promise<Buffer>
|
||||
/** 依赖探测注入点:默认读本机 PATH 与常见安装位置。 */
|
||||
probePython?: () => string | null
|
||||
probeChrome?: () => string | null
|
||||
}
|
||||
|
||||
const INDEX_FILE = 'index.json'
|
||||
const SUPPORTED_INDEX_VERSION = 1
|
||||
|
||||
interface TemplateIndexFile {
|
||||
version: number
|
||||
templates: unknown[]
|
||||
}
|
||||
|
||||
function parseRequirement(input: unknown): ExtensionTemplateRequirement {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return {}
|
||||
const raw = input as Record<string, unknown>
|
||||
const result: ExtensionTemplateRequirement = {}
|
||||
for (const key of ['python', 'chrome', 'externalScript'] as const) {
|
||||
const value = raw[key]
|
||||
if (value === true || value === false) {
|
||||
result[key] = value as never
|
||||
continue
|
||||
}
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
const item = value as Record<string, unknown>
|
||||
const required = item.required === true
|
||||
if (key === 'externalScript') {
|
||||
const scriptPath = typeof item.path === 'string' ? item.path.trim() : ''
|
||||
if (!scriptPath) continue
|
||||
result.externalScript = {
|
||||
required,
|
||||
path: scriptPath,
|
||||
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (key === 'python') {
|
||||
result.python = {
|
||||
required,
|
||||
...(typeof item.minVersion === 'string' ? { minVersion: item.minVersion } : {}),
|
||||
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
|
||||
}
|
||||
continue
|
||||
}
|
||||
result.chrome = {
|
||||
required,
|
||||
...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function parseEntry(input: unknown): ExtensionTemplateEntry | null {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
|
||||
const raw = input as Record<string, unknown>
|
||||
const templateId = String(raw.templateId ?? '').trim()
|
||||
const extensionId = String(raw.extensionId ?? '').trim()
|
||||
const name = String(raw.name ?? '').trim()
|
||||
const version = String(raw.version ?? '').trim()
|
||||
const file = String(raw.file ?? '').trim()
|
||||
const sha256 = String(raw.sha256 ?? '').trim()
|
||||
if (!templateId || !extensionId || !name || !version || !file || !sha256) return null
|
||||
// 索引来自资源目录,但依然不接受任何路径片段:读取时只拼在模板根目录下。
|
||||
if (file.includes('/') || file.includes('\\') || file.includes('..')) return null
|
||||
if (!/^[a-f0-9]{64}$/.test(sha256)) return null
|
||||
const platforms = Array.isArray(raw.platforms)
|
||||
? raw.platforms.filter((item): item is NodeJS.Platform => typeof item === 'string')
|
||||
: []
|
||||
return {
|
||||
templateId,
|
||||
extensionId,
|
||||
name,
|
||||
version,
|
||||
...(typeof raw.description === 'string' ? { description: raw.description.slice(0, 500) } : {}),
|
||||
permissions: normalizeExtensionPermissions(raw.permissions),
|
||||
file,
|
||||
sha256,
|
||||
bytes: Number(raw.bytes) || 0,
|
||||
fileCount: Number(raw.fileCount) || 0,
|
||||
platforms,
|
||||
requires: parseRequirement(raw.requires)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 官方模板目录。
|
||||
*
|
||||
* 只做三件事:读索引、校验资源、把模板与已安装状态对上。
|
||||
* 安装动作本身不在这里——它由 `ExtensionManager` 走统一的安装器,
|
||||
* 避免出现第二套 ZIP 解压逻辑。
|
||||
*/
|
||||
export class ExtensionTemplateCatalog {
|
||||
private readonly dependencies: ExtensionTemplateCatalogDependencies
|
||||
private readonly platform: NodeJS.Platform
|
||||
private cachedIndex: ExtensionTemplateEntry[] | null = null
|
||||
|
||||
constructor(dependencies: ExtensionTemplateCatalogDependencies) {
|
||||
this.dependencies = dependencies
|
||||
this.platform = dependencies.platform ?? process.platform
|
||||
}
|
||||
|
||||
/** 索引读取失败时返回空列表:模板资源缺失不应该让扩展中心整页崩掉。 */
|
||||
async list(): Promise<ExtensionTemplateStatus[]> {
|
||||
const entries = await this.loadIndex()
|
||||
const result: ExtensionTemplateStatus[] = []
|
||||
for (const template of entries) {
|
||||
result.push(await this.describe(template))
|
||||
}
|
||||
return result.sort((left, right) =>
|
||||
left.template.templateId.localeCompare(right.template.templateId)
|
||||
)
|
||||
}
|
||||
|
||||
get(templateId: string): ExtensionTemplateEntry | undefined {
|
||||
return this.cachedIndex?.find((item) => item.templateId === templateId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 取模板 ZIP 的绝对路径,并校验内容哈希。
|
||||
*
|
||||
* 这一步是安装前的最后一道闸:索引与 ZIP 若被单独替换,哈希就对不上,
|
||||
* 直接拒绝安装而不是把未知内容装进用户目录。
|
||||
*/
|
||||
async resolveZip(
|
||||
templateId: string
|
||||
): Promise<{ path: string; template: ExtensionTemplateEntry }> {
|
||||
const entries = await this.loadIndex()
|
||||
const template = entries.find((item) => item.templateId === templateId)
|
||||
if (!template) {
|
||||
throw new ExtensionError('EXTENSION_NOT_FOUND', `找不到模板:${templateId}`)
|
||||
}
|
||||
const zipPath = path.join(this.dependencies.templateRoot, template.file)
|
||||
const exists = this.dependencies.exists ?? defaultExists
|
||||
if (!exists(zipPath)) {
|
||||
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源缺失:${template.file}`)
|
||||
}
|
||||
const readFile = this.dependencies.readFile ?? fs.readFile
|
||||
let buffer: Buffer
|
||||
try {
|
||||
buffer = await readFile(zipPath)
|
||||
} catch {
|
||||
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源不可读:${template.file}`)
|
||||
}
|
||||
const digest = createHash('sha256').update(buffer).digest('hex')
|
||||
if (digest !== template.sha256) {
|
||||
throw new ExtensionError(
|
||||
'EXTENSION_INSTALL_FAILED',
|
||||
'模板资源校验失败:文件内容与索引不一致,已拒绝安装'
|
||||
)
|
||||
}
|
||||
return { path: zipPath, template }
|
||||
}
|
||||
|
||||
private async loadIndex(): Promise<ExtensionTemplateEntry[]> {
|
||||
if (this.cachedIndex) return this.cachedIndex
|
||||
const indexPath = path.join(this.dependencies.templateRoot, INDEX_FILE)
|
||||
const readFile = this.dependencies.readFile ?? fs.readFile
|
||||
let parsed: TemplateIndexFile
|
||||
try {
|
||||
const text = await readFile(indexPath)
|
||||
parsed = JSON.parse(text.toString('utf8')) as TemplateIndexFile
|
||||
} catch {
|
||||
this.cachedIndex = []
|
||||
return this.cachedIndex
|
||||
}
|
||||
if (
|
||||
!parsed ||
|
||||
Number(parsed.version) !== SUPPORTED_INDEX_VERSION ||
|
||||
!Array.isArray(parsed.templates)
|
||||
) {
|
||||
this.cachedIndex = []
|
||||
return this.cachedIndex
|
||||
}
|
||||
const entries: ExtensionTemplateEntry[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of parsed.templates) {
|
||||
const entry = parseEntry(item)
|
||||
if (!entry) continue
|
||||
if (seen.has(entry.templateId)) continue
|
||||
seen.add(entry.templateId)
|
||||
entries.push(entry)
|
||||
}
|
||||
this.cachedIndex = entries
|
||||
return entries
|
||||
}
|
||||
|
||||
private async describe(template: ExtensionTemplateEntry): Promise<ExtensionTemplateStatus> {
|
||||
const record = this.dependencies.getRecord(template.extensionId)
|
||||
const dependencies = await this.checkDependencies(template, record)
|
||||
const base = {
|
||||
template,
|
||||
...(record ? { installedVersion: record.version, installedSource: record.source } : {}),
|
||||
dependencies
|
||||
}
|
||||
|
||||
if (template.platforms.length > 0 && !template.platforms.includes(this.platform)) {
|
||||
return {
|
||||
...base,
|
||||
state: 'unsupported',
|
||||
message: `当前平台(${this.platform})不在模板支持范围内`
|
||||
}
|
||||
}
|
||||
|
||||
const damaged = await this.isDamaged(template)
|
||||
if (damaged) {
|
||||
return { ...base, state: 'damaged', message: '模板资源缺失或校验失败,请重新安装 TraceMemo' }
|
||||
}
|
||||
|
||||
if (!record) return { ...base, state: 'not-installed' }
|
||||
|
||||
// 同 id 但不是这个模板装的:不能静默接管用户自己的扩展。
|
||||
if (record.source !== 'template' || record.templateId !== template.templateId) {
|
||||
return {
|
||||
...base,
|
||||
state: 'conflict',
|
||||
message: '已安装同 ID 的非官方扩展,不会自动替换'
|
||||
}
|
||||
}
|
||||
|
||||
const compared = compareSemver(template.version, record.version)
|
||||
if (compared !== null && compared > 0) {
|
||||
return { ...base, state: 'update-available' }
|
||||
}
|
||||
return { ...base, state: 'installed' }
|
||||
}
|
||||
|
||||
private async isDamaged(template: ExtensionTemplateEntry): Promise<boolean> {
|
||||
const zipPath = path.join(this.dependencies.templateRoot, template.file)
|
||||
const exists = this.dependencies.exists ?? defaultExists
|
||||
if (!exists(zipPath)) return true
|
||||
const readFile = this.dependencies.readFile ?? fs.readFile
|
||||
try {
|
||||
const buffer = await readFile(zipPath)
|
||||
if (template.bytes > 0 && buffer.length !== template.bytes) return true
|
||||
return createHash('sha256').update(buffer).digest('hex') !== template.sha256
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 依赖检测只做本地文件探测:不执行脚本、不访问网络、不触发解析。
|
||||
*
|
||||
* `externalScript` 只在扩展已安装后才能判断——安装前它一定不存在,
|
||||
* 报「缺失」只会让用户以为模板坏了。
|
||||
*/
|
||||
private async checkDependencies(
|
||||
template: ExtensionTemplateEntry,
|
||||
record: ExtensionRegistryRecord | undefined
|
||||
): Promise<ExtensionTemplateStatus['dependencies']> {
|
||||
const checks: TemplateDependencyCheck[] = []
|
||||
const requires = template.requires
|
||||
|
||||
const python = requires.python
|
||||
if (python) {
|
||||
const required = typeof python === 'boolean' ? python : python.required
|
||||
const executable = (this.dependencies.probePython ?? (() => findPython(this.platform)))()
|
||||
checks.push({
|
||||
id: 'python',
|
||||
label: 'Python',
|
||||
ok: Boolean(executable),
|
||||
blocking: required,
|
||||
...(executable
|
||||
? { detail: '已找到可执行文件' }
|
||||
: {
|
||||
detail:
|
||||
typeof python === 'object' && python.reason
|
||||
? python.reason
|
||||
: '未在 PATH 中找到 Python'
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const chrome = requires.chrome
|
||||
if (chrome) {
|
||||
const required = typeof chrome === 'boolean' ? chrome : chrome.required
|
||||
const found = (this.dependencies.probeChrome ?? (() => findChrome(this.platform)))()
|
||||
checks.push({
|
||||
id: 'chrome',
|
||||
label: 'Chrome',
|
||||
ok: Boolean(found),
|
||||
blocking: required,
|
||||
...(found
|
||||
? { detail: '已找到 Chrome' }
|
||||
: {
|
||||
detail: typeof chrome === 'object' && chrome.reason ? chrome.reason : '未找到 Chrome'
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const externalScript = requires.externalScript
|
||||
if (externalScript) {
|
||||
const spec = typeof externalScript === 'object' ? externalScript : null
|
||||
const relative = spec?.path ?? 'scripts/douyin.py'
|
||||
if (!record) {
|
||||
checks.push({
|
||||
id: 'externalScript',
|
||||
label: '解析脚本',
|
||||
ok: false,
|
||||
blocking: false,
|
||||
detail: '安装后检测;该脚本不随应用分发'
|
||||
})
|
||||
} else {
|
||||
const scriptPath = path.join(
|
||||
this.dependencies.resolveInstallDir(template.extensionId),
|
||||
relative
|
||||
)
|
||||
const exists = this.dependencies.exists ?? defaultExists
|
||||
checks.push({
|
||||
id: 'externalScript',
|
||||
label: '解析脚本',
|
||||
ok: exists(scriptPath),
|
||||
blocking: spec?.required !== false,
|
||||
detail: exists(scriptPath)
|
||||
? '已找到解析脚本'
|
||||
: spec?.reason || '缺少解析脚本,模板暂时无法处理视频'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const blockingMissing = checks.some((check) => check.blocking && !check.ok)
|
||||
return { ready: !blockingMissing, checks }
|
||||
}
|
||||
}
|
||||
|
||||
function defaultExists(filePath: string): boolean {
|
||||
// 只查存在性,不读内容:检测阶段不触碰文件内容。
|
||||
return existsSync(filePath)
|
||||
}
|
||||
|
||||
/** 只在 PATH 里找可执行文件,**不执行**它——检测阶段不能启动任何外部进程。 */
|
||||
function findPython(platform: NodeJS.Platform): string | null {
|
||||
const names =
|
||||
platform === 'win32' ? ['python.exe', 'python3.exe', 'py.exe'] : ['python3', 'python']
|
||||
return findOnPath(names, platform)
|
||||
}
|
||||
|
||||
function findChrome(platform: NodeJS.Platform): string | null {
|
||||
const candidates: string[] = []
|
||||
if (platform === 'darwin') {
|
||||
candidates.push(
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
path.join(
|
||||
process.env.HOME || '',
|
||||
'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
|
||||
)
|
||||
)
|
||||
} else if (platform === 'win32') {
|
||||
for (const root of [
|
||||
process.env['PROGRAMFILES'] || '',
|
||||
process.env['PROGRAMFILES(X86)'] || '',
|
||||
process.env['LOCALAPPDATA'] || ''
|
||||
]) {
|
||||
if (!root) continue
|
||||
candidates.push(path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
||||
}
|
||||
}
|
||||
return candidates.find((candidate) => defaultExists(candidate)) || null
|
||||
}
|
||||
|
||||
function findOnPath(names: string[], platform: NodeJS.Platform): string | null {
|
||||
const separator = platform === 'win32' ? ';' : ':'
|
||||
const directories = String(process.env.PATH || '')
|
||||
.split(separator)
|
||||
.filter(Boolean)
|
||||
for (const name of names) {
|
||||
for (const directory of directories) {
|
||||
const candidate = path.join(directory, name)
|
||||
if (defaultExists(candidate)) return candidate
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { validateActionInput as validateWithSchema } from '../../shared/extensions/action-schema'
|
||||
import {
|
||||
EXTENSION_HOST_PROTOCOL_VERSION,
|
||||
type ExtensionAutomationActionOutput,
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
type ExtensionHostCallResult,
|
||||
type ExtensionHostEvent,
|
||||
type ExtensionHostInboundMessage,
|
||||
type ExtensionHostPageRequest,
|
||||
type ExtensionHostInvokeAction,
|
||||
type ExtensionHostTestSend,
|
||||
type ExtensionHostOutboundMessage,
|
||||
@@ -44,6 +46,10 @@ interface PendingCall {
|
||||
const pendingCalls = new Map<string, PendingCall>()
|
||||
const eventHandlers = new Set<MessageHandler>()
|
||||
const actions = new Map<string, RegisteredActionDefinition>()
|
||||
const pageHandlers = new Map<string, (params: Record<string, unknown>) => unknown>()
|
||||
/** 页面请求方法名:小写开头,允许点号分段,长度受限。 */
|
||||
const PAGE_REQUEST_METHOD = /^[a-z][a-zA-Z0-9]*(?:[._-][a-zA-Z0-9]+){0,3}$/
|
||||
const PAGE_RESULT_MAX_BYTES = 64 * 1024
|
||||
let permissions: string[] = []
|
||||
let activated = false
|
||||
let extensionDir = ''
|
||||
@@ -102,6 +108,45 @@ const tm = {
|
||||
return [...permissions]
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 页面 → 同扩展后台的通用请求处理器注册。
|
||||
*
|
||||
* 不需要额外权限:注册本身不产生任何能力,handler 内部若调用
|
||||
* `tm.wechat.send` 等能力,仍然各自走权限检查。
|
||||
*/
|
||||
page: {
|
||||
onRequest(method: string, handler: (params: Record<string, unknown>) => unknown): void {
|
||||
const name = String(method || '').trim()
|
||||
if (!PAGE_REQUEST_METHOD.test(name)) throw new Error(`页面请求方法名不合法:${name}`)
|
||||
if (typeof handler !== 'function') throw new Error('页面请求必须提供 handler')
|
||||
if (pageHandlers.has(name)) throw new Error(`页面请求重复注册:${name}`)
|
||||
pageHandlers.set(name, handler)
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 扩展私有凭据。
|
||||
*
|
||||
* 真正加密发生在主进程(`safeStorage`);子进程只在需要时拿到明文。
|
||||
* 每个扩展一个命名空间,A 扩展拿不到 B 的密钥。
|
||||
*/
|
||||
secrets: {
|
||||
async get(key: string): Promise<string | null> {
|
||||
requirePermission('secrets')
|
||||
return (await callHost('secrets.get', { key })) as string | null
|
||||
},
|
||||
async set(key: string, value: string): Promise<void> {
|
||||
requirePermission('secrets')
|
||||
await callHost('secrets.set', { key, value })
|
||||
},
|
||||
async delete(key: string): Promise<void> {
|
||||
requirePermission('secrets')
|
||||
await callHost('secrets.delete', { key })
|
||||
},
|
||||
async has(key: string): Promise<boolean> {
|
||||
requirePermission('secrets')
|
||||
return (await callHost('secrets.has', { key })) as boolean
|
||||
}
|
||||
},
|
||||
events: {
|
||||
on(name: 'message.received', handler: MessageHandler): () => void {
|
||||
if (name !== 'message.received' || typeof handler !== 'function') return () => undefined
|
||||
@@ -338,27 +383,62 @@ async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 UI 共用同一套校验规则。
|
||||
*
|
||||
* 两套实现一定会在某个边界上分叉,用户看到的就是「表单填得进去、执行时说参数错」。
|
||||
*/
|
||||
function validateActionInput(
|
||||
schema: Record<string, unknown> | undefined,
|
||||
input: Record<string, unknown>
|
||||
): void {
|
||||
if (!schema) return
|
||||
const required = Array.isArray(schema.required) ? schema.required : []
|
||||
for (const key of required) {
|
||||
if (typeof key === 'string' && !(key in input)) {
|
||||
throw new Error(`缺少必填参数:${key}`)
|
||||
}
|
||||
const result = validateWithSchema(schema as never, input)
|
||||
if (result.ok) return
|
||||
const [key, message] = Object.entries(result.errors)[0] ?? ['参数', '不合法']
|
||||
throw new Error(`参数 ${key} ${message}`)
|
||||
}
|
||||
|
||||
async function handlePageRequest(message: ExtensionHostPageRequest): Promise<void> {
|
||||
const handler = pageHandlers.get(message.method)
|
||||
if (!handler) {
|
||||
post({
|
||||
type: 'page-result',
|
||||
version: EXTENSION_HOST_PROTOCOL_VERSION,
|
||||
requestId: message.requestId,
|
||||
ok: false,
|
||||
error: { code: 'ACTION_FAILED', message: `页面请求未注册:${message.method}` }
|
||||
})
|
||||
return
|
||||
}
|
||||
const properties = schema.properties
|
||||
if (!properties || typeof properties !== 'object') return
|
||||
for (const [key, definition] of Object.entries(properties as Record<string, unknown>)) {
|
||||
if (!(key in input)) continue
|
||||
const type = (definition as { type?: unknown })?.type
|
||||
const value = input[key]
|
||||
if (type === 'string' && typeof value !== 'string') throw new Error(`参数 ${key} 必须是字符串`)
|
||||
if (type === 'number' && typeof value !== 'number') throw new Error(`参数 ${key} 必须是数字`)
|
||||
if (type === 'boolean' && typeof value !== 'boolean')
|
||||
throw new Error(`参数 ${key} 必须是布尔值`)
|
||||
try {
|
||||
const raw = await withTimeout(
|
||||
Promise.resolve(handler(message.params ?? {})),
|
||||
Math.max(1_000, Math.min(message.timeoutMs - 500, 30_000))
|
||||
)
|
||||
// 只允许纯 JSON:函数、循环引用、类实例都在这一步被拒绝。
|
||||
const serialized = JSON.stringify(raw ?? null)
|
||||
if (new TextEncoder().encode(serialized).length > PAGE_RESULT_MAX_BYTES) {
|
||||
throw new Error('页面请求响应超过 64KB')
|
||||
}
|
||||
post({
|
||||
type: 'page-result',
|
||||
version: EXTENSION_HOST_PROTOCOL_VERSION,
|
||||
requestId: message.requestId,
|
||||
ok: true,
|
||||
result: JSON.parse(serialized) as unknown
|
||||
})
|
||||
} catch (error) {
|
||||
post({
|
||||
type: 'page-result',
|
||||
version: EXTENSION_HOST_PROTOCOL_VERSION,
|
||||
requestId: message.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'ACTION_FAILED',
|
||||
message: error instanceof Error ? error.message.slice(0, 200) : '页面请求失败'
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,9 +545,13 @@ process.on('message', (raw: unknown) => {
|
||||
void invokeAction(message)
|
||||
return
|
||||
case 'test-send':
|
||||
// 旧协议:只有抖音扩展认这个入口。新代码统一走 page-request。
|
||||
if (extensionId !== 'com.example.douyin-sender') return
|
||||
void dispatchTestSend(message)
|
||||
return
|
||||
case 'page-request':
|
||||
void handlePageRequest(message)
|
||||
return
|
||||
case 'call-result': {
|
||||
const result = message as ExtensionHostCallResult
|
||||
const pending = pendingCalls.get(result.callId)
|
||||
|
||||
+13
-1
@@ -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(),
|
||||
|
||||
Vendored
+40
@@ -10,8 +10,12 @@ import type {
|
||||
ExtensionOperationResult,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionPageResponse,
|
||||
ExtensionActionInfo,
|
||||
ExtensionProjectResult,
|
||||
ExtensionSystemHealth,
|
||||
InstalledExtension
|
||||
} from '../shared/extensions/types'
|
||||
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
|
||||
import {
|
||||
GroupReportExportRequest,
|
||||
GroupReportExportResult,
|
||||
@@ -840,6 +844,42 @@ declare global {
|
||||
extensionId: string,
|
||||
enabled: boolean
|
||||
) => Promise<ExtensionOperationResult>
|
||||
getExtensionHealth: () => Promise<ExtensionSystemHealth>
|
||||
grantExtensionPermissions: (
|
||||
extensionId: string,
|
||||
permissions: string[]
|
||||
) => Promise<ExtensionOperationResult>
|
||||
revokeExtensionPermission: (
|
||||
extensionId: string,
|
||||
permission: string
|
||||
) => Promise<ExtensionOperationResult>
|
||||
resetExtensionStorage: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
listExtensionTemplates: () => Promise<ExtensionTemplateStatus[]>
|
||||
installExtensionTemplate: (templateId: string) => Promise<ExtensionInstallResult>
|
||||
acknowledgeExtensionRecovery: () => Promise<ExtensionOperationResult>
|
||||
acknowledgeExtensionStorage: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
adoptExtensionCode: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
rollbackExtensionUpgrade: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
pickExtensionProjectDirectory: () => Promise<string | null>
|
||||
linkExtensionDevelopment: (directory: string) => Promise<ExtensionInstallResult>
|
||||
reloadExtensionDevelopment: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
unlinkExtensionDevelopment: (
|
||||
extensionId: string,
|
||||
keepData?: boolean
|
||||
) => Promise<ExtensionOperationResult>
|
||||
convertExtensionDevelopment: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
createExtensionProject: (input: {
|
||||
templateId: string
|
||||
targetDirectory: string
|
||||
extensionId: string
|
||||
name?: string
|
||||
}) => Promise<ExtensionProjectResult>
|
||||
listExtensionActions: () => Promise<ExtensionActionInfo[]>
|
||||
openExtensionDevelopmentSource: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
exportExtensionAsProject: (
|
||||
extensionId: string,
|
||||
targetDirectory: string
|
||||
) => Promise<ExtensionProjectResult>
|
||||
uninstallExtension: (
|
||||
extensionId: string,
|
||||
keepData?: boolean
|
||||
|
||||
@@ -139,8 +139,12 @@ import type {
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionPageRequest,
|
||||
ExtensionPageResponse,
|
||||
ExtensionActionInfo,
|
||||
ExtensionProjectResult,
|
||||
ExtensionSystemHealth,
|
||||
InstalledExtension
|
||||
} from '../shared/extensions/types'
|
||||
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
|
||||
|
||||
// 渲染器的自定义 API
|
||||
const api = {
|
||||
@@ -287,6 +291,64 @@ const api = {
|
||||
ipcRenderer.invoke('extension:installPackage', packagePath),
|
||||
setExtensionEnabled: (extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }),
|
||||
getExtensionHealth: (): Promise<ExtensionSystemHealth> =>
|
||||
ipcRenderer.invoke('extension:health'),
|
||||
grantExtensionPermissions: (
|
||||
extensionId: string,
|
||||
permissions: string[]
|
||||
): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:grantPermissions', { id: extensionId, permissions }),
|
||||
revokeExtensionPermission: (
|
||||
extensionId: string,
|
||||
permission: string
|
||||
): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:revokePermission', { id: extensionId, permission }),
|
||||
resetExtensionStorage: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:resetStorage', extensionId),
|
||||
listExtensionTemplates: (): Promise<ExtensionTemplateStatus[]> =>
|
||||
ipcRenderer.invoke('extension:templates'),
|
||||
installExtensionTemplate: (templateId: string): Promise<ExtensionInstallResult> =>
|
||||
ipcRenderer.invoke('extension:installTemplate', templateId),
|
||||
acknowledgeExtensionRecovery: (): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:acknowledgeRecovery'),
|
||||
acknowledgeExtensionStorage: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:acknowledgeStorage', extensionId),
|
||||
adoptExtensionCode: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:adoptInstalledCode', extensionId),
|
||||
rollbackExtensionUpgrade: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:rollbackUpgrade', extensionId),
|
||||
pickExtensionProjectDirectory: (): Promise<string | null> =>
|
||||
ipcRenderer.invoke('extension:pickProjectDirectory'),
|
||||
linkExtensionDevelopment: (directory: string): Promise<ExtensionInstallResult> =>
|
||||
ipcRenderer.invoke('extension:linkDevelopment', directory),
|
||||
reloadExtensionDevelopment: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:reloadDevelopment', extensionId),
|
||||
unlinkExtensionDevelopment: (
|
||||
extensionId: string,
|
||||
keepData = true
|
||||
): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:unlinkDevelopment', { id: extensionId, keepData }),
|
||||
convertExtensionDevelopment: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:convertDevelopment', extensionId),
|
||||
createExtensionProject: (input: {
|
||||
templateId: string
|
||||
targetDirectory: string
|
||||
extensionId: string
|
||||
name?: string
|
||||
}): Promise<ExtensionProjectResult> =>
|
||||
ipcRenderer.invoke('extension:createProjectFromTemplate', input),
|
||||
listExtensionActions: (): Promise<ExtensionActionInfo[]> =>
|
||||
ipcRenderer.invoke('extension:actions'),
|
||||
openExtensionDevelopmentSource: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:openDevelopmentSource', extensionId),
|
||||
exportExtensionAsProject: (
|
||||
extensionId: string,
|
||||
targetDirectory: string
|
||||
): Promise<ExtensionProjectResult> =>
|
||||
ipcRenderer.invoke('extension:exportInstalledAsProject', {
|
||||
id: extensionId,
|
||||
targetDirectory
|
||||
}),
|
||||
uninstallExtension: (extensionId: string, keepData = true): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }),
|
||||
getExtensionLogs: (extensionId: string, limit?: number): Promise<ExtensionLogEntry[]> =>
|
||||
|
||||
@@ -44,9 +44,16 @@ import { switchGeneratedReportTemplate } from './utils/report-template-switch'
|
||||
import { runtimePlatform } from './utils/runtime-environment'
|
||||
import { Button, useToast } from './components/ui'
|
||||
import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt'
|
||||
import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace'
|
||||
import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace'
|
||||
import {
|
||||
GroupExitMonitorWorkspace,
|
||||
type GroupExitMonitorOpenViewRequest
|
||||
} from './features/group-exit-monitor/GroupExitMonitorWorkspace'
|
||||
import {
|
||||
AutomationWorkspace,
|
||||
type AutomationOpenRuleRequest
|
||||
} from './features/automation/AutomationWorkspace'
|
||||
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
|
||||
import type { ExtensionDeepLink } from '../../shared/extensions/types'
|
||||
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
|
||||
import {
|
||||
buildContactSearchIndex,
|
||||
@@ -258,6 +265,8 @@ function App(): React.ReactElement {
|
||||
const [databaseEnvironment, setDatabaseEnvironment] = useState<DatabaseKeyEnvironment>()
|
||||
const connectionOperationRef = React.useRef(0)
|
||||
const [activePage, setActivePage] = useState<AppPage>('archive')
|
||||
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
|
||||
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
|
||||
/**
|
||||
* 「退群监控 ⇄ 自动化」之间的跨页深链。
|
||||
*
|
||||
@@ -1612,6 +1621,12 @@ function App(): React.ReactElement {
|
||||
const isGroupContact = (contact: Contact | null): boolean =>
|
||||
Boolean(contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom'))
|
||||
|
||||
/** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */
|
||||
const openExtensionDeepLink = (target: ExtensionDeepLink): void => {
|
||||
setExtensionDeepLink(target)
|
||||
handlePageChange('extensions')
|
||||
}
|
||||
|
||||
const handlePageChange = (page: AppPage): void => {
|
||||
setActivePage(page)
|
||||
if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact)
|
||||
@@ -2136,12 +2151,18 @@ function App(): React.ReactElement {
|
||||
openRuleRequest={automationOpenRuleRequest}
|
||||
onOpenModelSettings={openModelSettings}
|
||||
onOpenAgentHub={openAgentHub}
|
||||
onOpenExtension={openExtensionDeepLink}
|
||||
/>
|
||||
)
|
||||
case 'agent-hub':
|
||||
return <AgentHubWorkspace selfInfo={selfInfo} />
|
||||
case 'extensions':
|
||||
return <ExtensionWorkspace />
|
||||
return (
|
||||
<ExtensionWorkspace
|
||||
deepLink={extensionDeepLink}
|
||||
onConsumeDeepLink={() => setExtensionDeepLink(null)}
|
||||
/>
|
||||
)
|
||||
case 'api':
|
||||
return (
|
||||
<ApiWorkspace
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import {
|
||||
AUTOMATION_RULE_TEMPLATES,
|
||||
BUILTIN_DAILY_REPORT_RULE_ID,
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
calculateNextRunAt,
|
||||
@@ -18,12 +19,12 @@ import {
|
||||
} from '../../components/ui'
|
||||
import { RuleListPanel } from './RuleListPanel'
|
||||
import { RuleEditorPanel } from './RuleEditorPanel'
|
||||
import type { RuleTemplateCardModel } from './RuleListPanel'
|
||||
import type { ExtensionTemplateStatus } from '../../../../shared/extensions/templates'
|
||||
import type { ExtensionDeepLink, InstalledExtension } from '../../../../shared/extensions/types'
|
||||
import { ExecutionLogPanel } from './ExecutionLogPanel'
|
||||
import { ExecutionDetailDrawer } from './ExecutionDetailDrawer'
|
||||
import {
|
||||
AutomationRuleTypeTabs,
|
||||
type AutomationRuleTabType
|
||||
} from './AutomationRuleTypeTabs'
|
||||
import { AutomationRuleTypeTabs, type AutomationRuleTabType } from './AutomationRuleTypeTabs'
|
||||
import { MessageInsertSwitches } from './MessageInsertSwitches'
|
||||
import { ScheduledReportEditor } from './ScheduledReportEditor'
|
||||
import { ScheduledReportRuleList } from './ScheduledReportRuleList'
|
||||
@@ -36,12 +37,14 @@ import {
|
||||
resolveGroupDisplayName,
|
||||
type ScheduledReportDraft
|
||||
} from './model/scheduled-report-model'
|
||||
import {
|
||||
LeaveNotificationEditor,
|
||||
type LeaveNotificationSaveInput
|
||||
} from './LeaveNotificationEditor'
|
||||
import { LeaveNotificationEditor, type LeaveNotificationSaveInput } from './LeaveNotificationEditor'
|
||||
import type { LeaveNotificationContactOption } from './LeaveNotificationTargetPicker'
|
||||
import { UNAVAILABLE_STATUS, automationApi, isAutomationApiAvailable, type AutomationGroupOption } from './model/api'
|
||||
import {
|
||||
UNAVAILABLE_STATUS,
|
||||
automationApi,
|
||||
isAutomationApiAvailable,
|
||||
type AutomationGroupOption
|
||||
} from './model/api'
|
||||
|
||||
/**
|
||||
* AutomationWorkspace —— 自动化一级菜单。
|
||||
@@ -63,6 +66,16 @@ export interface AutomationOpenRuleRequest {
|
||||
requestId: number
|
||||
}
|
||||
|
||||
/** 可选能力加载:宿主没有该 API 时返回兜底值,不抛错。 */
|
||||
async function safeLoad<T>(loader: () => Promise<T> | undefined, fallback: T): Promise<T> {
|
||||
try {
|
||||
const result = await loader()
|
||||
return result ?? fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export interface AutomationWorkspaceProps {
|
||||
dbReady: boolean
|
||||
/** 发送能力不可用时,引导用户去设置页。 */
|
||||
@@ -75,6 +88,8 @@ export interface AutomationWorkspaceProps {
|
||||
onOpenAgentHub?: () => void
|
||||
/** 深链请求(来自退群监控页的「退群通知自动化」入口)。 */
|
||||
openRuleRequest?: AutomationOpenRuleRequest | null
|
||||
/** 跳到扩展中心并定位模板 / 扩展 / 开发引导(规则模板卡片用)。 */
|
||||
onOpenExtension?: (target: ExtensionDeepLink) => void
|
||||
}
|
||||
|
||||
interface EditorState {
|
||||
@@ -90,7 +105,8 @@ export function AutomationWorkspace({
|
||||
onOpenExitMonitorGroups,
|
||||
onOpenModelSettings,
|
||||
onOpenAgentHub,
|
||||
openRuleRequest
|
||||
openRuleRequest,
|
||||
onOpenExtension
|
||||
}: AutomationWorkspaceProps): React.ReactElement {
|
||||
const { toast } = useToast()
|
||||
const apiAvailable = React.useMemo(() => isAutomationApiAvailable(), [])
|
||||
@@ -100,7 +116,9 @@ export function AutomationWorkspace({
|
||||
const [rules, setRules] = React.useState<AutomationRule[]>([])
|
||||
const [groups, setGroups] = React.useState<AutomationGroupOption[]>([])
|
||||
const [executions, setExecutions] = React.useState<AutomationExecution[]>([])
|
||||
const [sendableContacts, setSendableContacts] = React.useState<LeaveNotificationContactOption[]>([])
|
||||
const [sendableContacts, setSendableContacts] = React.useState<LeaveNotificationContactOption[]>(
|
||||
[]
|
||||
)
|
||||
const [monitoredGroupCount, setMonitoredGroupCount] = React.useState(0)
|
||||
/** 已监控群聊清单(含显示名)—— 退群通知「通知群聊」二次勾选的候选项。 */
|
||||
const [monitoredGroups, setMonitoredGroups] = React.useState<AutomationGroupOption[]>([])
|
||||
@@ -109,6 +127,63 @@ export function AutomationWorkspace({
|
||||
const [saving, setSaving] = React.useState(false)
|
||||
const [busyRuleId, setBusyRuleId] = React.useState<string | null>(null)
|
||||
const [editor, setEditor] = React.useState<EditorState | null>(null)
|
||||
/** 规则模板依赖的本机事实:官方模板目录 + 已安装扩展。 */
|
||||
const [extensionTemplates, setExtensionTemplates] = React.useState<ExtensionTemplateStatus[]>([])
|
||||
const [installedExtensions, setInstalledExtensions] = React.useState<InstalledExtension[]>([])
|
||||
|
||||
/**
|
||||
* 规则模板卡片的真实状态。
|
||||
*
|
||||
* 只读「官方模板目录 + 已装扩展」,不在自动化页维护第二份安装状态。
|
||||
*/
|
||||
const ruleTemplates = React.useMemo<RuleTemplateCardModel[]>(() => {
|
||||
return AUTOMATION_RULE_TEMPLATES.map((template) => {
|
||||
const installed = installedExtensions.find((item) => item.id === template.extensionId)
|
||||
const catalog = extensionTemplates.find(
|
||||
(item) => item.template.templateId === template.templateId
|
||||
)
|
||||
if (!installed) {
|
||||
const reason =
|
||||
catalog?.state === 'damaged'
|
||||
? catalog.message
|
||||
: catalog?.state === 'conflict'
|
||||
? catalog.message
|
||||
: undefined
|
||||
return { ...template, state: 'not-installed', ...(reason ? { reason } : {}) }
|
||||
}
|
||||
if (!installed.compatibility.compatible) {
|
||||
return {
|
||||
...template,
|
||||
state: 'unavailable',
|
||||
reason: installed.compatibility.reason || '扩展与当前 TraceMemo 版本不兼容'
|
||||
}
|
||||
}
|
||||
if (installed.runtime.state === 'error') {
|
||||
return {
|
||||
...template,
|
||||
state: 'unavailable',
|
||||
reason: installed.runtime.lastError || '扩展运行异常'
|
||||
}
|
||||
}
|
||||
if (!installed.enabled) {
|
||||
return { ...template, state: 'installed-disabled', reason: '已安装但未启用' }
|
||||
}
|
||||
return { ...template, state: 'ready' }
|
||||
})
|
||||
}, [extensionTemplates, installedExtensions])
|
||||
|
||||
const useRuleTemplate = (template: RuleTemplateCardModel): void => {
|
||||
if (!template.actionId) return
|
||||
// 打开的是「新建」,不复用上一次日报的编辑目标。
|
||||
setEditor({ mode: 'create', rule: null, ruleType: 'daily_report' })
|
||||
toast({
|
||||
title: '已打开新建规则',
|
||||
description:
|
||||
`在执行动作里添加「${template.name}」,选择扩展动作 ${template.actionId}。` +
|
||||
'若机器人当前是主动订阅模式,规则路径会自动跳过,不会双回复。',
|
||||
variant: 'default'
|
||||
})
|
||||
}
|
||||
const [selectedExecution, setSelectedExecution] = React.useState<AutomationExecution | null>(null)
|
||||
const [pendingDelete, setPendingDelete] = React.useState<AutomationRule | null>(null)
|
||||
|
||||
@@ -131,6 +206,15 @@ export function AutomationWorkspace({
|
||||
automationApi.getMonitoredGroupCount(),
|
||||
automationApi.getMonitoredGroups()
|
||||
])
|
||||
// 扩展状态是「模板能不能用」的唯一依据:不自己维护第二份。
|
||||
// 扩展 API 在旧版宿主或测试环境里可能整体缺失,缺失时按空列表处理,
|
||||
// 卡片会退化成「未安装」,而不是让整个自动化页崩掉。
|
||||
const [nextTemplates, nextExtensions] = await Promise.all([
|
||||
safeLoad<ExtensionTemplateStatus[]>(() => window.api?.listExtensionTemplates?.(), []),
|
||||
safeLoad<InstalledExtension[]>(() => window.api?.listExtensions?.(), [])
|
||||
])
|
||||
setExtensionTemplates(nextTemplates)
|
||||
setInstalledExtensions(nextExtensions)
|
||||
setStatus(nextStatus)
|
||||
setRules(nextRules)
|
||||
setGroups(nextGroups)
|
||||
@@ -186,7 +270,6 @@ export function AutomationWorkspace({
|
||||
const leaveNotificationRule =
|
||||
rules.find((item) => item.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID) ?? null
|
||||
|
||||
|
||||
/** 「指定好友」目标的显示名(首页卡片用;拿不到时留空,不伪造)。 */
|
||||
const leaveContactName = React.useMemo((): string => {
|
||||
const target = leaveNotificationRule?.leaveNotification?.target
|
||||
@@ -413,9 +496,7 @@ export function AutomationWorkspace({
|
||||
* 走独立的 singleton upsert 通道:这条规则 id 固定,保存永远不会多出一条。
|
||||
* 保存成功后清掉迁移遗留的 `targetNeedsReview`(用户已经做过选择)。
|
||||
*/
|
||||
const handleLeaveNotificationSave = async (
|
||||
input: LeaveNotificationSaveInput
|
||||
): Promise<void> => {
|
||||
const handleLeaveNotificationSave = async (input: LeaveNotificationSaveInput): Promise<void> => {
|
||||
// 静默 return 会让"点保存没反应"变成用户眼里的坏掉,必须说出来。
|
||||
if (!leaveNotificationRule) {
|
||||
toast({
|
||||
@@ -522,7 +603,11 @@ export function AutomationWorkspace({
|
||||
<div className="automation-status-card">
|
||||
<span className="automation-status-label">发送能力</span>
|
||||
<span className={`automation-status-value ${capabilityReady ? 'ok' : 'warn'}`}>
|
||||
{capabilityReady ? '可以发送文字和图片' : capability.ready ? '发送能力不完整' : '尚未就绪'}
|
||||
{capabilityReady
|
||||
? '可以发送文字和图片'
|
||||
: capability.ready
|
||||
? '发送能力不完整'
|
||||
: '尚未就绪'}
|
||||
</span>
|
||||
<small className="automation-status-note">{capability.message}</small>
|
||||
{!capabilityReady && onOpenSendSettings ? (
|
||||
@@ -637,9 +722,7 @@ export function AutomationWorkspace({
|
||||
{...(onOpenModelSettings ? { onOpenModelSettings } : {})}
|
||||
{...(scheduledEditor.ruleId
|
||||
? (() => {
|
||||
const rule = scheduledRules.find(
|
||||
(item) => item.id === scheduledEditor.ruleId
|
||||
)
|
||||
const rule = scheduledRules.find((item) => item.id === scheduledEditor.ruleId)
|
||||
const legacy = rule?.scheduledReport?.legacyTarget
|
||||
return legacy ? { legacyTarget: legacy } : {}
|
||||
})()
|
||||
@@ -709,8 +792,8 @@ export function AutomationWorkspace({
|
||||
<div className="automation-notice warning automation-notice-stack">
|
||||
<p>没有找到内置的退群通知规则。</p>
|
||||
<small>
|
||||
这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本,
|
||||
请重启 TraceMemo —— 已经跑起来的主进程不会自动换成新代码。
|
||||
这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本, 请重启 TraceMemo ——
|
||||
已经跑起来的主进程不会自动换成新代码。
|
||||
</small>
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -760,6 +843,9 @@ export function AutomationWorkspace({
|
||||
onEditLeaveNotification={() =>
|
||||
setEditor({ mode: 'edit', rule: null, ruleType: 'leave_notification' })
|
||||
}
|
||||
ruleTemplates={ruleTemplates}
|
||||
onOpenExtension={onOpenExtension}
|
||||
onUseRuleTemplate={useRuleTemplate}
|
||||
/>
|
||||
) : (
|
||||
<ExecutionLogPanel
|
||||
@@ -777,7 +863,11 @@ export function AutomationWorkspace({
|
||||
/>
|
||||
|
||||
{pendingDelete ? (
|
||||
<div className="automation-confirm-layer" role="presentation" onClick={() => setPendingDelete(null)}>
|
||||
<div
|
||||
className="automation-confirm-layer"
|
||||
role="presentation"
|
||||
onClick={() => setPendingDelete(null)}
|
||||
>
|
||||
<div
|
||||
className="automation-confirm"
|
||||
role="alertdialog"
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import * as React from 'react'
|
||||
import type { AutomationAction } from '../../../../shared/automation'
|
||||
import type { ExtensionActionInfo } from '../../../../shared/extensions/types'
|
||||
import type { ExtensionActionInputSchema } from '../../../../shared/extensions/action-schema'
|
||||
import { Button, Input, Switch } from '../../components/ui'
|
||||
|
||||
interface ExtensionActionListProps {
|
||||
/** 完整动作数组(含固定动作),本组件只挑 `extensionAction`。 */
|
||||
actions: AutomationAction[]
|
||||
available: ExtensionActionInfo[]
|
||||
onChange: (next: AutomationAction[]) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展动作编辑区。
|
||||
*
|
||||
* 按**数组索引**定位要改的那一条:同类型动作可以有多个,
|
||||
* 按 `type` 批量更新会把它们一起改掉。
|
||||
*/
|
||||
export function ExtensionActionList({
|
||||
actions,
|
||||
available,
|
||||
onChange
|
||||
}: ExtensionActionListProps): React.ReactElement {
|
||||
const [pendingExtension, setPendingExtension] = React.useState('')
|
||||
const [pendingAction, setPendingAction] = React.useState('')
|
||||
|
||||
const extensionActions = actions
|
||||
.map((action, index) => ({ action, index }))
|
||||
.filter((item) => item.action.type === 'extensionAction')
|
||||
|
||||
const groups = React.useMemo(() => {
|
||||
const map = new Map<string, { name: string; actions: ExtensionActionInfo[] }>()
|
||||
for (const item of available) {
|
||||
const entry = map.get(item.extensionId) ?? { name: item.extensionName, actions: [] }
|
||||
entry.actions.push(item)
|
||||
map.set(item.extensionId, entry)
|
||||
}
|
||||
return Array.from(map.entries()).sort((left, right) =>
|
||||
left[1].name.localeCompare(right[1].name)
|
||||
)
|
||||
}, [available])
|
||||
|
||||
const patchAt = (index: number, patch: Partial<AutomationAction>): void => {
|
||||
onChange(
|
||||
actions.map((action, current) => (current === index ? { ...action, ...patch } : action))
|
||||
)
|
||||
}
|
||||
|
||||
const removeAt = (index: number): void => {
|
||||
onChange(actions.filter((_action, current) => current !== index))
|
||||
}
|
||||
|
||||
const addAction = (): void => {
|
||||
const info = available.find(
|
||||
(item) => item.extensionId === pendingExtension && item.actionId === pendingAction
|
||||
)
|
||||
if (!info) return
|
||||
const input: Record<string, unknown> = {}
|
||||
if (info.inputSchema) {
|
||||
for (const [key, field] of Object.entries(info.inputSchema.properties)) {
|
||||
if (field.default !== undefined) input[key] = field.default
|
||||
}
|
||||
}
|
||||
onChange([
|
||||
...actions,
|
||||
{
|
||||
type: 'extensionAction',
|
||||
enabled: true,
|
||||
extensionId: info.extensionId,
|
||||
actionId: info.actionId,
|
||||
input
|
||||
}
|
||||
])
|
||||
setPendingAction('')
|
||||
}
|
||||
|
||||
const actionsOfSelectedExtension = pendingExtension
|
||||
? available.filter((item) => item.extensionId === pendingExtension)
|
||||
: []
|
||||
|
||||
return (
|
||||
<div className="automation-extension-actions">
|
||||
{extensionActions.length === 0 ? (
|
||||
<p className="automation-muted">还没有扩展动作。扩展启用后这里会出现它注册的动作。</p>
|
||||
) : (
|
||||
extensionActions.map(({ action, index }) => {
|
||||
const info = available.find(
|
||||
(item) => item.extensionId === action.extensionId && item.actionId === action.actionId
|
||||
)
|
||||
const schema: ExtensionActionInputSchema | undefined = info?.inputSchema
|
||||
const input = action.input ?? {}
|
||||
return (
|
||||
<div
|
||||
key={`${action.extensionId}-${action.actionId}-${index}`}
|
||||
className="automation-action-row"
|
||||
>
|
||||
<div className="automation-action-main">
|
||||
<div className="automation-switch-row compact">
|
||||
<div>
|
||||
<span className="automation-field-label">
|
||||
{info?.title || action.actionId || '未知动作'}
|
||||
<span className="automation-extension-badge">
|
||||
{info?.extensionName || action.extensionId}
|
||||
</span>
|
||||
</span>
|
||||
<small>
|
||||
{info?.available
|
||||
? info.description || '扩展动作'
|
||||
: info?.unavailableReason || '依赖的扩展不可用,规则会保留但无法执行'}
|
||||
</small>
|
||||
</div>
|
||||
<Switch
|
||||
checked={action.enabled}
|
||||
onCheckedChange={(checked) => patchAt(index, { enabled: checked })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{schema && action.enabled && (
|
||||
<div className="automation-extension-fields">
|
||||
{Object.entries(schema.properties).map(([key, field]) => {
|
||||
const required = schema.required?.includes(key) === true
|
||||
const label = field.title || key
|
||||
const value = input[key]
|
||||
return (
|
||||
<label key={key} className="automation-field">
|
||||
<span className="automation-field-label">
|
||||
{label}
|
||||
{required && <span className="automation-required">*</span>}
|
||||
</span>
|
||||
{field.type === 'boolean' ? (
|
||||
<Switch
|
||||
checked={value === true}
|
||||
onCheckedChange={(checked) =>
|
||||
patchAt(index, { input: { ...input, [key]: checked } })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
type={field.type === 'string' ? 'text' : 'number'}
|
||||
value={value === undefined || value === null ? '' : String(value)}
|
||||
placeholder={field.description || ''}
|
||||
onChange={(event) => {
|
||||
const raw = event.target.value
|
||||
const next: unknown =
|
||||
field.type === 'string'
|
||||
? raw
|
||||
: raw === ''
|
||||
? undefined
|
||||
: Number(raw)
|
||||
patchAt(index, { input: { ...input, [key]: next } })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="automation-extension-row-actions">
|
||||
<Button size="sm" variant="ghost" onClick={() => removeAt(index)}>
|
||||
移除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
|
||||
<div className="automation-extension-add">
|
||||
<select
|
||||
className="automation-select"
|
||||
value={pendingExtension}
|
||||
aria-label="选择扩展"
|
||||
onChange={(event) => {
|
||||
setPendingExtension(event.target.value)
|
||||
setPendingAction('')
|
||||
}}
|
||||
>
|
||||
<option value="">选择扩展…</option>
|
||||
{groups.map(([extensionId, group]) => (
|
||||
<option key={extensionId} value={extensionId}>
|
||||
{group.name}
|
||||
{group.actions.every((item) => !item.available) ? '(不可用)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
className="automation-select"
|
||||
value={pendingAction}
|
||||
aria-label="选择动作"
|
||||
disabled={!pendingExtension}
|
||||
onChange={(event) => setPendingAction(event.target.value)}
|
||||
>
|
||||
<option value="">选择动作…</option>
|
||||
{actionsOfSelectedExtension.map((item) => (
|
||||
<option key={item.actionId} value={item.actionId} disabled={!item.available}>
|
||||
{item.title}
|
||||
{item.available ? '' : `(${item.unavailableReason || '不可用'})`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={!pendingExtension || !pendingAction}
|
||||
onClick={addAction}
|
||||
>
|
||||
添加扩展动作
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
} from '../../../../shared/automation'
|
||||
import { Button, Input, SegmentedControl, SegmentedControlItem, Switch } from '../../components/ui'
|
||||
import { EffectPreview } from './EffectPreview'
|
||||
import { ExtensionActionList } from './ExtensionActionList'
|
||||
import type { AutomationGroupOption } from './model/api'
|
||||
import type { ExtensionActionInfo } from '../../../../shared/extensions/types'
|
||||
|
||||
/**
|
||||
* RuleEditorPanel —— 规则编辑页(对应 Stitch 设计稿 1)。
|
||||
@@ -90,19 +92,56 @@ export function RuleEditorPanel({
|
||||
setValidationError('')
|
||||
}, [rule])
|
||||
|
||||
/** 扩展动作列表:随扩展启用/停用自动刷新,规则里保存的引用不会被清掉。 */
|
||||
const [extensionActions, setExtensionActions] = React.useState<ExtensionActionInfo[]>([])
|
||||
React.useEffect(() => {
|
||||
let active = true
|
||||
const load = (): void => {
|
||||
// 旧宿主或测试环境可能没有扩展 API:此时退化成「没有扩展动作」,
|
||||
// 不能让整个规则编辑器崩掉。
|
||||
const loader = window.api?.listExtensionActions
|
||||
if (!loader) {
|
||||
setExtensionActions([])
|
||||
return
|
||||
}
|
||||
void Promise.resolve(loader.call(window.api))
|
||||
.then((list) => {
|
||||
if (active) setExtensionActions(Array.isArray(list) ? list : [])
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
load()
|
||||
const subscribe = window.api?.onExtensionChanged
|
||||
const unsubscribe = subscribe ? subscribe.call(window.api, () => load()) : () => undefined
|
||||
return () => {
|
||||
active = false
|
||||
unsubscribe()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const patchConditions = (patch: Partial<AutomationRuleDraft['conditions']>): void => {
|
||||
setDraft((current) => ({ ...current, conditions: { ...current.conditions, ...patch } }))
|
||||
}
|
||||
|
||||
const patchAction = (type: AutomationActionType, patch: { enabled?: boolean; text?: string }): void => {
|
||||
/**
|
||||
* 按**索引**更新动作。
|
||||
*
|
||||
* 固定动作每类只有一条,但扩展动作可以有多条同类型:
|
||||
* 按 `type` 批量更新会把它们一起改掉。
|
||||
*/
|
||||
const patchActionAt = (index: number, patch: { enabled?: boolean; text?: string }): void => {
|
||||
if (index < 0) return
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
actions: current.actions.map((action) =>
|
||||
action.type === type ? { ...action, ...patch } : action
|
||||
actions: current.actions.map((action, currentIndex) =>
|
||||
currentIndex === index ? { ...action, ...patch } : action
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
const indexOfType = (type: AutomationActionType): number =>
|
||||
draft.actions.findIndex((action) => action.type === type)
|
||||
|
||||
const actionOf = (type: AutomationActionType): { enabled: boolean; text?: string } =>
|
||||
draft.actions.find((action) => action.type === type) ?? { enabled: false }
|
||||
|
||||
@@ -268,7 +307,11 @@ export function RuleEditorPanel({
|
||||
key={group.id}
|
||||
className={`automation-group-option ${checked ? 'selected' : ''}`}
|
||||
>
|
||||
<input type="checkbox" checked={checked} onChange={() => toggleGroup(group.id)} />
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => toggleGroup(group.id)}
|
||||
/>
|
||||
<span>{group.name}</span>
|
||||
</label>
|
||||
)
|
||||
@@ -305,9 +348,7 @@ export function RuleEditorPanel({
|
||||
const next = Number(event.target.value)
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
replyDelaySeconds: normalizeReplyDelaySeconds(
|
||||
Number.isFinite(next) ? next : 0
|
||||
)
|
||||
replyDelaySeconds: normalizeReplyDelaySeconds(Number.isFinite(next) ? next : 0)
|
||||
}))
|
||||
}}
|
||||
className="automation-number-input"
|
||||
@@ -326,13 +367,17 @@ export function RuleEditorPanel({
|
||||
</div>
|
||||
<Switch
|
||||
checked={action.enabled}
|
||||
onCheckedChange={(checked) => patchAction(meta.type, { enabled: checked })}
|
||||
onCheckedChange={(checked) =>
|
||||
patchActionAt(indexOfType(meta.type), { enabled: checked })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{meta.type === 'replyText' && action.enabled ? (
|
||||
<Input
|
||||
value={action.text ?? ''}
|
||||
onChange={(event) => patchAction(meta.type, { text: event.target.value })}
|
||||
onChange={(event) =>
|
||||
patchActionAt(indexOfType(meta.type), { text: event.target.value })
|
||||
}
|
||||
placeholder={DEFAULT_REPLY_TEXT}
|
||||
aria-label="回复内容"
|
||||
/>
|
||||
@@ -341,6 +386,18 @@ export function RuleEditorPanel({
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
<div className="automation-subsection">
|
||||
<div className="automation-subsection-heading">
|
||||
<h4>执行扩展动作</h4>
|
||||
<small>由扩展注册,参数按扩展声明的 Schema 填写</small>
|
||||
</div>
|
||||
<ExtensionActionList
|
||||
actions={draft.actions}
|
||||
available={extensionActions}
|
||||
onChange={(next) => setDraft((current) => ({ ...current, actions: next }))}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="automation-section">
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as React from 'react'
|
||||
import {
|
||||
AUTOMATION_RULE_TEMPLATES,
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
describeLeaveNotificationNotifyScope,
|
||||
describeLeaveNotificationTarget,
|
||||
@@ -8,6 +7,7 @@ import {
|
||||
describeRuleTrigger,
|
||||
type AutomationRule
|
||||
} from '../../../../shared/automation'
|
||||
import type { ExtensionDeepLink } from '../../../../shared/extensions/types'
|
||||
import { Button, Spinner, Switch } from '../../components/ui'
|
||||
|
||||
/**
|
||||
@@ -40,6 +40,25 @@ export interface ScheduledReportCardModel {
|
||||
nextRunLabel: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则模板卡片的本机状态。
|
||||
*
|
||||
* 由工作区根据「官方模板目录 + 已安装扩展 + 运行状态」算出,
|
||||
* 面板只负责渲染,不自己判断可用性。
|
||||
*/
|
||||
export interface RuleTemplateCardModel {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
templateId: string
|
||||
extensionId: string
|
||||
/** 没有动作的模板只能打开配置,不能「用规则触发」。 */
|
||||
actionId?: string
|
||||
state: 'not-installed' | 'installed-disabled' | 'ready' | 'unavailable'
|
||||
/** 不可用/需要处理时的真实原因。 */
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export interface RuleListPanelProps {
|
||||
rules: AutomationRule[]
|
||||
groups: Array<{ id: string; name: string }>
|
||||
@@ -55,6 +74,12 @@ export interface RuleListPanelProps {
|
||||
onEditLeaveNotification: () => void
|
||||
/** 打开「定时日报」规则类型(多条,所以是"管理"而不是"编辑")。 */
|
||||
onManageScheduledReport: () => void
|
||||
/** 规则模板卡片(真实状态)。 */
|
||||
ruleTemplates?: RuleTemplateCardModel[]
|
||||
/** 跳到扩展中心并定位模板/扩展/开发引导。 */
|
||||
onOpenExtension?: (target: ExtensionDeepLink) => void
|
||||
/** 用该模板预填一条引用扩展动作的规则。 */
|
||||
onUseRuleTemplate?: (template: RuleTemplateCardModel) => void
|
||||
}
|
||||
|
||||
/** 把规则里的 conversationIds 翻成群名;找不到时显示占位而不是裸 id。 */
|
||||
@@ -92,7 +117,10 @@ export function RuleListPanel({
|
||||
onDelete,
|
||||
onCreate,
|
||||
onEditLeaveNotification,
|
||||
onManageScheduledReport
|
||||
onManageScheduledReport,
|
||||
ruleTemplates,
|
||||
onOpenExtension,
|
||||
onUseRuleTemplate
|
||||
}: RuleListPanelProps): React.ReactElement {
|
||||
// 退群通知有自己的卡片,别在「已配置的自动化」里重复渲染一遍。
|
||||
const configuredRules = rules.filter((rule) => rule.id !== BUILTIN_LEAVE_NOTIFICATION_RULE_ID)
|
||||
@@ -267,16 +295,99 @@ export function RuleListPanel({
|
||||
<h2>更多模板</h2>
|
||||
</div>
|
||||
<div className="automation-template-grid">
|
||||
{AUTOMATION_RULE_TEMPLATES.map((template) => (
|
||||
<article key={template.id} className="automation-template-card">
|
||||
<div className="automation-template-title">
|
||||
<h3>{template.name}</h3>
|
||||
<span className="automation-template-flag">即将支持</span>
|
||||
</div>
|
||||
<p>{template.description}</p>
|
||||
{template.unavailableReason ? <small>{template.unavailableReason}</small> : null}
|
||||
</article>
|
||||
))}
|
||||
{(ruleTemplates ?? []).map((template) => {
|
||||
const badge =
|
||||
template.state === 'ready'
|
||||
? '已就绪'
|
||||
: template.state === 'installed-disabled'
|
||||
? '已安装 · 未启用'
|
||||
: template.state === 'not-installed'
|
||||
? '未安装'
|
||||
: '不可用'
|
||||
return (
|
||||
<article key={template.id} className="automation-template-card">
|
||||
<div className="automation-template-title">
|
||||
<h3>{template.name}</h3>
|
||||
<span
|
||||
className={
|
||||
template.state === 'ready'
|
||||
? 'automation-template-flag is-ready'
|
||||
: 'automation-template-flag'
|
||||
}
|
||||
>
|
||||
{badge}
|
||||
</span>
|
||||
</div>
|
||||
<p>{template.description}</p>
|
||||
{template.reason ? <small>{template.reason}</small> : null}
|
||||
|
||||
<div className="automation-template-actions">
|
||||
{template.state === 'not-installed' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenExtension?.({ templateId: template.templateId })}
|
||||
>
|
||||
去扩展中心安装 →
|
||||
</Button>
|
||||
)}
|
||||
{template.state === 'installed-disabled' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenExtension?.({ extensionId: template.extensionId })}
|
||||
>
|
||||
去启用 →
|
||||
</Button>
|
||||
)}
|
||||
{template.state === 'ready' && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenExtension?.({ extensionId: template.extensionId })}
|
||||
>
|
||||
打开扩展配置 →
|
||||
</Button>
|
||||
{template.actionId ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onUseRuleTemplate?.(template)}
|
||||
>
|
||||
用规则触发
|
||||
</Button>
|
||||
) : (
|
||||
<small className="automation-template-note">
|
||||
该扩展没有注册自动化动作,靠消息事件触发
|
||||
</small>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* 模板之外还要有出口:没有现成模板可用时,用户应该能自己做一个。 */}
|
||||
<article className="automation-template-card is-guide">
|
||||
<div className="automation-template-title">
|
||||
<h3>做自己的扩展</h3>
|
||||
</div>
|
||||
<p>
|
||||
从官方模板克隆一份代码,改完直接在本地调试;官方升级不会覆盖你的改动。 也可以链接已经
|
||||
clone 到别处的项目。
|
||||
</p>
|
||||
<div className="automation-template-actions">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenExtension?.({ development: true })}
|
||||
>
|
||||
开始二次开发 →
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import * as React from 'react'
|
||||
import { Button } from '../../components/ui'
|
||||
import type { ExtensionTemplateEntry } from '../../../../shared/extensions/templates'
|
||||
|
||||
interface CreateProjectDialogProps {
|
||||
template: ExtensionTemplateEntry
|
||||
busy: boolean
|
||||
onCancel: () => void
|
||||
onSubmit: (input: { extensionId: string; name: string }) => void
|
||||
}
|
||||
|
||||
const ID_PATTERN =
|
||||
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
|
||||
|
||||
/** 默认 id 从模板 id 派生,用户可以直接改。 */
|
||||
function suggestExtensionId(templateId: string): string {
|
||||
const suffix = templateId.replace(/[^a-z0-9-]/gi, '-').toLowerCase()
|
||||
return `com.example.${suffix}-dev`
|
||||
}
|
||||
|
||||
/**
|
||||
* 从模板创建独立项目。
|
||||
*
|
||||
* 只收集「新 id」和「名称」:目录由调用方先选好,创建过程在主进程完成,
|
||||
* 这里不做任何文件操作。
|
||||
*/
|
||||
export function CreateProjectDialog({
|
||||
template,
|
||||
busy,
|
||||
onCancel,
|
||||
onSubmit
|
||||
}: CreateProjectDialogProps): React.ReactElement {
|
||||
const [extensionId, setExtensionId] = React.useState(() =>
|
||||
suggestExtensionId(template.templateId)
|
||||
)
|
||||
const [name, setName] = React.useState(`${template.name}(我的版本)`)
|
||||
|
||||
const trimmedId = extensionId.trim().toLowerCase()
|
||||
const idValid = ID_PATTERN.test(trimmedId)
|
||||
const conflictsWithTemplate = trimmedId === template.extensionId
|
||||
const canSubmit = idValid && !conflictsWithTemplate && !busy
|
||||
|
||||
return (
|
||||
<div className="extension-project-dialog" role="dialog" aria-label="从模板创建项目">
|
||||
<h4>从「{template.name}」创建独立项目</h4>
|
||||
<p className="extension-muted">
|
||||
会在你选择的目录里生成完整源码;不会复制任何配置、Cookie 或聊天数据。
|
||||
</p>
|
||||
|
||||
<label className="extension-field">
|
||||
<span>扩展 ID</span>
|
||||
<input
|
||||
value={extensionId}
|
||||
spellCheck={false}
|
||||
onChange={(event) => setExtensionId(event.target.value)}
|
||||
placeholder="com.acme.my-bot"
|
||||
/>
|
||||
</label>
|
||||
{!idValid && (
|
||||
<p className="extension-field-error">id 必须是反向域名格式(小写字母、数字、连字符)</p>
|
||||
)}
|
||||
{conflictsWithTemplate && (
|
||||
<p className="extension-field-error">不能沿用模板原 id,否则会和官方模板冲突</p>
|
||||
)}
|
||||
|
||||
<label className="extension-field">
|
||||
<span>显示名称</span>
|
||||
<input value={name} maxLength={60} onChange={(event) => setName(event.target.value)} />
|
||||
</label>
|
||||
|
||||
<div className="extension-project-dialog-actions">
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={onCancel}>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!canSubmit}
|
||||
onClick={() => onSubmit({ extensionId: trimmedId, name: name.trim() })}
|
||||
>
|
||||
{busy ? '创建中…' : '选择目录并创建'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import * as React from 'react'
|
||||
import { Button } from '../../components/ui'
|
||||
|
||||
interface DevelopmentGuideProps {
|
||||
/** 回到扩展列表。 */
|
||||
onBack: () => void
|
||||
/** 打开「从模板创建项目」:切到模板画廊并展开第一条可用模板。 */
|
||||
onCreateProject: () => void
|
||||
/** 链接已有本地项目。 */
|
||||
onLinkProject: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 二次开发引导。
|
||||
*
|
||||
* 这里**不复制文档正文**:文档在 `docs/extensions/`,正文改一次要同步两处必然不一致。
|
||||
* 界面只负责把「从哪开始、做完在哪看效果」讲清楚,并指到文档。
|
||||
*/
|
||||
const DOCS: Array<{ name: string; file: string; description: string }> = [
|
||||
{
|
||||
name: '快速开始',
|
||||
file: 'docs/extensions/getting-started.md',
|
||||
description: '最小 manifest、目录结构、第一次跑起来'
|
||||
},
|
||||
{
|
||||
name: '克隆与改造成自己的扩展',
|
||||
file: 'docs/extensions/clone-and-customize.md',
|
||||
description: '从官方模板复制代码、改 id、改成自己的逻辑'
|
||||
},
|
||||
{
|
||||
name: 'API 参考',
|
||||
file: 'docs/extensions/api-reference.md',
|
||||
description: 'manifest 字段、权限表、tm.* 能力清单'
|
||||
},
|
||||
{
|
||||
name: '架构与安全边界',
|
||||
file: 'docs/extensions/architecture.md',
|
||||
description: '代码在哪、数据在哪、页面为什么在 iframe 里'
|
||||
}
|
||||
]
|
||||
|
||||
export function DevelopmentGuide({
|
||||
onBack,
|
||||
onCreateProject,
|
||||
onLinkProject
|
||||
}: DevelopmentGuideProps): React.ReactElement {
|
||||
return (
|
||||
<div className="extension-development-guide">
|
||||
<header className="extension-guide-header">
|
||||
<div>
|
||||
<h3>二次开发</h3>
|
||||
<p>
|
||||
扩展代码放在你自己的目录,TraceMemo 直接运行它。改完点「重新加载」即可生效,
|
||||
不需要重新安装;官方升级也不会覆盖你的代码。
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" onClick={onBack}>
|
||||
← 返回扩展列表
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<ol className="extension-guide-steps">
|
||||
<li>
|
||||
<span className="extension-guide-index">1</span>
|
||||
<div>
|
||||
<strong>拿到一份代码</strong>
|
||||
<p>
|
||||
从官方模板生成独立项目(会替换成你自己的扩展 id),或直接链接已经在别处 clone
|
||||
好的目录。
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<span className="extension-guide-index">2</span>
|
||||
<div>
|
||||
<strong>链接到 TraceMemo</strong>
|
||||
<p>
|
||||
链接后代码不复制:宿主直接读你选的目录。配置、日志、缓存仍然写在 TraceMemo
|
||||
的用户数据目录,不会污染你的仓库。
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<span className="extension-guide-index">3</span>
|
||||
<div>
|
||||
<strong>改完重新加载</strong>
|
||||
<p>
|
||||
后台代码改动点「重新加载」;页面改动刷新 iframe 即可。Manifest 新增权限不会自动授予,
|
||||
需要在详情页逐项确认。
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<div className="extension-guide-actions">
|
||||
<Button size="sm" onClick={onCreateProject}>
|
||||
从模板创建项目
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={onLinkProject}>
|
||||
链接本地项目
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<section className="extension-guide-docs">
|
||||
<h4>开发文档</h4>
|
||||
<ul>
|
||||
{DOCS.map((doc) => (
|
||||
<li key={doc.file}>
|
||||
<div>
|
||||
<strong>{doc.name}</strong>
|
||||
<span className="extension-muted">{doc.description}</span>
|
||||
</div>
|
||||
<code>{doc.file}</code>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="extension-muted">
|
||||
文档随仓库分发,路径以上方为准;打包后的应用里不包含 docs 目录。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="extension-guide-boundary">
|
||||
<h4>几个边界</h4>
|
||||
<ul>
|
||||
<li>不会自动安装、自动启用或自动创建规则——每一步都要你点。</li>
|
||||
<li>移除链接只断开引用,不会删除你的项目目录。</li>
|
||||
<li>
|
||||
页面跑在 sandbox iframe 里,只能调用你自己后台注册的处理器,拿不到 Node 或
|
||||
<code>window.api</code>。
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import * as React from 'react'
|
||||
import {
|
||||
EXTENSION_PERMISSION_INFO,
|
||||
sortPermissionsByRisk,
|
||||
type ExtensionPermission
|
||||
} from '../../../../shared/extensions/permissions'
|
||||
import type { ExtensionTemplateStatus } from '../../../../shared/extensions/templates'
|
||||
import { Button, Spinner } from '../../components/ui'
|
||||
|
||||
interface ExtensionTemplateGalleryProps {
|
||||
templates: ExtensionTemplateStatus[]
|
||||
loading: boolean
|
||||
busyId: string | null
|
||||
onInstall: (templateId: string) => void
|
||||
/** 从该模板生成独立项目;未提供时不显示入口。 */
|
||||
onCreateProject?: (templateId: string) => void
|
||||
/** 深链定位:自动展开该模板的详情。 */
|
||||
focusTemplateId?: string | null
|
||||
}
|
||||
|
||||
const STATE_LABELS: Record<ExtensionTemplateStatus['state'], string> = {
|
||||
'not-installed': '未安装',
|
||||
installed: '已安装',
|
||||
'update-available': '有更新',
|
||||
conflict: '已被占用',
|
||||
unsupported: '不支持当前平台',
|
||||
damaged: '资源损坏'
|
||||
}
|
||||
|
||||
function stateTone(state: ExtensionTemplateStatus['state']): string {
|
||||
if (state === 'not-installed' || state === 'installed') return 'muted'
|
||||
if (state === 'update-available') return 'warning'
|
||||
return 'danger'
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (!bytes) return '—'
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
/**
|
||||
* 官方模板画廊。
|
||||
*
|
||||
* 只负责展示与触发安装;是否可安装、装完是什么状态全部来自主进程,
|
||||
* 这里不做第二套判断,避免界面和实际能力说两套话。
|
||||
*/
|
||||
export function ExtensionTemplateGallery({
|
||||
templates,
|
||||
loading,
|
||||
busyId,
|
||||
onInstall,
|
||||
onCreateProject,
|
||||
focusTemplateId
|
||||
}: ExtensionTemplateGalleryProps): React.ReactElement {
|
||||
const [expanded, setExpanded] = React.useState<string | null>(null)
|
||||
|
||||
// 深链进来时展开目标模板;滚动交给浏览器默认行为即可。
|
||||
React.useEffect(() => {
|
||||
if (focusTemplateId) setExpanded(focusTemplateId)
|
||||
}, [focusTemplateId])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="extension-template-empty">
|
||||
<Spinner />
|
||||
<p>正在读取官方模板…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (templates.length === 0) {
|
||||
return (
|
||||
<div className="extension-template-empty">
|
||||
<h3>官方模板</h3>
|
||||
<p>当前安装包没有携带模板资源。如果你是从源码运行,请先执行模板构建脚本。</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="extension-template-gallery">
|
||||
<header className="extension-template-header">
|
||||
<div>
|
||||
<h3>官方模板</h3>
|
||||
<p>安装后仍需你确认权限并手动启用,不会自动运行。</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<ul className="extension-template-list">
|
||||
{templates.map((item) => {
|
||||
const { template } = item
|
||||
const isOpen = expanded === template.templateId
|
||||
const canInstall = item.state === 'not-installed' || item.state === 'update-available'
|
||||
const blocked =
|
||||
item.state === 'conflict' || item.state === 'damaged' || item.state === 'unsupported'
|
||||
const missingBlocking = item.dependencies.checks.filter(
|
||||
(check) => check.blocking && !check.ok
|
||||
)
|
||||
|
||||
return (
|
||||
<li key={template.templateId} className="extension-template-card">
|
||||
<div className="extension-template-card-head">
|
||||
<div>
|
||||
<div className="extension-template-title">
|
||||
<strong>{template.name}</strong>
|
||||
<span className="extension-template-version">v{template.version}</span>
|
||||
<span className={`extension-grant tone-${stateTone(item.state)}`}>
|
||||
{STATE_LABELS[item.state]}
|
||||
</span>
|
||||
</div>
|
||||
<p className="extension-template-desc">
|
||||
{template.description || '官方提供的扩展示例。'}
|
||||
</p>
|
||||
<p className="extension-template-meta">
|
||||
{template.fileCount} 个文件 · {formatBytes(template.bytes)}
|
||||
{item.installedVersion && item.state !== 'not-installed'
|
||||
? ` · 已安装 v${item.installedVersion}`
|
||||
: ''}
|
||||
</p>
|
||||
</div>
|
||||
<div className="extension-template-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setExpanded(isOpen ? null : template.templateId)}
|
||||
>
|
||||
{isOpen ? '收起详情' : '查看详情'}
|
||||
</Button>
|
||||
{onCreateProject && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busyId === `create:${template.templateId}`}
|
||||
onClick={() => onCreateProject(template.templateId)}
|
||||
>
|
||||
创建项目
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!canInstall || busyId === template.templateId}
|
||||
onClick={() => onInstall(template.templateId)}
|
||||
>
|
||||
{busyId === template.templateId
|
||||
? '安装中…'
|
||||
: item.state === 'update-available'
|
||||
? '更新'
|
||||
: '安装'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{item.message && <p className="extension-template-warning">{item.message}</p>}
|
||||
|
||||
{missingBlocking.length > 0 && (
|
||||
<p className="extension-template-warning">
|
||||
缺少 {missingBlocking.map((check) => check.label).join('、')}
|
||||
:安装后可以查看配置页,但主要功能暂时不可用。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{isOpen && (
|
||||
<div className="extension-template-detail">
|
||||
<section>
|
||||
<h4>权限</h4>
|
||||
<ul className="extension-permission-list">
|
||||
{sortPermissionsByRisk(template.permissions).map(
|
||||
(permission: ExtensionPermission) => (
|
||||
<li key={permission}>
|
||||
<div>
|
||||
<span className="extension-permission-label">
|
||||
{EXTENSION_PERMISSION_INFO[permission].label}
|
||||
</span>
|
||||
<span
|
||||
className={`extension-permission-risk risk-${EXTENSION_PERMISSION_INFO[permission].risk}`}
|
||||
>
|
||||
{EXTENSION_PERMISSION_INFO[permission].risk === 'high'
|
||||
? '高'
|
||||
: EXTENSION_PERMISSION_INFO[permission].risk === 'medium'
|
||||
? '中'
|
||||
: '低'}
|
||||
</span>
|
||||
</div>
|
||||
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
|
||||
</li>
|
||||
)
|
||||
)}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>依赖</h4>
|
||||
{item.dependencies.checks.length === 0 ? (
|
||||
<p className="extension-muted">该模板不需要额外依赖。</p>
|
||||
) : (
|
||||
<ul className="extension-template-deps">
|
||||
{item.dependencies.checks.map((check) => (
|
||||
<li key={check.id}>
|
||||
<span
|
||||
className={`extension-dot ${check.ok ? 'is-ok' : 'is-missing'}`}
|
||||
/>
|
||||
<span>{check.label}</span>
|
||||
<span className="extension-muted">{check.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.state === 'conflict' && (
|
||||
<p className="extension-muted">
|
||||
你之前用同一扩展 ID 安装过其他来源的扩展。请先卸载它,或改用「安装 ZIP」手动更新。
|
||||
</p>
|
||||
)}
|
||||
{blocked && item.state === 'damaged' && (
|
||||
<p className="extension-muted">
|
||||
模板资源与你安装的版本不匹配,建议重新安装 TraceMemo。
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,10 +7,19 @@ import {
|
||||
import type {
|
||||
ExtensionLogEntry,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionSystemHealth,
|
||||
InstalledExtension
|
||||
} from '../../../../shared/extensions/types'
|
||||
import type {
|
||||
ExtensionTemplateEntry,
|
||||
ExtensionTemplateStatus
|
||||
} from '../../../../shared/extensions/templates'
|
||||
import type { ExtensionDeepLink } from '../../../../shared/extensions/types'
|
||||
import { Button, Spinner, useToast } from '../../components/ui'
|
||||
import { ExtensionPageHost } from './ExtensionPageHost'
|
||||
import { CreateProjectDialog } from './CreateProjectDialog'
|
||||
import { DevelopmentGuide } from './DevelopmentGuide'
|
||||
import { ExtensionTemplateGallery } from './ExtensionTemplateGallery'
|
||||
|
||||
const STATUS_LABELS: Record<InstalledExtension['runtime']['state'], string> = {
|
||||
inactive: '未运行',
|
||||
@@ -32,7 +41,17 @@ function statusTone(extension: InstalledExtension): 'success' | 'warning' | 'dan
|
||||
return 'warning'
|
||||
}
|
||||
|
||||
export function ExtensionWorkspace(): React.ReactElement {
|
||||
export interface ExtensionWorkspaceProps {
|
||||
/** 从其它页面跳过来时的定位目标。 */
|
||||
deepLink?: ExtensionDeepLink | null
|
||||
/** 消费后清空,避免返回再进来又跳一次。 */
|
||||
onConsumeDeepLink?: () => void
|
||||
}
|
||||
|
||||
export function ExtensionWorkspace({
|
||||
deepLink,
|
||||
onConsumeDeepLink
|
||||
}: ExtensionWorkspaceProps = {}): React.ReactElement {
|
||||
const { toast } = useToast()
|
||||
const [extensions, setExtensions] = React.useState<InstalledExtension[]>([])
|
||||
const [selectedId, setSelectedId] = React.useState<string | null>(null)
|
||||
@@ -41,10 +60,36 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
const [page, setPage] = React.useState<ExtensionPageDescriptor | null>(null)
|
||||
const [pendingEnable, setPendingEnable] = React.useState<InstalledExtension | null>(null)
|
||||
const [pendingUninstall, setPendingUninstall] = React.useState<string | null>(null)
|
||||
const [health, setHealth] = React.useState<ExtensionSystemHealth | null>(null)
|
||||
const [templates, setTemplates] = React.useState<ExtensionTemplateStatus[]>([])
|
||||
const [templatesLoading, setTemplatesLoading] = React.useState(true)
|
||||
const [installingTemplate, setInstallingTemplate] = React.useState<string | null>(null)
|
||||
/** 右侧主区域:扩展列表 or 官方模板画廊。 */
|
||||
const [view, setView] = React.useState<'extensions' | 'templates' | 'guide'>('extensions')
|
||||
/** 深链定位的模板:进入画廊时自动展开它。 */
|
||||
const [focusedTemplateId, setFocusedTemplateId] = React.useState<string | null>(null)
|
||||
/** 正在创建项目的模板;非空时显示创建对话框。 */
|
||||
const [creatingTemplate, setCreatingTemplate] = React.useState<ExtensionTemplateEntry | null>(
|
||||
null
|
||||
)
|
||||
/** 高风险权限的二次确认;低风险直接授权。 */
|
||||
const [pendingGrant, setPendingGrant] = React.useState<{
|
||||
extensionId: string
|
||||
permission: ExtensionPermission
|
||||
} | null>(null)
|
||||
/** 「转为正式安装」的二次确认。 */
|
||||
const [pendingConvert, setPendingConvert] = React.useState<InstalledExtension | null>(null)
|
||||
|
||||
const refresh = React.useCallback(async (): Promise<void> => {
|
||||
const list = await window.api.listExtensions()
|
||||
const [list, systemHealth, templateList] = await Promise.all([
|
||||
window.api.listExtensions(),
|
||||
window.api.getExtensionHealth().catch(() => null),
|
||||
window.api.listExtensionTemplates().catch(() => [])
|
||||
])
|
||||
setExtensions(list)
|
||||
setHealth(systemHealth)
|
||||
setTemplates(templateList)
|
||||
setTemplatesLoading(false)
|
||||
setSelectedId((current) => {
|
||||
if (current && list.some((item) => item.id === current)) return current
|
||||
return list[0]?.id ?? null
|
||||
@@ -59,6 +104,26 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
return unsubscribe
|
||||
}, [refresh])
|
||||
|
||||
/**
|
||||
* 消费深链:只切视图与选中项,不触发任何安装/启用动作。
|
||||
* 真正的操作仍要用户在界面上点。
|
||||
*/
|
||||
React.useEffect(() => {
|
||||
if (!deepLink) return
|
||||
if (deepLink.development) {
|
||||
setView('guide')
|
||||
}
|
||||
if (deepLink.templateId) {
|
||||
setView('templates')
|
||||
setFocusedTemplateId(deepLink.templateId)
|
||||
}
|
||||
if (deepLink.extensionId) {
|
||||
setView('extensions')
|
||||
setSelectedId(deepLink.extensionId)
|
||||
}
|
||||
onConsumeDeepLink?.()
|
||||
}, [deepLink, onConsumeDeepLink])
|
||||
|
||||
const selected = React.useMemo(
|
||||
() => extensions.find((item) => item.id === selectedId) ?? null,
|
||||
[extensions, selectedId]
|
||||
@@ -179,6 +244,284 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
}
|
||||
}
|
||||
|
||||
/** 授权 manifest 新声明的权限;后台会重启,新能力立即生效。 */
|
||||
const grantPending = async (extension: InstalledExtension): Promise<void> => {
|
||||
if (extension.pendingPermissions.length === 0) return
|
||||
const result = await run(() =>
|
||||
window.api.grantExtensionPermissions(extension.id, extension.pendingPermissions)
|
||||
)
|
||||
if (result?.success) {
|
||||
toast({ title: '权限已更新', description: extension.name, variant: 'success' })
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '授权失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 重置损坏的扩展配置;损坏现场已经由存储层另存。 */
|
||||
const resetStorage = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.resetExtensionStorage(extension.id))
|
||||
if (result?.success) {
|
||||
toast({ title: '配置已重置', description: extension.name, variant: 'success' })
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '重置失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const grantPermission = async (
|
||||
extension: InstalledExtension,
|
||||
permission: ExtensionPermission
|
||||
): Promise<void> => {
|
||||
const result = await run(() => window.api.grantExtensionPermissions(extension.id, [permission]))
|
||||
setPendingGrant(null)
|
||||
if (result?.success) {
|
||||
toast({
|
||||
title: '已授权',
|
||||
description: EXTENSION_PERMISSION_INFO[permission].label,
|
||||
variant: 'success'
|
||||
})
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '授权失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const revokePermission = async (
|
||||
extension: InstalledExtension,
|
||||
permission: ExtensionPermission
|
||||
): Promise<void> => {
|
||||
const result = await run(() => window.api.revokeExtensionPermission(extension.id, permission))
|
||||
if (result?.success) {
|
||||
toast({
|
||||
title: '已撤销',
|
||||
description: EXTENSION_PERMISSION_INFO[permission].label,
|
||||
variant: 'success'
|
||||
})
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '撤销失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 接受从备份恢复出来的配置;之后才允许启用该扩展。 */
|
||||
const acknowledgeStorage = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.acknowledgeExtensionStorage(extension.id))
|
||||
if (result?.success) {
|
||||
toast({ title: '已接受恢复的配置', description: '现在可以启用该扩展', variant: 'success' })
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/** 把状态记录的版本对齐到磁盘上的 manifest。 */
|
||||
const adoptInstalledCode = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.adoptExtensionCode(extension.id))
|
||||
if (result?.success) {
|
||||
toast({ title: '已采用当前代码版本', description: extension.name, variant: 'success' })
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/** 把升级过渡备份换回来。 */
|
||||
const rollbackUpgrade = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.rollbackExtensionUpgrade(extension.id))
|
||||
if (result?.success) {
|
||||
toast({ title: '已回滚到备份版本', description: extension.name, variant: 'success' })
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/** 确认「状态文件曾损坏并恢复」,只清除提示。 */
|
||||
const acknowledgeRecovery = async (): Promise<void> => {
|
||||
const result = await run(() => window.api.acknowledgeExtensionRecovery())
|
||||
if (result?.success) await refresh()
|
||||
}
|
||||
|
||||
const installTemplate = async (templateId: string): Promise<void> => {
|
||||
setInstallingTemplate(templateId)
|
||||
try {
|
||||
const result = await window.api.installExtensionTemplate(templateId)
|
||||
if (!result.success) {
|
||||
toast({
|
||||
title: '模板安装失败',
|
||||
description: result.error?.message || '安装失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
return
|
||||
}
|
||||
await refresh()
|
||||
setView('extensions')
|
||||
if (result.extension) setSelectedId(result.extension.id)
|
||||
toast({
|
||||
title: '模板已安装',
|
||||
description: `${result.extension?.name || ''} 需要你确认权限后手动启用`.trim(),
|
||||
variant: 'success'
|
||||
})
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: '模板安装失败',
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive'
|
||||
})
|
||||
} finally {
|
||||
setInstallingTemplate(null)
|
||||
}
|
||||
}
|
||||
|
||||
/** 链接外部开发项目;目录由主进程再校验一次。 */
|
||||
const linkProject = async (): Promise<void> => {
|
||||
const directory = await window.api.pickExtensionProjectDirectory()
|
||||
if (!directory) return
|
||||
const result = await run(() => window.api.linkExtensionDevelopment(directory))
|
||||
if (result?.success) {
|
||||
toast({
|
||||
title: '已链接开发项目',
|
||||
description: '确认权限后即可启用;修改代码后可点「重新加载」',
|
||||
variant: 'success'
|
||||
})
|
||||
await refresh()
|
||||
setView('extensions')
|
||||
if (result.extension) setSelectedId(result.extension.id)
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '链接失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const submitCreateProject = async (input: {
|
||||
extensionId: string
|
||||
name: string
|
||||
}): Promise<void> => {
|
||||
const template = creatingTemplate
|
||||
if (!template) return
|
||||
const targetDirectory = await window.api.pickExtensionProjectDirectory()
|
||||
if (!targetDirectory) return
|
||||
setInstallingTemplate(`create:${template.templateId}`)
|
||||
try {
|
||||
const result = await window.api.createExtensionProject({
|
||||
templateId: template.templateId,
|
||||
targetDirectory,
|
||||
extensionId: input.extensionId,
|
||||
name: input.name
|
||||
})
|
||||
if (!result.success) {
|
||||
toast({
|
||||
title: '创建项目失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
return
|
||||
}
|
||||
setCreatingTemplate(null)
|
||||
toast({
|
||||
title: '项目已生成',
|
||||
description: result.projectPath || '',
|
||||
variant: 'success'
|
||||
})
|
||||
await refresh()
|
||||
} finally {
|
||||
setInstallingTemplate(null)
|
||||
}
|
||||
}
|
||||
|
||||
const reloadDevelopment = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.reloadExtensionDevelopment(extension.id))
|
||||
if (result?.success) {
|
||||
toast({ title: '已重新加载', description: extension.name, variant: 'success' })
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '重新加载失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
await refresh()
|
||||
}
|
||||
|
||||
const unlinkDevelopment = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.unlinkExtensionDevelopment(extension.id, true))
|
||||
if (result?.success) {
|
||||
toast({
|
||||
title: '已移除开发链接',
|
||||
description: '外部源码目录没有被删除',
|
||||
variant: 'success'
|
||||
})
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '移除失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const convertDevelopment = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await run(() => window.api.convertExtensionDevelopment(extension.id))
|
||||
if (result?.success) {
|
||||
toast({ title: '已转为正式安装', description: extension.name, variant: 'success' })
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '转换失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const exportProject = async (extension: InstalledExtension): Promise<void> => {
|
||||
const targetDirectory = await window.api.pickExtensionProjectDirectory()
|
||||
if (!targetDirectory) return
|
||||
const result = await run(() =>
|
||||
window.api.exportExtensionAsProject(extension.id, targetDirectory)
|
||||
)
|
||||
if (result?.success) {
|
||||
toast({
|
||||
title: '已导出为开发项目',
|
||||
description: result.projectPath || '',
|
||||
variant: 'success'
|
||||
})
|
||||
await refresh()
|
||||
} else if (result && !result.success) {
|
||||
toast({
|
||||
title: '导出失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const openDevelopmentSource = async (extension: InstalledExtension): Promise<void> => {
|
||||
const result = await window.api.openExtensionDevelopmentSource(extension.id)
|
||||
if (!result.success) {
|
||||
toast({
|
||||
title: '无法打开源码目录',
|
||||
description: result.error?.message || '目录不可用',
|
||||
variant: 'destructive'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (page) {
|
||||
return (
|
||||
<ExtensionPageHost
|
||||
@@ -201,6 +544,52 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
</div>
|
||||
<span className="extension-count">{extensions.length}</span>
|
||||
</header>
|
||||
{health && health.registry.state !== 'ok' && (
|
||||
<div className="extension-health-banner">
|
||||
<span>
|
||||
{health.registry.state === 'unreadable'
|
||||
? '扩展状态文件损坏且无法恢复,已停止写入以保留现场。请保留 extensions-state 下的损坏文件。'
|
||||
: health.registry.message || '扩展状态文件曾损坏,已自动恢复。'}
|
||||
</span>
|
||||
{health.registry.state !== 'unreadable' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void acknowledgeRecovery()}
|
||||
>
|
||||
我知道了
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant={view === 'templates' ? 'default' : 'outline'}
|
||||
className="extension-template-entry"
|
||||
onClick={() => setView(view === 'templates' ? 'extensions' : 'templates')}
|
||||
>
|
||||
官方模板{templates.length > 0 ? ` (${templates.length})` : ''}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className={
|
||||
view === 'guide' ? 'extension-template-entry is-active' : 'extension-template-entry'
|
||||
}
|
||||
onClick={() => setView(view === 'guide' ? 'extensions' : 'guide')}
|
||||
>
|
||||
二次开发
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="extension-template-entry"
|
||||
disabled={busy}
|
||||
onClick={() => void linkProject()}
|
||||
>
|
||||
链接本地项目
|
||||
</Button>
|
||||
<div className="extension-install-row">
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -252,7 +641,25 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
</aside>
|
||||
|
||||
<section className="extension-detail" aria-label="扩展详情">
|
||||
{!selected ? (
|
||||
{view === 'guide' ? (
|
||||
<DevelopmentGuide
|
||||
onBack={() => setView('extensions')}
|
||||
onCreateProject={() => setView('templates')}
|
||||
onLinkProject={() => void linkProject()}
|
||||
/>
|
||||
) : view === 'templates' ? (
|
||||
<ExtensionTemplateGallery
|
||||
templates={templates}
|
||||
loading={templatesLoading}
|
||||
busyId={installingTemplate}
|
||||
onInstall={(templateId) => void installTemplate(templateId)}
|
||||
focusTemplateId={focusedTemplateId}
|
||||
onCreateProject={(templateId) => {
|
||||
const found = templates.find((item) => item.template.templateId === templateId)
|
||||
if (found) setCreatingTemplate(found.template)
|
||||
}}
|
||||
/>
|
||||
) : !selected ? (
|
||||
<div className="extension-detail-empty">
|
||||
<h3>选择左侧的扩展</h3>
|
||||
<p>安装后在这里查看权限、页面、自动化动作与执行日志。</p>
|
||||
@@ -277,8 +684,52 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
{selected.compatibility.reason || '扩展与当前版本不兼容'}
|
||||
</p>
|
||||
)}
|
||||
{selected.storage.state !== 'ok' && (
|
||||
<div className="extension-runtime-error extension-alert-row">
|
||||
<span>
|
||||
{selected.storage.state === 'recovered-from-backup'
|
||||
? '扩展配置曾损坏,已从备份恢复;确认前不会启动。'
|
||||
: '扩展配置损坏且没有可用备份,写入已停止。可在下方重置配置。'}
|
||||
</span>
|
||||
{selected.storage.state === 'recovered-from-backup' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void acknowledgeStorage(selected)}
|
||||
>
|
||||
使用恢复的配置
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{selected.runtime.note && (
|
||||
<p className="extension-muted">{selected.runtime.note}</p>
|
||||
)}
|
||||
{selected.runtime.lastError && (
|
||||
<p className="extension-runtime-error">{selected.runtime.lastError}</p>
|
||||
<div className="extension-runtime-error extension-alert-row">
|
||||
<span>{selected.runtime.lastError}</span>
|
||||
{selected.runtime.lastError.includes('升级可能中断') && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void adoptInstalledCode(selected)}
|
||||
>
|
||||
采用当前代码
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void rollbackUpgrade(selected)}
|
||||
>
|
||||
回滚到备份
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="extension-detail-actions">
|
||||
@@ -344,8 +795,107 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
)}
|
||||
</section>
|
||||
|
||||
{selected.development && (
|
||||
<section className="extension-card">
|
||||
<div className="extension-card-header">
|
||||
<h4>开发模式</h4>
|
||||
<span
|
||||
className={`extension-grant ${selected.development.available ? 'is-granted' : ''}`}
|
||||
>
|
||||
{selected.development.available ? '源码可用' : '源码不可用'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="extension-muted extension-source-path">
|
||||
{selected.development.sourcePath || '未记录源码路径'}
|
||||
</p>
|
||||
{!selected.development.available && (
|
||||
<p className="extension-runtime-error">
|
||||
源码目录被移动或删除。扩展配置与规则都还在,重新链接后即可继续。
|
||||
</p>
|
||||
)}
|
||||
{pendingConvert?.id === selected.id && (
|
||||
<div className="extension-confirm-block">
|
||||
<p>
|
||||
将把当前源码<strong>复制</strong>到 TraceMemo
|
||||
用户数据目录,之后运行的是这份安装副本。
|
||||
外部源码目录不会被删除,但你之后对它的修改<strong>不会</strong>
|
||||
自动同步过去。
|
||||
转换会停止当前后台,转换后保持「未启用」;已有配置、规则与缓存都保留。
|
||||
</p>
|
||||
<div className="extension-confirm-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
const target = pendingConvert
|
||||
setPendingConvert(null)
|
||||
if (target) void convertDevelopment(target)
|
||||
}}
|
||||
>
|
||||
确认转换
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setPendingConvert(null)}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="extension-detail-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy || !selected.development.available}
|
||||
onClick={() => void reloadDevelopment(selected)}
|
||||
>
|
||||
重新加载
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy || !selected.development.available}
|
||||
onClick={() => void openDevelopmentSource(selected)}
|
||||
>
|
||||
打开源码目录
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => setPendingConvert(selected)}
|
||||
>
|
||||
转为正式安装
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void unlinkDevelopment(selected)}
|
||||
>
|
||||
移除链接
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="extension-card">
|
||||
<h4>权限</h4>
|
||||
<div className="extension-card-header">
|
||||
<h4>权限</h4>
|
||||
{selected.pendingPermissions.length > 0 && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => void grantPending(selected)}
|
||||
>
|
||||
授权新增权限
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{selected.pendingPermissions.length > 0 && (
|
||||
<p className="extension-muted">
|
||||
新版本申请了 {selected.pendingPermissions.length} 项尚未授予的权限,当前不可用。
|
||||
</p>
|
||||
)}
|
||||
{selected.permissions.length === 0 ? (
|
||||
<p className="extension-muted">未申请任何权限。</p>
|
||||
) : (
|
||||
@@ -367,11 +917,59 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
</span>
|
||||
</div>
|
||||
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
|
||||
<span
|
||||
className={`extension-grant ${selected.grantedPermissions.includes(permission) ? 'is-granted' : ''}`}
|
||||
>
|
||||
{selected.grantedPermissions.includes(permission) ? '已授予' : '未授予'}
|
||||
</span>
|
||||
{selected.grantedPermissions.includes(permission) ? (
|
||||
<div className="extension-permission-actions">
|
||||
<span className="extension-grant is-granted">已授予</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void revokePermission(selected, permission)}
|
||||
>
|
||||
撤销
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="extension-permission-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (EXTENSION_PERMISSION_INFO[permission].risk === 'high') {
|
||||
setPendingGrant({ extensionId: selected.id, permission })
|
||||
} else {
|
||||
void grantPermission(selected, permission)
|
||||
}
|
||||
}}
|
||||
>
|
||||
授权
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{pendingGrant?.extensionId === selected.id &&
|
||||
pendingGrant.permission === permission && (
|
||||
<div className="extension-confirm-row">
|
||||
<span>
|
||||
该权限可以代替你执行敏感操作,确认授予「
|
||||
{EXTENSION_PERMISSION_INFO[permission].label}」?
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => void grantPermission(selected, permission)}
|
||||
>
|
||||
确认授权
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setPendingGrant(null)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -431,6 +1029,26 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
|
||||
<footer className="extension-detail-footer">
|
||||
<span>安装于 {formatTimestamp(selected.installedAt)}</span>
|
||||
{!selected.development && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
onClick={() => void exportProject(selected)}
|
||||
>
|
||||
导出为开发项目
|
||||
</Button>
|
||||
)}
|
||||
{selected.storage.state === 'unrecovered' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={busy}
|
||||
onClick={() => void resetStorage(selected)}
|
||||
>
|
||||
重置配置
|
||||
</Button>
|
||||
)}
|
||||
{pendingUninstall === selected.id ? (
|
||||
<span className="extension-uninstall-confirm">
|
||||
卸载后扩展代码会被移除,配置与数据默认保留。
|
||||
@@ -455,6 +1073,15 @@ export function ExtensionWorkspace(): React.ReactElement {
|
||||
)}
|
||||
</section>
|
||||
|
||||
{creatingTemplate && (
|
||||
<CreateProjectDialog
|
||||
template={creatingTemplate}
|
||||
busy={installingTemplate === `create:${creatingTemplate.templateId}`}
|
||||
onCancel={() => setCreatingTemplate(null)}
|
||||
onSubmit={(input) => void submitCreateProject(input)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{pendingEnable && (
|
||||
<div className="extension-modal-backdrop" role="dialog" aria-modal="true">
|
||||
<div className="extension-modal">
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -251,6 +251,28 @@
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
/* 状态文件损坏/降级提示:需要跨整行提醒,不能只在详情页里出现。 */
|
||||
.extension-health-banner {
|
||||
margin: 0 0 10px;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--wxex-radius-sm);
|
||||
background: color-mix(in srgb, var(--wxex-warning, #b45309) 12%, transparent);
|
||||
color: var(--wxex-warning, #b45309);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.extension-pending-list {
|
||||
margin: 6px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-detail-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -595,3 +617,414 @@
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── 官方模板画廊 ─────────────────────────────────────────── */
|
||||
|
||||
.extension-template-entry {
|
||||
width: 100%;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.extension-template-gallery {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 4px 2px 24px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.extension-template-header h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-template-header p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-template-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.extension-template-card {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid color-mix(in srgb, currentColor 12%, transparent);
|
||||
border-radius: var(--wxex-radius-md, 10px);
|
||||
background: color-mix(in srgb, currentColor 3%, transparent);
|
||||
}
|
||||
|
||||
.extension-template-card-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.extension-template-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.extension-template-version {
|
||||
font-size: 12px;
|
||||
color: var(--wxex-text-muted);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
|
||||
.extension-template-desc {
|
||||
margin: 6px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-template-meta {
|
||||
margin: 4px 0 0;
|
||||
font-size: 11px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-template-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.extension-template-warning {
|
||||
margin: 8px 0 0;
|
||||
padding: 6px 10px;
|
||||
border-radius: var(--wxex-radius-sm);
|
||||
background: color-mix(in srgb, var(--wxex-warning, #b45309) 10%, transparent);
|
||||
color: var(--wxex-warning, #b45309);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.extension-template-detail {
|
||||
margin-top: 10px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.extension-template-detail h4 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-template-deps {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.extension-template-deps li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.extension-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 999px;
|
||||
flex-shrink: 0;
|
||||
background: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-dot.is-ok {
|
||||
background: var(--wxex-success, #15803d);
|
||||
}
|
||||
|
||||
.extension-dot.is-missing {
|
||||
background: var(--wxex-danger);
|
||||
}
|
||||
|
||||
.extension-template-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 48px 16px;
|
||||
text-align: center;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-template-empty h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.extension-template-empty p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
/* 横幅与告警条需要「一句话 + 一个按钮」并排 */
|
||||
.extension-health-banner,
|
||||
.extension-alert-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.extension-health-banner span,
|
||||
.extension-alert-row span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ── 开发项目 ─────────────────────────────────────────────── */
|
||||
|
||||
.extension-project-dialog {
|
||||
position: fixed;
|
||||
z-index: 40;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: min(460px, calc(100vw - 48px));
|
||||
padding: 18px 20px;
|
||||
border-radius: var(--wxex-radius-md, 10px);
|
||||
border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
|
||||
background: var(--wxex-surface, #fff);
|
||||
box-shadow: 0 18px 48px color-mix(in srgb, currentColor 18%, transparent);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.extension-project-dialog h4 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-project-dialog p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.extension-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.extension-field input {
|
||||
height: 30px;
|
||||
padding: 0 10px;
|
||||
border-radius: var(--wxex-radius-sm);
|
||||
border: 1px solid color-mix(in srgb, currentColor 18%, transparent);
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font-size: 12px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
|
||||
.extension-field-error {
|
||||
color: var(--wxex-danger);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.extension-project-dialog-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.extension-source-path {
|
||||
word-break: break-all;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* ── 二次开发引导页 ───────────────────────────────────────── */
|
||||
|
||||
.extension-development-guide {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 22px;
|
||||
padding: 2px 2px 24px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.extension-guide-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
/* 标题块可以被压缩,右侧按钮不能:窄窗口下「返回扩展列表」不该折成两行 */
|
||||
.extension-guide-header > div {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.extension-guide-header > button {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.extension-guide-header h3 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-guide-header p {
|
||||
margin: 0;
|
||||
max-width: 620px;
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
/* 序号自己画,关掉 <ol> 的默认 marker,否则会出现「1.」和徽标两套编号 */
|
||||
.extension-guide-steps {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.extension-guide-steps li {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.extension-guide-index {
|
||||
flex: 0 0 20px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin-top: 1px;
|
||||
border-radius: 999px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--wxex-text-muted);
|
||||
background: color-mix(in srgb, currentColor 9%, transparent);
|
||||
}
|
||||
|
||||
.extension-guide-steps strong {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.extension-guide-steps p {
|
||||
margin: 3px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-guide-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.extension-guide-docs h4,
|
||||
.extension-guide-boundary h4 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-guide-docs ul,
|
||||
.extension-guide-boundary ul {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.extension-guide-docs li {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.extension-guide-docs li > div {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.extension-guide-docs strong {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-guide-docs code {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
color: var(--wxex-text-muted);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
|
||||
.extension-guide-docs > p {
|
||||
margin: 10px 0 0;
|
||||
font-size: 11px;
|
||||
line-height: 17px;
|
||||
}
|
||||
|
||||
.extension-guide-boundary li {
|
||||
position: relative;
|
||||
padding-left: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-guide-boundary li::before {
|
||||
content: '·';
|
||||
position: absolute;
|
||||
left: 2px;
|
||||
color: var(--wxex-text-muted);
|
||||
}
|
||||
|
||||
.extension-guide-boundary code {
|
||||
font-size: 11px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
|
||||
/* 侧栏里被选中的次级入口:不抢主操作,只做位置指示 */
|
||||
.extension-template-entry.is-active {
|
||||
border-color: color-mix(in srgb, currentColor 26%, transparent);
|
||||
background: color-mix(in srgb, currentColor 6%, transparent);
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* 扩展动作的输入参数 Schema。
|
||||
*
|
||||
* 刻意只支持一个**明确的子集**:完整 JSON Schema 会把「UI 怎么渲染」和
|
||||
* 「后台怎么校验」拆成两套实现,两边一旦不一致,用户看到的就是
|
||||
* 「表单说合法、执行时说参数错」。
|
||||
*
|
||||
* 支持范围:
|
||||
* - 顶层必须是 `type: 'object'` + `properties`
|
||||
* - 字段类型:string / number / integer / boolean
|
||||
* - 约束:required、enum、default、minimum/maximum、minLength/maxLength
|
||||
* - 展示:title、description
|
||||
*/
|
||||
|
||||
export const ACTION_SCHEMA_MAX_BYTES = 4 * 1024
|
||||
export const ACTION_SCHEMA_MAX_PROPERTIES = 24
|
||||
|
||||
export type ExtensionActionFieldType = 'string' | 'number' | 'integer' | 'boolean'
|
||||
|
||||
export interface ExtensionActionFieldSchema {
|
||||
type: ExtensionActionFieldType
|
||||
title?: string
|
||||
description?: string
|
||||
enum?: Array<string | number>
|
||||
default?: string | number | boolean
|
||||
minimum?: number
|
||||
maximum?: number
|
||||
minLength?: number
|
||||
maxLength?: number
|
||||
}
|
||||
|
||||
export interface ExtensionActionInputSchema {
|
||||
type: 'object'
|
||||
properties: Record<string, ExtensionActionFieldSchema>
|
||||
required?: string[]
|
||||
}
|
||||
|
||||
export type ActionSchemaParseResult =
|
||||
| { ok: true; schema: ExtensionActionInputSchema }
|
||||
| { ok: false; reason: string }
|
||||
|
||||
const FIELD_TYPES: readonly ExtensionActionFieldType[] = ['string', 'number', 'integer', 'boolean']
|
||||
const MAX_STRING_CONSTRAINT = 4_000
|
||||
const MAX_ABSOLUTE_NUMBER = 1e12
|
||||
const RESERVED_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
|
||||
const prototype = Object.getPrototypeOf(value)
|
||||
return prototype === Object.prototype || prototype === null
|
||||
}
|
||||
|
||||
function readFiniteNumber(value: unknown): number | undefined {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
||||
}
|
||||
|
||||
function readNonNegativeInteger(value: unknown): number | undefined {
|
||||
const parsed = readFiniteNumber(value)
|
||||
if (parsed === undefined || parsed < 0 || !Number.isInteger(parsed)) return undefined
|
||||
return Math.min(parsed, MAX_STRING_CONSTRAINT)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并规范化 Schema。
|
||||
*
|
||||
* 任何无法安全表达的内容都**整体拒绝**,不做部分裁剪:静默丢掉一个字段,
|
||||
* 界面会少一个输入框,而后台仍在等这个必填项。
|
||||
*/
|
||||
export function parseActionInputSchema(value: unknown): ActionSchemaParseResult {
|
||||
if (value === undefined || value === null) return { ok: false, reason: 'schema 为空' }
|
||||
if (!isPlainObject(value)) return { ok: false, reason: 'schema 必须是对象' }
|
||||
|
||||
let serialized: string
|
||||
try {
|
||||
serialized = JSON.stringify(value)
|
||||
} catch {
|
||||
return { ok: false, reason: 'schema 不能序列化(可能含循环引用)' }
|
||||
}
|
||||
const byteLength = new TextEncoder().encode(serialized).length
|
||||
if (byteLength > ACTION_SCHEMA_MAX_BYTES) {
|
||||
return { ok: false, reason: `schema 超过 ${ACTION_SCHEMA_MAX_BYTES} 字节上限` }
|
||||
}
|
||||
|
||||
if (value.type !== 'object') return { ok: false, reason: '顶层 type 必须是 object' }
|
||||
const properties = value.properties
|
||||
if (!isPlainObject(properties)) return { ok: false, reason: 'schema.properties 必须是对象' }
|
||||
const keys = Object.keys(properties)
|
||||
if (keys.length === 0) return { ok: false, reason: 'schema.properties 不能为空' }
|
||||
if (keys.length > ACTION_SCHEMA_MAX_PROPERTIES) {
|
||||
return { ok: false, reason: `参数数量超过 ${ACTION_SCHEMA_MAX_PROPERTIES} 个上限` }
|
||||
}
|
||||
|
||||
const normalized: Record<string, ExtensionActionFieldSchema> = {}
|
||||
for (const key of keys) {
|
||||
if (RESERVED_KEYS.has(key)) return { ok: false, reason: `参数名不合法:${key}` }
|
||||
if (key.length > 40) return { ok: false, reason: `参数名过长:${key}` }
|
||||
const field = properties[key]
|
||||
if (!isPlainObject(field)) return { ok: false, reason: `参数 ${key} 的定义必须是对象` }
|
||||
const type = field.type
|
||||
if (typeof type !== 'string' || !FIELD_TYPES.includes(type as ExtensionActionFieldType)) {
|
||||
return { ok: false, reason: `参数 ${key} 的类型不支持:${String(type)}` }
|
||||
}
|
||||
const fieldType = type as ExtensionActionFieldType
|
||||
|
||||
const entry: ExtensionActionFieldSchema = { type: fieldType }
|
||||
if (typeof field.title === 'string' && field.title.trim()) {
|
||||
entry.title = field.title.trim().slice(0, 60)
|
||||
}
|
||||
if (typeof field.description === 'string' && field.description.trim()) {
|
||||
entry.description = field.description.trim().slice(0, 200)
|
||||
}
|
||||
|
||||
if (field.enum !== undefined) {
|
||||
if (!Array.isArray(field.enum) || field.enum.length === 0 || field.enum.length > 50) {
|
||||
return { ok: false, reason: `参数 ${key} 的 enum 不合法` }
|
||||
}
|
||||
const allowed: Array<string | number> = []
|
||||
for (const option of field.enum) {
|
||||
if (fieldType === 'string' && typeof option === 'string') {
|
||||
allowed.push(option.slice(0, 200))
|
||||
} else if (
|
||||
fieldType !== 'string' &&
|
||||
typeof option === 'number' &&
|
||||
Number.isFinite(option)
|
||||
) {
|
||||
allowed.push(option)
|
||||
} else {
|
||||
return { ok: false, reason: `参数 ${key} 的 enum 项与类型不一致` }
|
||||
}
|
||||
}
|
||||
entry.enum = allowed
|
||||
}
|
||||
|
||||
if (field.default !== undefined) {
|
||||
const fallback = normalizeActionFieldValue(fieldType, field.default)
|
||||
if (fallback === undefined)
|
||||
return { ok: false, reason: `参数 ${key} 的 default 与类型不一致` }
|
||||
entry.default = fallback
|
||||
}
|
||||
|
||||
if (fieldType === 'string') {
|
||||
const minLength = readNonNegativeInteger(field.minLength)
|
||||
const maxLength = readNonNegativeInteger(field.maxLength)
|
||||
if (minLength !== undefined) entry.minLength = minLength
|
||||
if (maxLength !== undefined) entry.maxLength = maxLength
|
||||
if (
|
||||
entry.minLength !== undefined &&
|
||||
entry.maxLength !== undefined &&
|
||||
entry.minLength > entry.maxLength
|
||||
) {
|
||||
return { ok: false, reason: `参数 ${key} 的 minLength 大于 maxLength` }
|
||||
}
|
||||
} else if (fieldType === 'number' || fieldType === 'integer') {
|
||||
const minimum = readFiniteNumber(field.minimum)
|
||||
const maximum = readFiniteNumber(field.maximum)
|
||||
if (minimum !== undefined && Math.abs(minimum) <= MAX_ABSOLUTE_NUMBER) entry.minimum = minimum
|
||||
if (maximum !== undefined && Math.abs(maximum) <= MAX_ABSOLUTE_NUMBER) entry.maximum = maximum
|
||||
if (
|
||||
entry.minimum !== undefined &&
|
||||
entry.maximum !== undefined &&
|
||||
entry.minimum > entry.maximum
|
||||
) {
|
||||
return { ok: false, reason: `参数 ${key} 的 minimum 大于 maximum` }
|
||||
}
|
||||
}
|
||||
|
||||
normalized[key] = entry
|
||||
}
|
||||
|
||||
let required: string[] | undefined
|
||||
if (value.required !== undefined) {
|
||||
if (!Array.isArray(value.required)) return { ok: false, reason: 'required 必须是数组' }
|
||||
const list: string[] = []
|
||||
for (const item of value.required) {
|
||||
if (typeof item !== 'string' || !normalized[item]) {
|
||||
return { ok: false, reason: `required 引用了未定义的参数:${String(item)}` }
|
||||
}
|
||||
if (!list.includes(item)) list.push(item)
|
||||
}
|
||||
if (list.length) required = list
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
schema: { type: 'object', properties: normalized, ...(required ? { required } : {}) }
|
||||
}
|
||||
}
|
||||
|
||||
/** 把原始值按字段类型收敛;不合法返回 undefined。 */
|
||||
export function normalizeActionFieldValue(
|
||||
type: ExtensionActionFieldType,
|
||||
value: unknown
|
||||
): string | number | boolean | undefined {
|
||||
if (type === 'string') return typeof value === 'string' ? value.slice(0, 4_000) : undefined
|
||||
if (type === 'boolean') return typeof value === 'boolean' ? value : undefined
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
|
||||
if (type === 'integer' && !Number.isInteger(value)) return undefined
|
||||
return value
|
||||
}
|
||||
|
||||
export interface ActionInputValidationResult {
|
||||
ok: boolean
|
||||
/** 逐字段错误,key 是参数名。 */
|
||||
errors: Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 Schema 校验输入。
|
||||
*
|
||||
* UI 提交前与后台执行前都用这一个函数:两边规则一致才谈得上「所见即所得」。
|
||||
*/
|
||||
export function validateActionInput(
|
||||
schema: ExtensionActionInputSchema | undefined,
|
||||
input: Record<string, unknown> | undefined
|
||||
): ActionInputValidationResult {
|
||||
const errors: Record<string, string> = {}
|
||||
if (!schema) return { ok: true, errors }
|
||||
|
||||
const values = input && typeof input === 'object' ? input : {}
|
||||
const required = new Set(schema.required ?? [])
|
||||
|
||||
for (const [key, field] of Object.entries(schema.properties)) {
|
||||
const raw = (values as Record<string, unknown>)[key]
|
||||
const missing = raw === undefined || raw === null || raw === ''
|
||||
if (missing) {
|
||||
if (required.has(key)) errors[key] = '必填'
|
||||
continue
|
||||
}
|
||||
const normalized = normalizeActionFieldValue(field.type, raw)
|
||||
if (normalized === undefined) {
|
||||
errors[key] = field.type === 'integer' ? '需要整数' : `需要 ${field.type}`
|
||||
continue
|
||||
}
|
||||
if (field.enum && !field.enum.includes(normalized as string | number)) {
|
||||
errors[key] = '不在可选范围内'
|
||||
continue
|
||||
}
|
||||
if (typeof normalized === 'string') {
|
||||
if (field.minLength !== undefined && normalized.length < field.minLength) {
|
||||
errors[key] = `至少 ${field.minLength} 个字符`
|
||||
continue
|
||||
}
|
||||
if (field.maxLength !== undefined && normalized.length > field.maxLength) {
|
||||
errors[key] = `最多 ${field.maxLength} 个字符`
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (typeof normalized === 'number') {
|
||||
if (field.minimum !== undefined && normalized < field.minimum) {
|
||||
errors[key] = `不能小于 ${field.minimum}`
|
||||
continue
|
||||
}
|
||||
if (field.maximum !== undefined && normalized > field.maximum) {
|
||||
errors[key] = `不能大于 ${field.maximum}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
/** 按 Schema 生成一份带默认值的输入;缺省值缺失时留空。 */
|
||||
export function buildDefaultActionInput(
|
||||
schema: ExtensionActionInputSchema | undefined
|
||||
): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {}
|
||||
if (!schema) return result
|
||||
for (const [key, field] of Object.entries(schema.properties)) {
|
||||
if (field.default !== undefined) result[key] = field.default
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -23,7 +23,17 @@ export const EXTENSION_ERROR_CODES = [
|
||||
'ACTION_FAILED',
|
||||
'RATE_LIMITED',
|
||||
'INVALID_REQUEST',
|
||||
'STORAGE_LIMIT_EXCEEDED'
|
||||
'STORAGE_LIMIT_EXCEEDED',
|
||||
/** 状态文件损坏且无法恢复;写入被拒绝,现场保留。 */
|
||||
'EXTENSION_REGISTRY_UNREADABLE',
|
||||
/** 扩展配置损坏且没有可用备份;写入被拒绝。 */
|
||||
'EXTENSION_STORAGE_CORRUPTED',
|
||||
/** 开发模式的源码目录被移动或删除;Registry 与配置保留。 */
|
||||
'EXTENSION_SOURCE_MISSING',
|
||||
/** 目标目录已有文件 / 目标不可写;创建项目被拒绝。 */
|
||||
'EXTENSION_PROJECT_EXISTS',
|
||||
/** 检测到安装副本被用户修改,拒绝自动覆盖。 */
|
||||
'EXTENSION_MODIFIED_LOCALLY'
|
||||
] as const
|
||||
|
||||
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
|
||||
@@ -46,7 +56,12 @@ export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
|
||||
ACTION_FAILED: '扩展执行失败',
|
||||
RATE_LIMITED: '触发频率限制,请稍后再试',
|
||||
INVALID_REQUEST: '请求格式不合法',
|
||||
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限'
|
||||
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限',
|
||||
EXTENSION_REGISTRY_UNREADABLE: '扩展状态文件损坏且无法恢复',
|
||||
EXTENSION_STORAGE_CORRUPTED: '扩展配置已损坏',
|
||||
EXTENSION_SOURCE_MISSING: '开发源码目录不可用',
|
||||
EXTENSION_PROJECT_EXISTS: '目标项目目录不可用',
|
||||
EXTENSION_MODIFIED_LOCALLY: '扩展代码已被本地修改'
|
||||
}
|
||||
|
||||
export interface ExtensionErrorPayload {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -14,7 +14,8 @@ export const EXTENSION_PERMISSIONS = [
|
||||
'wechat.send.video',
|
||||
'ai.chat',
|
||||
'storage',
|
||||
'automation.action'
|
||||
'automation.action',
|
||||
'secrets'
|
||||
] as const
|
||||
|
||||
export type ExtensionPermission = (typeof EXTENSION_PERMISSIONS)[number]
|
||||
@@ -28,6 +29,12 @@ export interface ExtensionPermissionInfo {
|
||||
}
|
||||
|
||||
export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPermissionInfo> = {
|
||||
secrets: {
|
||||
label: '保存私有凭据',
|
||||
description:
|
||||
'在本机以系统安全存储加密保存该扩展自己的凭据(如 Cookie),只有该扩展能读取;不写入明文文件。',
|
||||
risk: 'medium'
|
||||
},
|
||||
'messages.subscribe': {
|
||||
label: '接收新消息事件',
|
||||
description:
|
||||
|
||||
@@ -22,6 +22,10 @@ export type ExtensionHostCallMethod =
|
||||
| 'wechat.send.video'
|
||||
| 'ai.chat'
|
||||
| 'capabilities.get'
|
||||
| 'secrets.get'
|
||||
| 'secrets.set'
|
||||
| 'secrets.delete'
|
||||
| 'secrets.has'
|
||||
|
||||
export interface ExtensionHostReady {
|
||||
type: 'ready'
|
||||
@@ -81,7 +85,15 @@ export interface ExtensionHostRegisterAction {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
hasInputSchema: boolean
|
||||
/**
|
||||
* 完整参数 Schema(未经校验的原始 JSON)。
|
||||
*
|
||||
* 宿主收到后统一走 `parseActionInputSchema`:非法或超限时**保留动作但不给 Schema**,
|
||||
* 并把原因记进日志与动作信息,绝不静默截断。
|
||||
*/
|
||||
inputSchema?: unknown
|
||||
/** 兼容字段:旧宿主只认这个布尔值。新宿主用 `inputSchema`。 */
|
||||
hasInputSchema?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +138,30 @@ export interface ExtensionHostLog {
|
||||
message: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展页面 → 同扩展后台的通用请求。
|
||||
*
|
||||
* 宿主只做路由与限额:页面拿不到任意 Node 能力,后台必须显式注册处理器。
|
||||
* 这是移除「宿主硬编码某个具体扩展业务」的关键通道。
|
||||
*/
|
||||
export interface ExtensionHostPageRequest {
|
||||
type: 'page-request'
|
||||
version: number
|
||||
requestId: string
|
||||
method: string
|
||||
params: Record<string, unknown>
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
export interface ExtensionHostPageResult {
|
||||
type: 'page-result'
|
||||
version: number
|
||||
requestId: string
|
||||
ok: boolean
|
||||
result?: unknown
|
||||
error?: { code: string; message: string }
|
||||
}
|
||||
|
||||
export type ExtensionHostOutboundMessage =
|
||||
| ExtensionHostReady
|
||||
| ExtensionHostActivated
|
||||
@@ -134,6 +170,7 @@ export type ExtensionHostOutboundMessage =
|
||||
| ExtensionHostLog
|
||||
| ExtensionHostActionResult
|
||||
| ExtensionHostTestResult
|
||||
| ExtensionHostPageResult
|
||||
|
||||
export type ExtensionHostInboundMessage =
|
||||
| ExtensionHostActivate
|
||||
@@ -143,6 +180,7 @@ export type ExtensionHostInboundMessage =
|
||||
| ExtensionHostInvokeAction
|
||||
| ExtensionHostTestSend
|
||||
| ExtensionHostTestResult
|
||||
| ExtensionHostPageRequest
|
||||
|
||||
/**
|
||||
* 自动化动作的返回值。
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user