feat(electron-shell): 新增插件目录选择接口并将版本升至 1.10.0

This commit is contained in:
2026-10-30 10:00:18 +08:00
parent 526116af83
commit 210de5b68b
337 changed files with 3254 additions and 49349 deletions
@@ -1,9 +1,14 @@
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
//
// 与 v1 的差异(适配当前壳子):
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
// 不能再当成普通失败提示。
//
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { PLUGIN_ID } from './api'
@@ -15,58 +20,37 @@ async function j(url, opts) {
}
if (!res.ok) {
let msg = `HTTP ${res.status}`
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
throw new Error(msg)
try {
msg = (await res.json()).detail || msg
} catch (_) { /* 保留默认 */ }
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
}
return res.json()
}
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
function loadConfig() {
return j(`/api/plugin-config/${PLUGIN_ID}`)
}
function saveConfig(data) {
return j(`/api/plugin-config/${PLUGIN_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
function listSchemes() {
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
}
function saveScheme(name, fields) {
return j('/api/plugin-configs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
})
}
function deleteScheme(cfgId) {
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
method: 'DELETE',
})
}
function startRun(fields) {
return j('/api/runs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
})
}
function getRun(runId) {
return j(`/api/runs/${runId}`)
}
function stopRun(runId) {
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
}
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
const saveScheme = (name, fields) => j('/api/plugin-configs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
})
const deleteScheme = (cfgId) =>
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
const startRun = (fields) => j('/api/runs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
})
const getRun = (runId) => j(`/api/runs/${runId}`)
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
function connectWS(onEvent) {
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
@@ -78,8 +62,18 @@ function connectWS(onEvent) {
// ---- 工具 ----
const clone = (o) => JSON.parse(JSON.stringify(o))
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
function readSavedAt() {
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
}
function writeSavedAt(v) {
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
}
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
// (空数组可能是有意配置,如「留空=不筛选」)
function mergeSaved(form, saved) {
Object.keys(form).forEach((k) => {
const v = saved ? saved[k] : undefined
@@ -88,22 +82,14 @@ function mergeSaved(form, saved) {
})
}
/**
* 插件 UI 公共状态机
* @param {Object} opts
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
*/
export function usePluginUI(opts = {}) {
const { defaults, validate, buildPayload } = opts
const form = reactive(defaults ? defaults() : {})
const loaded = ref(false)
const needLogin = ref(false)
const banner = ref(null)
const lastSavedAt = ref('')
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
const lastSavedAt = ref(readSavedAt())
const running = ref(false)
const progress = ref(0)
const stopping = ref(false)
@@ -113,20 +99,23 @@ export function usePluginUI(opts = {}) {
let pollTimer = null
let saveTimer = null
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
const notify = (type, text) => { notice.value = type ? { type, text } : null }
// ---------- 当前配置:加载 / 防抖自动保存 ----------
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
onMounted(async () => {
try {
const saved = await loadConfig()
mergeSaved(form, saved)
} catch (e) {
if (e.code === 401) needLogin.value = true
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
}
loaded.value = true
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
refreshSchemes()
})
// 配置变更自动保存(防抖 800ms),执行中不保存
watch(form, () => {
if (!loaded.value || running.value) return
clearTimeout(saveTimer)
@@ -137,6 +126,7 @@ export function usePluginUI(opts = {}) {
try {
await saveConfig(clone(form))
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
writeSavedAt(lastSavedAt.value)
if (explicit) ElMessage.success('配置已保存到本机')
} catch (e) {
if (e.code === 401) needLogin.value = true
@@ -146,12 +136,30 @@ export function usePluginUI(opts = {}) {
function resetDefaults() {
Object.assign(form, defaults ? defaults(form) : {})
notify(null)
ElMessage.info('已恢复默认配置')
}
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
const schemes = ref([]) // [{id, name, fields, at}]
const schemeSel = ref('') // '' = 当前配置(即表单本身)
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
async function restoreLastFields() {
try {
const r = await loadLastFields()
const fields = r.fields || {}
if (!Object.keys(fields).length) {
ElMessage.info('暂无上次执行参数')
return
}
mergeSaved(form, fields)
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
} catch (e) {
if (e.code === 401) needLogin.value = true
else ElMessage.error('恢复上次参数失败:' + e.message)
}
}
// ---------- 多配置方案 ----------
const schemes = ref([])
const schemeSel = ref('')
const schemeOptions = computed(() => [
{ value: '', label: '当前配置(自动保存)' },
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
@@ -161,15 +169,11 @@ export function usePluginUI(opts = {}) {
try {
const r = await listSchemes()
schemes.value = r.configs || []
} catch (_) {
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
}
} catch (_) { /* 方案是辅助能力,失败静默 */ }
}
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
function onSchemeChange(id) {
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
if (!id) return
const s = schemes.value.find((x) => x.id === id)
if (!s) return
mergeSaved(form, s.fields)
@@ -189,10 +193,10 @@ export function usePluginUI(opts = {}) {
cancelButtonText: '取消',
inputPattern: /\S/,
inputErrorMessage: '请输入方案名称',
}
},
))
} catch (_) {
return // 用户取消
return
}
name = String(name).trim()
if (!name) return
@@ -202,10 +206,10 @@ export function usePluginUI(opts = {}) {
await ElMessageBox.confirm(
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
'覆盖已有方案',
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
)
} catch (_) {
return // 用户取消覆盖
return
}
}
try {
@@ -226,7 +230,7 @@ export function usePluginUI(opts = {}) {
await ElMessageBox.confirm(
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
'删除方案',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
)
} catch (_) {
return
@@ -242,38 +246,45 @@ export function usePluginUI(opts = {}) {
}
// ---------- 执行 ----------
async function run() {
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
async function run(action) {
if (running.value) return
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
if (needLogin.value) {
try {
await loadConfig()
needLogin.value = false
ElMessage.success('登录态已恢复,请再次点击执行')
} catch (_) {
notify('error', '登录态未就绪,请稍后重试')
return
} catch (_) { /* 仍未登录 */ }
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
return
}
}
if (validate && !validate()) return
if (validate && !validate(action)) return
await saveNow(false)
notify(null)
running.value = true
progress.value = 0
banner.value = null
try {
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
const payload = buildPayload ? buildPayload(form) : clone(form)
if (action) payload.action = action
const r = await startRun(payload)
runId = r.run_id
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
connect()
startPolling()
} catch (e) {
running.value = false
stopPolling()
if (e.code === 401) needLogin.value = true
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
if (e.code === 401) {
needLogin.value = true
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
} else if (e.code === 409) {
// 壳子「入队确认」里用户点了取消
notify('warn', '已取消加入执行队列,本次没有启动')
} else {
notify('error', '启动执行失败:' + e.message)
}
}
}
// 强制停止(整树强杀执行子进程,含浏览器)
async function forceStop() {
if (!runId || stopping.value) return
stopping.value = true
@@ -287,11 +298,10 @@ export function usePluginUI(opts = {}) {
}
}
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
function connect() {
if (ws && ws.readyState <= 1) return
ws = connectWS((ev) => {
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
if (ev.run_id && ev.run_id !== runId) return
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
})
@@ -304,7 +314,7 @@ export function usePluginUI(opts = {}) {
if (!runId) return
try {
const r = await getRun(runId)
if (r.status === 'done') finished(r.result?.summary || '执行完成')
if (r.status === 'done') finished(r.result?.summary)
else if (r.status === 'error') failed(r.error || '执行失败')
} catch (_) { /* 下轮再试 */ }
}, 5000)
@@ -318,23 +328,20 @@ export function usePluginUI(opts = {}) {
stopPolling()
running.value = false
progress.value = 100
banner.value = { type: 'success', text: summary || '执行完成' }
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
if (summary) notify('ok', summary)
}
function failed(err) {
stopPolling()
running.value = false
banner.value = { type: 'error', text: '执行失败:' + err }
notify('error', '执行失败:' + err)
}
return {
// 状态
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
// 当前配置
saveNow, resetDefaults,
// 多配置方案
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
saveNow, resetDefaults, restoreLastFields,
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
// 执行
run, forceStop,
}
}