From fa3e1e28896457a826a559535b5413d8791e29f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Wed, 2 Dec 2026 23:11:13 -0700 Subject: [PATCH] feat: add plugin views and expand the sandboxed page bridge Plugins can add pages to the sidebar, VM tabs, Settings and dialogs. Their pages can now use host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, events and private storage. Plugin pages cannot change allow_ai_access, which stays the user's per-VM consent. Closing a page cancels its unfinished tasks, and running plugin tasks no longer block changing the data folder. Co-Authored-By: Claude Opus 5.5 --- changes/plugin-view-capabilities.json | 7 + docs/plugin-architecture.md | 10 +- frontend/bridge-contract.json | 67 ++-- frontend/scripts/test-plugins.mjs | 198 ++++++++++++ frontend/src/App.tsx | 156 ++++++++- frontend/src/components/AppSettingsPage.tsx | 25 +- frontend/src/components/PluginPanelFrame.tsx | 272 +++++++++++++--- frontend/src/components/PluginViewHost.tsx | 72 +++++ frontend/src/components/PluginsPage.tsx | 8 +- frontend/src/components/Sidebar.tsx | 20 +- frontend/src/i18n/domains/core.gen.ts | 8 + frontend/src/i18n/keys.gen.ts | 4 + frontend/src/lib/bridgeContract.ts | 19 +- frontend/src/lib/pluginAssets.ts | 16 + frontend/src/lib/pluginViewActions.ts | 137 ++++++++ frontend/src/lib/pluginViewEvents.ts | 13 + frontend/src/lib/pluginViewRouter.ts | 72 +++++ frontend/src/styles/app.css | 6 + frontend/src/styles/ui-contract.ts | 6 +- frontend/src/types.ts | 1 + frontend/src/ui/dialog.tsx | 10 +- frontend/ui-contract.json | 14 +- frontend/wailsjs/go/models.ts | 48 +++ internal/app/app.go | 11 +- internal/app/computer_use_host.go | 6 +- internal/app/plugin_bridge_data_test.go | 322 +++++++++++++++++++ internal/app/plugin_bridge_events.go | 62 ++++ internal/app/plugin_bridge_files.go | 222 +++++++++++++ internal/app/plugin_bridge_net.go | 165 ++++++++++ internal/app/plugin_bridge_settings.go | 138 ++++++++ internal/app/plugin_bridge_tasks.go | 195 +++++++++++ internal/app/plugin_bridge_ui.go | 162 ++++++++++ internal/app/plugin_bridge_vm.go | 38 +++ internal/app/plugins_flow.go | 166 +++++++++- internal/app/plugins_flow_test.go | 135 ++++++++ internal/app/tasks.go | 20 +- internal/i18n/catalog_gen.go | 9 + internal/plugin/contract.go | 77 ++--- internal/plugin/contract_test.go | 23 +- internal/plugin/manager.go | 50 +++ internal/plugin/registry.go | 62 ++++ internal/plugin/view_storage.go | 172 ++++++++++ internal/plugin/view_storage_test.go | 101 ++++++ internal/plugin/views_test.go | 47 +++ locales/en-US/core.json | 4 + locales/zh-CN/core.json | 4 + 46 files changed, 3197 insertions(+), 183 deletions(-) create mode 100644 changes/plugin-view-capabilities.json create mode 100644 frontend/src/components/PluginViewHost.tsx create mode 100644 frontend/src/lib/pluginAssets.ts create mode 100644 frontend/src/lib/pluginViewActions.ts create mode 100644 frontend/src/lib/pluginViewEvents.ts create mode 100644 frontend/src/lib/pluginViewRouter.ts create mode 100644 internal/app/plugin_bridge_data_test.go create mode 100644 internal/app/plugin_bridge_events.go create mode 100644 internal/app/plugin_bridge_files.go create mode 100644 internal/app/plugin_bridge_net.go create mode 100644 internal/app/plugin_bridge_settings.go create mode 100644 internal/app/plugin_bridge_tasks.go create mode 100644 internal/app/plugin_bridge_ui.go create mode 100644 internal/app/plugin_bridge_vm.go create mode 100644 internal/app/plugins_flow_test.go create mode 100644 internal/plugin/view_storage.go create mode 100644 internal/plugin/view_storage_test.go create mode 100644 internal/plugin/views_test.go diff --git a/changes/plugin-view-capabilities.json b/changes/plugin-view-capabilities.json new file mode 100644 index 0000000..c403eaa --- /dev/null +++ b/changes/plugin-view-capabilities.json @@ -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." +} diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 5e72e54..9347a73 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -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==`,条件不满足时宿主隐藏入口和页面。`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 作用域;秘密值读取时保持掩码,写入时沿用现有加密保存。`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。`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` 中声明兼容范围: diff --git a/frontend/bridge-contract.json b/frontend/bridge-contract.json index 3614e76..a967b6e 100644 --- a/frontend/bridge-contract.json +++ b/frontend/bridge-contract.json @@ -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": [] } } diff --git a/frontend/scripts/test-plugins.mjs b/frontend/scripts/test-plugins.mjs index 4923c05..a50c89b 100644 --- a/frontend/scripts/test-plugins.mjs +++ b/frontend/scripts/test-plugins.mjs @@ -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,197 @@ 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']) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 868e486..f9ba677 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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 { 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 = { export const App: React.FC = () => { const [state, setState] = useState(null) - const [selected, setSelected] = useState(HOST_ID) + const [selected, setSelectedPage] = useState(HOST_ID) const [appUpdate, setAppUpdate] = useState(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(null) + const [pluginViewState, setPluginViewState] = useState(emptyPluginViewState) + const [pluginViewMeta, setPluginViewMeta] = useState>({}) + // 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(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,97 @@ 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) : selectedVM + 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 (!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 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 = { 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))) + setPluginViewMeta((current) => Object.fromEntries(Object.entries(current).filter(([key]) => valid.has(key)))) + }, [pluginUI?.views, state?.vms]) + 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) => ( + updateViewMetadata(view, metadata)} + onOpenView={openView} + onCloseView={closeView} + onNavigate={navigateHost} + /> + ) + const renderVMTabs = () => { + if (!selectedVM) return null + const tabs = pluginViews.filter((view) => view.location === 'vm.tab' && viewAvailable(view)) + if (tabs.length === 0) return null + return ( +
+ + {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 ( + + ) + })} +
+ ) + } + + 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 +421,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)).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: () => openView(view) } + }) + const sidebarPluginViews = pluginViews.filter((view) => view.location === 'sidebar' && viewAvailable(view)).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 +460,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 +581,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({ @@ -526,7 +639,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 +1259,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) openView(item.view) + } else { + setSelected(id) + } if (sidebarOpen && window.matchMedia('(max-width: 768px)').matches) { toggleSidebar() } @@ -1161,6 +1281,7 @@ export const App: React.FC = () => { downloading={Object.values(taskMap).some(isActiveInstallerTask)} safeMode={state?.safe_mode} updateDot={!!appUpdate?.has_update} + pluginViews={sidebarPluginViews} updateCard={showUpdateCard ? ( {
{loadError ?
{loadError}
: …}
+ ) : activePluginRoute && activePluginView ? ( + <> + {activePluginRoute.location === 'vm.tab' && renderVMTabs()} + {renderPluginView(activePluginRoute, activePluginView)} + ) : selected === INSTALLERS_ID ? ( { onError={fail} onThemeChanged={() => setThemeRevision((r) => r + 1)} onLocaleSwitch={(l) => void setLang(l)} + onOpenView={openView} + onNavigate={navigateHost} /> ) : selectedVM ? ( - + {renderVMTabs()} + { onError={fail} dropping={dropping} pluginUI={pluginUI} - /> + /> + ) : selected === SETTINGS_ID ? ( { themeMode={effectiveThemeMode} canLight={canLight} canDark={canDark} + pluginViews={settingsPluginViews} onThemeMode={setThemeMode} onSetLocale={setLang} onRefresh={refresh} @@ -1491,6 +1623,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) + })} + {/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */} diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 30f2954..f97665b 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -53,6 +53,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 @@ -60,7 +62,7 @@ interface Props { } export const AppSettingsPage: React.FC = ({ - state, locale, locales, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError, + state, locale, locales, themeMode, canLight = true, canDark = true, pluginViews = [], onThemeMode, onSetLocale, onRefresh, onError, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const { host, config, optimizations } = state @@ -486,6 +488,27 @@ export const AppSettingsPage: React.FC = ({ + + {pluginViews.length > 0 && ( +
+
{tr('sidebarPlugins')}
+
+ {pluginViews.map((view) => ( +
+
+
+ {view.title} + {view.badge && {view.badge}} +
+
+
+ +
+
+ ))} +
+
+ )} ) } diff --git a/frontend/src/components/PluginPanelFrame.tsx b/frontend/src/components/PluginPanelFrame.tsx index 0937e5a..b645c52 100644 --- a/frontend/src/components/PluginPanelFrame.tsx +++ b/frontend/src/components/PluginPanelFrame.tsx @@ -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 = ({ - 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(null) + const wrapperRef = useRef(null) const localeRef = useRef(locale) localeRef.current = locale const [failed, setFailed] = useState(false) const [nonce, setNonce] = useState(0) + const [titleOverride, setTitleOverride] = useState(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(null) + const confirmResolverRef = useRef<((confirmed: boolean) => void) | null>(null) + const [formRequest, setFormRequest] = useState(null) + const [formError, setFormError] = useState('') + const formResolverRef = useRef<((result: PluginFormResult) => void) | null>(null) + const subscriptionsRef = useRef>(new Set()) + const intersectingRef = useRef(true) + const lastVisibilityRef = useRef(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((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((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 = ({ } }, [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 = ({ } 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 = ({ 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 = - rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams) - ? (rawParams as Record) - : {} + const params: Record = 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 = ({ 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 = ({