Merge pull request #138 from Nwflower/feat/plugin-view-capabilities
feat: add plugin views and host bridge capabilities
This commit is contained in:
46 files changed
+3350
-183
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "沙箱页面插件新增四种视图位置、宿主表单与导航、虚拟机和设置访问、授权文件读写、任务进度、受控网络请求及事件订阅,并支持确认、复制、外链和私有存储。",
|
||||
"en": "Add four view locations, host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, and event subscriptions to sandboxed plugins, alongside confirmations, clipboard copy, external links, and private storage."
|
||||
}
|
||||
@@ -54,7 +54,15 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
|
||||
|
||||
已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。
|
||||
|
||||
自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。
|
||||
自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。`contributes.views` 可在侧栏、VM 标签页、全局设置页或对话框中挂载完整视图,视图随插件作用域注册和释放,停用后自动回退到对应内置页面。视图的 `when` 支持 `vmState==<状态>` 与 `theme==<light|dark>`,条件不满足时宿主隐藏入口和页面。`minWidth` 设置页面的最小宽度,空间不足时横向滚动。
|
||||
|
||||
页面可通过 `ui.confirm` 请求确认框,通过 `ui.showForm` 打开声明式表单,通过 `ui.copy` 复制文本,通过 `ui.openExternal` 打开经宿主校验的 HTTPS 外链,并使用 `ui.setTitle`、`ui.setBadge` 更新当前视图元数据。`ui.openView` 仅打开本插件声明的视图,`ui.close` 关闭当前视图或顶层对话框,`ui.navigate` 进入内置宿主页面;这些操作不会关闭应用窗口。确认框使用 `ui:notify` 权限,其他界面动作使用 `ui:slot` 权限。
|
||||
|
||||
`vm.get` 返回不含宿主路径的虚拟机详情。`settings.get` 与 `settings.set` 仅访问本插件清单声明的设置,校验类型、枚举、数值范围和 app/VM 作用域。访问 VM 级设置要求 `vm:read` 权限。秘密值读取时保持掩码,写入时沿用现有加密保存。`allow_ai_access` 记录用户对单台虚拟机的授权,只能由用户在宿主设置中修改。`storage.get`、`storage.set`、`storage.list` 与 `storage.delete` 提供按插件隔离且重启后保留的 JSON 键值存储,需要 `fs:plugin_data` 权限;存储键、单值与总大小均有上限,文件损坏时明确报错,不自动清空已有状态。
|
||||
|
||||
`file.pick` 与 `file.save` 通过原生对话框取得插件专属文件句柄,`file.read` 与 `file.write` 只接受这些句柄,不接受任意宿主路径,支持 UTF-8 和 Base64,单个文件上限为 8 MiB。每个插件最多同时持有 32 个文件句柄,句柄在签发 15 分钟后失效。`task.start`、`task.update` 与 `task.finish` 复用底部任务进度区,任务按插件归属校验,支持协作取消。页面关闭或重新加载时,宿主取消该页面未结束的任务;停用、卸载或切换数据目录会取消任务并撤销文件句柄。
|
||||
|
||||
`net.fetch` 按清单中的 `net:<主机>` 发起请求,支持文本、JSON 和 Base64 响应,重定向目标逐次重新授权,不回传 `Set-Cookie`。`events.subscribe` 与 `events.unsubscribe` 管理 `vm.stateChanged`、`view.visibilityChanged` 和 `task.updated` 订阅;VM 事件要求 `vm:read`,任务事件只发送本插件任务,视图可见性事件在订阅时先发送当前状态。`theme.changed` 与 `locale.changed` 无需订阅即会送达。
|
||||
|
||||
公开契约按语义化版本分为三个独立版本面,插件在 `plugin.json` 的 `engines` 中声明兼容范围:
|
||||
|
||||
|
||||
@@ -4,45 +4,44 @@
|
||||
"hello",
|
||||
"i18n.getBundle",
|
||||
"ui.notify",
|
||||
"ui.confirm",
|
||||
"ui.copy",
|
||||
"ui.openExternal",
|
||||
"ui.showForm",
|
||||
"ui.setTitle",
|
||||
"ui.setBadge",
|
||||
"ui.openView",
|
||||
"ui.close",
|
||||
"ui.navigate",
|
||||
"vm.list",
|
||||
"command.invoke"
|
||||
"vm.get",
|
||||
"command.invoke",
|
||||
"settings.get",
|
||||
"settings.set",
|
||||
"storage.get",
|
||||
"storage.set",
|
||||
"storage.list",
|
||||
"storage.delete",
|
||||
"file.pick",
|
||||
"file.save",
|
||||
"file.read",
|
||||
"file.write",
|
||||
"task.start",
|
||||
"task.update",
|
||||
"task.finish",
|
||||
"net.fetch",
|
||||
"events.subscribe",
|
||||
"events.unsubscribe"
|
||||
],
|
||||
"events": [
|
||||
"theme.changed",
|
||||
"locale.changed"
|
||||
"locale.changed",
|
||||
"vm.stateChanged",
|
||||
"view.visibilityChanged",
|
||||
"task.updated"
|
||||
],
|
||||
"experimental": {
|
||||
"methods": [
|
||||
"ui.confirm",
|
||||
"ui.showForm",
|
||||
"ui.setTitle",
|
||||
"ui.setBadge",
|
||||
"ui.openView",
|
||||
"ui.close",
|
||||
"ui.navigate",
|
||||
"ui.openExternal",
|
||||
"vm.get",
|
||||
"settings.get",
|
||||
"settings.set",
|
||||
"storage.get",
|
||||
"storage.set",
|
||||
"storage.list",
|
||||
"storage.delete",
|
||||
"file.pick",
|
||||
"file.save",
|
||||
"file.read",
|
||||
"file.write",
|
||||
"task.start",
|
||||
"task.update",
|
||||
"task.finish",
|
||||
"net.fetch",
|
||||
"events.subscribe",
|
||||
"events.unsubscribe"
|
||||
],
|
||||
"events": [
|
||||
"vm.stateChanged",
|
||||
"view.visibilityChanged",
|
||||
"task.updated"
|
||||
]
|
||||
"methods": [],
|
||||
"events": []
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,10 @@ const appCSSPath = path.resolve(__dirname, '../src/styles/app.css')
|
||||
|
||||
const { hasVisibleDialog, isDialogElementVisible } = await loadTestModule(`export * from './lib/dialogState'`)
|
||||
const { resolvePluginApprovalNotice } = await loadTestModule(`export { resolvePluginApprovalNotice } from './components/PluginParts'`)
|
||||
const { createPluginTaskScope, initialFormValues, invokePluginViewAction, missingFormFields } = await loadTestModule(`export * from './lib/pluginViewActions'`)
|
||||
const { openPluginView, closePluginView, emptyPluginViewState, matchViewCondition, prunePluginViews } = await loadTestModule(`export * from './lib/pluginViewRouter'`)
|
||||
const { publishPluginHostEvent, subscribePluginHostEvents } = await loadTestModule(`export * from './lib/pluginViewEvents'`)
|
||||
const { buildSafePluginAssetURL } = await loadTestModule(`export * from './lib/pluginAssets'`)
|
||||
|
||||
function fakeDialog({
|
||||
display = 'block',
|
||||
@@ -118,3 +122,220 @@ test('dialog body children and plugin scan lists disable flex shrinking so tall
|
||||
assert.match(css, /\.dialog-body\s*>\s*\*\s*\{[^}]*flex-shrink\s*:\s*0/)
|
||||
assert.match(css, /\.plugin-scan-section\s*>\s*\.list\s*\{[^}]*flex-shrink\s*:\s*0/)
|
||||
})
|
||||
|
||||
test('packaged view assets stay on the same-origin plugin asset server', () => {
|
||||
assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', 'icons/console.svg'), '/plugin-assets/abc123/vendor.tool/icons/console.svg')
|
||||
assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', '../secret'), null)
|
||||
assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', 'icons\\secret.svg'), null)
|
||||
assert.equal(buildSafePluginAssetURL('abc123', 'vendor.tool', 'https://example.com/icon.svg'), null)
|
||||
assert.equal(buildSafePluginAssetURL('not-safe', 'vendor.tool', 'icon.svg'), null)
|
||||
})
|
||||
|
||||
test('plugin confirmation runs only after host validation and returns the user choice', async () => {
|
||||
const steps = []
|
||||
const result = await invokePluginViewAction('ui.confirm', { message: 'Publish?' }, {
|
||||
invoke: async (method, params) => {
|
||||
steps.push(['invoke', method, params.message])
|
||||
return { message: params.message, danger: true }
|
||||
},
|
||||
confirm: async (request) => {
|
||||
steps.push(['confirm', request.message, request.danger])
|
||||
return true
|
||||
},
|
||||
copy: async () => { throw new Error('unexpected copy') },
|
||||
})
|
||||
assert.deepEqual(result, { confirmed: true })
|
||||
assert.deepEqual(steps, [
|
||||
['invoke', 'ui.confirm', 'Publish?'],
|
||||
['confirm', 'Publish?', true],
|
||||
])
|
||||
})
|
||||
|
||||
test('plugin clipboard write waits for host approval and is skipped on rejection', async () => {
|
||||
const copied = []
|
||||
const result = await invokePluginViewAction('ui.copy', { text: 'first\nsecond' }, {
|
||||
invoke: async () => ({ text: 'first\nsecond' }),
|
||||
confirm: async () => { throw new Error('unexpected confirmation') },
|
||||
copy: async (text) => { copied.push(text) },
|
||||
})
|
||||
assert.deepEqual(result, { ok: true })
|
||||
assert.deepEqual(copied, ['first\nsecond'])
|
||||
|
||||
await assert.rejects(invokePluginViewAction('ui.copy', { text: 'secret' }, {
|
||||
invoke: async () => { throw new Error('permission denied') },
|
||||
confirm: async () => false,
|
||||
copy: async (text) => { copied.push(text) },
|
||||
}), /permission denied/)
|
||||
assert.deepEqual(copied, ['first\nsecond'])
|
||||
})
|
||||
|
||||
test('other plugin bridge methods pass through without UI interception', async () => {
|
||||
const result = await invokePluginViewAction('storage.list', {}, {
|
||||
invoke: async (method) => ({ keys: method === 'storage.list' ? ['draft'] : [] }),
|
||||
confirm: async () => { throw new Error('unexpected confirmation') },
|
||||
copy: async () => { throw new Error('unexpected copy') },
|
||||
})
|
||||
assert.deepEqual(result, { keys: ['draft'] })
|
||||
})
|
||||
|
||||
test('plugin view router preserves return state, handles dialogs, and prunes disabled views', () => {
|
||||
const sidebar = { pluginId: 'vendor.tool', viewId: 'console', location: 'sidebar' }
|
||||
const settings = { pluginId: 'vendor.tool', viewId: 'settings', location: 'settings' }
|
||||
const tab = { pluginId: 'vendor.tool', viewId: 'metrics', location: 'vm.tab', vm: 'builtin.macos:mac' }
|
||||
const dialog = { pluginId: 'vendor.tool', viewId: 'editor', location: 'dialog' }
|
||||
let state = openPluginView(emptyPluginViewState, sidebar)
|
||||
state = openPluginView(state, sidebar)
|
||||
assert.equal(state.returnStack.length, 0, 'duplicate open must not push history')
|
||||
state = openPluginView(state, settings)
|
||||
assert.equal(state.route.viewId, 'settings')
|
||||
assert.equal(state.returnStack.length, 1)
|
||||
state = closePluginView(state).state
|
||||
assert.equal(state.route.viewId, 'console')
|
||||
state = openPluginView(state, tab)
|
||||
state = closePluginView(state).state
|
||||
assert.equal(state.route, null, 'VM tab closes to overview')
|
||||
state = openPluginView(state, dialog)
|
||||
state = openPluginView(state, dialog)
|
||||
assert.equal(state.dialogs.length, 1, 'duplicate dialog only focuses the existing one')
|
||||
state = closePluginView(state).state
|
||||
assert.equal(state.dialogs.length, 0)
|
||||
state = openPluginView(state, sidebar)
|
||||
state = prunePluginViews(state, new Set(), () => false)
|
||||
assert.deepEqual(state, emptyPluginViewState)
|
||||
})
|
||||
|
||||
test('plugin event bus delivers only while subscribed', () => {
|
||||
const received = []
|
||||
const off = subscribePluginHostEvents((event, data) => { received.push([event, data]) })
|
||||
publishPluginHostEvent('task.updated', { id: 'task-1' })
|
||||
off()
|
||||
publishPluginHostEvent('task.updated', { id: 'task-2' })
|
||||
assert.deepEqual(received, [['task.updated', { id: 'task-1' }]])
|
||||
})
|
||||
|
||||
test('plugin form, metadata, navigation, and subscriptions execute after host validation', async () => {
|
||||
const steps = []
|
||||
const view = { id: 'editor', pluginId: 'vendor.tool', location: 'dialog', title: 'Editor', entry: 'index.html' }
|
||||
const handlers = {
|
||||
invoke: async (method) => {
|
||||
steps.push(['invoke', method])
|
||||
if (method === 'ui.showForm') return { title: 'Edit', schema: { properties: {} }, values: { name: 'demo' } }
|
||||
if (method === 'ui.openView') return view
|
||||
if (method === 'ui.setTitle') return { title: 'Live' }
|
||||
if (method === 'ui.setBadge') return { text: '2', tone: 'warn' }
|
||||
if (method.startsWith('events.')) return { events: method === 'events.unsubscribe' ? [] : ['task.updated'] }
|
||||
if (method === 'ui.navigate') return { page: 'settings' }
|
||||
return { ok: true }
|
||||
},
|
||||
confirm: async () => { throw new Error('unexpected confirmation') },
|
||||
showForm: async (request) => { steps.push(['form', request.values.name]); return { confirmed: true, values: request.values } },
|
||||
copy: async () => { throw new Error('unexpected copy') },
|
||||
setTitle: (title) => { steps.push(['title', title]) },
|
||||
setBadge: (text, tone) => { steps.push(['badge', text, tone]) },
|
||||
openView: (opened, vm) => { steps.push(['open', opened.id, vm]) },
|
||||
close: async () => ({ closed: true }),
|
||||
navigate: (target) => { steps.push(['navigate', target.page]) },
|
||||
subscribe: (events) => { steps.push(['subscribe', ...events]) },
|
||||
unsubscribe: (events) => { steps.push(['unsubscribe', events.length]) },
|
||||
}
|
||||
assert.deepEqual(await invokePluginViewAction('ui.showForm', {}, handlers), { confirmed: true, values: { name: 'demo' } })
|
||||
assert.deepEqual(await invokePluginViewAction('ui.openView', { vm: 'vm-1' }, handlers), { ok: true })
|
||||
assert.deepEqual(await invokePluginViewAction('ui.setTitle', {}, handlers), { title: 'Live' })
|
||||
assert.deepEqual(await invokePluginViewAction('ui.setBadge', {}, handlers), { text: '2', tone: 'warn' })
|
||||
assert.deepEqual(await invokePluginViewAction('events.subscribe', {}, handlers), { events: ['task.updated'] })
|
||||
assert.deepEqual(await invokePluginViewAction('events.unsubscribe', {}, handlers), { events: [] })
|
||||
assert.deepEqual(await invokePluginViewAction('ui.navigate', {}, handlers), { ok: true })
|
||||
assert.deepEqual(steps, [
|
||||
['invoke', 'ui.showForm'], ['form', 'demo'],
|
||||
['invoke', 'ui.openView'], ['open', 'editor', 'vm-1'],
|
||||
['invoke', 'ui.setTitle'], ['title', 'Live'],
|
||||
['invoke', 'ui.setBadge'], ['badge', '2', 'warn'],
|
||||
['invoke', 'events.subscribe'], ['subscribe', 'task.updated'],
|
||||
['invoke', 'events.unsubscribe'], ['unsubscribe', 0],
|
||||
['invoke', 'ui.navigate'], ['navigate', 'settings'],
|
||||
])
|
||||
})
|
||||
|
||||
test('closing a plugin view restores the page it was opened from', () => {
|
||||
const sidebar = { pluginId: 'vendor.tool', viewId: 'console', location: 'sidebar', from: 'host' }
|
||||
const tab = { pluginId: 'vendor.tool', viewId: 'metrics', location: 'vm.tab', vm: 'builtin.macos:mac', from: 'builtin.macos:mac' }
|
||||
const settings = { pluginId: 'vendor.tool', viewId: 'settings', location: 'settings', from: 'builtin.macos:mac' }
|
||||
|
||||
const back = closePluginView(openPluginView(openPluginView(emptyPluginViewState, tab), settings))
|
||||
assert.equal(back.state.route.viewId, 'metrics')
|
||||
assert.equal(back.page, 'builtin.macos:mac', 'the VM must be selected again under its tab')
|
||||
|
||||
let state = openPluginView(openPluginView(emptyPluginViewState, { ...tab, viewId: 'other' }), tab)
|
||||
state = closePluginView(state).state
|
||||
state = closePluginView(openPluginView(state, sidebar)).state
|
||||
assert.equal(state.route, null, 'a tab left through Overview must not reopen')
|
||||
})
|
||||
|
||||
test('reopening a plugin dialog returns to it and keeps the ones below', () => {
|
||||
const dialog = (viewId) => ({ pluginId: 'vendor.tool', viewId, location: 'dialog' })
|
||||
let state = ['a', 'b', 'c'].reduce((current, id) => openPluginView(current, dialog(id)), emptyPluginViewState)
|
||||
state = openPluginView(state, dialog('b'))
|
||||
assert.deepEqual(state.dialogs.map((item) => item.viewId), ['a', 'b'])
|
||||
})
|
||||
|
||||
test('view conditions match the state they name', () => {
|
||||
assert.equal(matchViewCondition(undefined, {}), true)
|
||||
assert.equal(matchViewCondition('default', {}), true)
|
||||
assert.equal(matchViewCondition('vmState == running', { vmState: 'running' }), true)
|
||||
assert.equal(matchViewCondition('vmState==running', { vmState: 'stopped' }), false)
|
||||
assert.equal(matchViewCondition('unknown', {}), false)
|
||||
})
|
||||
|
||||
test('plugin forms start from the displayed values and report empty required fields', () => {
|
||||
const schema = { properties: {
|
||||
mode: { type: 'string', enum: ['dev', 'prod'] },
|
||||
count: { type: 'integer', minimum: 2 },
|
||||
enabled: { type: 'boolean' },
|
||||
label: { type: 'string', default: 'x' },
|
||||
name: { type: 'string', required: true },
|
||||
} }
|
||||
const values = initialFormValues(schema, { label: 'given' })
|
||||
assert.deepEqual(values, { mode: 'dev', count: 2, enabled: false, label: 'given', name: '' })
|
||||
assert.deepEqual(missingFormFields(schema, values), ['name'])
|
||||
assert.deepEqual(missingFormFields(schema, { ...values, name: 'demo' }), [])
|
||||
})
|
||||
|
||||
test('closing a plugin page cancels only its unfinished tasks', async () => {
|
||||
const canceled = []
|
||||
let next = 0
|
||||
const scope = createPluginTaskScope(async (method, params) => {
|
||||
if (method === 'task.start') return { id: `task-${++next}` }
|
||||
if (params.status === 'canceled') canceled.push(params.id)
|
||||
return {}
|
||||
})
|
||||
await scope.invoke('task.start', {})
|
||||
await scope.invoke('task.start', {})
|
||||
await scope.invoke('task.finish', { id: 'task-1' })
|
||||
const late = scope.invoke('task.start', {})
|
||||
scope.close()
|
||||
await late
|
||||
assert.deepEqual(canceled, ['task-2', 'task-3'])
|
||||
})
|
||||
|
||||
test('closing a page retries cleanup of a late task after rate limiting', async () => {
|
||||
let attempts = 0
|
||||
const scope = createPluginTaskScope(async (method) => {
|
||||
if (method === 'task.start') return { id: 'late-task' }
|
||||
if (++attempts === 1) throw new Error('plugin exceeded Host API rate limit')
|
||||
return {}
|
||||
})
|
||||
const start = scope.invoke('task.start', {})
|
||||
scope.close()
|
||||
await start
|
||||
assert.equal(attempts, 2)
|
||||
})
|
||||
|
||||
test('pruning removes an unavailable page but keeps open dialogs until their VM disappears', () => {
|
||||
const page = { pluginId: 'demo', viewId: 'vm', location: 'vm.tab', vm: 'vm-1' }
|
||||
const dialog = { ...page, viewId: 'dialog', location: 'dialog' }
|
||||
let state = openPluginView(emptyPluginViewState, page)
|
||||
state = openPluginView(state, dialog)
|
||||
const views = new Set(['demo/vm', 'demo/dialog'])
|
||||
assert.deepEqual(prunePluginViews(state, views, () => true, () => false), { ...emptyPluginViewState, dialogs: [dialog] })
|
||||
assert.deepEqual(prunePluginViews(state, views, () => false), emptyPluginViewState)
|
||||
})
|
||||
+161
-9
@@ -11,6 +11,8 @@ import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
|
||||
import { DataRootReadOnly } from './components/DataRootReadOnly'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
import { PluginViewHost } from './components/PluginViewHost'
|
||||
import { locText } from './components/SchemaForm'
|
||||
import { VMAction, VMBusyAction, VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
@@ -21,7 +23,10 @@ import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFo
|
||||
import { hasVisibleDialog } from './lib/dialogState'
|
||||
import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats'
|
||||
import { vmRefKey } from './lib/vmRef'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
|
||||
import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter'
|
||||
import { publishPluginHostEvent } from './lib/pluginViewEvents'
|
||||
import { buildSafePluginAssetURL } from './lib/pluginAssets'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, ViewContribution } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
import { ConfirmDialog, Modal } from './ui/dialog'
|
||||
import { Toaster, useToasts } from './ui/toast'
|
||||
@@ -74,7 +79,7 @@ const failKey: Record<VMBusyAction, I18nKey> = {
|
||||
|
||||
export const App: React.FC = () => {
|
||||
const [state, setState] = useState<AppState | null>(null)
|
||||
const [selected, setSelected] = useState<string>(HOST_ID)
|
||||
const [selected, setSelectedPage] = useState<string>(HOST_ID)
|
||||
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(null)
|
||||
// Check for a new release once the app is up, then every 6 hours, so the
|
||||
// sidebar's update button shows up without opening the About page.
|
||||
@@ -119,6 +124,13 @@ export const App: React.FC = () => {
|
||||
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
|
||||
)
|
||||
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
|
||||
const [pluginViewState, setPluginViewState] = useState<PluginViewState>(emptyPluginViewState)
|
||||
const [pluginViewMeta, setPluginViewMeta] = useState<Record<string, { title?: string; badge?: { text: string; tone: string } }>>({})
|
||||
// Host navigation always leaves plugin views, even when the target page is already selected underneath.
|
||||
const setSelected = useCallback((id: string) => {
|
||||
setPluginViewState(emptyPluginViewState)
|
||||
setSelectedPage(id)
|
||||
}, [])
|
||||
const [activeThemePayload, setActiveThemePayload] = useState<ActiveThemePayload | null>(null)
|
||||
const [themeRevision, setThemeRevision] = useState(0)
|
||||
|
||||
@@ -206,7 +218,7 @@ export const App: React.FC = () => {
|
||||
const s = await api.GetState()
|
||||
setState(s)
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
setSelectedPage((cur) => {
|
||||
if (PAGE_IDS.includes(cur)) return cur
|
||||
if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID
|
||||
@@ -272,6 +284,111 @@ export const App: React.FC = () => {
|
||||
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
|
||||
const pluginViews = pluginUI?.views ?? []
|
||||
const findVM = (ref: string) => vms.find((item) => vmRefKey(item) === ref || item.name === ref)
|
||||
const viewAvailable = (view: ViewContribution, vmRef?: string) => {
|
||||
const vm = vmRef ? findVM(vmRef) : undefined
|
||||
return matchViewCondition(view.when, { vmState: vm ? state?.transitions[vmRefKey(vm)] ?? vm.state : '', theme })
|
||||
}
|
||||
const openView = (view: ViewContribution, targetVM?: string) => {
|
||||
const route: PluginViewRoute = { pluginId: view.pluginId ?? '', viewId: view.id, location: view.location as PluginViewRoute['location'], vm: targetVM, from: selected }
|
||||
if (view.location === 'vm.tab') {
|
||||
const target = findVM(targetVM || (selectedVM ? vmRefKey(selectedVM) : ''))
|
||||
if (!target) throw new Error('A valid VM is required for this view')
|
||||
route.vm = vmRefKey(target)
|
||||
}
|
||||
if (!route.vm && view.when?.split('==')[0].trim() === 'vmState' && selectedVM) route.vm = vmRefKey(selectedVM)
|
||||
if (!viewAvailable(view, route.vm)) throw new Error('This view is not available in the current state')
|
||||
if (view.location === 'vm.tab') setSelectedPage(route.vm!)
|
||||
else if (view.location === 'settings') setSelectedPage(SETTINGS_ID)
|
||||
setPluginViewState((current) => openPluginView(current, route))
|
||||
}
|
||||
const openViewFromClick = (view: ViewContribution, targetVM?: string) => {
|
||||
try {
|
||||
openView(view, targetVM)
|
||||
} catch (error) {
|
||||
fail(tr('open'), error)
|
||||
}
|
||||
}
|
||||
const closeView = () => {
|
||||
const result = closePluginView(pluginViewState)
|
||||
setPluginViewState(result.state)
|
||||
if (result.page && (PAGE_IDS.includes(result.page) || findVM(result.page))) setSelectedPage(result.page)
|
||||
return { closed: result.closed }
|
||||
}
|
||||
const navigateHost = (target: { page?: string; vm?: string }) => {
|
||||
if (target.vm) {
|
||||
const vm = findVM(target.vm)
|
||||
if (!vm) throw new Error(`Unknown VM: ${target.vm}`)
|
||||
setSelected(vmRefKey(vm))
|
||||
return
|
||||
}
|
||||
const pages: Record<string, string> = { host: HOST_ID, images: INSTALLERS_ID, plugins: PLUGINS_ID, settings: SETTINGS_ID, about: ABOUT_ID }
|
||||
const page = pages[target.page ?? '']
|
||||
if (!page) throw new Error(`Unknown page: ${target.page}`)
|
||||
setSelected(page)
|
||||
}
|
||||
const updateViewMetadata = (view: ViewContribution, metadata: { title?: string; badge?: { text: string; tone: string } }) => {
|
||||
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
||||
setPluginViewMeta((current) => ({ ...current, [key]: { ...current[key], ...metadata } }))
|
||||
}
|
||||
useEffect(() => {
|
||||
const valid = new Set(pluginViews.map((view) => pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })))
|
||||
setPluginViewState((current) => prunePluginViews(current, valid, (vm) => !!vm && vms.some((item) => vmRefKey(item) === vm), (route) => {
|
||||
const view = findRouteView(route)
|
||||
return !!view && viewAvailable(view, route.vm)
|
||||
}))
|
||||
setPluginViewMeta((current) => Object.fromEntries(Object.entries(current).filter(([key]) => valid.has(key))))
|
||||
}, [pluginUI?.views, state?.vms, state?.transitions, selected, theme])
|
||||
const findRouteView = (route: PluginViewRoute) =>
|
||||
pluginViews.find((view) => (view.pluginId ?? '') === route.pluginId && view.id === route.viewId && view.location === route.location)
|
||||
const routedView = pluginViewState.route ? findRouteView(pluginViewState.route) : undefined
|
||||
const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined
|
||||
const activePluginRoute = activePluginView ? pluginViewState.route : null
|
||||
const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => (
|
||||
<PluginViewHost
|
||||
key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`}
|
||||
view={view}
|
||||
locale={locale}
|
||||
appearance={theme}
|
||||
assetToken={pluginUI?.asset_token ?? ''}
|
||||
vm={route.vm}
|
||||
dialog={dialog}
|
||||
metadata={pluginViewMeta[pluginViewKey(route)]}
|
||||
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
|
||||
onOpenView={openView}
|
||||
onCloseView={dialog ? () => {
|
||||
setPluginViewState((current) => closePluginDialog(current, route))
|
||||
return { closed: true }
|
||||
} : closeView}
|
||||
onNavigate={navigateHost}
|
||||
/>
|
||||
)
|
||||
const renderVMTabs = () => {
|
||||
if (!selectedVM) return null
|
||||
const tabs = pluginViews.filter((view) => view.location === 'vm.tab' && viewAvailable(view, vmRefKey(selectedVM)))
|
||||
if (tabs.length === 0) return null
|
||||
return (
|
||||
<div className="tabs rg-p-tabs" role="tablist" aria-label={tr('overview')}>
|
||||
<button type="button" role="tab" className="tab rg-p-tab" aria-selected={!activePluginRoute || activePluginRoute.location !== 'vm.tab'} onClick={closeView}>
|
||||
{tr('overview')}
|
||||
</button>
|
||||
{tabs.map((view) => {
|
||||
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
||||
const selectedTab = activePluginRoute?.location === 'vm.tab' && pluginViewKey(activePluginRoute) === key
|
||||
const badge = pluginViewMeta[key]?.badge
|
||||
return (
|
||||
<button key={key} type="button" role="tab" className="tab rg-p-tab" aria-selected={selectedTab} onClick={() => openViewFromClick(view, vmRefKey(selectedVM))}>
|
||||
{locText(view.title, locale, view.id)}{badge ? ` · ${badge.text}` : ''}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarSelected = activePluginRoute?.location === 'sidebar' ? `__plugin_view__:${pluginViewKey(activePluginRoute)}` : selected
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setDetail(null); return }
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
@@ -318,6 +435,15 @@ export const App: React.FC = () => {
|
||||
}
|
||||
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales, state?.detected_locale)
|
||||
const dir = localeDir(locale)
|
||||
const settingsPluginViews = pluginViews.filter((view) => view.location === 'settings' && viewAvailable(view, selectedVM ? vmRefKey(selectedVM) : undefined)).map((view) => {
|
||||
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
||||
return { id: key, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, onOpen: () => openViewFromClick(view) }
|
||||
})
|
||||
const sidebarPluginViews = pluginViews.filter((view) => view.location === 'sidebar' && viewAvailable(view, selectedVM ? vmRefKey(selectedVM) : undefined)).map((view) => {
|
||||
const key = pluginViewKey({ pluginId: view.pluginId ?? '', viewId: view.id })
|
||||
const icon = view.icon ? buildSafePluginAssetURL(pluginUI?.asset_token ?? '', view.pluginId, view.icon) ?? undefined : undefined
|
||||
return { id: `__plugin_view__:${key}`, view, title: locText(view.title, locale, view.id), badge: pluginViewMeta[key]?.badge?.text, icon }
|
||||
})
|
||||
useEffect(() => {
|
||||
const html = document.documentElement
|
||||
html.lang = locale === 'en-XA' ? 'en' : locale
|
||||
@@ -348,6 +474,7 @@ export const App: React.FC = () => {
|
||||
const canSuspend = state?.can_suspend ?? false
|
||||
|
||||
onTaskRef.current = (task: Task) => {
|
||||
publishPluginHostEvent('task.updated', task)
|
||||
if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) {
|
||||
notifiedTasks.current.set(task.id, task.updated_at)
|
||||
fail(tr('updateFailed'), task.error ?? '')
|
||||
@@ -468,7 +595,7 @@ export const App: React.FC = () => {
|
||||
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
|
||||
|
||||
// UI Contract v2 read-only document state attributes.
|
||||
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
|
||||
const currentView = showSetup ? 'setup' : activePluginRoute?.location === 'sidebar' ? 'plugins' : activePluginRoute?.location === 'settings' ? 'settings' : activePluginRoute?.location === 'vm.tab' ? 'vm' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
|
||||
const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0
|
||||
const hasAnyError = unseenErrors > 0 || !!loadError
|
||||
const uiStateRef = useRef<UIStateSnapshot>({
|
||||
@@ -526,7 +653,9 @@ export const App: React.FC = () => {
|
||||
for (const v of vms) {
|
||||
const key = vmRefKey(v)
|
||||
if (prev[key] !== undefined && prev[key] !== next[key]) {
|
||||
emitThemeEvent('vm.stateChanged', { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] })
|
||||
const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }
|
||||
emitThemeEvent('vm.stateChanged', payload)
|
||||
publishPluginHostEvent('vm.stateChanged', payload)
|
||||
}
|
||||
}
|
||||
}, [vms, state?.transitions])
|
||||
@@ -1144,11 +1273,16 @@ export const App: React.FC = () => {
|
||||
vms={vms}
|
||||
transitions={state?.transitions ?? {}}
|
||||
busyActions={busy}
|
||||
selected={selected}
|
||||
selected={sidebarSelected}
|
||||
hostReady={hostReady}
|
||||
canSuspend={canSuspend}
|
||||
onSelect={(id) => {
|
||||
setSelected(id)
|
||||
if (id.startsWith('__plugin_view__:')) {
|
||||
const item = sidebarPluginViews.find((entry) => entry.id === id)
|
||||
if (item) openViewFromClick(item.view)
|
||||
} else {
|
||||
setSelected(id)
|
||||
}
|
||||
if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) {
|
||||
toggleSidebar()
|
||||
}
|
||||
@@ -1161,6 +1295,7 @@ export const App: React.FC = () => {
|
||||
downloading={Object.values(taskMap).some(isActiveInstallerTask)}
|
||||
safeMode={state?.safe_mode}
|
||||
updateDot={!!appUpdate?.has_update}
|
||||
pluginViews={sidebarPluginViews}
|
||||
updateCard={showUpdateCard ? (
|
||||
<UpdateCapsule
|
||||
locale={locale}
|
||||
@@ -1184,6 +1319,11 @@ export const App: React.FC = () => {
|
||||
<div className="page">
|
||||
{loadError ? <div className="notice notice-error">{loadError}</div> : <span className="muted">…</span>}
|
||||
</div>
|
||||
) : activePluginRoute && activePluginView ? (
|
||||
<>
|
||||
{activePluginRoute.location === 'vm.tab' && renderVMTabs()}
|
||||
{renderPluginView(activePluginRoute, activePluginView)}
|
||||
</>
|
||||
) : selected === INSTALLERS_ID ? (
|
||||
<ImagesPage
|
||||
locale={locale}
|
||||
@@ -1216,9 +1356,13 @@ export const App: React.FC = () => {
|
||||
onError={fail}
|
||||
onThemeChanged={() => setThemeRevision((r) => r + 1)}
|
||||
onLocaleSwitch={(l) => void setLang(l)}
|
||||
onOpenView={openView}
|
||||
onNavigate={navigateHost}
|
||||
/>
|
||||
) : selectedVM ? (
|
||||
<VMPage
|
||||
<>
|
||||
{renderVMTabs()}
|
||||
<VMPage
|
||||
locale={locale}
|
||||
name={selectedVM.name}
|
||||
driverID={selectedVM.driver_id ?? ''}
|
||||
@@ -1274,7 +1418,8 @@ export const App: React.FC = () => {
|
||||
onError={fail}
|
||||
dropping={dropping}
|
||||
pluginUI={pluginUI}
|
||||
/>
|
||||
/>
|
||||
</>
|
||||
) : selected === SETTINGS_ID ? (
|
||||
<AppSettingsPage
|
||||
state={state}
|
||||
@@ -1284,6 +1429,7 @@ export const App: React.FC = () => {
|
||||
themeMode={effectiveThemeMode}
|
||||
canLight={canLight}
|
||||
canDark={canDark}
|
||||
pluginViews={settingsPluginViews}
|
||||
onThemeMode={setThemeMode}
|
||||
onSetLocale={setLang}
|
||||
onRefresh={refresh}
|
||||
@@ -1493,6 +1639,12 @@ export const App: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Every open dialog stays mounted so the ones underneath keep their state. */}
|
||||
{pluginViewState.dialogs.map((route) => {
|
||||
const view = findRouteView(route)
|
||||
return view && renderPluginView(route, view, true)
|
||||
})}
|
||||
|
||||
<div className="rg-layer rg-layer-overlay" data-rg-layer="layer.overlay" aria-hidden="true" />
|
||||
</div>
|
||||
{/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */}
|
||||
|
||||
@@ -56,6 +56,8 @@ interface Props {
|
||||
themeMode: ThemeMode
|
||||
canLight?: boolean
|
||||
canDark?: boolean
|
||||
/** Plugin views declared for this page. */
|
||||
pluginViews?: { id: string; title: string; badge?: string; onOpen: () => void }[]
|
||||
onThemeMode: (mode: ThemeMode) => void
|
||||
onSetLocale: (l: Locale) => void
|
||||
onRefresh: () => void
|
||||
@@ -64,7 +66,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export const AppSettingsPage: React.FC<Props> = ({
|
||||
state, locale, locales, tasks, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onToast, onError,
|
||||
state, locale, locales, tasks, themeMode, canLight = true, canDark = true, pluginViews = [], onThemeMode, onSetLocale, onRefresh, onToast, onError,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { host, config, optimizations } = state
|
||||
@@ -587,6 +589,27 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{pluginViews.length > 0 && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('sidebarPlugins')}</div>
|
||||
<div className="list">
|
||||
{pluginViews.map((view) => (
|
||||
<div className="row" key={view.id}>
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{view.title}
|
||||
{view.badge && <span className="badge rg-p-badge badge-idle">{view.badge}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button aria-label={`${tr('open')} ${view.title}`} onClick={view.onOpen}>{tr('open')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{confirmHypervisor && (
|
||||
<Modal
|
||||
className="md"
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
|
||||
import { Locale, PanelContribution } from '../types'
|
||||
import { Locale, PanelContribution, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { ConfirmDialog } from '../ui/dialog'
|
||||
import { api } from '../wails'
|
||||
import { locText } from './SchemaForm'
|
||||
import { ClipboardSetText } from '../../wailsjs/runtime/runtime'
|
||||
import {
|
||||
createPluginTaskScope, initialFormValues, invokePluginViewAction, missingFormFields,
|
||||
PluginConfirmRequest, PluginFormRequest, PluginFormResult,
|
||||
} from '../lib/pluginViewActions'
|
||||
import { buildSafePluginAssetURL } from '../lib/pluginAssets'
|
||||
import { subscribePluginHostEvents } from '../lib/pluginViewEvents'
|
||||
import { locText, SchemaForm } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -15,40 +23,130 @@ interface Props {
|
||||
headless?: boolean
|
||||
/** Upper bound for the iframe height in px (defaults to 480 for inline panels). */
|
||||
maxHeight?: number
|
||||
/** Narrower containers scroll horizontally instead of shrinking the page below this width. */
|
||||
minWidth?: number
|
||||
/** Incrementing this reloads the iframe cleanly. */
|
||||
refreshSignal?: number
|
||||
viewLocation?: ViewContribution['location']
|
||||
vm?: string
|
||||
onOpenView?: (view: ViewContribution, vm?: string) => void
|
||||
onCloseView?: () => { closed: boolean }
|
||||
onNavigate?: (target: { page?: string; vm?: string }) => void
|
||||
onMetadata?: (metadata: { title?: string; badge?: { text: string; tone: string } }) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Sandboxed L4 iframe panel verifying window identity (`event.source === iframe.contentWindow`
|
||||
* and opaque `null` origin) and routing Host API calls through `PanelBridgeCall`.
|
||||
*/
|
||||
const RE_SAFE_TOKEN = /^[a-f0-9]+$/
|
||||
const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/
|
||||
const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/
|
||||
|
||||
function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null {
|
||||
if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null
|
||||
if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null
|
||||
const raw = (entry || 'index.html').trim().replace(/^\/+/, '')
|
||||
if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) {
|
||||
return null
|
||||
}
|
||||
const segs = raw.split('/')
|
||||
for (const seg of segs) {
|
||||
if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null
|
||||
}
|
||||
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
|
||||
}
|
||||
|
||||
/** Sandboxed plugin frame with identity-checked host RPC and local UI effects. */
|
||||
export const PluginPanelFrame: React.FC<Props> = ({
|
||||
locale, panel, assetToken, appearance, headless, maxHeight = 480, refreshSignal = 0,
|
||||
locale, panel, assetToken, appearance, headless, maxHeight = 480, minWidth, refreshSignal = 0,
|
||||
viewLocation, vm, onOpenView, onCloseView, onNavigate, onMetadata,
|
||||
}) => {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const wrapperRef = useRef<HTMLDivElement>(null)
|
||||
const localeRef = useRef<Locale>(locale)
|
||||
localeRef.current = locale
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [nonce, setNonce] = useState(0)
|
||||
const [titleOverride, setTitleOverride] = useState<string | null>(null)
|
||||
const [badge, setBadge] = useState<{ text: string; tone: string } | null>(null)
|
||||
const metadataRef = useRef<{ title?: string; badge?: { text: string; tone: string } }>({})
|
||||
const actionContextRef = useRef({ vm, onOpenView, onCloseView, onNavigate, onMetadata })
|
||||
actionContextRef.current = { vm, onOpenView, onCloseView, onNavigate, onMetadata }
|
||||
const [confirmRequest, setConfirmRequest] = useState<PluginConfirmRequest | null>(null)
|
||||
const confirmResolverRef = useRef<((confirmed: boolean) => void) | null>(null)
|
||||
const [formRequest, setFormRequest] = useState<PluginFormRequest | null>(null)
|
||||
const [formError, setFormError] = useState('')
|
||||
const formResolverRef = useRef<((result: PluginFormResult) => void) | null>(null)
|
||||
const subscriptionsRef = useRef<Set<string>>(new Set())
|
||||
const intersectingRef = useRef(true)
|
||||
const lastVisibilityRef = useRef<boolean | null>(null)
|
||||
|
||||
const src = buildSafePluginAssetURL(assetToken, panel.pluginId, panel.entry)
|
||||
const title = titleOverride || locText(panel.title, locale, panel.id)
|
||||
|
||||
const updateMetadata = (patch: { title?: string; badge?: { text: string; tone: string } }) => {
|
||||
metadataRef.current = { ...metadataRef.current, ...patch }
|
||||
if (patch.title !== undefined) setTitleOverride(patch.title)
|
||||
if ('badge' in patch) setBadge(patch.badge ?? null)
|
||||
actionContextRef.current.onMetadata?.(metadataRef.current)
|
||||
}
|
||||
|
||||
const finishConfirmation = (confirmed: boolean) => {
|
||||
const resolve = confirmResolverRef.current
|
||||
confirmResolverRef.current = null
|
||||
setConfirmRequest(null)
|
||||
resolve?.(confirmed)
|
||||
}
|
||||
|
||||
const requestConfirmation = (request: PluginConfirmRequest) => new Promise<boolean>((resolve, reject) => {
|
||||
if (confirmResolverRef.current || formResolverRef.current) {
|
||||
reject(new Error('A plugin dialog is already pending'))
|
||||
return
|
||||
}
|
||||
confirmResolverRef.current = resolve
|
||||
setConfirmRequest(request)
|
||||
})
|
||||
|
||||
const finishForm = (confirmed: boolean) => {
|
||||
const resolve = formResolverRef.current
|
||||
formResolverRef.current = null
|
||||
const values = formRequest?.values
|
||||
setFormRequest(null)
|
||||
resolve?.(confirmed ? { confirmed: true, values } : { confirmed: false })
|
||||
}
|
||||
|
||||
const requestForm = (request: PluginFormRequest) => new Promise<PluginFormResult>((resolve, reject) => {
|
||||
if (confirmResolverRef.current || formResolverRef.current) {
|
||||
reject(new Error('A plugin dialog is already pending'))
|
||||
return
|
||||
}
|
||||
formResolverRef.current = resolve
|
||||
setFormError('')
|
||||
setFormRequest({ ...request, values: initialFormValues(request.schema, request.values) })
|
||||
})
|
||||
|
||||
const submitForm = (e: React.MouseEvent, request: PluginFormRequest) => {
|
||||
const missing = missingFormFields(request.schema, request.values)
|
||||
if (missing.length === 0) {
|
||||
finishForm(true)
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
const fields = missing.map((key) => locText(request.schema.properties?.[key]?.title, locale, key)).join(', ')
|
||||
setFormError(t(locale, 'formRequiredFields', { fields }))
|
||||
}
|
||||
|
||||
const emitVisibility = (reason: string, force = false) => {
|
||||
const visible = !document.hidden && intersectingRef.current
|
||||
if (!force && lastVisibilityRef.current === visible) return
|
||||
lastVisibilityRef.current = visible
|
||||
if (!subscriptionsRef.current.has('view.visibilityChanged')) return
|
||||
iframeRef.current?.contentWindow?.postMessage({
|
||||
type: 'reims:event', event: 'view.visibilityChanged', data: { visible, reason },
|
||||
}, '*')
|
||||
}
|
||||
|
||||
const subscribe = (events: string[]) => {
|
||||
for (const event of events) subscriptionsRef.current.add(event)
|
||||
if (events.includes('view.visibilityChanged')) emitVisibility('subscribe', true)
|
||||
}
|
||||
|
||||
const unsubscribe = (events: string[]) => {
|
||||
if (events.length === 0) subscriptionsRef.current.clear()
|
||||
else for (const event of events) subscriptionsRef.current.delete(event)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setConfirmRequest(null)
|
||||
setFormRequest(null)
|
||||
subscriptionsRef.current.clear()
|
||||
lastVisibilityRef.current = null
|
||||
return () => {
|
||||
confirmResolverRef.current?.(false)
|
||||
confirmResolverRef.current = null
|
||||
formResolverRef.current?.({ confirmed: false })
|
||||
formResolverRef.current = null
|
||||
}
|
||||
}, [src, nonce])
|
||||
|
||||
useEffect(() => {
|
||||
if (refreshSignal > 0) {
|
||||
@@ -57,7 +155,30 @@ export const PluginPanelFrame: React.FC<Props> = ({
|
||||
}
|
||||
}, [refreshSignal])
|
||||
|
||||
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
|
||||
useEffect(() => {
|
||||
const onVisibility = () => emitVisibility('document')
|
||||
document.addEventListener('visibilitychange', onVisibility)
|
||||
const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver((entries) => {
|
||||
intersectingRef.current = entries[0]?.isIntersecting ?? true
|
||||
emitVisibility('viewport')
|
||||
})
|
||||
if (wrapperRef.current) observer?.observe(wrapperRef.current)
|
||||
emitVisibility('mount', true)
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', onVisibility)
|
||||
observer?.disconnect()
|
||||
subscriptionsRef.current.clear()
|
||||
}
|
||||
}, [src, nonce])
|
||||
|
||||
useEffect(() => subscribePluginHostEvents((event, data) => {
|
||||
if (!subscriptionsRef.current.has(event)) return
|
||||
if (event === 'task.updated') {
|
||||
const task = data as { kind?: string }
|
||||
if (task.kind !== `plugin:${panel.pluginId}`) return
|
||||
}
|
||||
iframeRef.current?.contentWindow?.postMessage({ type: 'reims:event', event, data }, '*')
|
||||
}), [panel.pluginId, nonce, src])
|
||||
|
||||
const syncTheme = () => {
|
||||
const win = iframeRef.current?.contentWindow
|
||||
@@ -69,10 +190,8 @@ export const PluginPanelFrame: React.FC<Props> = ({
|
||||
}
|
||||
const dir = localeDir(locale)
|
||||
const messages = getPluginMessageBundle(panel.pluginId ?? '', locale)
|
||||
// bridgeApi 1.0 events (bridgeContract.ts).
|
||||
win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*')
|
||||
win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*')
|
||||
// Pre-1.0 message types, kept for panels written before the bridge contract.
|
||||
win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*')
|
||||
win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*')
|
||||
}
|
||||
@@ -85,30 +204,48 @@ export const PluginPanelFrame: React.FC<Props> = ({
|
||||
useEffect(() => {
|
||||
if (!src) return
|
||||
let cancelled = false
|
||||
|
||||
const taskScope = createPluginTaskScope((method, input) => api.PanelBridgeCall(panel.pluginId ?? '', method, input))
|
||||
const onMessage = async (e: MessageEvent) => {
|
||||
const win = iframeRef.current?.contentWindow
|
||||
// Require opaque origin and exact contentWindow identity for sandbox="allow-scripts".
|
||||
if (!win || e.source !== win || e.origin !== 'null') return
|
||||
const msg = e.data
|
||||
if (!msg || typeof msg !== 'object' || msg.type !== 'reims:rpc' || typeof msg.id !== 'string' || typeof msg.method !== 'string') return
|
||||
const rawParams = msg.params
|
||||
const params: Record<string, unknown> =
|
||||
rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams)
|
||||
? (rawParams as Record<string, unknown>)
|
||||
: {}
|
||||
const params: Record<string, unknown> = rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams) ? rawParams : {}
|
||||
try {
|
||||
if (msg.method === 'i18n.getBundle') {
|
||||
const curLocale = localeRef.current
|
||||
const bundle = {
|
||||
locale: curLocale,
|
||||
dir: localeDir(curLocale),
|
||||
messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale),
|
||||
}
|
||||
const bundle = { locale: curLocale, dir: localeDir(curLocale), messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale) }
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result: bundle }, '*')
|
||||
return
|
||||
}
|
||||
const result = await api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params)
|
||||
const result = await invokePluginViewAction(msg.method, params, {
|
||||
invoke: taskScope.invoke,
|
||||
confirm: requestConfirmation,
|
||||
showForm: requestForm,
|
||||
copy: async (text) => {
|
||||
if (!await ClipboardSetText(text)) throw new Error('The clipboard is unavailable')
|
||||
},
|
||||
setTitle: (nextTitle) => updateMetadata({ title: nextTitle }),
|
||||
setBadge: (text, tone) => updateMetadata({ badge: text ? { text, tone } : undefined }),
|
||||
openView: (view, targetVM) => {
|
||||
const context = actionContextRef.current
|
||||
if (!context.onOpenView) throw new Error('not_supported')
|
||||
context.onOpenView(view, targetVM ?? context.vm)
|
||||
},
|
||||
close: async () => {
|
||||
const context = actionContextRef.current
|
||||
if (!context.onCloseView) throw new Error('not_supported')
|
||||
return context.onCloseView()
|
||||
},
|
||||
navigate: (target) => {
|
||||
const context = actionContextRef.current
|
||||
if (!context.onNavigate) throw new Error('not_supported')
|
||||
context.onNavigate(target)
|
||||
},
|
||||
subscribe,
|
||||
unsubscribe,
|
||||
})
|
||||
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*')
|
||||
} catch (err) {
|
||||
@@ -116,10 +253,10 @@ export const PluginPanelFrame: React.FC<Props> = ({
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: parseAppError(err).summary || 'RPC failed' }, '*')
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('message', onMessage)
|
||||
return () => {
|
||||
cancelled = true
|
||||
taskScope.close()
|
||||
window.removeEventListener('message', onMessage)
|
||||
}
|
||||
}, [panel.pluginId, nonce, src])
|
||||
@@ -131,30 +268,65 @@ export const PluginPanelFrame: React.FC<Props> = ({
|
||||
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{t(locale, 'panelLoadFailed')}</span>
|
||||
</span>
|
||||
{src && (
|
||||
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
|
||||
{t(locale, 'installersRetry')}
|
||||
</Button>
|
||||
)}
|
||||
{src && <Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>{t(locale, 'installersRetry')}</Button>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId}>
|
||||
{!headless && <div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>}
|
||||
<div ref={wrapperRef} className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId} data-view-location={viewLocation} style={minWidth ? { overflowX: 'auto' } : undefined}>
|
||||
{!headless && (
|
||||
<div className="plugin-panel-head">
|
||||
<span>{title}</span>
|
||||
{badge && <span className={`badge rg-p-badge badge-${badge.tone === 'ok' ? 'ok' : badge.tone === 'warn' ? 'warn' : badge.tone === 'error' ? 'error' : 'idle'}`}>{badge.text}</span>}
|
||||
</div>
|
||||
)}
|
||||
<iframe
|
||||
key={nonce}
|
||||
ref={iframeRef}
|
||||
className="plugin-panel-frame"
|
||||
title={locText(panel.title, locale, panel.id)}
|
||||
title={title}
|
||||
src={src}
|
||||
sandbox="allow-scripts"
|
||||
referrerPolicy="no-referrer"
|
||||
style={{ height: Math.max(120, Math.min(maxHeight, panel.height || 220)) }}
|
||||
style={{ height: Math.max(120, Math.min(maxHeight, panel.height || 220)), minWidth }}
|
||||
onLoad={syncTheme}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
{confirmRequest && (
|
||||
<ConfirmDialog
|
||||
title={confirmRequest.title || title}
|
||||
description={confirmRequest.message}
|
||||
confirmLabel={confirmRequest.confirmLabel || t(locale, 'confirm')}
|
||||
cancelLabel={confirmRequest.cancelLabel || t(locale, 'cancel')}
|
||||
tone={confirmRequest.danger ? 'danger' : 'neutral'}
|
||||
onCancel={() => finishConfirmation(false)}
|
||||
onConfirm={() => finishConfirmation(true)}
|
||||
/>
|
||||
)}
|
||||
{formRequest && (
|
||||
<ConfirmDialog
|
||||
title={formRequest.title}
|
||||
description={formRequest.message || ''}
|
||||
confirmLabel={formRequest.confirmLabel || t(locale, 'confirm')}
|
||||
cancelLabel={formRequest.cancelLabel || t(locale, 'cancel')}
|
||||
tone={formRequest.danger ? 'danger' : 'neutral'}
|
||||
onCancel={() => finishForm(false)}
|
||||
onConfirm={(e) => submitForm(e, formRequest)}
|
||||
>
|
||||
<SchemaForm
|
||||
locale={locale}
|
||||
schema={formRequest.schema}
|
||||
values={formRequest.values}
|
||||
hideGroupHeader
|
||||
onChange={(next) => {
|
||||
setFormError('')
|
||||
setFormRequest((current) => current ? { ...current, values: next } : current)
|
||||
}}
|
||||
/>
|
||||
{formError && <div className="notice notice-error" role="alert">{formError}</div>}
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import React from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Locale, ViewContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { PluginPanelFrame } from './PluginPanelFrame'
|
||||
import { locText } from './SchemaForm'
|
||||
|
||||
interface Props {
|
||||
view: ViewContribution
|
||||
locale: Locale
|
||||
appearance: 'light' | 'dark'
|
||||
assetToken: string
|
||||
vm?: string
|
||||
dialog?: boolean
|
||||
metadata?: { title?: string; badge?: { text: string; tone: string } }
|
||||
onMetadata: (metadata: { title?: string; badge?: { text: string; tone: string } }) => void
|
||||
onOpenView: (view: ViewContribution, vm?: string) => void
|
||||
onCloseView: () => { closed: boolean }
|
||||
onNavigate: (target: { page?: string; vm?: string }) => void
|
||||
}
|
||||
|
||||
export const PluginViewHost: React.FC<Props> = ({
|
||||
view, locale, appearance, assetToken, vm, dialog, metadata, onMetadata, onOpenView, onCloseView, onNavigate,
|
||||
}) => {
|
||||
const title = metadata?.title || locText(view.title, locale, view.id)
|
||||
const badge = metadata?.badge
|
||||
const panel = {
|
||||
id: view.id,
|
||||
pluginId: view.pluginId,
|
||||
title: view.title,
|
||||
entry: view.entry,
|
||||
slot: '',
|
||||
height: 640,
|
||||
}
|
||||
const frame = (
|
||||
<PluginPanelFrame
|
||||
locale={locale}
|
||||
panel={panel}
|
||||
assetToken={assetToken}
|
||||
appearance={appearance}
|
||||
headless
|
||||
maxHeight={720}
|
||||
minWidth={view.minWidth}
|
||||
viewLocation={view.location}
|
||||
vm={vm}
|
||||
onOpenView={onOpenView}
|
||||
onCloseView={onCloseView}
|
||||
onNavigate={onNavigate}
|
||||
onMetadata={onMetadata}
|
||||
/>
|
||||
)
|
||||
if (dialog) {
|
||||
return (
|
||||
<Modal title={title} subtitle={badge?.text} closeLabel={t(locale, 'close')} onClose={onCloseView}>
|
||||
{frame}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="page plugin-view-page">
|
||||
<header className="page-head">
|
||||
<div className="page-title">
|
||||
<h1>{title}</h1>
|
||||
{badge && <span className={`badge rg-p-badge badge-${badge.tone === 'ok' ? 'ok' : badge.tone === 'warn' ? 'warn' : badge.tone === 'error' ? 'error' : 'idle'}`}>{badge.text}</span>}
|
||||
</div>
|
||||
<Button onClick={onCloseView}>{t(locale, 'close')}</Button>
|
||||
</header>
|
||||
{frame}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport,
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport, ViewContribution,
|
||||
} from '../types'
|
||||
import { Button, IconButton, Tip } from '../ui/controls'
|
||||
import { ConfirmDialog, Modal } from '../ui/dialog'
|
||||
@@ -32,6 +32,8 @@ interface Props {
|
||||
onThemeChanged?: () => void
|
||||
/** Switches the app language (used after enabling a language pack). */
|
||||
onLocaleSwitch?: (l: Locale) => void
|
||||
onOpenView?: (view: ViewContribution, vm?: string) => void
|
||||
onNavigate?: (target: { page?: string; vm?: string }) => void
|
||||
}
|
||||
|
||||
// VM-only settings are edited in each VM's settings.
|
||||
@@ -46,7 +48,7 @@ function hasAppSettings(p: PluginInfo): boolean {
|
||||
|
||||
/** Top-level Plugins & Themes management page. */
|
||||
export const PluginsPage: React.FC<Props> = ({
|
||||
locale, appearance, safeMode, onRefresh, onError, onThemeChanged, onLocaleSwitch,
|
||||
locale, appearance, safeMode, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed')
|
||||
@@ -791,6 +793,8 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
panel={panel}
|
||||
assetToken={contribs.asset_token!}
|
||||
appearance={appearance}
|
||||
onOpenView={onOpenView}
|
||||
onNavigate={onNavigate}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
|
||||
@@ -46,15 +46,17 @@ interface Props {
|
||||
updateCard?: React.ReactNode
|
||||
/** A newer release exists: dot on the About entry. */
|
||||
updateDot?: boolean
|
||||
/** Declared plugin pages shown after the built-in Plugins entry. */
|
||||
pluginViews?: { id: string; title: string; badge?: string; icon?: string }[]
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [],
|
||||
}) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ctxOpenedByPointerRef = useRef(false)
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, ...pluginViews.map((view) => view.id), HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -81,6 +83,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
onDoubleClick?: () => void,
|
||||
dot?: boolean,
|
||||
vm?: { state: string; driver: string; busy: boolean },
|
||||
badgeText?: string,
|
||||
) => (
|
||||
<button
|
||||
key={id}
|
||||
@@ -101,6 +104,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
<span className={`nav-icon-badge ${badgeClass}`} aria-hidden="true">{icon}</span>
|
||||
<span className="nav-label">{label}</span>
|
||||
{dot && <span className="nav-dot" aria-hidden="true" />}
|
||||
{badgeText && <span className="badge rg-p-badge badge-idle">{badgeText}</span>}
|
||||
{kind && (
|
||||
<Tip label={stateLabel} side="right">
|
||||
<span className="hstack"><StatusShape kind={kind} /></span>
|
||||
@@ -256,6 +260,18 @@ export const Sidebar: React.FC<Props> = ({
|
||||
safeMode ? tr('pluginSafeModeShort') : '',
|
||||
safeMode ? 'warn' : null,
|
||||
)}
|
||||
{pluginViews.map((view) => navBtn(
|
||||
view.id,
|
||||
view.title,
|
||||
view.icon ? <span className="plugin-view-icon" aria-hidden="true" style={{ WebkitMaskImage: `url("${view.icon}")`, maskImage: `url("${view.icon}")` }} /> : <Puzzle size={13} />,
|
||||
'nav-icon-plugins',
|
||||
'',
|
||||
null,
|
||||
undefined,
|
||||
false,
|
||||
undefined,
|
||||
view.badge,
|
||||
))}
|
||||
{navBtn(
|
||||
HOST_ID,
|
||||
tr('sidebarHost'),
|
||||
|
||||
@@ -12,6 +12,7 @@ export const coreZh: Record<string, string> = {
|
||||
"close": "关闭",
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
"confirm": "确认",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"dataRootChooseOther": "选择其他数据目录",
|
||||
@@ -47,6 +48,7 @@ export const coreZh: Record<string, string> = {
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, other {# 台运行中}}",
|
||||
"forceStop": "硬关机",
|
||||
"formRequiredFields": "请填写必填项:{fields}",
|
||||
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
|
||||
@@ -113,7 +115,9 @@ export const coreZh: Record<string, string> = {
|
||||
"noRuntimeAlert": "先在「内核」导入运行时包",
|
||||
"off": "关闭",
|
||||
"on": "开启",
|
||||
"open": "打开",
|
||||
"openFolder": "打开所在文件夹",
|
||||
"overview": "概述",
|
||||
"panelLoadFailed": "面板加载失败",
|
||||
"pauseDownload": "暂停下载",
|
||||
"pluginSafeModeShort": "安全模式",
|
||||
@@ -206,6 +210,7 @@ export const coreEn: Record<string, string> = {
|
||||
"close": "Close",
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
"confirm": "Confirm",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"dataRootChooseOther": "Choose another data folder",
|
||||
@@ -241,6 +246,7 @@ export const coreEn: Record<string, string> = {
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, one {# running} other {# running}}",
|
||||
"forceStop": "Force shut down",
|
||||
"formRequiredFields": "Fill in the required fields: {fields}",
|
||||
"gpuErrMissingExt": "Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA",
|
||||
"gpuErrVulkanCpu": "Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} is below the required 1.3 floor; update GPU drivers or use VMware SVGA",
|
||||
@@ -307,7 +313,9 @@ export const coreEn: Record<string, string> = {
|
||||
"noRuntimeAlert": "Import a runtime under Engine first",
|
||||
"off": "Off",
|
||||
"on": "On",
|
||||
"open": "Open",
|
||||
"openFolder": "Show in folder",
|
||||
"overview": "Overview",
|
||||
"panelLoadFailed": "Panel failed to load",
|
||||
"pauseDownload": "Pause download",
|
||||
"pluginSafeModeShort": "Safe mode",
|
||||
|
||||
@@ -140,6 +140,7 @@ export type I18nKey =
|
||||
| "commandToggle"
|
||||
| "commandToggleHint"
|
||||
| "configured"
|
||||
| "confirm"
|
||||
| "connGroup"
|
||||
| "copy"
|
||||
| "copyScreenshot"
|
||||
@@ -330,6 +331,7 @@ export type I18nKey =
|
||||
| "forceQuitAppTitle"
|
||||
| "forceQuitInProgress"
|
||||
| "forceStop"
|
||||
| "formRequiredFields"
|
||||
| "fullscreenDecoupledHint"
|
||||
| "fullscreenLaunch"
|
||||
| "fullscreenLaunchHint"
|
||||
@@ -674,6 +676,7 @@ export type I18nKey =
|
||||
| "onlineRecoveryConfirm"
|
||||
| "onlineRecoveryDesc"
|
||||
| "onlineRecoveryTitle"
|
||||
| "open"
|
||||
| "openFolder"
|
||||
| "openSharedFolder"
|
||||
| "openShort"
|
||||
@@ -697,6 +700,7 @@ export type I18nKey =
|
||||
| "optSchedSub"
|
||||
| "optSchedTitle"
|
||||
| "optUnavailable"
|
||||
| "overview"
|
||||
| "panelLoadFailed"
|
||||
| "pauseDownload"
|
||||
| "pendingChanges"
|
||||
|
||||
@@ -14,20 +14,18 @@ export const BRIDGE_METHODS = [
|
||||
'hello',
|
||||
'i18n.getBundle',
|
||||
'ui.notify',
|
||||
'vm.list',
|
||||
'command.invoke',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_METHODS_EXPERIMENTAL = [
|
||||
'ui.confirm',
|
||||
'ui.copy',
|
||||
'ui.openExternal',
|
||||
'ui.showForm',
|
||||
'ui.setTitle',
|
||||
'ui.setBadge',
|
||||
'ui.openView',
|
||||
'ui.close',
|
||||
'ui.navigate',
|
||||
'ui.openExternal',
|
||||
'vm.list',
|
||||
'vm.get',
|
||||
'command.invoke',
|
||||
'settings.get',
|
||||
'settings.set',
|
||||
'storage.get',
|
||||
@@ -46,17 +44,18 @@ export const BRIDGE_METHODS_EXPERIMENTAL = [
|
||||
'events.unsubscribe',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_METHODS_EXPERIMENTAL = [] as const
|
||||
|
||||
export const BRIDGE_EVENTS = [
|
||||
'theme.changed',
|
||||
'locale.changed',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_EVENTS_EXPERIMENTAL = [
|
||||
'vm.stateChanged',
|
||||
'view.visibilityChanged',
|
||||
'task.updated',
|
||||
] as const
|
||||
|
||||
export const BRIDGE_EVENTS_EXPERIMENTAL = [] as const
|
||||
|
||||
export type BridgeMethod = (typeof BRIDGE_METHODS)[number] | (typeof BRIDGE_METHODS_EXPERIMENTAL)[number]
|
||||
export type BridgeEventName = (typeof BRIDGE_EVENTS)[number] | (typeof BRIDGE_EVENTS_EXPERIMENTAL)[number]
|
||||
|
||||
@@ -73,7 +72,7 @@ export type BridgeResult =
|
||||
| { type: 'reims:rpc-result'; id: string; ok: true; result: unknown }
|
||||
| { type: 'reims:rpc-result'; id: string; ok: false; error: string }
|
||||
|
||||
/** Host → plugin event. Stable events are always delivered; others only after `events.subscribe`. */
|
||||
/** Host → plugin event. Theme and locale events are always delivered; the others only after `events.subscribe`. */
|
||||
export interface BridgeEvent {
|
||||
type: 'reims:event'
|
||||
event: BridgeEventName
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
const RE_SAFE_TOKEN = /^[a-f0-9]+$/
|
||||
const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/
|
||||
const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/
|
||||
|
||||
/** Builds a same-origin URL for a validated packaged plugin asset. */
|
||||
export function buildSafePluginAssetURL(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null {
|
||||
if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null
|
||||
if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null
|
||||
const raw = (entry || 'index.html').trim().replace(/^\/+/, '')
|
||||
if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) return null
|
||||
const segs = raw.split('/')
|
||||
for (const seg of segs) {
|
||||
if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null
|
||||
}
|
||||
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import type { SettingsSchema, ViewContribution } from '../types'
|
||||
|
||||
export interface PluginConfirmRequest {
|
||||
title?: string
|
||||
message: string
|
||||
confirmLabel?: string
|
||||
cancelLabel?: string
|
||||
danger?: boolean
|
||||
}
|
||||
|
||||
export interface PluginFormRequest extends PluginConfirmRequest {
|
||||
title: string
|
||||
schema: SettingsSchema
|
||||
values: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface PluginFormResult {
|
||||
confirmed: boolean
|
||||
values?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface PluginViewActionHandlers {
|
||||
invoke(method: string, params: Record<string, unknown>): Promise<unknown>
|
||||
confirm(request: PluginConfirmRequest): Promise<boolean>
|
||||
showForm(request: PluginFormRequest): Promise<PluginFormResult>
|
||||
copy(text: string): Promise<void>
|
||||
setTitle(title: string): void
|
||||
setBadge(text: string, tone: string): void
|
||||
openView(view: ViewContribution, vm?: string): void
|
||||
close(): Promise<{ closed: boolean }>
|
||||
navigate(target: { page?: string; vm?: string }): void
|
||||
subscribe(events: string[]): void
|
||||
unsubscribe(events: string[]): void
|
||||
}
|
||||
|
||||
/** Starting form values: request values, then defaults, then what SchemaForm shows for an unset field. */
|
||||
export function initialFormValues(schema: SettingsSchema, values: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
||||
if (property.default !== undefined && property.default !== null) out[key] = property.default
|
||||
else if (property.type === 'boolean') out[key] = false
|
||||
else if (property.enum && property.enum.length > 0) out[key] = property.enum[0]
|
||||
else if (property.type === 'integer' || property.type === 'number') {
|
||||
out[key] = Math.min(property.maximum ?? Infinity, Math.max(property.minimum ?? 0, 0))
|
||||
} else out[key] = ''
|
||||
}
|
||||
return { ...out, ...values }
|
||||
}
|
||||
|
||||
/** Keys of required fields that are still empty. */
|
||||
export function missingFormFields(schema: SettingsSchema, values: Record<string, unknown>): string[] {
|
||||
return Object.entries(schema.properties ?? {})
|
||||
.filter(([key, property]) => property.required && (values[key] === undefined || values[key] === null || values[key] === ''))
|
||||
.map(([key]) => key)
|
||||
}
|
||||
|
||||
type PluginInvoke = PluginViewActionHandlers['invoke']
|
||||
|
||||
/** Tracks the tasks one page starts; closing the scope cancels the unfinished ones. */
|
||||
export function createPluginTaskScope(call: PluginInvoke): { invoke: PluginInvoke; close: () => void } {
|
||||
const running = new Set<string>()
|
||||
let closed = false
|
||||
const cancel = async (id: string) => {
|
||||
const params = { id, status: 'canceled' }
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
await call('task.finish', params)
|
||||
return
|
||||
} catch (error) {
|
||||
// Allow the host's one-second rate window to reset before retrying cleanup.
|
||||
if (attempt < 2 && /exceeded Host API rate limit/.test(String(error))) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
continue
|
||||
}
|
||||
console.warn('[plugin] cancel task of a closed page failed:', id, error)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
invoke: async (method, params) => {
|
||||
const result = await call(method, params)
|
||||
if (method === 'task.start') {
|
||||
const { id } = result as { id: string }
|
||||
if (closed) await cancel(id)
|
||||
else running.add(id)
|
||||
} else if (method === 'task.finish') {
|
||||
running.delete(String(params.id))
|
||||
}
|
||||
return result
|
||||
},
|
||||
close: () => {
|
||||
closed = true
|
||||
running.forEach(cancel)
|
||||
running.clear()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Executes view actions whose UI effect must run in the host window. */
|
||||
export async function invokePluginViewAction(
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
handlers: PluginViewActionHandlers,
|
||||
): Promise<unknown> {
|
||||
if (method === 'ui.confirm') {
|
||||
const request = await handlers.invoke(method, params) as PluginConfirmRequest
|
||||
return { confirmed: await handlers.confirm(request) }
|
||||
}
|
||||
if (method === 'ui.showForm') {
|
||||
const request = await handlers.invoke(method, params) as PluginFormRequest
|
||||
return handlers.showForm(request)
|
||||
}
|
||||
if (method === 'ui.copy') {
|
||||
const request = await handlers.invoke(method, params) as { text: string }
|
||||
await handlers.copy(request.text)
|
||||
return { ok: true }
|
||||
}
|
||||
if (method === 'ui.setTitle') {
|
||||
const request = await handlers.invoke(method, params) as { title: string }
|
||||
handlers.setTitle(request.title)
|
||||
return request
|
||||
}
|
||||
if (method === 'ui.setBadge') {
|
||||
const request = await handlers.invoke(method, params) as { text: string; tone: string }
|
||||
handlers.setBadge(request.text, request.tone)
|
||||
return request
|
||||
}
|
||||
if (method === 'ui.openView') {
|
||||
const view = await handlers.invoke(method, params) as ViewContribution
|
||||
handlers.openView(view, typeof params.vm === 'string' ? params.vm : undefined)
|
||||
return { ok: true }
|
||||
}
|
||||
if (method === 'ui.close') {
|
||||
await handlers.invoke(method, params)
|
||||
return handlers.close()
|
||||
}
|
||||
if (method === 'ui.navigate') {
|
||||
const target = await handlers.invoke(method, params) as { page?: string; vm?: string }
|
||||
handlers.navigate(target)
|
||||
return { ok: true }
|
||||
}
|
||||
if (method === 'events.subscribe' || method === 'events.unsubscribe') {
|
||||
const result = await handlers.invoke(method, params) as { events: string[] }
|
||||
if (method === 'events.subscribe') handlers.subscribe(result.events)
|
||||
else handlers.unsubscribe(result.events)
|
||||
return result
|
||||
}
|
||||
return handlers.invoke(method, params)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type PluginHostEvent = 'vm.stateChanged' | 'task.updated'
|
||||
export type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void
|
||||
|
||||
const listeners = new Set<PluginHostEventListener>()
|
||||
|
||||
export function publishPluginHostEvent(event: PluginHostEvent, data: unknown): void {
|
||||
for (const listener of [...listeners]) {
|
||||
try {
|
||||
listener(event, data)
|
||||
} catch (error) {
|
||||
console.warn('[plugin] could not deliver host event:', event, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribePluginHostEvents(listener: PluginHostEventListener): () => void {
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
export type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog'
|
||||
|
||||
export interface PluginViewRoute {
|
||||
pluginId: string
|
||||
viewId: string
|
||||
location: PluginViewLocation
|
||||
vm?: string
|
||||
/** Host page that was selected when this view opened; closing the view restores it. */
|
||||
from?: string
|
||||
}
|
||||
|
||||
export interface PluginViewState {
|
||||
route: PluginViewRoute | null
|
||||
dialogs: PluginViewRoute[]
|
||||
returnStack: PluginViewRoute[]
|
||||
}
|
||||
|
||||
export const emptyPluginViewState: PluginViewState = { route: null, dialogs: [], returnStack: [] }
|
||||
|
||||
export function pluginViewKey(route: Pick<PluginViewRoute, 'pluginId' | 'viewId'>): string {
|
||||
return `${route.pluginId}/${route.viewId}`
|
||||
}
|
||||
|
||||
function sameRoute(a: PluginViewRoute | null, b: PluginViewRoute): boolean {
|
||||
return !!a && pluginViewKey(a) === pluginViewKey(b) && a.location === b.location && (a.vm ?? '') === (b.vm ?? '')
|
||||
}
|
||||
|
||||
/** Evaluates a view's `when`, e.g. "vmState==running" (same syntax as theme decoration states). */
|
||||
export function matchViewCondition(when: string | undefined, values: Record<string, string>): boolean {
|
||||
const expr = (when ?? '').trim()
|
||||
if (!expr || expr === 'default') return true
|
||||
const [key, value] = expr.split('==').map((part) => part.trim())
|
||||
return value !== undefined && values[key] === value
|
||||
}
|
||||
|
||||
export function openPluginView(state: PluginViewState, target: PluginViewRoute): PluginViewState {
|
||||
if (target.location === 'dialog') {
|
||||
// Reopening a dialog returns to it by closing the ones stacked above it.
|
||||
const open = state.dialogs.findIndex((item) => sameRoute(item, target))
|
||||
return { ...state, dialogs: open >= 0 ? state.dialogs.slice(0, open + 1) : [...state.dialogs, target] }
|
||||
}
|
||||
if (sameRoute(state.route, target)) return { ...state, dialogs: [] }
|
||||
const returnStack = state.route ? [...state.returnStack, state.route].slice(-16) : state.returnStack
|
||||
return { route: target, dialogs: [], returnStack }
|
||||
}
|
||||
|
||||
/** Closes the top dialog or the current view; `page` is the host page to select again. */
|
||||
export function closePluginView(state: PluginViewState): { state: PluginViewState; closed: boolean; page?: string } {
|
||||
if (state.dialogs.length > 0) {
|
||||
return { state: { ...state, dialogs: state.dialogs.slice(0, -1) }, closed: true }
|
||||
}
|
||||
if (!state.route) return { state, closed: false }
|
||||
// A VM tab always closes to that VM's overview, which ends the history.
|
||||
if (state.route.location === 'vm.tab') return { state: emptyPluginViewState, closed: true }
|
||||
const returnStack = [...state.returnStack]
|
||||
const route = returnStack.pop() ?? null
|
||||
return { state: { route, dialogs: [], returnStack }, closed: true, page: state.route.from }
|
||||
}
|
||||
|
||||
export function closePluginDialog(state: PluginViewState, target: PluginViewRoute): PluginViewState {
|
||||
return { ...state, dialogs: state.dialogs.filter((route) => !sameRoute(route, target)) }
|
||||
}
|
||||
|
||||
export function prunePluginViews(
|
||||
state: PluginViewState,
|
||||
validViews: ReadonlySet<string>,
|
||||
validVM: (vm: string | undefined) => boolean,
|
||||
available: (route: PluginViewRoute) => boolean = () => true,
|
||||
): PluginViewState {
|
||||
const valid = (route: PluginViewRoute) => validViews.has(pluginViewKey(route)) && (!route.vm || validVM(route.vm))
|
||||
const usable = (route: PluginViewRoute) => valid(route) && available(route)
|
||||
const route = state.route && usable(state.route) ? state.route : null
|
||||
return {
|
||||
route,
|
||||
dialogs: state.dialogs.filter(valid),
|
||||
returnStack: route ? state.returnStack.filter(usable) : [],
|
||||
}
|
||||
}
|
||||
@@ -283,6 +283,12 @@ h1, h2, h3, p { margin: 0; }
|
||||
display: grid; place-items: center; color: #ffffff;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.14), inset 0 1px 0 rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
.plugin-view-icon {
|
||||
display: block; width: 13px; height: 13px; background: currentColor;
|
||||
-webkit-mask-repeat: no-repeat; mask-repeat: no-repeat;
|
||||
-webkit-mask-position: center; mask-position: center;
|
||||
-webkit-mask-size: contain; mask-size: contain;
|
||||
}
|
||||
/* A VM's macOS version artwork (VersionArt) as its icon. */
|
||||
.nav-icon-art { overflow: hidden; background: #8d95a9; }
|
||||
.nav-icon-art svg { width: 100%; height: 100%; display: block; }
|
||||
|
||||
@@ -183,15 +183,15 @@ export type UIContractIcon = (typeof UI_CONTRACT_ICONS)[number]
|
||||
export const UI_CONTRACT_ICONS_EXPERIMENTAL = [] as const
|
||||
|
||||
// Where plugin `views` can appear.
|
||||
export const UI_CONTRACT_VIEW_LOCATIONS = [] as const
|
||||
|
||||
export const UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL = [
|
||||
export const UI_CONTRACT_VIEW_LOCATIONS = [
|
||||
'sidebar',
|
||||
'vm.tab',
|
||||
'settings',
|
||||
'dialog',
|
||||
] as const
|
||||
|
||||
export const UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL = [] as const
|
||||
|
||||
// UI SDK event stream for interactive themes (`sdk.on(event, cb)`).
|
||||
export const UI_CONTRACT_SDK_EVENTS = [
|
||||
'vm.stateChanged',
|
||||
|
||||
@@ -170,6 +170,7 @@ export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
|
||||
export type MenuContribution = plugin.MenuContribution
|
||||
export type VMCardContribution = plugin.VMCardContribution
|
||||
export type PanelContribution = plugin.PanelContribution
|
||||
export type ViewContribution = plugin.ViewContribution
|
||||
export type ImageSourceContribution = plugin.ImageSourceContribution
|
||||
export type StatusItemContribution = plugin.StatusItemContribution
|
||||
export type PluginUIContributions = app.PluginUIContributions
|
||||
|
||||
@@ -10,11 +10,13 @@ interface ConfirmDialogProps {
|
||||
cancelLabel: string
|
||||
confirmLabel: string
|
||||
onCancel: () => void
|
||||
onConfirm: () => void
|
||||
/** Call preventDefault to keep the dialog open. */
|
||||
onConfirm: (e: React.MouseEvent<HTMLButtonElement>) => void
|
||||
tone?: 'neutral' | 'danger'
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => {
|
||||
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, tone = 'danger', children }) => {
|
||||
const prevFocusRef = React.useRef<HTMLElement | null>(
|
||||
typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
@@ -26,7 +28,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description
|
||||
<Alert.Overlay className="overlay" />
|
||||
<Alert.Content
|
||||
className="dialog rg-p-dialog sm"
|
||||
data-tone="danger"
|
||||
data-tone={tone}
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
const prev = prevFocusRef.current
|
||||
@@ -40,7 +42,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<Alert.Cancel asChild><Button>{cancelLabel}</Button></Alert.Cancel>
|
||||
<Alert.Action asChild><Button variant="danger" onClick={onConfirm}>{confirmLabel}</Button></Alert.Action>
|
||||
<Alert.Action asChild onClick={onConfirm}><Button variant={tone === 'danger' ? 'danger' : 'primary'}>{confirmLabel}</Button></Alert.Action>
|
||||
</div>
|
||||
</Alert.Content>
|
||||
</Alert.Portal>
|
||||
|
||||
@@ -125,7 +125,12 @@
|
||||
"vm.state.busy",
|
||||
"vm.state.error"
|
||||
],
|
||||
"viewLocations": [],
|
||||
"viewLocations": [
|
||||
"sidebar",
|
||||
"vm.tab",
|
||||
"settings",
|
||||
"dialog"
|
||||
],
|
||||
"sdkEvents": [
|
||||
"vm.stateChanged",
|
||||
"task.started",
|
||||
@@ -231,12 +236,7 @@
|
||||
"layers": [],
|
||||
"layoutOptions": [],
|
||||
"icons": [],
|
||||
"viewLocations": [
|
||||
"sidebar",
|
||||
"vm.tab",
|
||||
"settings",
|
||||
"dialog"
|
||||
],
|
||||
"viewLocations": [],
|
||||
"sdkEvents": []
|
||||
}
|
||||
}
|
||||
@@ -250,6 +250,7 @@ export namespace app {
|
||||
settings_pages?: plugin.SettingsPageContribution[];
|
||||
status_items?: plugin.StatusItemContribution[];
|
||||
panels?: plugin.PanelContribution[];
|
||||
views?: plugin.ViewContribution[];
|
||||
image_sources?: plugin.ImageSourceContribution[];
|
||||
vm_templates?: plugin.VMTemplateContribution[];
|
||||
themes?: plugin.ThemeContribution[];
|
||||
@@ -272,6 +273,7 @@ export namespace app {
|
||||
this.settings_pages = this.convertValues(source["settings_pages"], plugin.SettingsPageContribution);
|
||||
this.status_items = this.convertValues(source["status_items"], plugin.StatusItemContribution);
|
||||
this.panels = this.convertValues(source["panels"], plugin.PanelContribution);
|
||||
this.views = this.convertValues(source["views"], plugin.ViewContribution);
|
||||
this.image_sources = this.convertValues(source["image_sources"], plugin.ImageSourceContribution);
|
||||
this.vm_templates = this.convertValues(source["vm_templates"], plugin.VMTemplateContribution);
|
||||
this.themes = this.convertValues(source["themes"], plugin.ThemeContribution);
|
||||
@@ -2191,6 +2193,52 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class ViewContribution {
|
||||
id: string;
|
||||
title: LocalizedText;
|
||||
icon?: string;
|
||||
location: string;
|
||||
entry: string;
|
||||
order?: number;
|
||||
when?: string;
|
||||
minWidth?: number;
|
||||
pluginId?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ViewContribution(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
this.title = this.convertValues(source["title"], LocalizedText);
|
||||
this.icon = source["icon"];
|
||||
this.location = source["location"];
|
||||
this.entry = source["entry"];
|
||||
this.order = source["order"];
|
||||
this.when = source["when"];
|
||||
this.minWidth = source["minWidth"];
|
||||
this.pluginId = source["pluginId"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class PermissionSpec {
|
||||
name: string;
|
||||
level: string;
|
||||
|
||||
+7
-4
@@ -133,6 +133,7 @@ type App struct {
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
pluginMgr *plugin.Manager
|
||||
pluginFiles map[string]pluginFileGrant
|
||||
pluginMarket *plugin.MarketClient
|
||||
controlServer *control.Server
|
||||
driverRouter *driver.Router
|
||||
@@ -189,6 +190,7 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: make(map[string]cachedDiskPath),
|
||||
procSamples: make(map[string]host.ProcessSample),
|
||||
pluginFiles: make(map[string]pluginFileGrant),
|
||||
uiHealth: uiHealthState{windowHidden: launch.Background},
|
||||
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
||||
}
|
||||
@@ -1013,7 +1015,9 @@ func (a *App) resetDataRootCaches() {
|
||||
a.lastVMListErr = nil
|
||||
a.diskPaths = make(map[string]cachedDiskPath)
|
||||
a.procSamples = make(map[string]host.ProcessSample)
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
a.mu.Unlock()
|
||||
cancelPluginTasks("")
|
||||
}
|
||||
|
||||
func (a *App) SetDataRoot(dir string) error {
|
||||
@@ -1042,10 +1046,9 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
for _, t := range tasks.list() {
|
||||
if t.Status == TaskRunning {
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
|
||||
}
|
||||
// Plugin tasks do not block the switch; resetDataRootCaches cancels them.
|
||||
if hostTaskRunning() {
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
|
||||
}
|
||||
|
||||
dir = strings.TrimSpace(dir)
|
||||
|
||||
@@ -614,11 +614,15 @@ func computerUseVMPhase(vm driver.VMInfo) string {
|
||||
return "normal"
|
||||
}
|
||||
|
||||
// computerUseAccessSetting records the user's per-VM consent. Only the host
|
||||
// settings UI may write it; the plugin bridge rejects it.
|
||||
const computerUseAccessSetting = "allow_ai_access"
|
||||
|
||||
func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
|
||||
if mgr == nil || strings.TrimSpace(pluginID) == "" || strings.TrimSpace(vmKey) == "" {
|
||||
return false
|
||||
}
|
||||
return mgr.SavedBoolSetting(pluginID, vmKey, "allow_ai_access")
|
||||
return mgr.SavedBoolSetting(pluginID, vmKey, computerUseAccessSetting)
|
||||
}
|
||||
|
||||
// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func TestPanelVMViewOmitsHostPaths(t *testing.T) {
|
||||
view := panelVMView(driver.VMInfo{Name: "mac", DriverID: "builtin.macos", State: "running", Directory: "secret-dir", DiskPath: "secret-disk", SSHPort: 2222})
|
||||
for _, key := range []string{"directory", "disk_path", "ssh_port"} {
|
||||
if _, exists := view[key]; exists {
|
||||
t.Fatalf("%s leaked in VM view: %#v", key, view)
|
||||
}
|
||||
}
|
||||
if view["phase"] != "normal" || view["vm"] != "builtin.macos:mac" {
|
||||
t.Fatalf("VM view = %#v", view)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeViewsAndForm(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "ui:slot")
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "ui.openView", map[string]any{"view": "console"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if view := result.(plugin.ViewContribution); view.Location != "sidebar" || view.ID != "console" || view.PluginID != "vendor.panel" {
|
||||
t.Fatalf("openView = %+v", view)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.openView", map[string]any{"view": "other"}); err == nil {
|
||||
t.Fatal("unknown view was accepted")
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.setTitle", map[string]any{"title": "Live console"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.setBadge", map[string]any{"text": "3", "tone": "warn"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.setBadge", map[string]any{"text": "Working", "tone": "busy"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := map[string]any{"properties": map[string]any{
|
||||
"name": map[string]any{"type": "string"},
|
||||
"count": map[string]any{"type": "integer", "minimum": 0, "maximum": 10},
|
||||
}}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "ui.showForm", map[string]any{
|
||||
"title": "Create item", "schema": schema, "values": map[string]any{"name": "demo"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
form := result.(panelFormRequest)
|
||||
if form.Values["name"] != "demo" || form.Schema.Properties["count"].Type != "integer" {
|
||||
t.Fatalf("form = %+v", form)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.showForm", map[string]any{
|
||||
"title": "Invalid", "schema": schema, "values": map[string]any{"count": 11.0},
|
||||
}); err == nil {
|
||||
t.Fatal("out-of-range form value was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeSettings(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t)
|
||||
for _, method := range []string{"settings.get", "settings.set"} {
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", method, map[string]any{"vm": "unknown"}); err == nil || !strings.Contains(err.Error(), `lacks permission "vm:read"`) {
|
||||
t.Fatalf("%s resolved the VM without vm:read: %v", method, err)
|
||||
}
|
||||
}
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "settings.get", map[string]any{"key": "mode"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := result.(map[string]any); got["value"] != "dev" || got["configured"] != false {
|
||||
t.Fatalf("schema default was treated as configured: %#v", got)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "settings.set", map[string]any{"key": "secret", "value": "plain-text"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "settings.get", map[string]any{"key": "secret"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret := result.(map[string]any)
|
||||
if secret["value"] != "••••••••" || secret["secret"] != true {
|
||||
t.Fatalf("secret was not masked: %#v", secret)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "settings.set", map[string]any{"values": map[string]any{
|
||||
"enabled": false, "count": 4.0, "mode": "prod",
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "settings.get", map[string]any{"key": "count"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := result.(map[string]any); got["value"] != 4.0 || got["configured"] != true {
|
||||
t.Fatalf("count = %#v", got)
|
||||
}
|
||||
for name, params := range map[string]map[string]any{
|
||||
"range": {"key": "count", "value": 11.0},
|
||||
"scope": {"key": "vm_only", "value": true},
|
||||
"required": {"key": "required", "value": ""},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "settings.set", params); err == nil {
|
||||
t.Fatal("invalid setting was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeTaskLifecycleAndOwnership(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "task:progress")
|
||||
t.Cleanup(func() { cancelPluginTasks("vendor.panel") })
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "task.start", map[string]any{"title": "Convert document", "cancelable": true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task := result.(Task)
|
||||
if task.Kind != "plugin:vendor.panel" || !task.Cancelable {
|
||||
t.Fatalf("task = %+v", task)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "task.update", map[string]any{"id": task.ID, "done": 2.0, "total": 10.0})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated := result.(Task); updated.Percent != 20 {
|
||||
t.Fatalf("task percent = %v", updated.Percent)
|
||||
}
|
||||
if _, err := pluginTaskFor("other.plugin", task.ID); err == nil {
|
||||
t.Fatal("another plugin passed the task ownership check")
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "task.finish", map[string]any{"id": task.ID, "status": "done", "result": "ready"})
|
||||
if err != nil || result.(Task).Status != TaskDone {
|
||||
t.Fatalf("finish = %+v, %v", result, err)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "task.finish", map[string]any{"id": task.ID, "status": "failed"})
|
||||
if err != nil || result.(Task).Status != TaskDone {
|
||||
t.Fatalf("idempotent finish changed terminal state: %+v, %v", result, err)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "task.start", map[string]any{"subject": "Cancel me", "cancelable": true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancelable := result.(Task)
|
||||
if err := a.CancelTask(cancelable.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := tasks.get(cancelable.ID); got.Status != TaskCanceled {
|
||||
t.Fatalf("canceled task = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeFileGrantLifecycle(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "fs:pick")
|
||||
path := filepath.Join(t.TempDir(), "note.txt")
|
||||
if err := os.WriteFile(path, []byte("hello"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grant, err := a.issuePluginFileGrant("vendor.panel", path, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := grant["id"].(string)
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "file.read", map[string]any{"id": id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := result.(map[string]any); got["data"] != "hello" || got["encoding"] != "utf8" || got["size"] != 5 {
|
||||
t.Fatalf("read = %#v", got)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("other.plugin", "file.read", map[string]any{"id": id}); err == nil {
|
||||
t.Fatal("another plugin read the file handle")
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "file.write", map[string]any{"id": id, "data": "no"}); err == nil {
|
||||
t.Fatal("read-only handle allowed a write")
|
||||
}
|
||||
writeGrant, err := a.issuePluginFileGrant("vendor.panel", path, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeID := writeGrant["id"].(string)
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte("updated"))
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "file.write", map[string]any{"id": writeID, "data": encoded, "encoding": "base64"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || string(data) != "updated" {
|
||||
t.Fatalf("updated file = %q, %v", data, err)
|
||||
}
|
||||
a.revokePluginFiles("vendor.panel")
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "file.read", map[string]any{"id": id}); err == nil {
|
||||
t.Fatal("revoked file handle still works")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginFileGrantsExpireAndAreCapped(t *testing.T) {
|
||||
a := &App{}
|
||||
path := filepath.Join(t.TempDir(), "note.txt")
|
||||
var first string
|
||||
for range maxPluginFileGrants {
|
||||
grant, err := a.issuePluginFileGrant("vendor.panel", path, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == "" {
|
||||
first = grant["id"].(string)
|
||||
}
|
||||
}
|
||||
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err == nil {
|
||||
t.Fatal("plugin exceeded its file grant limit")
|
||||
}
|
||||
grant := a.pluginFiles[first]
|
||||
grant.Expires = time.Now().Add(-time.Minute)
|
||||
a.pluginFiles[first] = grant
|
||||
if _, err := a.pluginFilePath("vendor.panel", first, true); err == nil {
|
||||
t.Fatal("expired file grant was accepted")
|
||||
}
|
||||
if _, err := a.issuePluginFileGrant("vendor.panel", path, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return fn(req) }
|
||||
|
||||
func TestPanelNetFetchAndRedirectAuthorization(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "net:example.com")
|
||||
mgr := a.pluginMgr
|
||||
requests := 0
|
||||
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
requests++
|
||||
return &http.Response{
|
||||
StatusCode: 200,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "Set-Cookie": []string{"secret=1"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
result, err := panelNetFetchWithClient(mgr, "vendor.panel", map[string]any{"url": "https://example.com/data", "responseType": "json"}, client)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := result.(map[string]any)
|
||||
if got["json"].(map[string]any)["ok"] != true {
|
||||
t.Fatalf("JSON response = %#v", got)
|
||||
}
|
||||
if _, exists := got["headers"].(map[string]string)["Set-Cookie"]; exists {
|
||||
t.Fatal("Set-Cookie leaked to plugin")
|
||||
}
|
||||
if _, err := panelNetFetchWithClient(mgr, "vendor.panel", map[string]any{"url": "https://other.example/data"}, client); err == nil {
|
||||
t.Fatal("undeclared origin was accepted")
|
||||
}
|
||||
if _, err := panelNetFetchWithClient(mgr, "vendor.panel", map[string]any{"url": "https://example.com", "headers": map[string]any{"Proxy-Authorization": "bad"}}, client); err == nil {
|
||||
t.Fatal("proxy credential header was accepted")
|
||||
}
|
||||
if _, err := panelNetFetchWithClient(mgr, "vendor.panel", map[string]any{"url": "https://example.com", "responseType": "invalid"}, client); err == nil {
|
||||
t.Fatal("invalid response type was accepted")
|
||||
}
|
||||
if requests != 1 {
|
||||
t.Fatalf("validation failures issued %d HTTP requests", requests)
|
||||
}
|
||||
redirects := 0
|
||||
redirectClient := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
redirects++
|
||||
if redirects == 1 {
|
||||
return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{"https://other.example/data"}}, Body: io.NopCloser(strings.NewReader("")), Request: req}, nil
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("ok")), Request: req}, nil
|
||||
})}
|
||||
if _, err := panelNetFetchWithClient(mgr, "vendor.panel", map[string]any{"url": "https://example.com/start"}, redirectClient); err == nil {
|
||||
t.Fatal("redirect bypassed origin authorization")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelEventSubscriptions(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "vm:read")
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "events.subscribe", map[string]any{"events": []any{"vm.stateChanged", "task.updated"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := result.(map[string]any)["events"].([]string); len(got) != 2 || got[0] != "task.updated" {
|
||||
t.Fatalf("subscriptions = %v", got)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "events.unsubscribe", map[string]any{"events": []any{}})
|
||||
if err != nil || len(result.(map[string]any)["events"].([]string)) != 0 {
|
||||
t.Fatalf("unsubscribe all = %#v, %v", result, err)
|
||||
}
|
||||
withoutRead := newPanelBridgeTestApp(t)
|
||||
if _, err := withoutRead.PanelBridgeCall("vendor.panel", "events.subscribe", map[string]any{"events": []any{"vm.stateChanged"}}); err == nil {
|
||||
t.Fatal("vm state subscription succeeded without vm:read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelEventsCoverBridgeCatalog(t *testing.T) {
|
||||
for name := range plugin.BridgeEventCatalog {
|
||||
if _, ok := panelEventPermissions[name]; !ok {
|
||||
t.Errorf("published event %s cannot be subscribed to", name)
|
||||
}
|
||||
}
|
||||
if len(panelEventPermissions) != len(plugin.BridgeEventCatalog) {
|
||||
t.Errorf("subscribable events = %d, published = %d", len(panelEventPermissions), len(plugin.BridgeEventCatalog))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeCannotGrantAIAccess(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t)
|
||||
info, ok := a.pluginMgr.Registry().Info("vendor.panel")
|
||||
if !ok || info.Settings == nil {
|
||||
t.Fatal("test plugin has no settings schema")
|
||||
}
|
||||
if _, declared := info.Settings.Properties[computerUseAccessSetting]; !declared {
|
||||
t.Fatal("test plugin must declare the consent setting")
|
||||
}
|
||||
for name, params := range map[string]map[string]any{
|
||||
"key": {"key": computerUseAccessSetting, "value": true},
|
||||
"values": {"values": map[string]any{"enabled": true, computerUseAccessSetting: true}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "settings.set", params); err == nil {
|
||||
t.Fatal("plugin page changed the user's AI access consent")
|
||||
}
|
||||
if a.pluginMgr.SavedBoolSetting("vendor.panel", "", computerUseAccessSetting) {
|
||||
t.Fatal("consent was stored")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginTasksDoNotBlockDataRootSwitch(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "task:progress")
|
||||
t.Cleanup(func() { cancelPluginTasks("vendor.panel") })
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "task.start", map[string]any{"title": "Index files"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hostTaskRunning() {
|
||||
t.Fatal("a plugin task counts as host work")
|
||||
}
|
||||
id := tasks.start("vm-create", "mac", "mac", nil)
|
||||
t.Cleanup(func() { tasks.dismiss(id) })
|
||||
if !hostTaskRunning() {
|
||||
t.Fatal("a VM creation task no longer blocks the switch")
|
||||
}
|
||||
tasks.finish(id, "", nil)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// panelEventPermissions covers every BridgeEventCatalog entry. The theme and
|
||||
// locale events are always delivered, so subscribing to them changes nothing.
|
||||
var panelEventPermissions = map[string]string{
|
||||
"theme.changed": "",
|
||||
"locale.changed": "",
|
||||
"vm.stateChanged": "vm:read",
|
||||
"view.visibilityChanged": "",
|
||||
"task.updated": "",
|
||||
}
|
||||
|
||||
func panelEventNames(params map[string]any, allowEmpty bool) ([]string, error) {
|
||||
raw, ok := params["events"].([]any)
|
||||
if !ok || (!allowEmpty && len(raw) == 0) || len(raw) > len(panelEventPermissions) {
|
||||
return nil, fmt.Errorf("events must be a non-empty array")
|
||||
}
|
||||
seen := make(map[string]bool, len(raw))
|
||||
names := make([]string, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
name, ok := item.(string)
|
||||
if !ok || seen[name] {
|
||||
return nil, fmt.Errorf("invalid event list")
|
||||
}
|
||||
if _, ok := panelEventPermissions[name]; !ok {
|
||||
return nil, fmt.Errorf("unknown event %q", name)
|
||||
}
|
||||
seen[name] = true
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func panelEventsCall(mgr *plugin.Manager, pluginID, method string, params map[string]any) (any, error) {
|
||||
names, err := panelEventNames(params, method == "events.unsubscribe")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if method == "events.subscribe" {
|
||||
for _, name := range names {
|
||||
permission := panelEventPermissions[name]
|
||||
if permission != "" {
|
||||
if err := mgr.Broker().Authorize(pluginID, permission); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err := mgr.Broker().AllowRate(pluginID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
} else if err := mgr.Broker().AllowRate(pluginID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"events": names}, nil
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPanelFileBytes = 8 << 20
|
||||
maxPluginFileGrants = 32
|
||||
pluginFileGrantTTL = 15 * time.Minute
|
||||
)
|
||||
|
||||
type pluginFileGrant struct {
|
||||
PluginID string
|
||||
Path string
|
||||
Write bool
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
func (a *App) issuePluginFileGrant(pluginID, path string, write bool) (map[string]any, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return map[string]any{"canceled": true}, nil
|
||||
}
|
||||
clean, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var token [16]byte
|
||||
if _, err := rand.Read(token[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := hex.EncodeToString(token[:])
|
||||
result := map[string]any{"id": id, "name": filepath.Base(clean), "write": write}
|
||||
if info, err := os.Stat(clean); err == nil {
|
||||
result["size"] = info.Size()
|
||||
} else if !write {
|
||||
return nil, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
now := time.Now()
|
||||
count := 0
|
||||
for key, grant := range a.pluginFiles {
|
||||
if !now.Before(grant.Expires) {
|
||||
delete(a.pluginFiles, key)
|
||||
} else if grant.PluginID == pluginID {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count >= maxPluginFileGrants {
|
||||
return nil, errors.New("too many open file handles for this plugin")
|
||||
}
|
||||
if a.pluginFiles == nil {
|
||||
a.pluginFiles = make(map[string]pluginFileGrant)
|
||||
}
|
||||
a.pluginFiles[id] = pluginFileGrant{PluginID: pluginID, Path: clean, Write: write, Expires: now.Add(pluginFileGrantTTL)}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *App) revokePluginFiles(pluginID string) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for id, grant := range a.pluginFiles {
|
||||
if grant.PluginID == pluginID {
|
||||
delete(a.pluginFiles, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) pluginFilePath(pluginID, id string, write bool) (string, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
grant, ok := a.pluginFiles[id]
|
||||
if ok && !time.Now().Before(grant.Expires) {
|
||||
delete(a.pluginFiles, id)
|
||||
ok = false
|
||||
}
|
||||
if !ok || grant.PluginID != pluginID || (write && !grant.Write) {
|
||||
return "", errors.New("file handle is not available to this plugin")
|
||||
}
|
||||
return grant.Path, nil
|
||||
}
|
||||
|
||||
func panelFileEncoding(params map[string]any) (string, error) {
|
||||
encoding, err := panelTextParam(params, "encoding", false, 16, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch encoding {
|
||||
case "", "utf8", "base64":
|
||||
return encoding, nil
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported encoding %q", encoding)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) panelFileCall(mgr *plugin.Manager, pluginID, method string, params map[string]any) (any, error) {
|
||||
if err := mgr.Broker().Authorize(pluginID, "fs:pick"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch method {
|
||||
case "file.pick", "file.save":
|
||||
if a.ctx == nil {
|
||||
return nil, errors.New("window context not ready")
|
||||
}
|
||||
title, err := panelTextParam(params, "title", false, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pattern, err := panelTextParam(params, "pattern", false, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if method == "file.pick" {
|
||||
path, err := a.PickFile(title, pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a.issuePluginFileGrant(pluginID, path, false)
|
||||
}
|
||||
defaultFilename, err := panelTextParam(params, "defaultFilename", false, 255, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if defaultFilename != "" && (filepath.Base(defaultFilename) != defaultFilename || defaultFilename == "." || defaultFilename == "..") {
|
||||
return nil, errors.New("defaultFilename must be a file name")
|
||||
}
|
||||
opts := wailsRuntime.SaveDialogOptions{Title: title, DefaultFilename: defaultFilename, CanCreateDirectories: true}
|
||||
if pattern != "" {
|
||||
opts.Filters = []wailsRuntime.FileFilter{{DisplayName: pattern, Pattern: pattern}}
|
||||
}
|
||||
path, err := wailsRuntime.SaveFileDialog(a.ctx, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a.issuePluginFileGrant(pluginID, path, true)
|
||||
case "file.read":
|
||||
id, err := panelTextParam(params, "id", true, 64, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path, err := a.pluginFilePath(pluginID, id, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoding, err := panelFileEncoding(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if info.Size() > maxPanelFileBytes {
|
||||
return nil, fmt.Errorf("file exceeds %d bytes", maxPanelFileBytes)
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(file, maxPanelFileBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) > maxPanelFileBytes {
|
||||
return nil, fmt.Errorf("file exceeds %d bytes", maxPanelFileBytes)
|
||||
}
|
||||
result := map[string]any{"name": filepath.Base(path), "size": len(data)}
|
||||
if encoding == "base64" {
|
||||
result["encoding"] = "base64"
|
||||
result["data"] = base64.StdEncoding.EncodeToString(data)
|
||||
} else {
|
||||
if !utf8.Valid(data) {
|
||||
return nil, errors.New("file is not valid UTF-8")
|
||||
}
|
||||
result["encoding"] = "utf8"
|
||||
result["data"] = string(data)
|
||||
}
|
||||
return result, nil
|
||||
case "file.write":
|
||||
id, err := panelTextParam(params, "id", true, 64, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path, err := a.pluginFilePath(pluginID, id, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoding, err := panelFileEncoding(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawData, ok := params["data"].(string)
|
||||
if !ok {
|
||||
return nil, errors.New("data must be a string")
|
||||
}
|
||||
if encoding == "base64" && len(rawData) > (maxPanelFileBytes+2)/3*4 {
|
||||
return nil, fmt.Errorf("encoded data exceeds %d bytes", maxPanelFileBytes)
|
||||
}
|
||||
if encoding != "base64" && len(rawData) > maxPanelFileBytes {
|
||||
return nil, fmt.Errorf("data exceeds %d bytes", maxPanelFileBytes)
|
||||
}
|
||||
var data []byte
|
||||
if encoding == "base64" {
|
||||
data, err = base64.StdEncoding.DecodeString(rawData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode base64 data: %w", err)
|
||||
}
|
||||
} else {
|
||||
data = []byte(rawData)
|
||||
}
|
||||
if len(data) > maxPanelFileBytes {
|
||||
return nil, fmt.Errorf("data exceeds %d bytes", maxPanelFileBytes)
|
||||
}
|
||||
tmp := path + "." + id + ".reims-plugin-tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true, "name": filepath.Base(path), "size": len(data)}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported plugin file method %q", method)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPanelNetRequestBytes = 1 << 20
|
||||
maxPanelNetResponseBytes = 4 << 20
|
||||
)
|
||||
|
||||
func authorizePanelNetURL(mgr *plugin.Manager, pluginID, rawURL string) error {
|
||||
clean, err := validateExternalHTTPSURL(rawURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u, err := url.Parse(clean)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, ok := mgr.Registry().Info(pluginID)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown plugin %q", pluginID)
|
||||
}
|
||||
for _, permission := range info.Permissions {
|
||||
if !strings.HasPrefix(permission.Name, "net:") {
|
||||
continue
|
||||
}
|
||||
host := strings.TrimPrefix(permission.Name, "net:")
|
||||
if strings.EqualFold(host, u.Host) || strings.EqualFold(host, u.Hostname()) {
|
||||
return mgr.Broker().Authorize(pluginID, permission.Name)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("plugin %q has not declared net:%s", pluginID, u.Host)
|
||||
}
|
||||
|
||||
func panelNetFetch(mgr *plugin.Manager, pluginID string, params map[string]any) (any, error) {
|
||||
client := netproxy.NewClient()
|
||||
client.Timeout = 30 * time.Second
|
||||
return panelNetFetchWithClient(mgr, pluginID, params, client)
|
||||
}
|
||||
|
||||
func panelNetFetchWithClient(mgr *plugin.Manager, pluginID string, params map[string]any, client *http.Client) (any, error) {
|
||||
rawURL, err := panelTextParam(params, "url", true, 2048, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := authorizePanelNetURL(mgr, pluginID, rawURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawURL = strings.TrimSpace(rawURL)
|
||||
previousRedirect := client.CheckRedirect
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if err := authorizePanelNetURL(mgr, pluginID, req.URL.String()); err != nil {
|
||||
return err
|
||||
}
|
||||
if previousRedirect != nil {
|
||||
return previousRedirect(req, via)
|
||||
}
|
||||
if len(via) >= 10 {
|
||||
return fmt.Errorf("stopped after 10 redirects")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
method, err := panelTextParam(params, "method", false, 16, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if method == "" {
|
||||
method = http.MethodGet
|
||||
}
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead:
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported HTTP method %q", method)
|
||||
}
|
||||
bodyText, err := panelTextParam(params, "body", false, maxPanelNetRequestBytes, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
responseType, err := panelTextParam(params, "responseType", false, 16, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch responseType {
|
||||
case "", "text", "json", "base64":
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported responseType %q", responseType)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, strings.NewReader(bodyText))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rawHeaders, ok := params["headers"]; ok && rawHeaders != nil {
|
||||
headers, ok := rawHeaders.(map[string]any)
|
||||
if !ok || len(headers) > 32 {
|
||||
return nil, fmt.Errorf("invalid headers")
|
||||
}
|
||||
for name, raw := range headers {
|
||||
value, ok := raw.(string)
|
||||
lowerName := strings.ToLower(strings.TrimSpace(name))
|
||||
if lowerName == "host" || lowerName == "content-length" || strings.HasPrefix(lowerName, "proxy-") {
|
||||
return nil, fmt.Errorf("header %q is managed by the host", name)
|
||||
}
|
||||
if !ok || strings.TrimSpace(name) == "" || strings.ContainsAny(name, "\r\n:") || strings.ContainsAny(value, "\r\n") {
|
||||
return nil, fmt.Errorf("invalid header %q", name)
|
||||
}
|
||||
req.Header.Set(name, value)
|
||||
}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxPanelNetResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(body) > maxPanelNetResponseBytes {
|
||||
return nil, fmt.Errorf("response exceeds %d bytes", maxPanelNetResponseBytes)
|
||||
}
|
||||
headers := make(map[string]string, len(resp.Header))
|
||||
for key, values := range resp.Header {
|
||||
if strings.EqualFold(key, "Set-Cookie") {
|
||||
continue
|
||||
}
|
||||
headers[key] = strings.Join(values, ", ")
|
||||
}
|
||||
result := map[string]any{"status": resp.StatusCode, "headers": headers, "url": resp.Request.URL.String()}
|
||||
switch responseType {
|
||||
case "", "text":
|
||||
if !utf8.Valid(body) {
|
||||
return nil, fmt.Errorf("response is not valid UTF-8")
|
||||
}
|
||||
result["body"] = string(body)
|
||||
result["encoding"] = "utf8"
|
||||
case "base64":
|
||||
result["body"] = base64.StdEncoding.EncodeToString(body)
|
||||
result["encoding"] = "base64"
|
||||
case "json":
|
||||
var value any
|
||||
if err := json.Unmarshal(body, &value); err != nil {
|
||||
return nil, fmt.Errorf("decode JSON response: %w", err)
|
||||
}
|
||||
result["json"] = value
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported responseType %q", responseType)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func panelValidateSettingValue(prop plugin.SettingProperty, value any) error {
|
||||
switch prop.Type {
|
||||
case "boolean":
|
||||
if _, ok := value.(bool); !ok {
|
||||
return fmt.Errorf("expected boolean")
|
||||
}
|
||||
case "string":
|
||||
text, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected string")
|
||||
}
|
||||
if len(prop.Enum) > 0 && !slices.Contains(prop.Enum, text) {
|
||||
return fmt.Errorf("value is not in enum")
|
||||
}
|
||||
case "number", "integer":
|
||||
number, ok := value.(float64)
|
||||
if !ok || math.IsNaN(number) || math.IsInf(number, 0) {
|
||||
return fmt.Errorf("expected finite number")
|
||||
}
|
||||
if prop.Type == "integer" && math.Trunc(number) != number {
|
||||
return fmt.Errorf("expected integer")
|
||||
}
|
||||
if prop.Minimum != nil && number < *prop.Minimum {
|
||||
return fmt.Errorf("number is below minimum")
|
||||
}
|
||||
if prop.Maximum != nil && number > *prop.Maximum {
|
||||
return fmt.Errorf("number is above maximum")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported setting type %q", prop.Type)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func panelSettingScope(schema *plugin.SettingsSchema, key string) string {
|
||||
if prop, ok := schema.Properties[key]; ok && prop.Scope != "" {
|
||||
return prop.Scope
|
||||
}
|
||||
if schema.Scope != "" {
|
||||
return schema.Scope
|
||||
}
|
||||
return "app"
|
||||
}
|
||||
|
||||
func (a *App) panelSettingsVM(vm string) (string, error) {
|
||||
if vm == "" {
|
||||
return "", nil
|
||||
}
|
||||
info, err := a.resolveComputerUseVMInfo(vm)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return info.Ref().Key(), nil
|
||||
}
|
||||
|
||||
func (a *App) panelSettingsCall(mgr *plugin.Manager, pluginID, method string, params map[string]any) (any, error) {
|
||||
vm, err := panelTextParam(params, "vm", false, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if vm != "" {
|
||||
err = mgr.Broker().Authorize(pluginID, "vm:read")
|
||||
} else {
|
||||
err = mgr.Broker().AllowRate(pluginID)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err = a.panelSettingsVM(vm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch method {
|
||||
case "settings.get":
|
||||
values := mgr.GetSettings(pluginID, vm, true)
|
||||
key, err := panelTextParam(params, "key", false, 128, false)
|
||||
if err != nil || key == "" {
|
||||
return values, err
|
||||
}
|
||||
info, ok := mgr.Registry().Info(pluginID)
|
||||
if !ok || info.Settings == nil {
|
||||
return nil, fmt.Errorf("plugin %q has no settings schema", pluginID)
|
||||
}
|
||||
prop, ok := info.Settings.Properties[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown setting %q", key)
|
||||
}
|
||||
value := values[key]
|
||||
configured := mgr.SettingConfigured(pluginID, vm, key)
|
||||
return map[string]any{"value": value, "configured": configured, "secret": prop.Secret}, nil
|
||||
case "settings.set":
|
||||
info, ok := mgr.Registry().Info(pluginID)
|
||||
if !ok || info.Settings == nil {
|
||||
return nil, fmt.Errorf("plugin %q has no settings schema", pluginID)
|
||||
}
|
||||
values, ok := params["values"].(map[string]any)
|
||||
if !ok {
|
||||
key, keyErr := panelTextParam(params, "key", true, 128, false)
|
||||
if keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
values = map[string]any{key: params["value"]}
|
||||
}
|
||||
if len(values) == 0 {
|
||||
return nil, fmt.Errorf("values must be a non-empty object")
|
||||
}
|
||||
for key, value := range values {
|
||||
if key == computerUseAccessSetting {
|
||||
return nil, fmt.Errorf("setting %q can only be changed by the user", key)
|
||||
}
|
||||
prop, ok := info.Settings.Properties[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown setting %q", key)
|
||||
}
|
||||
scope := panelSettingScope(info.Settings, key)
|
||||
if (vm == "" && scope == "vm") || (vm != "" && scope == "app") {
|
||||
return nil, fmt.Errorf("setting %q is not valid at this scope", key)
|
||||
}
|
||||
if prop.Required && (value == nil || value == "") {
|
||||
return nil, fmt.Errorf("setting %q is required", key)
|
||||
}
|
||||
if err := panelValidateSettingValue(prop, value); err != nil {
|
||||
return nil, fmt.Errorf("setting %q: %w", key, err)
|
||||
}
|
||||
}
|
||||
if err := mgr.SetSettings(pluginID, vm, values); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported plugin settings method %q", method)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
const pluginTaskKindPrefix = "plugin:"
|
||||
|
||||
func pluginTaskKind(pluginID string) string { return pluginTaskKindPrefix + pluginID }
|
||||
|
||||
// hostTaskRunning reports whether a task owned by the host itself is running.
|
||||
func hostTaskRunning() bool {
|
||||
for _, task := range tasks.list() {
|
||||
if task.Status == TaskRunning && !strings.HasPrefix(task.Kind, pluginTaskKindPrefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func panelNumberParam(params map[string]any, key string, required bool, min, max float64) (float64, bool, error) {
|
||||
raw, ok := params[key]
|
||||
if !ok || raw == nil {
|
||||
if required {
|
||||
return 0, false, fmt.Errorf("%s is required", key)
|
||||
}
|
||||
return 0, false, nil
|
||||
}
|
||||
value, ok := raw.(float64)
|
||||
if !ok || math.IsNaN(value) || math.IsInf(value, 0) || value < min || value > max {
|
||||
return 0, false, fmt.Errorf("invalid %s", key)
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
func pluginTaskFor(pluginID, taskID string) (Task, error) {
|
||||
task, ok := tasks.get(taskID)
|
||||
if !ok || task.Kind != pluginTaskKind(pluginID) {
|
||||
return Task{}, fmt.Errorf("task %q is not owned by plugin %q", taskID, pluginID)
|
||||
}
|
||||
return task, nil
|
||||
}
|
||||
|
||||
func (a *App) panelTaskCall(mgr *plugin.Manager, pluginID, method string, params map[string]any) (any, error) {
|
||||
if err := mgr.Broker().Authorize(pluginID, "task:progress"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.ensureTaskEmitter()
|
||||
switch method {
|
||||
case "task.start":
|
||||
subject, err := panelTextParam(params, "subject", false, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if subject == "" {
|
||||
subject, err = panelTextParam(params, "title", true, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
vm, err := panelTextParam(params, "vm", false, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err = a.panelSettingsVM(vm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cancelable := false
|
||||
if raw, ok := params["cancelable"]; ok && raw != nil {
|
||||
value, ok := raw.(bool)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid cancelable")
|
||||
}
|
||||
cancelable = value
|
||||
}
|
||||
id := tasks.startWithCancelFactory(pluginTaskKind(pluginID), subject, vm, "", "", "", func(id string) context.CancelFunc {
|
||||
if !cancelable {
|
||||
return nil
|
||||
}
|
||||
return func() { tasks.finish(id, "", context.Canceled) }
|
||||
})
|
||||
task, _ := tasks.get(id)
|
||||
return task, nil
|
||||
case "task.update":
|
||||
taskID, err := panelTextParam(params, "id", true, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := pluginTaskFor(pluginID, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if current.Status != TaskRunning {
|
||||
return nil, errors.New("task is already finished")
|
||||
}
|
||||
step, err := panelTextParam(params, "step", false, 500, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
done, hasDone, err := panelNumberParam(params, "done", false, 0, math.MaxInt64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
total, hasTotal, err := panelNumberParam(params, "total", false, 0, math.MaxInt64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
percent, hasPercent, err := panelNumberParam(params, "percent", false, 0, 100)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasDone && !hasTotal && !hasPercent {
|
||||
tasks.update(taskID, host.Update{Kind: host.KindStep, Message: step, Percent: -1})
|
||||
} else {
|
||||
if !hasDone {
|
||||
done = float64(current.Done)
|
||||
}
|
||||
if !hasTotal {
|
||||
total = float64(current.Total)
|
||||
}
|
||||
if !hasPercent {
|
||||
percent = -1
|
||||
if total > 0 {
|
||||
percent = done * 100 / total
|
||||
}
|
||||
}
|
||||
tasks.update(taskID, host.Update{Kind: host.KindProgress, Step: step, Done: int64(done), Total: int64(total), Percent: percent})
|
||||
}
|
||||
updated, _ := tasks.get(taskID)
|
||||
return updated, nil
|
||||
case "task.finish":
|
||||
taskID, err := panelTextParam(params, "id", true, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := pluginTaskFor(pluginID, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if current.Status != TaskRunning {
|
||||
return current, nil
|
||||
}
|
||||
status, err := panelTextParam(params, "status", false, 20, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := panelTextParam(params, "result", false, 4000, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message, err := panelTextParam(params, "error", false, 2000, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch status {
|
||||
case "", TaskDone:
|
||||
tasks.finish(taskID, result, nil)
|
||||
case TaskFailed:
|
||||
if message == "" {
|
||||
message = "plugin task failed"
|
||||
}
|
||||
tasks.finish(taskID, result, errors.New(message))
|
||||
case TaskCanceled:
|
||||
tasks.finish(taskID, result, context.Canceled)
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid task status %q", status)
|
||||
}
|
||||
finished, _ := tasks.get(taskID)
|
||||
return finished, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported plugin task method %q", method)
|
||||
}
|
||||
}
|
||||
|
||||
func cancelPluginTasks(pluginID string) {
|
||||
for _, task := range tasks.list() {
|
||||
if task.Status != TaskRunning || !strings.HasPrefix(task.Kind, pluginTaskKindPrefix) {
|
||||
continue
|
||||
}
|
||||
if pluginID != "" && task.Kind != pluginTaskKind(pluginID) {
|
||||
continue
|
||||
}
|
||||
if err := tasks.cancel(task.ID); err != nil {
|
||||
tasks.finish(task.ID, "", context.Canceled)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
type panelFormRequest struct {
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Schema plugin.SettingsSchema `json:"schema"`
|
||||
Values map[string]any `json:"values"`
|
||||
ConfirmLabel string `json:"confirmLabel,omitempty"`
|
||||
CancelLabel string `json:"cancelLabel,omitempty"`
|
||||
Danger bool `json:"danger,omitempty"`
|
||||
}
|
||||
|
||||
func panelFormPayload(params map[string]any) (panelFormRequest, error) {
|
||||
req := panelFormRequest{Values: map[string]any{}}
|
||||
var err error
|
||||
if req.Title, err = panelTextParam(params, "title", true, 200, false); err != nil {
|
||||
return req, err
|
||||
}
|
||||
if req.Message, err = panelTextParam(params, "message", false, 4000, true); err != nil {
|
||||
return req, err
|
||||
}
|
||||
if req.ConfirmLabel, err = panelTextParam(params, "confirmLabel", false, 80, false); err != nil {
|
||||
return req, err
|
||||
}
|
||||
if req.ConfirmLabel == "" {
|
||||
if req.ConfirmLabel, err = panelTextParam(params, "submitLabel", false, 80, false); err != nil {
|
||||
return req, err
|
||||
}
|
||||
}
|
||||
if req.CancelLabel, err = panelTextParam(params, "cancelLabel", false, 80, false); err != nil {
|
||||
return req, err
|
||||
}
|
||||
if rawDanger, ok := params["danger"]; ok && rawDanger != nil {
|
||||
danger, ok := rawDanger.(bool)
|
||||
if !ok {
|
||||
return req, errors.New("invalid danger")
|
||||
}
|
||||
req.Danger = danger
|
||||
}
|
||||
rawSchema, ok := params["schema"]
|
||||
if !ok {
|
||||
return req, errors.New("schema is required")
|
||||
}
|
||||
schemaJSON, err := json.Marshal(rawSchema)
|
||||
if err != nil {
|
||||
return req, err
|
||||
}
|
||||
if err := json.Unmarshal(schemaJSON, &req.Schema); err != nil {
|
||||
return req, fmt.Errorf("invalid form schema: %w", err)
|
||||
}
|
||||
if len(req.Schema.Properties) == 0 || len(req.Schema.Properties) > 32 {
|
||||
return req, errors.New("form schema must contain between 1 and 32 properties")
|
||||
}
|
||||
for key, prop := range req.Schema.Properties {
|
||||
if key == "" || len(key) > 128 {
|
||||
return req, fmt.Errorf("invalid form field name")
|
||||
}
|
||||
switch prop.Type {
|
||||
case "boolean", "string", "number", "integer":
|
||||
default:
|
||||
return req, fmt.Errorf("form field %q has unsupported type %q", key, prop.Type)
|
||||
}
|
||||
if prop.Default != nil {
|
||||
if err := panelValidateSettingValue(prop, prop.Default); err != nil {
|
||||
return req, fmt.Errorf("form field %q default: %w", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if rawValues, exists := params["values"]; exists && rawValues != nil {
|
||||
values, ok := rawValues.(map[string]any)
|
||||
if !ok {
|
||||
return req, errors.New("form values must be an object")
|
||||
}
|
||||
req.Values = values
|
||||
}
|
||||
for key, value := range req.Values {
|
||||
prop, ok := req.Schema.Properties[key]
|
||||
if !ok {
|
||||
return req, fmt.Errorf("unknown form field %q", key)
|
||||
}
|
||||
if err := panelValidateSettingValue(prop, value); err != nil {
|
||||
return req, fmt.Errorf("form field %q: %w", key, err)
|
||||
}
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func panelUICall(mgr *plugin.Manager, pluginID, method string, params map[string]any) (any, error) {
|
||||
if err := mgr.Broker().Authorize(pluginID, "ui:slot"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch method {
|
||||
case "ui.showForm":
|
||||
return panelFormPayload(params)
|
||||
case "ui.setTitle":
|
||||
title, err := panelTextParam(params, "title", true, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"title": title}, nil
|
||||
case "ui.setBadge":
|
||||
if _, ok := params["text"]; !ok {
|
||||
return nil, errors.New("text is required")
|
||||
}
|
||||
text, err := panelTextParam(params, "text", false, 80, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tone, err := panelTextParam(params, "tone", false, 20, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch tone {
|
||||
case "", "neutral", "ok", "warn", "error", "busy":
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid badge tone %q", tone)
|
||||
}
|
||||
return map[string]any{"text": text, "tone": tone}, nil
|
||||
case "ui.openView":
|
||||
viewID, err := panelTextParam(params, "view", true, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
view, ok := mgr.Registry().View(pluginID, viewID)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("plugin %q has no active view %q", pluginID, viewID)
|
||||
}
|
||||
return view, nil
|
||||
case "ui.close":
|
||||
return map[string]any{"ok": true}, nil
|
||||
case "ui.navigate":
|
||||
page, err := panelTextParam(params, "page", false, 40, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err := panelTextParam(params, "vm", false, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if (page == "") == (vm == "") {
|
||||
return nil, errors.New("exactly one of page or vm is required")
|
||||
}
|
||||
if page != "" {
|
||||
switch page {
|
||||
case "plugins", "settings", "images", "host", "about":
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown page %q", page)
|
||||
}
|
||||
}
|
||||
return map[string]any{"page": page, "vm": vm}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported plugin UI method %q", method)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func panelVMView(vm driver.VMInfo) map[string]any {
|
||||
return map[string]any{
|
||||
"vm": vm.Ref().Key(),
|
||||
"name": vm.Name,
|
||||
"driver_id": vm.DriverID,
|
||||
"driver_name": vm.DriverName,
|
||||
"state": vm.State,
|
||||
"phase": computerUseVMPhase(vm),
|
||||
"cpus": vm.CPUs,
|
||||
"memory": vm.Memory,
|
||||
"disk_summary": vm.DiskSummary,
|
||||
"network": vm.Network,
|
||||
"capabilities": vm.Capabilities,
|
||||
"driver_unavailable": vm.DriverUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) panelVMGet(mgr *plugin.Manager, pluginID string, params map[string]any) (any, error) {
|
||||
if err := mgr.Broker().Authorize(pluginID, "vm:read"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ref, err := panelTextParam(params, "vm", true, 200, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm, err := a.resolveComputerUseVMInfo(ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return panelVMView(vm), nil
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
@@ -41,6 +43,7 @@ type PluginUIContributions struct {
|
||||
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
||||
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
||||
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
||||
Views []plugin.ViewContribution `json:"views,omitempty"`
|
||||
ImageSources []plugin.ImageSourceContribution `json:"image_sources,omitempty"`
|
||||
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
|
||||
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
|
||||
@@ -684,7 +687,12 @@ func (a *App) DisablePlugin(id string) error {
|
||||
if mgr == nil {
|
||||
return errors.New("plugin manager not initialized")
|
||||
}
|
||||
return mgr.Disable(context.Background(), id)
|
||||
if err := mgr.Disable(context.Background(), id); err != nil {
|
||||
return err
|
||||
}
|
||||
a.revokePluginFiles(id)
|
||||
cancelPluginTasks(id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RemovePlugin(id string, purgeData bool) error {
|
||||
@@ -694,7 +702,12 @@ func (a *App) RemovePlugin(id string, purgeData bool) error {
|
||||
if mgr == nil {
|
||||
return errors.New("plugin manager not initialized")
|
||||
}
|
||||
return mgr.Remove(context.Background(), id, purgeData)
|
||||
if err := mgr.Remove(context.Background(), id, purgeData); err != nil {
|
||||
return err
|
||||
}
|
||||
a.revokePluginFiles(id)
|
||||
cancelPluginTasks(id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) GetPluginSettings(pluginID, vmKey string) map[string]any {
|
||||
@@ -746,6 +759,7 @@ func (a *App) GetPluginUIContributions() PluginUIContributions {
|
||||
SettingsPages: mgr.LocalizeSettingsPages(reg.SettingsPages()),
|
||||
StatusItems: mgr.LocalizeStatusItems(reg.StatusItems()),
|
||||
Panels: mgr.LocalizePanels(reg.Panels("")),
|
||||
Views: mgr.LocalizeViews(reg.Views("")),
|
||||
ImageSources: mgr.LocalizeImageSources(reg.ImageSources()),
|
||||
VMTemplates: reg.VMTemplates(),
|
||||
Themes: reg.Themes(),
|
||||
@@ -1136,8 +1150,44 @@ func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.P
|
||||
return info, err
|
||||
}
|
||||
|
||||
type panelConfirmRequest struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Message string `json:"message"`
|
||||
ConfirmLabel string `json:"confirmLabel,omitempty"`
|
||||
CancelLabel string `json:"cancelLabel,omitempty"`
|
||||
Danger bool `json:"danger,omitempty"`
|
||||
}
|
||||
|
||||
type panelCopyRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func panelTextParam(params map[string]any, key string, required bool, maxBytes int, multiline bool) (string, error) {
|
||||
raw, ok := params[key]
|
||||
if !ok || raw == nil {
|
||||
if required {
|
||||
return "", fmt.Errorf("%s is required", key)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
value, ok := raw.(string)
|
||||
if !ok || !utf8.ValidString(value) || len(value) > maxBytes || (required && strings.TrimSpace(value) == "") {
|
||||
return "", fmt.Errorf("invalid %s", key)
|
||||
}
|
||||
for _, r := range value {
|
||||
if !unicode.IsControl(r) {
|
||||
continue
|
||||
}
|
||||
if multiline && (r == '\n' || r == '\r' || r == '\t') {
|
||||
continue
|
||||
}
|
||||
return "", fmt.Errorf("invalid control character in %s", key)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// PanelBridgeCall handles permission-checked, rate-limited, redacted Host API
|
||||
// reads from sandboxed L4 iframe panels (§7.3).
|
||||
// requests from sandboxed L4 iframe panels (§7.3).
|
||||
func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (any, error) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
@@ -1153,7 +1203,15 @@ func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (a
|
||||
}
|
||||
}
|
||||
if !hasPanel {
|
||||
return nil, fmt.Errorf("plugin %q has no active panel", pluginID)
|
||||
for _, view := range mgr.Registry().Views("") {
|
||||
if view.PluginID == pluginID {
|
||||
hasPanel = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasPanel {
|
||||
return nil, fmt.Errorf("plugin %q has no active panel or view", pluginID)
|
||||
}
|
||||
method, spec, known := plugin.ResolveBridgeMethod(method)
|
||||
if !known {
|
||||
@@ -1220,7 +1278,107 @@ func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (a
|
||||
cmdArgs, _ := params["args"].(map[string]any)
|
||||
mgr.Broker().Audit(pluginID, "PANEL_CMD", cmdID)
|
||||
return mgr.Registry().InvokeCommand(context.Background(), pluginID, cmdID, cmdArgs)
|
||||
case "ui.confirm":
|
||||
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req := panelConfirmRequest{}
|
||||
var err error
|
||||
if req.Title, err = panelTextParam(params, "title", false, 200, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.Message, err = panelTextParam(params, "message", true, 4000, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.ConfirmLabel, err = panelTextParam(params, "confirmLabel", false, 80, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.CancelLabel, err = panelTextParam(params, "cancelLabel", false, 80, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rawDanger, ok := params["danger"]; ok && rawDanger != nil {
|
||||
danger, ok := rawDanger.(bool)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid danger")
|
||||
}
|
||||
req.Danger = danger
|
||||
}
|
||||
return req, nil
|
||||
case "ui.copy":
|
||||
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := params["text"]; !ok {
|
||||
return nil, errors.New("text is required")
|
||||
}
|
||||
text, err := panelTextParam(params, "text", false, 1<<20, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return panelCopyRequest{Text: text}, nil
|
||||
case "ui.openExternal":
|
||||
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawURL, err := panelTextParam(params, "url", true, 2048, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.OpenURL(rawURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mgr.Broker().Audit(pluginID, "PANEL_UI", method)
|
||||
return map[string]any{"ok": true}, nil
|
||||
case "storage.get", "storage.set", "storage.list", "storage.delete":
|
||||
if err := mgr.Broker().Authorize(pluginID, spec.Permission); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if method == "storage.list" {
|
||||
keys, err := mgr.ViewStorageList(pluginID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"keys": keys}, nil
|
||||
}
|
||||
key, err := panelTextParam(params, "key", true, 128, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch method {
|
||||
case "storage.get":
|
||||
value, found, err := mgr.ViewStorageGet(pluginID, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"value": value, "found": found}, nil
|
||||
case "storage.set":
|
||||
if err := mgr.ViewStorageSet(pluginID, key, params["value"]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
case "storage.delete":
|
||||
deleted, err := mgr.ViewStorageDelete(pluginID, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"deleted": deleted}, nil
|
||||
}
|
||||
case "ui.showForm", "ui.setTitle", "ui.setBadge", "ui.openView", "ui.close", "ui.navigate":
|
||||
return panelUICall(mgr, pluginID, method, params)
|
||||
case "vm.get":
|
||||
return a.panelVMGet(mgr, pluginID, params)
|
||||
case "settings.get", "settings.set":
|
||||
return a.panelSettingsCall(mgr, pluginID, method, params)
|
||||
case "file.pick", "file.save", "file.read", "file.write":
|
||||
return a.panelFileCall(mgr, pluginID, method, params)
|
||||
case "task.start", "task.update", "task.finish":
|
||||
return a.panelTaskCall(mgr, pluginID, method, params)
|
||||
case "net.fetch":
|
||||
return panelNetFetch(mgr, pluginID, params)
|
||||
case "events.subscribe", "events.unsubscribe":
|
||||
return panelEventsCall(mgr, pluginID, method, params)
|
||||
default:
|
||||
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
|
||||
}
|
||||
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func float64Ptr(value float64) *float64 { return &value }
|
||||
|
||||
func newPanelBridgeTestApp(t *testing.T, permissions ...string) *App {
|
||||
t.Helper()
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: t.TempDir(), HostVersion: "0.2.12"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Close)
|
||||
def := plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1, ID: "vendor.panel", Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: "Test panel"},
|
||||
Permissions: permissions,
|
||||
Settings: &plugin.SettingsSchema{Scope: "both", Properties: map[string]plugin.SettingProperty{
|
||||
"enabled": {Type: "boolean", Default: true},
|
||||
"count": {Type: "integer", Minimum: float64Ptr(0), Maximum: float64Ptr(10)},
|
||||
"mode": {Type: "string", Enum: []string{"dev", "prod"}, Default: "dev"},
|
||||
"secret": {Type: "string", Secret: true},
|
||||
"vm_only": {Type: "boolean", Scope: "vm"},
|
||||
"required": {Type: "string", Required: true},
|
||||
computerUseAccessSetting: {Type: "boolean"},
|
||||
}},
|
||||
Contributes: plugin.Contributes{
|
||||
Panels: []plugin.PanelContribution{{ID: "main", Slot: "settings.plugin", Title: plugin.LocalizedText{EnUS: "Test panel"}}},
|
||||
Views: []plugin.ViewContribution{{ID: "console", Location: "sidebar", Title: plugin.LocalizedText{EnUS: "Console"}, Entry: "index.html"}},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceBuiltin, Desired: true,
|
||||
}
|
||||
if err := mgr.Registry().Register(def); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
if !mgr.Registry().IsActive("vendor.panel") {
|
||||
t.Fatal("test panel did not activate")
|
||||
}
|
||||
return &App{pluginMgr: mgr}
|
||||
}
|
||||
|
||||
func TestPanelBridgeConfirmationAndCopy(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "ui:notify", "ui:slot")
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "ui.confirm", map[string]any{
|
||||
"title": "Publish", "message": "Publish this draft?",
|
||||
"confirmLabel": "Publish", "cancelLabel": "Keep editing", "danger": true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
confirm, ok := result.(panelConfirmRequest)
|
||||
if !ok {
|
||||
t.Fatalf("confirmation result has type %T", result)
|
||||
}
|
||||
if confirm.Message != "Publish this draft?" || confirm.ConfirmLabel != "Publish" || !confirm.Danger {
|
||||
t.Fatalf("unexpected confirmation: %+v", confirm)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "ui.copy", map[string]any{"text": "first\nsecond"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copyReq, ok := result.(panelCopyRequest)
|
||||
if !ok || copyReq.Text != "first\nsecond" {
|
||||
t.Fatalf("unexpected copy request: %#v", result)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "ui.copy", map[string]any{"text": ""})
|
||||
if err != nil || result.(panelCopyRequest).Text != "" {
|
||||
t.Fatalf("empty clipboard text was rejected: %#v, %v", result, err)
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.copy", map[string]any{"text": 42}); err == nil {
|
||||
t.Fatal("non-string clipboard input was accepted")
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.confirm", map[string]any{"message": "bad\x00message"}); err == nil {
|
||||
t.Fatal("control character in confirmation was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeStorage(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "fs:plugin_data")
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "storage.set", map[string]any{
|
||||
"key": "draft", "value": map[string]any{"enabled": true},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := a.PanelBridgeCall("vendor.panel", "storage.get", map[string]any{"key": "draft"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := result.(map[string]any)
|
||||
if got["found"] != true {
|
||||
t.Fatalf("stored value was not found: %#v", got)
|
||||
}
|
||||
raw := got["value"].(json.RawMessage)
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(value, map[string]any{"enabled": true}) {
|
||||
t.Fatalf("stored value = %#v", value)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "storage.list", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keys := result.(map[string]any)["keys"].([]string); !reflect.DeepEqual(keys, []string{"draft"}) {
|
||||
t.Fatalf("storage keys = %v", keys)
|
||||
}
|
||||
result, err = a.PanelBridgeCall("vendor.panel", "storage.delete", map[string]any{"key": "draft"})
|
||||
if err != nil || result.(map[string]any)["deleted"] != true {
|
||||
t.Fatalf("delete result = %#v, err = %v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelBridgeRejectsUnavailableActions(t *testing.T) {
|
||||
a := newPanelBridgeTestApp(t, "ui:slot")
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "storage.set", map[string]any{"key": "draft", "value": true}); err == nil {
|
||||
t.Fatal("storage write succeeded without fs:plugin_data")
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "ui.openExternal", map[string]any{"url": "file:///C:/Windows/System32"}); err == nil {
|
||||
t.Fatal("non-HTTPS external URL was accepted")
|
||||
}
|
||||
if _, err := a.PanelBridgeCall("vendor.panel", "file.pick", nil); err == nil {
|
||||
t.Fatal("experimental file.pick became available without an implementation")
|
||||
}
|
||||
}
|
||||
+21
-4
@@ -32,7 +32,7 @@ const (
|
||||
// Task is one tracked job as the frontend sees it.
|
||||
type Task struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"` // "installer-download" | "recovery-download" | "vm-create" | "runtime-install" | "app-update"
|
||||
Kind string `json:"kind"` // installer/recovery/VM/runtime/app tasks or "plugin:<pluginID>"
|
||||
Subject string `json:"subject"` // release ("26.7.3") or VM name
|
||||
VM string `json:"vm,omitempty"`
|
||||
InstallerKind string `json:"installer_kind,omitempty"` // "offline" | "online" while an installer download is attached
|
||||
@@ -80,9 +80,14 @@ func (m *taskManager) start(kind, subject, vm string, cancel context.CancelFunc)
|
||||
}
|
||||
|
||||
func (m *taskManager) startWithInstaller(kind, subject, vm, installerKind, installerVersion, installerPhase string, cancel context.CancelFunc) string {
|
||||
return m.startWithCancelFactory(kind, subject, vm, installerKind, installerVersion, installerPhase, func(string) context.CancelFunc { return cancel })
|
||||
}
|
||||
|
||||
func (m *taskManager) startWithCancelFactory(kind, subject, vm, installerKind, installerVersion, installerPhase string, makeCancel func(string) context.CancelFunc) string {
|
||||
m.mu.Lock()
|
||||
m.seq++
|
||||
id := fmt.Sprintf("%s-%d", kind, m.seq)
|
||||
cancel := makeCancel(id)
|
||||
now := time.Now().UnixMilli()
|
||||
step := ""
|
||||
if installerPhase == TaskPhaseQueued {
|
||||
@@ -242,15 +247,17 @@ func (m *taskManager) finish(id string, result string, err error) {
|
||||
|
||||
func (m *taskManager) cancel(id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
e, ok := m.tasks[id]
|
||||
if !ok {
|
||||
m.mu.Unlock()
|
||||
return fmt.Errorf("no task %s", id)
|
||||
}
|
||||
if e.cancel == nil {
|
||||
cancel := e.cancel
|
||||
m.mu.Unlock()
|
||||
if cancel == nil {
|
||||
return fmt.Errorf("task %s can't be stopped", id)
|
||||
}
|
||||
e.cancel()
|
||||
cancel()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -276,6 +283,16 @@ func (m *taskManager) dismiss(id string) {
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *taskManager) get(id string) (Task, bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
e, ok := m.tasks[id]
|
||||
if !ok {
|
||||
return Task{}, false
|
||||
}
|
||||
return e.task, true
|
||||
}
|
||||
|
||||
func (m *taskManager) list() []Task {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
@@ -69,6 +69,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
"compat.gpu_icd_rebound": "显卡 Vulkan ICD 路径已从 {old} 更新为 {new}",
|
||||
"confirm": "确认",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off",
|
||||
@@ -232,6 +233,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, other {# 台运行中}}",
|
||||
"forceStop": "硬关机",
|
||||
"formRequiredFields": "请填写必填项:{fields}",
|
||||
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
|
||||
@@ -494,7 +496,9 @@ var catalog = map[Locale]map[string]string{
|
||||
"noRuntimeAlert": "先在「内核」导入运行时包",
|
||||
"off": "关闭",
|
||||
"on": "开启",
|
||||
"open": "打开",
|
||||
"openFolder": "打开所在文件夹",
|
||||
"overview": "概述",
|
||||
"panelLoadFailed": "面板加载失败",
|
||||
"pauseDownload": "暂停下载",
|
||||
"plugin.disabled": "已停用 {id}",
|
||||
@@ -754,6 +758,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
"compat.gpu_icd_rebound": "Updated the GPU Vulkan ICD path from {old} to {new}",
|
||||
"confirm": "Confirm",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied",
|
||||
@@ -917,6 +922,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, one {# running} other {# running}}",
|
||||
"forceStop": "Force shut down",
|
||||
"formRequiredFields": "Fill in the required fields: {fields}",
|
||||
"gpuErrMissingExt": "Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA",
|
||||
"gpuErrVulkanCpu": "Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} is below the required 1.3 floor; update GPU drivers or use VMware SVGA",
|
||||
@@ -1179,7 +1185,9 @@ var catalog = map[Locale]map[string]string{
|
||||
"noRuntimeAlert": "Import a runtime under Engine first",
|
||||
"off": "Off",
|
||||
"on": "On",
|
||||
"open": "Open",
|
||||
"openFolder": "Show in folder",
|
||||
"overview": "Overview",
|
||||
"panelLoadFailed": "Panel failed to load",
|
||||
"pauseDownload": "Pause download",
|
||||
"plugin.disabled": "Disabled {id}",
|
||||
@@ -1461,6 +1469,7 @@ var paramOrder = map[string][]string{
|
||||
"footerMemTip": {"avail", "total", "used"},
|
||||
"footerMemValue": {"total", "used"},
|
||||
"footerRunningVMs": {"n"},
|
||||
"formRequiredFields": {"fields"},
|
||||
"gpuErrMissingExt": {"ext"},
|
||||
"gpuErrVulkanTooOld": {"ver"},
|
||||
"gpuWarnAmdLegacy": {"ref"},
|
||||
|
||||
+39
-38
@@ -51,7 +51,7 @@ var ContributionCatalog = map[string]ContractStatus{
|
||||
"statusItems": ContractExperimental,
|
||||
"panels": ContractStable,
|
||||
"imageSources": ContractStable,
|
||||
"views": ContractExperimental,
|
||||
"views": ContractStable,
|
||||
"diagnostics": ContractExperimental,
|
||||
}
|
||||
|
||||
@@ -119,10 +119,10 @@ type ViewLocationSpec struct {
|
||||
|
||||
// ViewLocationCatalog lists `views[].location` values.
|
||||
var ViewLocationCatalog = map[string]ViewLocationSpec{
|
||||
"sidebar": {Status: ContractExperimental, PerPlugin: 2},
|
||||
"vm.tab": {Status: ContractExperimental, PerPlugin: 4},
|
||||
"settings": {Status: ContractExperimental, PerPlugin: 1},
|
||||
"dialog": {Status: ContractExperimental, PerPlugin: 8},
|
||||
"sidebar": {Status: ContractStable, PerPlugin: 2},
|
||||
"vm.tab": {Status: ContractStable, PerPlugin: 4},
|
||||
"settings": {Status: ContractStable, PerPlugin: 1},
|
||||
"dialog": {Status: ContractStable, PerPlugin: 8},
|
||||
}
|
||||
|
||||
// UILayerCatalog lists full-window layers.
|
||||
@@ -155,37 +155,38 @@ type BridgeMethodSpec struct {
|
||||
|
||||
// BridgeMethodCatalog lists bridgeApi 1.0 methods.
|
||||
var BridgeMethodCatalog = map[string]BridgeMethodSpec{
|
||||
"hello": {Status: ContractStable},
|
||||
"i18n.getBundle": {Status: ContractStable},
|
||||
"ui.notify": {Status: ContractStable, Permission: "ui:notify"},
|
||||
"vm.list": {Status: ContractStable, Permission: "vm:read"},
|
||||
"command.invoke": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"hello": {Status: ContractStable},
|
||||
"i18n.getBundle": {Status: ContractStable},
|
||||
"ui.notify": {Status: ContractStable, Permission: "ui:notify"},
|
||||
"ui.confirm": {Status: ContractStable, Permission: "ui:notify"},
|
||||
"ui.copy": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"ui.openExternal": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"vm.list": {Status: ContractStable, Permission: "vm:read"},
|
||||
"command.invoke": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"storage.get": {Status: ContractStable, Permission: "fs:plugin_data"},
|
||||
"storage.set": {Status: ContractStable, Permission: "fs:plugin_data"},
|
||||
"storage.list": {Status: ContractStable, Permission: "fs:plugin_data"},
|
||||
"storage.delete": {Status: ContractStable, Permission: "fs:plugin_data"},
|
||||
|
||||
"ui.confirm": {Status: ContractExperimental, Permission: "ui:notify"},
|
||||
"ui.showForm": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"ui.setTitle": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"ui.setBadge": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"ui.openView": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"ui.close": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"ui.navigate": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"ui.openExternal": {Status: ContractExperimental, Permission: "ui:slot"},
|
||||
"vm.get": {Status: ContractExperimental, Permission: "vm:read"},
|
||||
"settings.get": {Status: ContractExperimental},
|
||||
"settings.set": {Status: ContractExperimental},
|
||||
"storage.get": {Status: ContractExperimental, Permission: "fs:plugin_data"},
|
||||
"storage.set": {Status: ContractExperimental, Permission: "fs:plugin_data"},
|
||||
"storage.list": {Status: ContractExperimental, Permission: "fs:plugin_data"},
|
||||
"storage.delete": {Status: ContractExperimental, Permission: "fs:plugin_data"},
|
||||
"file.pick": {Status: ContractExperimental, Permission: "fs:pick"},
|
||||
"file.save": {Status: ContractExperimental, Permission: "fs:pick"},
|
||||
"file.read": {Status: ContractExperimental, Permission: "fs:pick"},
|
||||
"file.write": {Status: ContractExperimental, Permission: "fs:pick"},
|
||||
"task.start": {Status: ContractExperimental, Permission: "task:progress"},
|
||||
"task.update": {Status: ContractExperimental, Permission: "task:progress"},
|
||||
"task.finish": {Status: ContractExperimental, Permission: "task:progress"},
|
||||
"net.fetch": {Status: ContractExperimental, Permission: "net:"}, // matched against net:<origin>
|
||||
"events.subscribe": {Status: ContractExperimental},
|
||||
"events.unsubscribe": {Status: ContractExperimental},
|
||||
"ui.showForm": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"ui.setTitle": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"ui.setBadge": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"ui.openView": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"ui.close": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"ui.navigate": {Status: ContractStable, Permission: "ui:slot"},
|
||||
"vm.get": {Status: ContractStable, Permission: "vm:read"},
|
||||
"settings.get": {Status: ContractStable},
|
||||
"settings.set": {Status: ContractStable},
|
||||
"file.pick": {Status: ContractStable, Permission: "fs:pick"},
|
||||
"file.save": {Status: ContractStable, Permission: "fs:pick"},
|
||||
"file.read": {Status: ContractStable, Permission: "fs:pick"},
|
||||
"file.write": {Status: ContractStable, Permission: "fs:pick"},
|
||||
"task.start": {Status: ContractStable, Permission: "task:progress"},
|
||||
"task.update": {Status: ContractStable, Permission: "task:progress"},
|
||||
"task.finish": {Status: ContractStable, Permission: "task:progress"},
|
||||
"net.fetch": {Status: ContractStable, Permission: "net:"}, // matched against net:<origin>
|
||||
"events.subscribe": {Status: ContractStable},
|
||||
"events.unsubscribe": {Status: ContractStable},
|
||||
}
|
||||
|
||||
// BridgeMethodAliases maps pre-1.0 method names to their bridgeApi 1.0 names.
|
||||
@@ -195,9 +196,9 @@ var BridgeMethodAliases = map[string]string{"notify": "ui.notify"}
|
||||
var BridgeEventCatalog = map[string]ContractStatus{
|
||||
"theme.changed": ContractStable,
|
||||
"locale.changed": ContractStable,
|
||||
"vm.stateChanged": ContractExperimental,
|
||||
"view.visibilityChanged": ContractExperimental,
|
||||
"task.updated": ContractExperimental,
|
||||
"vm.stateChanged": ContractStable,
|
||||
"view.visibilityChanged": ContractStable,
|
||||
"task.updated": ContractStable,
|
||||
}
|
||||
|
||||
// ResolveBridgeMethod maps an incoming method name to its catalog entry.
|
||||
|
||||
@@ -92,14 +92,16 @@ func TestContractCatalogsMatchFrontend(t *testing.T) {
|
||||
assertSameSet(t, "layout options", layout, tsArray(t, ui, "UI_CONTRACT_LAYOUT_OPTIONS"))
|
||||
assertSameSet(t, "icon names", ThemeIconNames, tsArray(t, ui, "UI_CONTRACT_ICONS"))
|
||||
|
||||
var locations []string
|
||||
var locations, expLocations []string
|
||||
for loc, spec := range ViewLocationCatalog {
|
||||
if spec.Status != ContractExperimental {
|
||||
t.Errorf("view location %s is stable in Go but listed as experimental in TS", loc)
|
||||
if spec.Status == ContractStable {
|
||||
locations = append(locations, loc)
|
||||
} else {
|
||||
expLocations = append(expLocations, loc)
|
||||
}
|
||||
locations = append(locations, loc)
|
||||
}
|
||||
assertSameSet(t, "view locations", locations, tsArray(t, ui, "UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL"))
|
||||
assertSameSet(t, "stable view locations", locations, tsArray(t, ui, "UI_CONTRACT_VIEW_LOCATIONS"))
|
||||
assertSameSet(t, "experimental view locations", expLocations, tsArray(t, ui, "UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL"))
|
||||
|
||||
bridge := readFrontendContract(t, "lib/bridgeContract.ts")
|
||||
if got := tsVersion(t, bridge, "BRIDGE_API_VERSION"); got != BridgeAPIVersion {
|
||||
@@ -151,12 +153,12 @@ func TestHostFeaturesAreStableOnly(t *testing.T) {
|
||||
for _, f := range features {
|
||||
has[f] = true
|
||||
}
|
||||
for _, want := range []string{"bridge.hello", "bridge.vm.list", "event.theme.changed", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes", "contrib.imageSources", "slot.vm.toolbar", "slot.nav.item.trailing", "layer.overlay", "layer.background", "theme.icons", "theme.layout", "theme.brandMark"} {
|
||||
for _, want := range []string{"bridge.hello", "bridge.vm.list", "bridge.file.pick", "contrib.views", "view.sidebar", "event.theme.changed", "event.vm.stateChanged", "event.task.updated", "event.view.visibilityChanged", "slot.sidebar.footer", "slot.settings.plugin.panel", "slot.vm.toolbar.menu", "contrib.themes", "contrib.imageSources", "slot.vm.toolbar", "slot.nav.item.trailing", "layer.overlay", "layer.background", "theme.icons", "theme.layout", "theme.brandMark"} {
|
||||
if !has[want] {
|
||||
t.Errorf("missing stable feature %s", want)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range []string{"bridge.file.pick", "contrib.views", "view.sidebar", "slot.sidebar.footer.panel", "slot.vm.card.vmCard", "contrib.statusItems"} {
|
||||
for _, unwanted := range []string{"slot.sidebar.footer.panel", "slot.vm.card.vmCard", "contrib.statusItems"} {
|
||||
if has[unwanted] {
|
||||
t.Errorf("experimental entry %s advertised as a feature", unwanted)
|
||||
}
|
||||
@@ -167,7 +169,7 @@ func TestResolveBridgeMethodAliases(t *testing.T) {
|
||||
if name, spec, ok := ResolveBridgeMethod("notify"); !ok || name != "ui.notify" || spec.Status != ContractStable {
|
||||
t.Fatalf("notify alias = %q %+v %v", name, spec, ok)
|
||||
}
|
||||
if _, spec, ok := ResolveBridgeMethod("file.pick"); !ok || spec.Status != ContractExperimental || spec.Permission != "fs:pick" {
|
||||
if _, spec, ok := ResolveBridgeMethod("file.pick"); !ok || spec.Status != ContractStable || spec.Permission != "fs:pick" {
|
||||
t.Fatalf("file.pick = %+v %v", spec, ok)
|
||||
}
|
||||
if _, _, ok := ResolveBridgeMethod("fs.readAny"); ok {
|
||||
@@ -274,7 +276,7 @@ func TestContractFindings(t *testing.T) {
|
||||
checks[f.Check] = append(checks[f.Check], f.Target)
|
||||
}
|
||||
exp := strings.Join(checks["contract-experimental"], " ")
|
||||
for _, want := range []string{"contributes.views", "panel:card"} {
|
||||
for _, want := range []string{"panel:card"} {
|
||||
if !strings.Contains(exp, want) {
|
||||
t.Errorf("experimental findings %q miss %s", exp, want)
|
||||
}
|
||||
@@ -282,6 +284,9 @@ func TestContractFindings(t *testing.T) {
|
||||
if strings.Contains(exp, "panel:s") {
|
||||
t.Error("settings.plugin panels are stable and must not be reported")
|
||||
}
|
||||
if strings.Contains(exp, "contributes.views") {
|
||||
t.Error("implemented views are stable and must not be reported")
|
||||
}
|
||||
if len(checks["contract-unknown-field"]) != 1 {
|
||||
t.Errorf("unknown field findings = %v", checks["contract-unknown-field"])
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ type Manager struct {
|
||||
assets *AssetServer
|
||||
|
||||
mu sync.RWMutex
|
||||
viewStorageMu sync.Mutex
|
||||
state *StateFile
|
||||
stateLoadErr error
|
||||
safeMode bool
|
||||
@@ -992,6 +993,33 @@ func (m *Manager) DownloaderSettings(pluginID string) (map[string]any, error) {
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
// SettingConfigured reports whether a value was explicitly saved at the requested scope.
|
||||
func (m *Manager) SettingConfigured(pluginID, vmName, key string) bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if m.state == nil {
|
||||
return false
|
||||
}
|
||||
rec := m.state.Plugins[pluginID]
|
||||
if rec == nil {
|
||||
return false
|
||||
}
|
||||
if vmName != "" {
|
||||
if _, ok := rec.VMSettings[vmName][key]; ok {
|
||||
return true
|
||||
}
|
||||
var schema *SettingsSchema
|
||||
if info, ok := m.registry.Info(pluginID); ok {
|
||||
schema = info.Settings
|
||||
}
|
||||
if !inheritsAppSetting(schema, key) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
_, ok := rec.AppSettings[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// SavedBoolSetting reads an explicitly stored boolean without applying schema
|
||||
// defaults. Security decisions must not be authorized by plugin metadata.
|
||||
func (m *Manager) SavedBoolSetting(pluginID, vmName, key string) bool {
|
||||
@@ -1808,6 +1836,28 @@ func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeViews applies active Language Pack manifest overrides onto ViewContribution titles.
|
||||
func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]ViewContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Title = cloneLocalizedText(it.Title)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "view."+it.ID+".title"); v != "" {
|
||||
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeImageSources applies active Language Pack manifest overrides onto ImageSourceContribution labels.
|
||||
func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
|
||||
@@ -117,6 +117,7 @@ type Registry struct {
|
||||
settingsPages []SettingsPageContribution
|
||||
statusItems []StatusItemContribution
|
||||
panels []PanelContribution
|
||||
views []ViewContribution
|
||||
imageSources []ImageSourceContribution
|
||||
diagnostics []RegisteredDiagnostics
|
||||
}
|
||||
@@ -619,6 +620,10 @@ func (r *Registry) registerManifestContributions(sc *Scope, m Manifest) {
|
||||
pnl.PluginID = pid
|
||||
r.RegisterPanel(sc, pnl)
|
||||
}
|
||||
for _, view := range m.Contributes.Views {
|
||||
view.PluginID = pid
|
||||
r.RegisterView(sc, view)
|
||||
}
|
||||
for _, src := range m.Contributes.ImageSources {
|
||||
src.PluginID = pid
|
||||
r.RegisterImageSource(sc, src)
|
||||
@@ -1430,6 +1435,81 @@ func (r *Registry) Panels(slot string) []PanelContribution {
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterView(sc *Scope, view ViewContribution) {
|
||||
view.ID = strings.TrimSpace(view.ID)
|
||||
if view.ID == "" {
|
||||
return
|
||||
}
|
||||
location, ok := ViewLocationCatalog[view.Location]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
view.PluginID = sc.PluginID()
|
||||
r.mu.Lock()
|
||||
count := 0
|
||||
for _, existing := range r.views {
|
||||
if existing.PluginID != view.PluginID {
|
||||
continue
|
||||
}
|
||||
if existing.ID == view.ID {
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if existing.Location == view.Location {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if location.PerPlugin > 0 && count >= location.PerPlugin {
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
r.views = append(r.views, view)
|
||||
r.mu.Unlock()
|
||||
sc.OnDispose(func() {
|
||||
r.mu.Lock()
|
||||
kept := r.views[:0]
|
||||
for _, item := range r.views {
|
||||
if !(item.PluginID == sc.PluginID() && item.ID == view.ID) {
|
||||
kept = append(kept, item)
|
||||
}
|
||||
}
|
||||
r.views = kept
|
||||
r.mu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Registry) Views(location string) []ViewContribution {
|
||||
r.mu.RLock()
|
||||
out := make([]ViewContribution, 0, len(r.views))
|
||||
for _, view := range r.views {
|
||||
if location == "" || view.Location == location {
|
||||
out = append(out, view)
|
||||
}
|
||||
}
|
||||
r.mu.RUnlock()
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].Order != out[j].Order {
|
||||
return out[i].Order < out[j].Order
|
||||
}
|
||||
if out[i].PluginID != out[j].PluginID {
|
||||
return out[i].PluginID < out[j].PluginID
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Registry) View(pluginID, viewID string) (ViewContribution, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
for _, view := range r.views {
|
||||
if view.PluginID == pluginID && view.ID == viewID {
|
||||
return view, true
|
||||
}
|
||||
}
|
||||
return ViewContribution{}, false
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterImageSource(sc *Scope, src ImageSourceContribution) {
|
||||
src.ID = strings.TrimSpace(src.ID)
|
||||
if src.ID == "" {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
viewStorageVersion = 1
|
||||
viewStorageFileName = "view-storage.json"
|
||||
maxViewStorageKeys = 256
|
||||
maxViewStorageKeyBytes = 128
|
||||
maxViewStorageValueBytes = 256 << 10
|
||||
maxViewStorageFileBytes = 1 << 20
|
||||
)
|
||||
|
||||
type viewStorageFile struct {
|
||||
Version int `json:"version"`
|
||||
Values map[string]json.RawMessage `json:"values"`
|
||||
}
|
||||
|
||||
func validateViewStorageKey(key string) error {
|
||||
if key == "" || key != strings.TrimSpace(key) || !utf8.ValidString(key) || len(key) > maxViewStorageKeyBytes {
|
||||
return fmt.Errorf("invalid storage key")
|
||||
}
|
||||
for _, r := range key {
|
||||
if unicode.IsControl(r) {
|
||||
return fmt.Errorf("invalid storage key")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) viewStoragePath(pluginID string) string {
|
||||
return filepath.Join(m.layout.DataDir(pluginID), viewStorageFileName)
|
||||
}
|
||||
|
||||
func (m *Manager) loadViewStorage(pluginID string) (*viewStorageFile, error) {
|
||||
st := &viewStorageFile{Version: viewStorageVersion, Values: make(map[string]json.RawMessage)}
|
||||
raw, err := os.ReadFile(m.viewStoragePath(pluginID))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return st, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) > maxViewStorageFileBytes {
|
||||
return nil, fmt.Errorf("plugin view storage exceeds %d bytes", maxViewStorageFileBytes)
|
||||
}
|
||||
if err := json.Unmarshal(raw, st); err != nil {
|
||||
return nil, fmt.Errorf("decode plugin view storage: %w", err)
|
||||
}
|
||||
if st.Version != viewStorageVersion {
|
||||
return nil, fmt.Errorf("unsupported plugin view storage version %d", st.Version)
|
||||
}
|
||||
if st.Values == nil {
|
||||
st.Values = make(map[string]json.RawMessage)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func (m *Manager) saveViewStorage(pluginID string, st *viewStorageFile) error {
|
||||
raw, err := json.MarshalIndent(st, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
raw = append(raw, '\n')
|
||||
if len(raw) > maxViewStorageFileBytes {
|
||||
return fmt.Errorf("plugin view storage exceeds %d bytes", maxViewStorageFileBytes)
|
||||
}
|
||||
dir := m.layout.DataDir(pluginID)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
target := m.viewStoragePath(pluginID)
|
||||
tmp := target + ".tmp"
|
||||
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, target); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ViewStorageGet returns one value from a plugin's persistent private view store.
|
||||
func (m *Manager) ViewStorageGet(pluginID, key string) (json.RawMessage, bool, error) {
|
||||
if err := validateViewStorageKey(key); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
m.viewStorageMu.Lock()
|
||||
defer m.viewStorageMu.Unlock()
|
||||
st, err := m.loadViewStorage(pluginID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
value, ok := st.Values[key]
|
||||
if !ok {
|
||||
return nil, false, nil
|
||||
}
|
||||
return append(json.RawMessage(nil), value...), true, nil
|
||||
}
|
||||
|
||||
// ViewStorageSet persists one JSON value in a plugin's private view store.
|
||||
func (m *Manager) ViewStorageSet(pluginID, key string, value any) error {
|
||||
if err := validateViewStorageKey(key); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode storage value: %w", err)
|
||||
}
|
||||
if len(raw) > maxViewStorageValueBytes {
|
||||
return fmt.Errorf("storage value exceeds %d bytes", maxViewStorageValueBytes)
|
||||
}
|
||||
m.viewStorageMu.Lock()
|
||||
defer m.viewStorageMu.Unlock()
|
||||
st, err := m.loadViewStorage(pluginID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, exists := st.Values[key]; !exists && len(st.Values) >= maxViewStorageKeys {
|
||||
return fmt.Errorf("plugin view storage exceeds %d keys", maxViewStorageKeys)
|
||||
}
|
||||
st.Values[key] = append(json.RawMessage(nil), raw...)
|
||||
return m.saveViewStorage(pluginID, st)
|
||||
}
|
||||
|
||||
// ViewStorageList returns sorted keys from a plugin's private view store.
|
||||
func (m *Manager) ViewStorageList(pluginID string) ([]string, error) {
|
||||
m.viewStorageMu.Lock()
|
||||
defer m.viewStorageMu.Unlock()
|
||||
st, err := m.loadViewStorage(pluginID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys := make([]string, 0, len(st.Values))
|
||||
for key := range st.Values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// ViewStorageDelete removes one key and reports whether it existed.
|
||||
func (m *Manager) ViewStorageDelete(pluginID, key string) (bool, error) {
|
||||
if err := validateViewStorageKey(key); err != nil {
|
||||
return false, err
|
||||
}
|
||||
m.viewStorageMu.Lock()
|
||||
defer m.viewStorageMu.Unlock()
|
||||
st, err := m.loadViewStorage(pluginID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, ok := st.Values[key]; !ok {
|
||||
return false, nil
|
||||
}
|
||||
delete(st.Values, key)
|
||||
if err := m.saveViewStorage(pluginID, st); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestViewStorageLifecycleAndPersistence(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mgr, err := NewManager(ManagerOptions{DataRoot: root, HostVersion: "0.2.12"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Close)
|
||||
|
||||
if _, found, err := mgr.ViewStorageGet("vendor.panel", "missing"); err != nil || found {
|
||||
t.Fatalf("missing value: found=%v err=%v", found, err)
|
||||
}
|
||||
want := map[string]any{"enabled": true, "count": float64(3)}
|
||||
if err := mgr.ViewStorageSet("vendor.panel", "draft", want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mgr.ViewStorageSet("vendor.panel", "alpha", "first"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, found, err := mgr.ViewStorageGet("vendor.panel", "draft")
|
||||
if err != nil || !found {
|
||||
t.Fatalf("get draft: found=%v err=%v", found, err)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(raw, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("stored value = %#v, want %#v", got, want)
|
||||
}
|
||||
keys, err := mgr.ViewStorageList("vendor.panel")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(keys, []string{"alpha", "draft"}) {
|
||||
t.Fatalf("keys = %v", keys)
|
||||
}
|
||||
|
||||
restarted, err := NewManager(ManagerOptions{DataRoot: root, HostVersion: "0.2.12"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer restarted.Close()
|
||||
if _, found, err := restarted.ViewStorageGet("vendor.panel", "draft"); err != nil || !found {
|
||||
t.Fatalf("value did not survive restart: found=%v err=%v", found, err)
|
||||
}
|
||||
deleted, err := restarted.ViewStorageDelete("vendor.panel", "draft")
|
||||
if err != nil || !deleted {
|
||||
t.Fatalf("delete draft: deleted=%v err=%v", deleted, err)
|
||||
}
|
||||
deleted, err = restarted.ViewStorageDelete("vendor.panel", "draft")
|
||||
if err != nil || deleted {
|
||||
t.Fatalf("delete missing draft: deleted=%v err=%v", deleted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewStorageRejectsInvalidInputAndPreservesCorruptState(t *testing.T) {
|
||||
mgr, err := NewManager(ManagerOptions{DataRoot: t.TempDir(), HostVersion: "0.2.12"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Close)
|
||||
for _, key := range []string{"", " leading", "trailing ", "bad\nkey", strings.Repeat("k", maxViewStorageKeyBytes+1)} {
|
||||
if err := mgr.ViewStorageSet("vendor.panel", key, true); err == nil {
|
||||
t.Errorf("key %q was accepted", key)
|
||||
}
|
||||
}
|
||||
if err := mgr.ViewStorageSet("vendor.panel", "large", strings.Repeat("x", maxViewStorageValueBytes+1)); err == nil {
|
||||
t.Fatal("oversized value was accepted")
|
||||
}
|
||||
|
||||
dir := mgr.layout.DataDir("vendor.panel")
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, viewStorageFileName)
|
||||
corrupt := []byte("{not-json\n")
|
||||
if err := os.WriteFile(path, corrupt, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := mgr.ViewStorageGet("vendor.panel", "draft"); err == nil {
|
||||
t.Fatal("corrupt storage was not reported")
|
||||
}
|
||||
got, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, corrupt) {
|
||||
t.Fatal("corrupt storage was modified")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestViewRegistrationEnforcesIDsAndQuotas(t *testing.T) {
|
||||
reg := NewRegistry(nil)
|
||||
scope := newScope("vendor.views", reg)
|
||||
reg.RegisterView(scope, ViewContribution{ID: "first", Location: "settings"})
|
||||
reg.RegisterView(scope, ViewContribution{ID: "first", Location: "dialog"})
|
||||
reg.RegisterView(scope, ViewContribution{ID: "second", Location: "settings"})
|
||||
if views := reg.Views(""); len(views) != 1 || views[0].ID != "first" || views[0].Location != "settings" {
|
||||
t.Fatalf("views = %+v", views)
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewsRegisterSortFindAndDispose(t *testing.T) {
|
||||
reg := NewRegistry(nil)
|
||||
manifest := Manifest{
|
||||
Schema: 1, ID: "vendor.views", Version: "1.0.0", Name: LocalizedText{EnUS: "Views"},
|
||||
Permissions: []string{"ui:slot"},
|
||||
Contributes: Contributes{Views: []ViewContribution{
|
||||
{ID: "z", Title: LocalizedText{EnUS: "Z"}, Location: "sidebar", Entry: "z.html", Order: 2},
|
||||
{ID: "a", Title: LocalizedText{EnUS: "A"}, Location: "sidebar", Entry: "a.html", Order: 1},
|
||||
{ID: "tab", Title: LocalizedText{EnUS: "Tab"}, Location: "vm.tab", Entry: "tab.html"},
|
||||
}},
|
||||
}
|
||||
if err := reg.Register(PluginDef{Manifest: manifest, Source: SourceBuiltin, Desired: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
views := reg.Views("sidebar")
|
||||
if len(views) != 2 || views[0].ID != "a" || views[1].ID != "z" {
|
||||
t.Fatalf("sidebar views = %+v", views)
|
||||
}
|
||||
if view, ok := reg.View("vendor.views", "tab"); !ok || view.Location != "vm.tab" {
|
||||
t.Fatalf("find tab: %+v, %v", view, ok)
|
||||
}
|
||||
if err := reg.SetDesired(context.Background(), "vendor.views", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := reg.Views(""); len(got) != 0 {
|
||||
t.Fatalf("views were not disposed: %+v", got)
|
||||
}
|
||||
if err := reg.SetDesired(context.Background(), "vendor.views", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := reg.Views(""); len(got) != 3 {
|
||||
t.Fatalf("views were not restored: %+v", got)
|
||||
}
|
||||
ids := []string{reg.Views("")[0].ID, reg.Views("")[1].ID, reg.Views("")[2].ID}
|
||||
if !reflect.DeepEqual(ids, []string{"tab", "a", "z"}) {
|
||||
t.Fatalf("view order = %v", ids)
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,10 @@
|
||||
"refresh": "Refresh",
|
||||
"copy": "Copy",
|
||||
"clear": "Clear",
|
||||
"confirm": "Confirm",
|
||||
"open": "Open",
|
||||
"formRequiredFields": "Fill in the required fields: {fields}",
|
||||
"overview": "Overview",
|
||||
"cancel": "Cancel",
|
||||
"close": "Close",
|
||||
"save": "Save",
|
||||
|
||||
@@ -105,6 +105,10 @@
|
||||
"refresh": "刷新",
|
||||
"copy": "复制",
|
||||
"clear": "清空",
|
||||
"confirm": "确认",
|
||||
"open": "打开",
|
||||
"formRequiredFields": "请填写必填项:{fields}",
|
||||
"overview": "概述",
|
||||
"cancel": "取消",
|
||||
"close": "关闭",
|
||||
"save": "保存",
|
||||
|
||||
Reference in new issue
Block a user