From d5a03606b76ff613ab5d96c88ee8ccd43ebf6475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 28 Oct 2026 23:08:31 -0700 Subject: [PATCH] feat: rebuild plugin UI with host rendering and standard settings (#4053) * feat: rebuild plugin pages with host rendering and native settings * fix(plugins): contain host-view errors, isolate editing, and migrate fixtures * fix(plugins): migrate remaining permission fixture hosts --- .gitignore | 3 + AGENTS.md | 5 + application/app/AppHandlers.ts | 3 +- application/app/AppSideEffects.tsx | 3 + application/i18n/locales/en/core.ts | 1 + application/i18n/locales/es/core.ts | 1 + application/i18n/locales/ru/core.ts | 1 + application/i18n/locales/zh-CN/core.ts | 1 + application/i18n/locales/zh-TW/core.ts | 1 + .../pluginHostSecurityVisibility.test.ts | 36 - .../state/pluginHostSecurityVisibility.ts | 21 - application/state/pluginKeybindings.ts | 5 + application/state/pluginRemoteTree.test.tsx | 67 + application/state/pluginRemoteTree.ts | 41 + application/state/pluginViewLifecycle.test.ts | 135 +- application/state/pluginViewLifecycle.ts | 246 -- application/state/pluginViewSession.test.ts | 41 + application/state/pluginViewSession.ts | 78 + .../terminalSidePanelPluginTabs.test.tsx | 44 + application/state/terminalSidePanelTabs.ts | 44 +- application/state/useEmbeddedPluginView.ts | 119 - application/state/useHostDrawnPluginView.ts | 42 + application/state/usePluginContributions.ts | 42 - application/state/usePluginManager.ts | 10 +- application/state/usePluginSettingsModel.ts | 22 + application/state/usePluginViewLifecycle.ts | 218 +- application/state/useToolbarItemLayout.ts | 3 + components/PluginAIContextHost.test.tsx | 14 +- components/PluginGlobalAgentHost.test.tsx | 16 +- components/PluginPermissionHost.test.tsx | 22 +- ...ectedContextPermission.entrypoint.test.tsx | 4 +- components/PluginTerminalSidebar.test.tsx | 56 +- components/PluginVaultPages.test.tsx | 51 +- components/plugins/PluginContributionHost.tsx | 22 +- components/plugins/PluginHostDrawnPage.tsx | 15 + .../plugins/PluginRemoteSurface.test.tsx | 130 + components/plugins/PluginRemoteSurface.tsx | 120 + components/plugins/PluginSettingsEntry.tsx | 85 + components/plugins/PluginSettingsForm.tsx | 275 ++ components/plugins/PluginTerminalSidebar.tsx | 41 +- components/plugins/PluginVaultPages.tsx | 24 +- components/plugins/PluginViewPopover.tsx | 41 + components/settings/tabs/PluginInfo.tsx | 12 +- .../tabs/PluginInstalledGrid.test.tsx | 18 +- ...luginManagementDialog.interaction.test.tsx | 14 - .../settings/tabs/PluginManagementDialog.tsx | 25 +- .../tabs/PluginPackageManager.test.tsx | 3 +- .../settings/tabs/PluginPackageManager.tsx | 47 +- .../settings/tabs/PluginPermissionPanel.tsx | 8 +- .../PluginSettingsGearNavigation.test.tsx | 134 +- .../tabs/PluginSettingsLanding.test.tsx | 2 +- .../settings/tabs/PluginSettingsLanding.tsx | 15 +- .../tabs/PluginSettingsVisibility.test.tsx | 21 +- .../tabs/PluginUninstall.interaction.test.tsx | 86 + .../SettingsPluginsTab.interaction.test.tsx | 9 +- .../settings/tabs/SettingsPluginsTab.test.tsx | 2 +- .../settings/tabs/SettingsPluginsTab.tsx | 401 +- components/terminal/TerminalToolbar.tsx | 2 +- .../TerminalLayerSidePanelSection.tsx | 32 +- docs/plugin-platform/embedded-ui-research.md | 64 + docs/plugin-platform/host-rendered-ui.md | 163 + .../native-react-ui-research.md | 199 + docs/plugin-platform/plugin-settings.md | 76 + docs/plugin-platform/plugin-ui-prior-art.md | 42 + docs/plugin-platform/terminal-sidebar.md | 64 +- docs/plugin-platform/ui-contributions.md | 67 +- docs/plugin-platform/vault-pages.md | 90 +- domain/pluginRemoteTreePolicy.cjs | 81 + domain/pluginRemoteTreePolicy.test.cjs | 46 + domain/pluginViewStylePolicy.cjs | 57 + domain/pluginViewStylePolicy.test.cjs | 26 + electron-builder.config.cjs | 2 + electron/main/registerBridges.cjs | 2 +- .../plugins/ai/aiContextEntrypoint.test.cjs | 9 +- electron/plugins/byteStreamService.test.cjs | 8 +- electron/plugins/catalog.json | 3 +- electron/plugins/contributionService.cjs | 1 + electron/plugins/contributionService.test.cjs | 16 + .../plugins/electronRuntime.live.test.cjs | 21 + .../embeddedFrameSecurity.live.test.cjs | 53 + .../plugins/fixtures/hostReactPreload.cjs | 16 + .../fixtures/static-distribution/catalog.json | 3 +- .../static-distribution/delivery.json | 4 +- .../fixtures/static-distribution/index.json | 3 +- .../static-distribution/snapshot.json | 20 +- .../generated/plugin-contract.schema.json | 269 +- electron/plugins/helloWorldV2.live.test.cjs | 53 + electron/plugins/hostDrawnStyle.live.test.cjs | 24 + electron/plugins/hostDrawnViewHost.cjs | 149 + electron/plugins/hostDrawnViewHost.test.cjs | 78 + electron/plugins/hostReact.live.test.cjs | 49 + electron/plugins/hostReactUi.live.test.cjs | 145 + electron/plugins/hostService.cjs | 20 +- electron/plugins/hostService.test.cjs | 13 + electron/plugins/packaging.test.cjs | 7 +- .../permissionWindowEntrypoint.test.cjs | 21 +- electron/plugins/pluginBridge.cjs | 59 +- electron/plugins/pluginBridge.test.cjs | 37 +- electron/plugins/pluginProtocol.cjs | 37 +- electron/plugins/pluginProtocol.test.cjs | 46 - electron/plugins/pluginViewHost.cjs | 374 -- electron/plugins/pluginViewHost.test.cjs | 476 -- electron/plugins/runtime/viewPreload.cjs | 65 - electron/plugins/settingsViewFixture.test.cjs | 8 +- electron/plugins/starterExample.test.cjs | 80 +- electron/plugins/staticDistribution.test.cjs | 6 +- electron/plugins/viewPreload.test.cjs | 65 - electron/plugins/viewResourceService.cjs | 24 + electron/plugins/viewResourceService.test.cjs | 23 + electron/plugins/viewThemeExamples.test.cjs | 71 +- electron/preload.cjs | 4 +- electron/preload/api.cjs | 28 +- electron/preload/api.pluginAIHost.test.cjs | 2 +- electron/preloadDataBacklog.test.cjs | 12 +- examples/plugins/assistant/README.md | 10 +- examples/plugins/assistant/build.mjs | 13 +- examples/plugins/assistant/host.js | 16 + .../plugins/assistant/netcatty.plugin.json | 69 +- examples/plugins/assistant/panel.js | 46 +- .../plugins/assistant/{panel.css => view.css} | 9 +- .../assistant/{panel.html => view.html} | 16 +- examples/plugins/database-minimal/build.mjs | 3 + examples/plugins/database-minimal/host.js | 16 + .../database-minimal/netcatty.plugin.json | 58 +- examples/plugins/database-minimal/panel.css | 1 - examples/plugins/database-minimal/panel.js | 31 +- .../plugins/database-minimal/panel.test.cjs | 25 +- examples/plugins/database-minimal/prepare.mjs | 9 +- examples/plugins/database-minimal/view.css | 2 + .../{panel.html => view.html} | 6 +- .../plugins/database-rfam-readonly/build.mjs | 3 + .../plugins/database-rfam-readonly/host.js | 16 + .../netcatty.plugin.json | 58 +- .../plugins/database-rfam-readonly/panel.css | 1 - .../plugins/database-rfam-readonly/panel.js | 25 +- .../database-rfam-readonly/prepare.mjs | 6 +- .../plugins/database-rfam-readonly/view.css | 2 + .../{panel.html => view.html} | 6 +- examples/plugins/global-agent/README.md | 8 + examples/plugins/global-agent/build.mjs | 10 +- examples/plugins/global-agent/host.js | 16 + .../plugins/global-agent/netcatty.plugin.json | 83 +- examples/plugins/global-agent/package.json | 10 +- examples/plugins/global-agent/panel.js | 26 +- examples/plugins/global-agent/panel.test.cjs | 21 +- .../global-agent/{panel.css => view.css} | 11 +- .../global-agent/{panel.html => view.html} | 5 +- examples/plugins/hello-react-host/LICENSE | 21 + examples/plugins/hello-react-host/README.md | 22 + examples/plugins/hello-react-host/build.mjs | 5 + examples/plugins/hello-react-host/mark.svg | 1 + .../hello-react-host/netcatty.plugin.json | 173 + .../plugins/hello-react-host/package.json | 8 + .../plugins/hello-react-host/src/index.tsx | 67 + examples/plugins/hello-vault/README.md | 11 + examples/plugins/hello-vault/build.mjs | 3 + examples/plugins/hello-vault/host.js | 16 + .../plugins/hello-vault/netcatty.plugin.json | 47 +- examples/plugins/hello-vault/page.html | 5 - examples/plugins/hello-vault/view.css | 19 + examples/plugins/hello-vault/view.html | 1 + examples/plugins/hello-vault/view.js | 1 + examples/plugins/hello-world-v2/LICENSE | 21 + examples/plugins/hello-world-v2/README.md | 24 + examples/plugins/hello-world-v2/build.mjs | 3 + examples/plugins/hello-world-v2/host.js | 16 + examples/plugins/hello-world-v2/index.js | 1 + .../hello-world-v2/netcatty.plugin.json | 91 + examples/plugins/hello-world-v2/page.js | 24 + examples/plugins/hello-world-v2/view.css | 27 + examples/plugins/hello-world-v2/view.html | 1 + examples/plugins/session-scratchpad/README.md | 11 +- examples/plugins/session-scratchpad/build.mjs | 3 + examples/plugins/session-scratchpad/host.js | 16 + .../session-scratchpad/netcatty.plugin.json | 3 +- examples/plugins/session-scratchpad/page.html | 7 - examples/plugins/session-scratchpad/page.js | 23 +- examples/plugins/session-scratchpad/theme.js | 24 - .../panel.css => session-scratchpad/view.css} | 9 +- examples/plugins/session-scratchpad/view.html | 4 + .../plugins/settings-view-fixture/README.md | 27 +- .../plugins/settings-view-fixture/build.mjs | 3 + .../plugins/settings-view-fixture/host.js | 16 + .../netcatty.plugin.json | 53 +- .../plugins/settings-view-fixture/view.css | 1 + .../plugins/settings-view-fixture/view.html | 4 +- .../plugins/settings-view-fixture/view.js | 1 + examples/plugins/starter-netcatty/README.md | 11 +- examples/plugins/starter-netcatty/build.mjs | 3 + examples/plugins/starter-netcatty/host.js | 16 + .../starter-netcatty/netcatty.plugin.json | 5 +- .../plugins/starter-netcatty/package.json | 2 +- examples/plugins/starter-netcatty/panel.html | 3 - examples/plugins/starter-netcatty/panel.js | 25 +- examples/plugins/starter-netcatty/theme.js | 24 - .../page.css => starter-netcatty/view.css} | 9 +- examples/plugins/starter-netcatty/view.html | 1 + examples/plugins/vault-scratchpad/README.md | 11 +- examples/plugins/vault-scratchpad/build.mjs | 3 + examples/plugins/vault-scratchpad/host.js | 16 + .../vault-scratchpad/netcatty.plugin.json | 48 +- examples/plugins/vault-scratchpad/page.html | 7 - examples/plugins/vault-scratchpad/page.js | 23 +- examples/plugins/vault-scratchpad/theme.js | 24 - .../page.css => vault-scratchpad/view.css} | 9 +- examples/plugins/vault-scratchpad/view.html | 4 + global.d.ts | 24 +- .../ai/plugin/modelInvocationAdapter.test.ts | 11 +- package-lock.json | 91 +- package.json | 9 +- packages/plugin-cli/src/archive.ts | 2 - packages/plugin-cli/src/manifest.ts | 1 - .../schema/plugin-contract.schema.json | 3827 ++++++++++++++--- packages/plugin-contract/src/contract.test.ts | 23 +- .../src/generated/plugin-contract.ts | 58 +- packages/plugin-sdk/package.json | 25 +- packages/plugin-sdk/src/hostDom.ts | 109 + packages/plugin-sdk/src/hostReact.test.tsx | 59 + packages/plugin-sdk/src/hostReact.ts | 22 + packages/plugin-sdk/view/netcatty.css | 15 + scripts/build-plugin-view-example.mjs | 16 + scripts/build-plugin-view-examples.mjs | 5 + scripts/fixtures/host-plugin-react.html | 1 + scripts/fixtures/host-plugin-react.tsx | 43 + scripts/plugin-assistant-panel.test.cjs | 62 +- .../plugin-global-agent-layout.live.test.cjs | 8 +- vite.config.ts | 4 +- 227 files changed, 8298 insertions(+), 4172 deletions(-) delete mode 100644 application/state/pluginHostSecurityVisibility.test.ts delete mode 100644 application/state/pluginHostSecurityVisibility.ts create mode 100644 application/state/pluginRemoteTree.test.tsx create mode 100644 application/state/pluginRemoteTree.ts create mode 100644 application/state/pluginViewSession.test.ts create mode 100644 application/state/pluginViewSession.ts create mode 100644 application/state/terminalSidePanelPluginTabs.test.tsx delete mode 100644 application/state/useEmbeddedPluginView.ts create mode 100644 application/state/useHostDrawnPluginView.ts create mode 100644 application/state/usePluginSettingsModel.ts create mode 100644 components/plugins/PluginHostDrawnPage.tsx create mode 100644 components/plugins/PluginRemoteSurface.test.tsx create mode 100644 components/plugins/PluginRemoteSurface.tsx create mode 100644 components/plugins/PluginSettingsEntry.tsx create mode 100644 components/plugins/PluginSettingsForm.tsx create mode 100644 components/plugins/PluginViewPopover.tsx create mode 100644 components/settings/tabs/PluginUninstall.interaction.test.tsx create mode 100644 docs/plugin-platform/embedded-ui-research.md create mode 100644 docs/plugin-platform/host-rendered-ui.md create mode 100644 docs/plugin-platform/native-react-ui-research.md create mode 100644 docs/plugin-platform/plugin-settings.md create mode 100644 docs/plugin-platform/plugin-ui-prior-art.md create mode 100644 domain/pluginRemoteTreePolicy.cjs create mode 100644 domain/pluginRemoteTreePolicy.test.cjs create mode 100644 domain/pluginViewStylePolicy.cjs create mode 100644 domain/pluginViewStylePolicy.test.cjs create mode 100644 electron/plugins/embeddedFrameSecurity.live.test.cjs create mode 100644 electron/plugins/fixtures/hostReactPreload.cjs create mode 100644 electron/plugins/helloWorldV2.live.test.cjs create mode 100644 electron/plugins/hostDrawnStyle.live.test.cjs create mode 100644 electron/plugins/hostDrawnViewHost.cjs create mode 100644 electron/plugins/hostDrawnViewHost.test.cjs create mode 100644 electron/plugins/hostReact.live.test.cjs create mode 100644 electron/plugins/hostReactUi.live.test.cjs delete mode 100644 electron/plugins/pluginViewHost.cjs delete mode 100644 electron/plugins/pluginViewHost.test.cjs delete mode 100644 electron/plugins/runtime/viewPreload.cjs delete mode 100644 electron/plugins/viewPreload.test.cjs create mode 100644 electron/plugins/viewResourceService.cjs create mode 100644 electron/plugins/viewResourceService.test.cjs create mode 100644 examples/plugins/assistant/host.js rename examples/plugins/assistant/{panel.css => view.css} (70%) rename examples/plugins/assistant/{panel.html => view.html} (72%) create mode 100644 examples/plugins/database-minimal/build.mjs create mode 100644 examples/plugins/database-minimal/host.js delete mode 100644 examples/plugins/database-minimal/panel.css create mode 100644 examples/plugins/database-minimal/view.css rename examples/plugins/database-minimal/{panel.html => view.html} (67%) create mode 100644 examples/plugins/database-rfam-readonly/build.mjs create mode 100644 examples/plugins/database-rfam-readonly/host.js delete mode 100644 examples/plugins/database-rfam-readonly/panel.css create mode 100644 examples/plugins/database-rfam-readonly/view.css rename examples/plugins/database-rfam-readonly/{panel.html => view.html} (64%) create mode 100644 examples/plugins/global-agent/host.js rename examples/plugins/global-agent/{panel.css => view.css} (73%) rename examples/plugins/global-agent/{panel.html => view.html} (78%) create mode 100644 examples/plugins/hello-react-host/LICENSE create mode 100644 examples/plugins/hello-react-host/README.md create mode 100644 examples/plugins/hello-react-host/build.mjs create mode 100644 examples/plugins/hello-react-host/mark.svg create mode 100644 examples/plugins/hello-react-host/netcatty.plugin.json create mode 100644 examples/plugins/hello-react-host/package.json create mode 100644 examples/plugins/hello-react-host/src/index.tsx create mode 100644 examples/plugins/hello-vault/build.mjs create mode 100644 examples/plugins/hello-vault/host.js delete mode 100644 examples/plugins/hello-vault/page.html create mode 100644 examples/plugins/hello-vault/view.css create mode 100644 examples/plugins/hello-vault/view.html create mode 100644 examples/plugins/hello-vault/view.js create mode 100644 examples/plugins/hello-world-v2/LICENSE create mode 100644 examples/plugins/hello-world-v2/README.md create mode 100644 examples/plugins/hello-world-v2/build.mjs create mode 100644 examples/plugins/hello-world-v2/host.js create mode 100644 examples/plugins/hello-world-v2/index.js create mode 100644 examples/plugins/hello-world-v2/netcatty.plugin.json create mode 100644 examples/plugins/hello-world-v2/page.js create mode 100644 examples/plugins/hello-world-v2/view.css create mode 100644 examples/plugins/hello-world-v2/view.html create mode 100644 examples/plugins/session-scratchpad/build.mjs create mode 100644 examples/plugins/session-scratchpad/host.js delete mode 100644 examples/plugins/session-scratchpad/page.html delete mode 100644 examples/plugins/session-scratchpad/theme.js rename examples/plugins/{starter-netcatty/panel.css => session-scratchpad/view.css} (76%) create mode 100644 examples/plugins/session-scratchpad/view.html create mode 100644 examples/plugins/settings-view-fixture/build.mjs create mode 100644 examples/plugins/settings-view-fixture/host.js create mode 100644 examples/plugins/settings-view-fixture/view.css create mode 100644 examples/plugins/settings-view-fixture/view.js create mode 100644 examples/plugins/starter-netcatty/build.mjs create mode 100644 examples/plugins/starter-netcatty/host.js delete mode 100644 examples/plugins/starter-netcatty/panel.html delete mode 100644 examples/plugins/starter-netcatty/theme.js rename examples/plugins/{vault-scratchpad/page.css => starter-netcatty/view.css} (76%) create mode 100644 examples/plugins/starter-netcatty/view.html create mode 100644 examples/plugins/vault-scratchpad/build.mjs create mode 100644 examples/plugins/vault-scratchpad/host.js delete mode 100644 examples/plugins/vault-scratchpad/page.html delete mode 100644 examples/plugins/vault-scratchpad/theme.js rename examples/plugins/{session-scratchpad/page.css => vault-scratchpad/view.css} (76%) create mode 100644 examples/plugins/vault-scratchpad/view.html create mode 100644 packages/plugin-sdk/src/hostDom.ts create mode 100644 packages/plugin-sdk/src/hostReact.test.tsx create mode 100644 packages/plugin-sdk/src/hostReact.ts create mode 100644 packages/plugin-sdk/view/netcatty.css create mode 100644 scripts/build-plugin-view-example.mjs create mode 100644 scripts/build-plugin-view-examples.mjs create mode 100644 scripts/fixtures/host-plugin-react.html create mode 100644 scripts/fixtures/host-plugin-react.tsx diff --git a/.gitignore b/.gitignore index caab67641..56bb92cf4 100755 --- a/.gitignore +++ b/.gitignore @@ -170,3 +170,6 @@ build_with_vs2022.bat /resources/et/*/et.exe /resources/et/*/et-*-dlls/ /resources/et/*/*.dll + +# Local plugin example staging and bundles +/examples/plugins/*/.package/ diff --git a/AGENTS.md b/AGENTS.md index 25a44d4fb..9e796cb6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,6 +127,11 @@ second private RPC shape when extending the host. - `PluginRpcRouter` owns correlation, cancellation, deadlines, stream credit and protocol-failure containment. Runtime identity is assigned by the host and is never accepted from request parameters. +- Custom views use only host-rendered DOM: plugin scripts stay in the isolated + runtime; the host validates incoming trees, styles, resources and events before + rendering. Never reintroduce native child views, iframe UI, or plugin code in + the host renderer. See `docs/plugin-platform/host-rendered-ui.md` for authoring, + lifecycle, limits and verification. - App quit goes through `runPluginShutdown()` after the dirty-editor guard; do not add another independent quit interception path. diff --git a/application/app/AppHandlers.ts b/application/app/AppHandlers.ts index b8b42a1ab..ef42c55b4 100644 --- a/application/app/AppHandlers.ts +++ b/application/app/AppHandlers.ts @@ -16,6 +16,7 @@ import { isPortForwardingAutoReconnectEnabled } from '../../domain/portForwardin import { buildNumberShortcutTabTargets } from './tabShortcutTargets'; import { captureInheritedCwd } from '../state/inheritedCwd'; import { fromEditorTabId, isEditorTabId } from '../state/activeTabStore'; +import { isPluginViewEditingTarget } from '../state/pluginKeybindings'; import { resolveBatchTabCloseFocus } from '../state/pluginViewTabStore'; type AppContextGetter = () => Record; @@ -264,7 +265,7 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo } } - const isFormElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable; + const isFormElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable || isPluginViewEditingTarget(target); const isMonacoElement = target instanceof HTMLElement && !!target.closest?.('.monaco-editor, .monaco-diff-editor, .monaco-inputbox'); diff --git a/application/app/AppSideEffects.tsx b/application/app/AppSideEffects.tsx index 58b8df13f..95949060f 100755 --- a/application/app/AppSideEffects.tsx +++ b/application/app/AppSideEffects.tsx @@ -59,6 +59,7 @@ import { collectSessionIds } from '../../domain/workspace'; import { resolveAgentHostWorkspace } from '../../domain/agentHostWorkspace'; import { useHostOpenSessionReuse } from '../state/useHostOpenSessionReuse'; import type { PaneMagnificationController } from '../../domain/paneMagnification'; +import { isPluginViewEditingTarget } from '../state/pluginKeybindings'; import { resolveCloseIntent } from '../state/resolveCloseIntent'; import { resolveSnippetsShortcutIntent } from '../state/resolveSnippetsShortcutIntent'; import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from '../state/windowCommandClose'; @@ -1156,6 +1157,8 @@ export function AppSideEffects() { const topmostOpenDialog = openDialogs[openDialogs.length - 1] ?? null; const topmostDialogClose = topmostOpenDialog?.querySelector('[data-dialog-close="true"]'); + if (!topmostDialogClose && isPluginViewEditingTarget(document.activeElement)) return; + const intent = resolveWindowCommandCloseIntent({ activeTabId: activeTabStore.getActiveTabId(), editorTabIds: editorTabs.map((tab) => toEditorTabId(tab.id)), diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 506e653f2..83b05c443 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -1401,6 +1401,7 @@ Highlight the focused split pane: "settings.plugins.sources.local": "Local import", "settings.plugins.sources.all": "All sources", "settings.plugins.title": "Plugins", + "settings.plugins.configuration": "Plugin settings", "settings.plugins.description": "Manage your plugins and explore the catalog.", 'settings.plugins.loading': 'Loading plugin settings…', 'settings.plugins.empty': 'No enabled plugin contributes settings.', diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts index dcad0a70b..44ed396b6 100644 --- a/application/i18n/locales/es/core.ts +++ b/application/i18n/locales/es/core.ts @@ -1401,6 +1401,7 @@ Resalta el panel dividido enfocado: "settings.plugins.sources.local": "Local import", "settings.plugins.sources.all": "All sources", "settings.plugins.title": "Plugins", + "settings.plugins.configuration": "Ajustes del plugin", "settings.plugins.description": "Gestiona tus plugins y explora el catálogo.", 'settings.plugins.loading': 'Cargando ajustes del plugin…', 'settings.plugins.empty': 'Ningún plugin activado aporta ajustes.', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 4a264b1bc..0a12cc3fa 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -1266,6 +1266,7 @@ export const ruCoreMessages: Messages = { "settings.plugins.sources.local": "Local import", "settings.plugins.sources.all": "All sources", "settings.plugins.title": "Плагины", + "settings.plugins.configuration": "Настройки плагина", "settings.plugins.description": "Управляйте плагинами и просматривайте каталог.", 'settings.plugins.loading': 'Загрузка настроек плагинов…', 'settings.plugins.empty': 'Включённые плагины не предоставляют настройки.', diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index a115f841f..b9f6d5128 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -1316,6 +1316,7 @@ Vaults 标签保持扁平,不使用这块背景。 "settings.plugins.sources.local": "本地导入", "settings.plugins.sources.all": "全部来源", "settings.plugins.title": "插件", + "settings.plugins.configuration": "插件设置", "settings.plugins.description": "管理已安装插件,浏览精选目录。", 'settings.plugins.loading': '正在加载插件设置…', 'settings.plugins.empty': '当前没有已启用插件提供设置。', diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts index a26124795..acb6bbe16 100644 --- a/application/i18n/locales/zh-TW/core.ts +++ b/application/i18n/locales/zh-TW/core.ts @@ -1287,6 +1287,7 @@ Vaults 分頁維持扁平,不使用這塊背景。 "settings.plugins.sources.local": "本地导入", "settings.plugins.sources.all": "全部来源", "settings.plugins.title": "插件", + "settings.plugins.configuration": "插件設定", "settings.plugins.description": "管理已安裝插件,瀏覽精選目錄。", 'settings.plugins.loading': '正在載入外掛程式設定…', "settings.plugins.market.results": "{count} 個插件", diff --git a/application/state/pluginHostSecurityVisibility.test.ts b/application/state/pluginHostSecurityVisibility.test.ts deleted file mode 100644 index d85655f24..000000000 --- a/application/state/pluginHostSecurityVisibility.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { JSDOM } from 'jsdom'; -import { observePluginHostSecurityVisibility } from './pluginHostSecurityVisibility'; - -test('native modal yields to the host chooser, restores on dismissal, and never restores after cleanup', async () => { - const dom = new JSDOM('
'); - try { - const { document } = dom.window; - const calls: boolean[] = []; - const stop = observePluginHostSecurityVisibility(document.getElementById('mount')!, (visible) => calls.push(visible)); - const flush = () => new Promise((resolve) => dom.window.queueMicrotask(resolve)); - assert.deepEqual(calls, []); // Its own modal does not hide the plugin. - const chooser = document.createElement('div'); - chooser.dataset.hostSecuritySurface = ''; - document.body.append(chooser); - await flush(); assert.deepEqual(calls, [false]); - chooser.remove(); await flush(); assert.deepEqual(calls, [false, true]); - document.body.append(chooser); await flush(); - assert.deepEqual(calls, [false, true, false]); - stop(); chooser.remove(); await flush(); - assert.deepEqual(calls, [false, true, false]); - } finally { dom.window.close(); } -}); - -test('hidden security surfaces do not occlude a native view', async () => { - const dom = new JSDOM('
'); - try { - const calls: boolean[] = []; - const stop = observePluginHostSecurityVisibility(dom.window.document.getElementById('mount')!, (visible) => calls.push(visible)); - assert.deepEqual(calls, []); - dom.window.document.querySelector('[hidden]')!.removeAttribute('hidden'); - await new Promise((resolve) => dom.window.queueMicrotask(resolve)); - assert.deepEqual(calls, [false]); stop(); - } finally { dom.window.close(); } -}); diff --git a/application/state/pluginHostSecurityVisibility.ts b/application/state/pluginHostSecurityVisibility.ts deleted file mode 100644 index 1907c3bc3..000000000 --- a/application/state/pluginHostSecurityVisibility.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** Native plugin views must yield while a host-owned security dialog is open. */ -export function observePluginHostSecurityVisibility(mount: HTMLElement, publish: (visible: boolean) => void): () => void { - const document = mount.ownerDocument; - let visible = true; - const update = () => { - const blocked = [...document.querySelectorAll('[data-host-security-surface]')].some((surface) => { - const style = document.defaultView!.getComputedStyle(surface); - return style.display !== 'none' && style.visibility !== 'hidden' - && !surface.closest('[hidden], [inert], [aria-hidden="true"]'); - }); - if (visible === !blocked) return; - visible = !blocked; - publish(visible); - }; - const observer = new document.defaultView!.MutationObserver(update); - observer.observe(document.body, { childList: true, subtree: true, attributes: true, - attributeFilter: ['class', 'style', 'hidden', 'inert', 'aria-hidden', 'data-host-security-surface'] }); - update(); - // The view lifecycle owns close/retention. Cleanup must never reveal an old view. - return () => observer.disconnect(); -} diff --git a/application/state/pluginKeybindings.ts b/application/state/pluginKeybindings.ts index c472280d4..579d2dc56 100644 --- a/application/state/pluginKeybindings.ts +++ b/application/state/pluginKeybindings.ts @@ -33,6 +33,7 @@ const NAMED_KEYS = new Map([ ['tab', 'tab'], ]); const PLUGIN_SHORTCUT_EDITABLE_SELECTOR = [ + '[data-plugin-editing]', 'input', 'textarea', 'select', @@ -44,6 +45,10 @@ const PLUGIN_SHORTCUT_EDITABLE_SELECTOR = [ '.monaco-menu-container', ].join(', '); +export function isPluginViewEditingTarget(node: EventTarget | null): boolean { + return Boolean((node as Element | null)?.closest?.('[data-plugin-editing]')); +} + function hasEditableShortcutAncestor(node: unknown): boolean { const closest = (node as { closest?: (selector: string) => unknown } | null)?.closest; return typeof closest === 'function' diff --git a/application/state/pluginRemoteTree.test.tsx b/application/state/pluginRemoteTree.test.tsx new file mode 100644 index 000000000..0c150fa19 --- /dev/null +++ b/application/state/pluginRemoteTree.test.tsx @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { JSDOM } from 'jsdom'; + +test('React 19 changes are staged as safe data before any host rendering', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) { + saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] }); + } + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true }); + const { default: React, act, useState } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { RemoteMutationObserver } = await import('@remote-dom/core/elements'); + const { createPluginRemoteTree } = await import('./pluginRemoteTree'); + const staged = createPluginRemoteTree(); + const snapshots: ReturnType[] = []; + const observer = new RemoteMutationObserver({ + mutate(records) { snapshots.push(staged.apply(JSON.parse(JSON.stringify(records)))); }, + call() { throw new Error('Host method calls are unavailable'); }, + }); + const container = document.getElementById('remote')!; + observer.observe(container); + const root = createRoot(container); + function Example() { + const [count, setCount] = useState(0); + return

Hello

; + } + try { + await act(async () => { root.render(); await new Promise((resolve) => setTimeout(resolve, 10)); }); + const first = snapshots.at(-1)!; + const section = first.children[0]; assert.equal(section.type, 1); + if (section.type !== 1) throw new Error('Expected section'); + assert.equal(section.attributes.class, 'card'); + assert.match(section.attributes.style, /display:\s*grid/); + await act(async () => { container.querySelector('button')!.click(); await new Promise((resolve) => setTimeout(resolve, 10)); }); + const updated = JSON.stringify(snapshots.at(-1)); + assert.match(updated, /Count /); assert.match(updated, /"data":"1"/); + assert.equal(staged.isFailed(), false); + assert.throws(() => staged.apply([[3, section.id, 'onclick', 'attack()']])); + assert.deepEqual(staged.snapshot(), { children: [] }); + assert.equal(staged.isFailed(), true); + assert.throws(() => staged.apply([])); + } finally { + observer.disconnect(); await act(async () => { root.unmount(); }); + for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); } + Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); dom.window.close(); + } +}); + +test('removed attributes do not keep checkboxes, menus or old inline styles active', async () => { + const { createPluginRemoteTree } = await import('./pluginRemoteTree'); + const tree = createPluginRemoteTree(); + tree.apply([[0, '~', { id: 'control', type: 1, element: 'input', attributes: { type: 'checkbox', checked: '', style: 'color:red' }, children: [] }, 0]]); + const updated = tree.apply([[3, 'control', 'checked', null], [3, 'control', 'style', null]]); + assert.deepEqual(updated.children[0], { id: 'control', type: 1, element: 'input', attributes: { type: 'checkbox' }, children: [] }); +}); + +test('inserting a child into an existing void element fails the view', async () => { + const { createPluginRemoteTree } = await import('./pluginRemoteTree'); + const tree = createPluginRemoteTree(); + tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: {}, children: [] }, 0]]); + assert.throws(() => tree.apply([[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0]]), /Void view elements/); + assert.equal(tree.isFailed(), true); + assert.deepEqual(tree.snapshot(), { children: [] }); +}); diff --git a/application/state/pluginRemoteTree.ts b/application/state/pluginRemoteTree.ts new file mode 100644 index 000000000..ed7c878fd --- /dev/null +++ b/application/state/pluginRemoteTree.ts @@ -0,0 +1,41 @@ +import { RemoteReceiver } from '@remote-dom/core/receivers'; +import { validatePluginMutationBatch, validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs'; + +type WireNode = { id: string; type: 3 | 8; data: string } | { + id: string; type: 1; element: string; attributes: Record; children: WireNode[]; +}; +type WireTree = { children: WireNode[] }; + +/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */ +export function createPluginRemoteTree() { + const receiver = new RemoteReceiver(); + let current: WireTree = { children: [] }; + let failed = false; + const project = (node: unknown): WireNode => { + const value = node as { id: string; type: number; data?: string; element?: string; attributes?: Record; children?: unknown[] }; + if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' }; + return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) }; + }; + return { + apply(input: unknown): WireTree { + if (failed) throw new Error('Plugin view has been closed after an invalid update'); + try { + validatePluginMutationBatch(input); + // Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver + // defaults those to properties, so explicitly mark them as attributes. + const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record); + receiver.connection.mutate(batch as unknown as Parameters[0]); + const next = { children: receiver.root.children.map(project) }; + validatePluginRemoteTree(next); + current = next; + return next; + } catch (error) { + failed = true; + current = { children: [] }; + throw error; + } + }, + snapshot(): WireTree { return current; }, + isFailed(): boolean { return failed; }, + }; +} diff --git a/application/state/pluginViewLifecycle.test.ts b/application/state/pluginViewLifecycle.test.ts index beefeb6aa..f2cbf7f2b 100644 --- a/application/state/pluginViewLifecycle.test.ts +++ b/application/state/pluginViewLifecycle.test.ts @@ -1,111 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; - -import { - PluginViewLifecycleController, - consumeClosedPluginViewInstance, - reconcilePluginViewTabCatalog, - markPluginViewOpenTokensClosed, - reconcileClosedPluginView, - rememberClosedPluginViewInstance, - resolvePluginViewSnapshotSelection, - shouldReconcilePluginViewTabCatalog, - withdrawPluginViewTab, - type HostedPluginViewState, -} from './pluginViewLifecycle.ts'; -import { PluginViewTabStore } from './pluginViewTabStore.ts'; - -function view(id: string, tabId?: string): HostedPluginViewState { - return { - id, - viewId: `view.${id}`, - scopeId: 'window:main', - retainContextWhenHidden: false, - ...(tabId ? { tabId } : {}), - }; -} - -test('host close events clear the active renderer instance and identify its native tab', () => { - const current = view('active', 'plugin-view:publisher.plugin:view.active'); - const result = reconcileClosedPluginView({ - current, - retained: new Map([['retained', view('retained')]]), - instanceId: 'active', - }); - - assert.equal(result.current, null); - assert.equal(result.matchedCurrent, true); - assert.equal(result.closedTabId, current.tabId); - assert.equal(result.retained.size, 1); -}); - -test('host close events remove retained instances without dismissing another active view', () => { - const current = view('active'); - const retainedTab = view('retained-closed', 'plugin-view:publisher.plugin:view.retained'); - const result = reconcileClosedPluginView({ - current, - retained: new Map([ - ['closed', retainedTab], - ['kept', view('retained-kept')], - ]), - instanceId: 'retained-closed', - }); - - assert.equal(result.current, current); - assert.equal(result.matchedCurrent, false); - assert.equal(result.matchedRetained, true); - assert.deepEqual([...result.retained.keys()], ['kept']); - assert.equal(result.closedTabId, retainedTab.tabId); -}); - -test('explicit native-tab close destroys active and retained instances instead of retaining them', () => { - const tabId = 'plugin-view:publisher.plugin:view.shared'; - const result = withdrawPluginViewTab({ - current: view('active', tabId), - retained: new Map([ - ['same-tab', view('retained-same', tabId)], - ['other-tab', view('retained-other', 'plugin-view:publisher.plugin:view.other')], - ]), - tabId, - }); - - assert.equal(result.current, null); - assert.equal(result.matchedCurrent, true); - assert.equal(result.matchedRetained, true); - assert.deepEqual(result.instanceIds, ['active', 'retained-same']); - assert.deepEqual([...result.retained.keys()], ['other-tab']); -}); - -test('an early host close tombstone is consumed when the open response arrives later', () => { - const tombstones = new Set(); - rememberClosedPluginViewInstance(tombstones, 'instance-early'); - assert.equal(consumeClosedPluginViewInstance(tombstones, 'instance-early'), true); - assert.equal(consumeClosedPluginViewInstance(tombstones, 'instance-early'), false); - - for (let index = 0; index < 300; index += 1) { - rememberClosedPluginViewInstance(tombstones, `instance-${index}`); - } - assert.equal(tombstones.size, 256); - assert.equal(tombstones.has('instance-0'), false); -}); - -test('explicit close marks only in-flight opens owned by the closed surface', () => { - const first = Symbol('first'); - const second = Symbol('second'); - const explicitlyClosed = new Set(); - const opening = new Map>([ - ['window:main\0view.first', new Set([first])], - ['window:main\0view.second', new Set([second])], - ]); - - assert.equal(markPluginViewOpenTokensClosed( - opening, - explicitlyClosed, - 'window:main\0view.first', - ), 1); - assert.deepEqual([...explicitlyClosed], [first]); - assert.equal(markPluginViewOpenTokensClosed(opening, explicitlyClosed, null), 0); -}); +import { reconcilePluginViewTabCatalog, resolvePluginViewSnapshotSelection, shouldReconcilePluginViewTabCatalog } from './pluginViewLifecycle'; +import { PluginViewTabStore } from './pluginViewTabStore'; test('locale-only snapshot refresh keeps the owned view alive without weakening context fail-closed behavior', () => { const previous = { @@ -184,30 +80,3 @@ test('active-tab context refresh cannot withdraw the plugin tab that triggered i assert.equal(store.getTabs()[0]?.title, 'Localized View'); assert.equal(activeTabId, tab.id); }); - -test('lifecycle controller owns retained views, open tokens, tombstones, and teardown', () => { - const controller = new PluginViewLifecycleController(); - const tabId = 'plugin-view:publisher.plugin:view.shared'; - const active = view('active', tabId); - const retained = view('retained'); - controller.setCurrent(active); - controller.retain('window:main\0view.retained', retained); - - const token = controller.beginOpen({ - viewKey: 'window:main\0view.active', - tabId, - }); - const closed = controller.handleTabClose(tabId); - assert.deepEqual(closed.instanceIds, [active.id]); - assert.equal(controller.shouldCloseOpen(token), true); - controller.finishOpen({ token, viewKey: 'window:main\0view.active', tabId }); - assert.equal(controller.shouldCloseOpen(token), false); - - const early = controller.handleHostClose('instance-before-open-response'); - assert.equal(early.matchedCurrent, false); - assert.equal(early.matchedRetained, false); - assert.equal(controller.consumeHostClose('instance-before-open-response'), true); - - assert.deepEqual(controller.drain().map((candidate) => candidate.id), [retained.id]); - assert.equal(controller.getCurrent(), null); -}); diff --git a/application/state/pluginViewLifecycle.ts b/application/state/pluginViewLifecycle.ts index acc4d37c4..1cd81e3db 100644 --- a/application/state/pluginViewLifecycle.ts +++ b/application/state/pluginViewLifecycle.ts @@ -1,11 +1,3 @@ -export interface HostedPluginViewState { - id: string; - viewId: string; - scopeId: string; - retainContextWhenHidden: boolean; - tabId?: string; -} - export interface PluginViewSnapshotSelection { requestViewId: string; contextKey: string; @@ -81,241 +73,3 @@ export function reconcilePluginViewTabCatalog({ store.refreshMetadata(entries); return true; } - -export function reconcileClosedPluginView({ - current, - retained, - instanceId, -}: { - current: T | null; - retained: ReadonlyMap; - instanceId: string; -}): { - current: T | null; - retained: Map; - matchedCurrent: boolean; - matchedRetained: boolean; - closedTabId?: string; -} { - const matchedCurrent = current?.id === instanceId; - let matchedRetained = false; - let retainedTabId: string | undefined; - const nextRetained = new Map(); - for (const [key, view] of retained) { - if (view.id === instanceId) { - matchedRetained = true; - retainedTabId = view.tabId; - } - else nextRetained.set(key, view); - } - return { - current: matchedCurrent ? null : current, - retained: nextRetained, - matchedCurrent, - matchedRetained, - ...((matchedCurrent ? current?.tabId : retainedTabId) - ? { closedTabId: matchedCurrent ? current?.tabId : retainedTabId } - : {}), - }; -} - -export function withdrawPluginViewTab({ - current, - retained, - tabId, -}: { - current: T | null; - retained: ReadonlyMap; - tabId: string; -}): { - current: T | null; - retained: Map; - instanceIds: string[]; - matchedCurrent: boolean; - matchedRetained: boolean; -} { - const matchedCurrent = current?.tabId === tabId; - let matchedRetained = false; - const instanceIds: string[] = []; - if (matchedCurrent && current) instanceIds.push(current.id); - const nextRetained = new Map(); - for (const [key, view] of retained) { - if (view.tabId === tabId) { - matchedRetained = true; - instanceIds.push(view.id); - } else { - nextRetained.set(key, view); - } - } - return { - current: matchedCurrent ? null : current, - retained: nextRetained, - instanceIds, - matchedCurrent, - matchedRetained, - }; -} - -export function rememberClosedPluginViewInstance( - tombstones: Set, - instanceId: string, - limit = 256, -): void { - if (tombstones.size >= limit) { - const oldest = tombstones.values().next().value; - if (typeof oldest === 'string') tombstones.delete(oldest); - } - tombstones.add(instanceId); -} - -export function consumeClosedPluginViewInstance(tombstones: Set, instanceId: string): boolean { - return tombstones.delete(instanceId); -} - -export function markPluginViewOpenTokensClosed( - openingTokens: ReadonlyMap>, - explicitlyClosedTokens: Set, - ownerKey: string | null | undefined, -): number { - if (!ownerKey) return 0; - const tokens = openingTokens.get(ownerKey); - if (!tokens) return 0; - for (const token of tokens) explicitlyClosedTokens.add(token); - return tokens.size; -} - -export class PluginViewLifecycleController { - private current: T | null = null; - private retained = new Map(); - private readonly closedInstanceIds = new Set(); - private readonly openingTokensByTab = new Map>(); - private readonly openingTokensByView = new Map>(); - private readonly explicitlyClosedOpenTokens = new Set(); - - getCurrent(): T | null { - return this.current; - } - - setCurrent(view: T | null): void { - this.current = view; - } - - takeCurrent(): T | null { - const current = this.current; - this.current = null; - return current; - } - - retain(key: string, view: T): void { - this.retained.set(key, view); - } - - takeRetained(key: string): T | null { - const retained = this.retained.get(key) ?? null; - if (retained) this.retained.delete(key); - return retained; - } - - removeRetained(key: string): void { - this.retained.delete(key); - } - - removeRetainedWhere(predicate: (view: T) => boolean): T[] { - const removed: T[] = []; - for (const [key, view] of this.retained) { - if (!predicate(view)) continue; - this.retained.delete(key); - removed.push(view); - } - return removed; - } - - handleHostClose(instanceId: string) { - const next = reconcileClosedPluginView({ - current: this.current, - retained: this.retained, - instanceId, - }); - this.current = next.current; - this.retained = next.retained; - if (!next.matchedCurrent && !next.matchedRetained) { - rememberClosedPluginViewInstance(this.closedInstanceIds, instanceId); - } - return next; - } - - handleTabClose(tabId: string) { - const next = withdrawPluginViewTab({ - current: this.current, - retained: this.retained, - tabId, - }); - this.current = next.current; - this.retained = next.retained; - markPluginViewOpenTokensClosed( - this.openingTokensByTab, - this.explicitlyClosedOpenTokens, - tabId, - ); - return next; - } - - markViewClosed(viewKey: string | null | undefined): number { - return markPluginViewOpenTokensClosed( - this.openingTokensByView, - this.explicitlyClosedOpenTokens, - viewKey, - ); - } - - beginOpen({ - viewKey, - tabId, - label, - }: { - viewKey: string; - tabId?: string; - label?: string; - }): symbol { - const token = Symbol(label ?? tabId ?? viewKey); - const viewTokens = this.openingTokensByView.get(viewKey) ?? new Set(); - viewTokens.add(token); - this.openingTokensByView.set(viewKey, viewTokens); - if (tabId) { - const tabTokens = this.openingTokensByTab.get(tabId) ?? new Set(); - tabTokens.add(token); - this.openingTokensByTab.set(tabId, tabTokens); - } - return token; - } - - finishOpen({ token, viewKey, tabId }: { token: symbol; viewKey: string; tabId?: string }): void { - this.explicitlyClosedOpenTokens.delete(token); - const viewTokens = this.openingTokensByView.get(viewKey); - viewTokens?.delete(token); - if (viewTokens?.size === 0) this.openingTokensByView.delete(viewKey); - if (!tabId) return; - const tabTokens = this.openingTokensByTab.get(tabId); - tabTokens?.delete(token); - if (tabTokens?.size === 0) this.openingTokensByTab.delete(tabId); - } - - shouldCloseOpen(token: symbol): boolean { - return this.explicitlyClosedOpenTokens.has(token); - } - - consumeHostClose(instanceId: string): boolean { - return consumeClosedPluginViewInstance(this.closedInstanceIds, instanceId); - } - - drain(): T[] { - const values = [this.current, ...this.retained.values()].filter((view): view is T => Boolean(view)); - this.current = null; - this.retained.clear(); - this.closedInstanceIds.clear(); - this.openingTokensByTab.clear(); - this.openingTokensByView.clear(); - this.explicitlyClosedOpenTokens.clear(); - return values; - } -} diff --git a/application/state/pluginViewSession.test.ts b/application/state/pluginViewSession.test.ts new file mode 100644 index 000000000..848bf2e10 --- /dev/null +++ b/application/state/pluginViewSession.test.ts @@ -0,0 +1,41 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { HostDrawnViewMessage, HostDrawnViewOpenRequest } from '@netcatty/plugin-contract'; +type Update = Extract & { viewId: string }; +import { PluginViewSessions } from './pluginViewSession'; +function fixture() { + let updates: (data: Update) => void = () => {}; let closed: (data: NetcattyPluginViewClosedEvent) => void = () => {}; + const opened: HostDrawnViewOpenRequest[] = []; const closes: string[] = []; const events: unknown[] = []; + const bridge = { openHostDrawnPluginView: async (request: HostDrawnViewOpenRequest) => { opened.push(request); return { instanceId: request.instanceId }; }, + closeHostDrawnPluginView: async (id: string) => { closes.push(id); }, + onHostDrawnPluginViewUpdate: (listener: typeof updates) => { updates = listener; return () => {}; }, + onPluginViewClosed: (listener: typeof closed) => { closed = listener; return () => {}; }, + sendHostDrawnPluginViewEvent: async (id: string, event: unknown) => { events.push({ id, event }); } }; + return { bridge, opened, closes, events, update: (data: Update) => updates(data), close: (data: { instanceId: string }) => closed({ ...data, viewId: request.viewId, pluginId: 'com.example', reason: 'test' }) }; +} +const request = { viewId: 'com.example.view', scopeId: 'window:one', context: {} }; +test('a hidden view resumes its existing state and plugin instance', async () => { + const f = fixture(); const store = new PluginViewSessions(); + const first = store.acquire('view', f.bridge, request); const id = f.opened[0].instanceId; + f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '', mutations: [[0, '~', { id: 'text', type: 3, data: 'kept' }, 0]] }); + first.release(); const next = store.acquire('view', f.bridge, request); + assert.equal(next, first); assert.equal(f.opened.length, 1); assert.deepEqual(next.getSnapshot().tree.children[0], { id: 'text', type: 3, data: 'kept' }); + next.release(); store.dispose(); await Promise.resolve(); assert.equal(new Set(f.closes).size, 1); +}); +test('host invalidation clears retained content and a reopen creates a new instance', () => { + const f = fixture(); const store = new PluginViewSessions(); const old = store.acquire('view', f.bridge, request); + f.close({ instanceId: f.opened[0].instanceId }); assert.equal(old.getSnapshot().error, true); assert.deepEqual(old.getSnapshot().tree.children, []); + const next = store.acquire('view', f.bridge, request); assert.notEqual(old, next); store.dispose(); +}); +test('unacknowledged input is not overwritten by an older plugin update', () => { + const f = fixture(); const store = new PluginViewSessions(); const view = store.acquire('view', f.bridge, request); + view.send({ type: 'input', nodeId: 'field', value: 'latest' }); assert.equal(view.getSnapshot().settled, false); + const base = { kind: 'host-ui.update' as const, viewId: request.viewId, instanceId: f.opened[0].instanceId, css: '', mutations: [] }; + f.update({ ...base, sequence: 1, acknowledgedEvent: 0 }); assert.equal(view.getSnapshot().settled, false); + f.update({ ...base, sequence: 2, acknowledgedEvent: 1 }); assert.equal(view.getSnapshot().settled, true); store.dispose(); +}); +test('idle instances are evicted while active instances are never silently replaced', () => { + const f = fixture(); const store = new PluginViewSessions(1); const first = store.acquire('one', f.bridge, request); + assert.throws(() => store.acquire('two', f.bridge, request), /Too many/); first.release(); + const second = store.acquire('two', f.bridge, request); assert.notEqual(second, first); assert.equal(f.closes.length, 1); store.dispose(); +}); diff --git a/application/state/pluginViewSession.ts b/application/state/pluginViewSession.ts new file mode 100644 index 000000000..f42db0a4d --- /dev/null +++ b/application/state/pluginViewSession.ts @@ -0,0 +1,78 @@ +import { createPluginRemoteTree } from './pluginRemoteTree'; +import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs'; +import type { HostDrawnViewEvent } from '@netcatty/plugin-contract'; + +type Bridge = Pick>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>; +export type PluginViewSnapshot = { tree: ReturnType['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean }; +const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true }); + +/** Owns a window's bounded, retained UI instances independently of React mounts. */ +export class PluginViewSessions { + private sessions = new Map>(); + constructor(private readonly capacity = 16, private readonly idleMs = 300_000) {} + private create(key: string, bridge: Bridge, request: Omit) { + const id = crypto.randomUUID(); + const tree = createPluginRemoteTree(); + let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0; + let timer: ReturnType | undefined; + const listeners = new Set<() => void>(); + const publish = (next: PluginViewSnapshot) => { state = next; for (const listener of listeners) listener(); }; + const cleanup: Array<() => void> = []; + const dispose = (failed = false) => { + if (disposed) return; + disposed = true; clearTimeout(timer); cleanup.forEach((stop) => stop()); + this.sessions.delete(key); + publish({ ...empty(), loading: false, error: failed }); + void bridge.closeHostDrawnPluginView?.(id).catch(() => {}); + }; + if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable'); + cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => { + if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return; + try { + if (update.sequence !== sequence++) throw new Error('Invalid plugin update order'); + publish({ tree: tree.apply(update.mutations), css: validatePluginStylesheet(update.css), loading: false, error: false, settled: (update.acknowledgedEvent ?? 0) >= eventId }); + } catch { dispose(true); } + })); + cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); })); + void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => { + if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {}); + }).catch(() => dispose(true)); + return { + viewId: request.viewId, + scope: request.scopeId, + image: async (path: string) => { + if (disposed || !bridge.getPluginViewResource) throw new Error('Plugin image unavailable'); + const result = await bridge.getPluginViewResource({ instanceId: id, path }); + if (disposed) throw new Error('Plugin view closed'); + return result.url; + }, + get idle() { return users === 0; }, + getSnapshot: () => state, + subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; }, + acquire: () => { clearTimeout(timer); users++; }, + release: () => { if (--users === 0 && !disposed) timer = setTimeout(() => dispose(), this.idleMs); }, + send: (event: HostDrawnViewEvent) => { + if (disposed || users === 0) return; + publish({ ...state, settled: false }); + void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true)); + }, + dispose, + }; + } + acquire(key: string, bridge: Bridge, request: Omit) { + let session = this.sessions.get(key); + if (!session) { + while (this.sessions.size >= this.capacity) { + const candidate = [...this.sessions.values()].find((item) => item.idle); + if (!candidate) throw new Error('Too many open plugin views'); + candidate.dispose(); + } + session = this.create(key, bridge, request); this.sessions.set(key, session); + } + session.acquire(); return session; + } + closeView(viewId: string) { for (const session of [...this.sessions.values()]) if (session.viewId === viewId) session.dispose(); } + closeScope(scope: string) { for (const session of [...this.sessions.values()]) if (session.scope === scope) session.dispose(); } + dispose() { for (const session of [...this.sessions.values()]) session.dispose(); } +} +export const pluginViewSessions = new PluginViewSessions(); diff --git a/application/state/terminalSidePanelPluginTabs.test.tsx b/application/state/terminalSidePanelPluginTabs.test.tsx new file mode 100644 index 000000000..cdbfa184b --- /dev/null +++ b/application/state/terminalSidePanelPluginTabs.test.tsx @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { JSDOM } from 'jsdom'; + +test('plugin tools stay in the toolbar and retain placement across catalog changes and remount', async () => { + const dom = new JSDOM('
', { url: 'http://localhost' }); + const previous = new Map(); + for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) { + previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] }); + } + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true }); + const { default: React, act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { useTerminalSidePanelTabOrder, TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER } = await import('./terminalSidePanelTabs'); + const { STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT } = await import('../../infrastructure/config/storageKeys'); + const plugin = 'plugin-view:com.example.sidebar.page' as const; + dom.window.localStorage.setItem(STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT, JSON.stringify({ order: TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, placement: {} })); + let model: ReturnType; + let tools: typeof plugin[] = []; + function Fixture() { model = useTerminalSidePanelTabOrder(tools); return
; } + const root = createRoot(document.getElementById('root')!); + const render = async () => { await act(async () => { root.render(); }); }; + try { + await render(); + tools = [plugin]; await render(); + assert.equal(model!.sidePanelTabOrder[1], plugin, 'new plugin is a visible toolbar item'); + assert.ok(model!.partition([...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]).shown.includes(plugin)); + await act(async () => { model!.setPlacement(plugin, 'collapse', [...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]); }); + tools = []; await render(); + assert.ok(!model!.partition(TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER).collapsed.includes(plugin)); + tools = [plugin]; await render(); + assert.ok(model!.partition([...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]).collapsed.includes(plugin)); + await act(async () => { root.unmount(); }); + const nextRoot = createRoot(document.getElementById('root')!); + tools = []; await act(async () => { nextRoot.render(); }); + tools = [plugin]; await act(async () => { nextRoot.render(); }); + assert.ok(model!.partition([...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]).collapsed.includes(plugin), 'cold catalog loading preserves preference'); + await act(async () => { nextRoot.unmount(); }); + } finally { + for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } + Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); dom.window.close(); + } +}); diff --git a/application/state/terminalSidePanelTabs.ts b/application/state/terminalSidePanelTabs.ts index dcfed3362..b2aaae970 100644 --- a/application/state/terminalSidePanelTabs.ts +++ b/application/state/terminalSidePanelTabs.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useEffect, useMemo, useRef } from 'react'; import { normalizeToolbarItemLayout, @@ -13,7 +13,7 @@ import { } from '../../infrastructure/config/storageKeys'; import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; import { useToolbarItemLayout } from './useToolbarItemLayout'; -import type { BuiltinSidePanelTool, SidePanelTool } from '../../domain/sidePanelLayout'; +import { isPluginSidePanelTool, type BuiltinSidePanelTool, type SidePanelTool } from '../../domain/sidePanelLayout'; export type TerminalSidePanelTabId = SidePanelTool; @@ -101,7 +101,7 @@ function migrateSidePanelTabLayoutIfNeeded(): void { migrateSidePanelTabLayoutIfNeeded(); -export function useTerminalSidePanelTabOrder(): { +export function useTerminalSidePanelTabOrder(pluginTools: readonly SidePanelTool[] = []): { sidePanelTabOrder: TerminalSidePanelTabId[]; setSidePanelTabOrder: (order: TerminalSidePanelTabId[]) => void; layout: ToolbarItemLayout; @@ -111,6 +111,23 @@ export function useTerminalSidePanelTabOrder(): { resetLayout: () => void; partition: ReturnType['partition']; } { + // Keep preferences for temporarily unavailable/disabled plugins, including + // across a cold start before the contribution catalog finishes loading. + const knownPluginTools = useRef | null>(null); + if (!knownPluginTools.current) { + let stored: unknown; + try { stored = localStorageAdapter.read(STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT); } catch { stored = null; } + const order = stored && typeof stored === 'object' && !Array.isArray(stored) + ? (stored as { order?: unknown }).order : []; + knownPluginTools.current = new Set(Array.isArray(order) + ? order.filter((id): id is string => typeof id === 'string' && isPluginSidePanelTool(id)) : []); + } + for (const tool of pluginTools) if (isPluginSidePanelTool(tool)) knownPluginTools.current.add(tool); + const pluginKey = [...knownPluginTools.current].join('\0'); + const defaults = useMemo(() => { + const plugins = pluginKey ? pluginKey.split('\0') : []; + return { order: [TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER[0], ...plugins, ...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER.slice(1)] }; + }, [pluginKey]); const { layout, setPlacement, @@ -121,9 +138,28 @@ export function useTerminalSidePanelTabOrder(): { partition, } = useToolbarItemLayout( STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT, - TERMINAL_SIDE_PANEL_TAB_LAYOUT_DEFAULTS, + defaults, ); + // Newly installed plugins get a visible slot near the start even when an + // older saved layout already exists. Existing choices always keep their order. + const activePluginKey = pluginTools.filter(isPluginSidePanelTool).join('\0'); + useEffect(() => { + const active = activePluginKey ? activePluginKey.split('\0') : []; + if (!active.length || active.some((id) => !layout.order.includes(id))) return; + let stored: unknown; + try { stored = localStorageAdapter.read(STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT); } catch { return; } + const storedOrder = stored && typeof stored === 'object' && !Array.isArray(stored) + ? (stored as { order?: unknown }).order : null; + const saved = new Set(Array.isArray(storedOrder) ? storedOrder : []); + const fresh = active.filter((id) => !saved.has(id)); + if (!fresh.length) return; + const rest = layout.order.filter((id) => !fresh.includes(id)); + const index = Math.max(0, rest.indexOf('sftp') + 1); + const next = [...rest.slice(0, index), ...fresh, ...rest.slice(index)]; + if (next.some((id, i) => id !== layout.order[i])) setOrder(next); + }, [activePluginKey, layout.order, setOrder]); + const sidePanelTabOrder = layout.order as TerminalSidePanelTabId[]; const setSidePanelTabOrder = useCallback( diff --git a/application/state/useEmbeddedPluginView.ts b/application/state/useEmbeddedPluginView.ts deleted file mode 100644 index a2727ece7..000000000 --- a/application/state/useEmbeddedPluginView.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { useEffect, useRef, useState } from 'react'; -import { PluginViewLifecycleController, type HostedPluginViewState } from './pluginViewLifecycle'; -import { resolvePluginViewWindowScope } from './pluginViewScopes'; -import { isPluginViewOccluded } from './pluginViewOcclusion'; -import type { UsePluginContributionsResult } from './usePluginContributions'; - -type ViewAdapter = Pick; - -/** Host-owned mounting only. No plugin router, DOM, session or vault data API. */ -export function useEmbeddedPluginView({ viewId, version, slot, active, context, adapter, subscribeHidden, unavailable, focused, focusOnReveal = false }: { - viewId: string; - version: string; - slot: string; - active: boolean; - context: Record; - adapter: ViewAdapter; - subscribeHidden(listener: () => void): () => void; - unavailable(): void; - focused?(): void; - focusOnReveal?: boolean; -}) { - const mountRef = useRef(null); - const [loading, setLoading] = useState(true); - const adapterRef = useRef(adapter); - const unavailableRef = useRef(unavailable); - const focusedRef = useRef(focused); - const revealFocusRef = useRef(focusOnReveal); - const requestFocusRef = useRef<() => void>(() => {}); - revealFocusRef.current = focusOnReveal; - focusedRef.current = focused; - adapterRef.current = adapter; - unavailableRef.current = unavailable; - useEffect(() => { - const mount = mountRef.current; - if (!active || !mount) return; - let cancelled = false; - const lifecycle = new PluginViewLifecycleController(); - const instanceId = crypto.randomUUID(); - const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, - search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` }); - const { openView, closeView, focusView, setViewBounds, setViewVisibility, onViewClosed, onViewFocused } = adapterRef.current; - const close = () => { - if (cancelled) return; - cancelled = true; - lifecycle.markViewClosed(viewId); - void closeView(instanceId).catch(() => {}); - }; - const failCurrent = () => { - if (cancelled) return; - close(); - unavailableRef.current(); - }; - const unsubscribe = onViewClosed((event) => { - lifecycle.handleHostClose(event.instanceId); - if (event.instanceId === instanceId && !cancelled) { - close(); - unavailableRef.current(); - } - }); - const stopOnHide = subscribeHidden(close); - const stopOnFocus = onViewFocused((event) => { - if (!cancelled && event.instanceId === instanceId) focusedRef.current?.(); - }); - const bounds = () => { - const rect = mount.getBoundingClientRect(); - return { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.max(1, Math.round(rect.width)), height: Math.max(1, Math.round(rect.height)) }; - }; - let opened = false; - let lastBounds = ''; - let visible = false; - const focus = () => { - if (!cancelled && opened && visible && revealFocusRef.current && !isPluginViewOccluded(mount)) void focusView(instanceId).catch(() => {}); - }; - requestFocusRef.current = focus; - const updateVisibility = () => { - if (!opened || cancelled) return; - const rect = mount.getBoundingClientRect(); - const next = rect.width > 0 && rect.height > 0 && !isPluginViewOccluded(mount); - if (visible === next) return; - visible = next; - void setViewVisibility(instanceId, next).then(() => { if (next) focus(); }).catch(failCurrent); - }; - const resize = () => { - if (opened && !cancelled) { - const next = bounds(); - const key = JSON.stringify(next); - if (key !== lastBounds) { lastBounds = key; void setViewBounds(instanceId, next).catch(failCurrent); } - } - updateVisibility(); - }; - const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(resize); - observer?.observe(mount); - const mutations = new MutationObserver(resize); - mutations.observe(document.body, { childList: true, subtree: true, attributes: true, - attributeFilter: ['class', 'style', 'hidden', 'inert', 'role', 'aria-modal', 'aria-hidden', 'data-state', 'data-app-lock-overlay', 'data-radix-popper-content-wrapper', 'data-native-view-occluder'] }); - window.addEventListener('resize', resize); - document.addEventListener('scroll', resize, true); - setLoading(true); - const opening = lifecycle.beginOpen({ viewKey: viewId }); - void openView({ viewId, instanceId, scopeId, bounds: bounds(), context }).then(async (result) => { - if (cancelled || lifecycle.shouldCloseOpen(opening) || lifecycle.consumeHostClose(result.instanceId)) { - await closeView(result.instanceId); - return; - } - opened = true; - lifecycle.setCurrent({ id: result.instanceId, viewId, scopeId, retainContextWhenHidden: false }); - resize(); - setLoading(false); - }).catch(() => { - if (!cancelled) { close(); unavailableRef.current(); } - }).finally(() => lifecycle.finishOpen({ token: opening, viewKey: viewId })); - return () => { - close(); unsubscribe(); stopOnHide(); stopOnFocus(); observer?.disconnect(); mutations.disconnect(); - window.removeEventListener('resize', resize); document.removeEventListener('scroll', resize, true); - }; - }, [active, context, slot, subscribeHidden, version, viewId]); - useEffect(() => { if (focusOnReveal) requestFocusRef.current(); }, [focusOnReveal]); - return { mountRef, loading }; -} diff --git a/application/state/useHostDrawnPluginView.ts b/application/state/useHostDrawnPluginView.ts new file mode 100644 index 000000000..6f7b0f7ca --- /dev/null +++ b/application/state/useHostDrawnPluginView.ts @@ -0,0 +1,42 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { netcattyBridge } from '../../infrastructure/services/netcattyBridge'; +import { resolvePluginViewWindowScope } from './pluginViewScopes'; +import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession'; +import type { HostDrawnViewEvent } from '@netcatty/plugin-contract'; + +const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true }); +export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: { + viewId: string; version: string; slot: string; active: boolean; context: Record; + subscribeHidden(listener: () => void): () => void; unavailable(): void; +}) { + const contextKey = JSON.stringify(context); + const key = JSON.stringify([viewId, version, slot, contextKey]); + const [state, setState] = useState<{ key: string; snapshot: PluginViewSnapshot }>({ key: '', snapshot: initial() }); + const [hidden, setHidden] = useState(false); + const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable; + const sessionRef = useRef<{ key: string; image(path: string): Promise; send(event: HostDrawnViewEvent): void } | null>(null); + useEffect(() => { + if (!active) return; + const bridge = netcattyBridge.get(); + if (!bridge) { unavailableRef.current(); return; } + const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` }); + try { + const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) }); + const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot }); if (snapshot.error) unavailableRef.current(); }; + const stop = session.subscribe(update); update(); setHidden(false); + sessionRef.current = { key, send: session.send, image: session.image }; + const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); }); + return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); }; + } catch { unavailableRef.current(); } + }, [active, contextKey, key, slot, subscribeHidden, viewId]); + const loadImage = useCallback((path: string) => { + const session = sessionRef.current; + return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable')); + }, [active, key]); + const sendEvent = useCallback((event: HostDrawnViewEvent) => { + const session = sessionRef.current; if (active && session?.key === key) session.send(event); + }, [active, key]); + // A newly selected plugin must never receive values from the previous tree, + // even during the render before effect cleanup and the next activation. + return { ...(state.key === key ? state.snapshot : initial()), visible: active && !hidden, loadImage, sendEvent }; +} diff --git a/application/state/usePluginContributions.ts b/application/state/usePluginContributions.ts index 2d2230747..365273c8c 100644 --- a/application/state/usePluginContributions.ts +++ b/application/state/usePluginContributions.ts @@ -86,14 +86,8 @@ export interface UsePluginContributionsResult { updateSetting(pluginId: string, settingId: string, value: unknown, scopeId?: string): Promise<{ restartRequired: boolean }>; resetSetting(pluginId: string, settingId: string, scopeId?: string): Promise<{ restartRequired: boolean }>; selectSettingPath(kind: 'file' | 'directory', title: string, defaultPath?: string): Promise; - openView(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>; - closeView(instanceId: string): Promise; - focusView(instanceId: string): Promise; - setViewBounds(instanceId: string, bounds: { x: number; y: number; width: number; height: number }): Promise; - setViewVisibility(instanceId: string, visible: boolean): Promise; setEnvironment(environment: NetcattyPluginEnvironment): Promise; onViewClosed(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void; - onViewFocused(callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void): () => void; } export function usePluginContributions( @@ -189,32 +183,6 @@ export function usePluginContributions( return picker(title, defaultPath); }, [bridge]); - const openView = useCallback(async (payload: NetcattyPluginViewOpenRequest) => { - if (!bridge?.openPluginView) throw new Error('Plugin views are unavailable'); - return bridge.openPluginView(payload); - }, [bridge]); - - const closeView = useCallback(async (instanceId: string) => { - if (!bridge?.closePluginView) return; - await bridge.closePluginView(instanceId); - }, [bridge]); - const focusView = useCallback(async (instanceId: string) => { - await bridge?.focusPluginView?.({ instanceId }); - }, [bridge]); - - const setViewBounds = useCallback(async ( - instanceId: string, - bounds: { x: number; y: number; width: number; height: number }, - ) => { - if (!bridge?.setPluginViewBounds) return; - await bridge.setPluginViewBounds(instanceId, bounds); - }, [bridge]); - - const setViewVisibility = useCallback(async (instanceId: string, visible: boolean) => { - if (!bridge?.setPluginViewVisibility) return; - await bridge.setPluginViewVisibility(instanceId, visible); - }, [bridge]); - const setEnvironment = useCallback(async (environment: NetcattyPluginEnvironment) => { if (!bridge?.setPluginEnvironment) return; await bridge.setPluginEnvironment(environment); @@ -223,10 +191,6 @@ export function usePluginContributions( const onViewClosed = useCallback((callback: (event: NetcattyPluginViewClosedEvent) => void) => ( bridge?.onPluginViewClosed?.(callback) ?? (() => {}) ), [bridge]); - const onViewFocused = useCallback((callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void) => ( - bridge?.onPluginViewFocused?.(callback) ?? (() => {}) - ), [bridge]); - const currentLoadState = resolvePluginContributionLoadState({ currentQueryKey: queryKey, loadedQueryKey: loadedSnapshot.queryKey, @@ -245,13 +209,7 @@ export function usePluginContributions( updateSetting, resetSetting, selectSettingPath, - openView, - closeView, - focusView, - setViewBounds, - setViewVisibility, setEnvironment, onViewClosed, - onViewFocused, }; } diff --git a/application/state/usePluginManager.ts b/application/state/usePluginManager.ts index a8f5d4b0d..80d37e5c0 100644 --- a/application/state/usePluginManager.ts +++ b/application/state/usePluginManager.ts @@ -38,18 +38,20 @@ export function usePluginManager() { const refreshGeneration = generation; return () => { refreshGeneration.current++; unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', update); }; }, [refresh]); - const run = useCallback(async (action: (bridge: NetcattyBridge) => Promise) => { + const run = useCallback(async (action: (bridge: NetcattyBridge) => Promise, throwOnError = false) => { if (mutation.current) return; mutation.current = true; setBusy(true); setError(null); + let failure: Error | null = null; try { await action(netcattyBridge.require()); } - catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); } + catch (cause) { failure = cause instanceof Error ? cause : new Error(String(cause)); setError(failure.message); } finally { - try { await refresh(); } catch (cause) { setError(String(cause)); } + try { await refresh(); } catch (cause) { failure ??= cause instanceof Error ? cause : new Error(String(cause)); setError(failure.message); } mutation.current = false; setBusy(false); } + if (throwOnError && failure) throw failure; }, [refresh]); return { plugins, available, statusKnown, busy, error, credentialStorageAvailable, refresh, @@ -70,6 +72,6 @@ export function usePluginManager() { if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable'); await bridge.resetPluginSource(id, source.id); } - }), + }, true), }; } diff --git a/application/state/usePluginSettingsModel.ts b/application/state/usePluginSettingsModel.ts new file mode 100644 index 000000000..40717401e --- /dev/null +++ b/application/state/usePluginSettingsModel.ts @@ -0,0 +1,22 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useI18n } from '../i18n/I18nProvider'; +import { usePluginContributions } from './usePluginContributions'; +import { resolvePluginSettingScopeSelection, usePluginSettingScopeCatalog } from './usePluginSettingScopeCatalog'; + +export function usePluginSettingsModel(pluginId: string) { + const { locale } = useI18n(); + const catalog = usePluginSettingScopeCatalog(); + const [scopeIds, setScopeIds] = useState>>({}); + useEffect(() => { + setScopeIds(current => resolvePluginSettingScopeSelection(catalog, current)); + }, [catalog]); + const query = useMemo(() => ({ + locale, context: { 'netcatty.surface': 'settings' }, scopeIds, + }), [locale, scopeIds]); + const contributions = usePluginContributions(query); + const plugin = contributions.snapshot.plugins.find(item => item.id === pluginId); + const settings = plugin?.settings.filter(setting => setting.visible) ?? []; + const contextualScopes = [...new Set(settings.map(setting => setting.scope) + .filter((scope): scope is NetcattyPluginSettingScopeKind => scope !== 'application'))]; + return { ...contributions, plugin, settings, catalog, scopeIds, setScopeIds, contextualScopes }; +} diff --git a/application/state/usePluginViewLifecycle.ts b/application/state/usePluginViewLifecycle.ts index 1c595a52d..007ecaf12 100644 --- a/application/state/usePluginViewLifecycle.ts +++ b/application/state/usePluginViewLifecycle.ts @@ -14,19 +14,12 @@ import { usePluginViewTabs, } from './pluginViewTabStore'; import { - PluginViewLifecycleController, reconcilePluginViewTabCatalog, resolvePluginViewSnapshotSelection, - type HostedPluginViewState, type PluginViewSnapshotSelection, } from './pluginViewLifecycle'; -import { - canRetainPluginViewInScope, - resolvePluginRetainedViewKey, - resolvePluginViewWindowScope, -} from './pluginViewScopes'; +import { pluginViewSessions } from './pluginViewSession'; import { usePluginContributions } from './usePluginContributions'; -import { observePluginHostSecurityVisibility } from './pluginHostSecurityVisibility'; export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view'; @@ -70,17 +63,8 @@ export function usePluginViewLifecycle({ const { snapshot, executeCommand, - openView, - closeView, - setViewBounds, - setViewVisibility, setEnvironment, - onViewClosed, } = contributions; - const [instance, setInstance] = useState(null); - const lifecycleRef = useRef(new PluginViewLifecycleController()); - const closeViewRef = useRef(closeView); - const mountRef = useRef(null); const resolvedActiveView = useMemo(() => viewContributions.snapshot.plugins .flatMap((plugin) => plugin.views.map((view) => ({ plugin, view }))) .find(({ view }) => view.id === effectiveRequested?.viewId && view.visible && !['vault-page', 'terminal-sidebar'].includes(view.location)) ?? null, @@ -93,16 +77,6 @@ export function usePluginViewLifecycle({ requestedViewId: effectiveRequested?.viewId, contextKey: viewQueryContextKey, }); - const activeViewId = activeView?.view.id; - const viewScopeId = typeof window === 'undefined' - ? 'window:server' - : resolvePluginViewWindowScope(window.location); - const retainedViewKey = activeViewId - ? resolvePluginRetainedViewKey(activeViewId, viewScopeId) - : null; - - useEffect(() => { closeViewRef.current = closeView; }, [closeView]); - useEffect(() => { if (viewContributions.loading) return; stableActiveViewRef.current = resolvedActiveView && effectiveRequested?.viewId @@ -114,26 +88,6 @@ export function usePluginViewLifecycle({ : null; }, [effectiveRequested?.viewId, resolvedActiveView, viewContributions.loading, viewQueryContextKey]); - useEffect(() => onViewClosed((event) => { - const next = lifecycleRef.current.handleHostClose(event.instanceId); - if (next.matchedCurrent) { - setInstance(null); - setRequested(null); - } - if (next.closedTabId) pluginViewTabStore.close(next.closedTabId); - }), [onViewClosed]); - - useEffect(() => pluginViewTabStore.onDidClose(({ tab }) => { - const next = lifecycleRef.current.handleTabClose(tab.id); - if (next.matchedCurrent) { - setInstance(null); - setRequested(null); - } - for (const instanceId of next.instanceIds) { - void closeViewRef.current(instanceId).catch(() => {}); - } - }), []); - useEffect(() => { const bindings = snapshot.plugins.flatMap((plugin) => plugin.keybindings) .filter((binding) => binding.enabled) @@ -182,164 +136,16 @@ export function usePluginViewLifecycle({ setRequested(null); }, [activeView, requested]); - const hideOrClose = useCallback(async (current: HostedPluginViewState) => { - if (!current.retainContextWhenHidden) { - await closeView(current.id); - return; - } - const key = resolvePluginRetainedViewKey(current.viewId, current.scopeId); - lifecycleRef.current.retain(key, current); - try { - await setViewVisibility(current.id, false); - } catch { - lifecycleRef.current.removeRetained(key); - await closeView(current.id); - } - }, [closeView, setViewVisibility]); + useEffect(() => { + const stop = pluginViewTabStore.onDidClose(({ tab }) => pluginViewSessions.closeView(tab.viewId)); + return () => { stop(); }; + }, []); const close = useCallback(async () => { - lifecycleRef.current.markViewClosed(retainedViewKey); - const current = lifecycleRef.current.takeCurrent(); - setInstance(null); setRequested(null); - if (current) await closeView(current.id); - }, [closeView, retainedViewKey]); - - useEffect(() => { - const removed = lifecycleRef.current.removeRetainedWhere( - (retained) => !canRetainPluginViewInScope(retained.scopeId, viewScopeId), - ); - for (const retained of removed) void closeView(retained.id).catch(() => {}); - }, [closeView, viewScopeId]); - - useEffect(() => { - if (!instance) return; - if (effectiveRequested?.viewId === instance.viewId - && activeViewId === instance.viewId - && instance.scopeId === viewScopeId) return; - lifecycleRef.current.takeCurrent(); - setInstance(null); - if (canRetainPluginViewInScope(instance.scopeId, viewScopeId)) { - void hideOrClose(instance); - } else { - void closeView(instance.id).catch(() => {}); - } - }, [activeViewId, closeView, effectiveRequested?.viewId, hideOrClose, instance, viewScopeId]); - - useEffect(() => { - if (!activeViewId || !retainedViewKey || !mountRef.current || instance) return; - let cancelled = false; - const openingTabId = activePluginTab?.id; - const openingToken = lifecycleRef.current.beginOpen({ - viewKey: retainedViewKey, - tabId: openingTabId, - label: activePluginTab?.id ?? activeViewId, - }); - const bounds = mountRef.current.getBoundingClientRect(); - const nextBounds = { - x: Math.round(bounds.x), - y: Math.round(bounds.y), - width: Math.max(1, Math.round(bounds.width)), - height: Math.max(1, Math.round(bounds.height)), - }; - void (async () => { - let opened = lifecycleRef.current.takeRetained(retainedViewKey); - if (opened) { - try { - await setViewBounds(opened.id, nextBounds); - await setViewVisibility(opened.id, true); - } catch { - try { await closeView(opened.id); } catch { /* best-effort cleanup after restore failure */ } - opened = null; - } - } - if (!opened) { - const result = await openView({ - viewId: activeViewId, - scopeId: viewScopeId, - bounds: nextBounds, - context: effectiveRequested?.context, - }); - opened = { - id: result.instanceId, - viewId: activeViewId, - scopeId: viewScopeId, - retainContextWhenHidden: activeView.view.retainContextWhenHidden === true, - ...(activePluginTab ? { tabId: activePluginTab.id } : {}), - }; - } - if (lifecycleRef.current.consumeHostClose(opened.id)) { - throw new Error('Plugin view closed while its open response was in flight'); - } - if (lifecycleRef.current.shouldCloseOpen(openingToken)) { - await closeView(opened.id); - return; - } - if (cancelled) { - await hideOrClose(opened); - return; - } - lifecycleRef.current.setCurrent(opened); - setInstance(opened); - })().catch(() => { - if (cancelled) return; - if (activePluginTab) pluginViewTabStore.close(activePluginTab.id); - else setRequested(null); - }).finally(() => { - lifecycleRef.current.finishOpen({ - token: openingToken, - viewKey: retainedViewKey, - tabId: openingTabId, - }); - }); - return () => { cancelled = true; }; - }, [ - activePluginTab, - activeView?.view.retainContextWhenHidden, - activeViewId, - closeView, - effectiveRequested?.context, - hideOrClose, - instance, - openView, - retainedViewKey, - setViewBounds, - setViewVisibility, - viewScopeId, - ]); - - useEffect(() => { - if (!instance || !mountRef.current) return; - let disposed = false; - const stop = observePluginHostSecurityVisibility(mountRef.current, (visible) => { - void setViewVisibility(instance.id, visible).catch(() => { - if (!disposed) void closeView(instance.id).catch(() => {}); - }); - }); - return () => { disposed = true; stop(); }; - }, [closeView, instance, setViewVisibility]); - - useEffect(() => { - if (!instance || !mountRef.current) return; - const update = () => { - const bounds = mountRef.current?.getBoundingClientRect(); - if (!bounds) return; - void setViewBounds(instance.id, { - x: Math.round(bounds.x), - y: Math.round(bounds.y), - width: Math.max(1, Math.round(bounds.width)), - height: Math.max(1, Math.round(bounds.height)), - }); - }; - const observer = new ResizeObserver(update); - observer.observe(mountRef.current); - window.addEventListener('resize', update); - update(); - return () => { - observer.disconnect(); - window.removeEventListener('resize', update); - }; - }, [instance, setViewBounds]); + if (activeView) pluginViewSessions.closeView(activeView.view.id); + if (activePluginTab) pluginViewTabStore.close(activePluginTab.id); + }, [activePluginTab, activeView]); useEffect(() => { if (!contributions.available) return; @@ -376,16 +182,10 @@ export function usePluginViewLifecycle({ }; }, [contributions.available, locale, setEnvironment, suppliedThemeTokens, theme]); - useEffect(() => () => { - const views = lifecycleRef.current.drain(); - const ids = new Set(views.map((view) => view.id)); - for (const id of ids) void closeViewRef.current(id); - }, []); - return { activeView, close, effectiveRequested, - mountRef, + viewQueryContext, }; } diff --git a/application/state/useToolbarItemLayout.ts b/application/state/useToolbarItemLayout.ts index fb32b4bc1..929bc65dc 100644 --- a/application/state/useToolbarItemLayout.ts +++ b/application/state/useToolbarItemLayout.ts @@ -63,6 +63,9 @@ export function useToolbarItemLayout( const [layout, setLayout] = useState(() => readLayout(storageKey, defaults)); useEffect(() => { + // Defaults can include dynamically discovered items; re-read without writing + // so temporary catalog changes never erase stored toolbar preferences. + setLayout(readLayout(storageKey, defaults)); const sync = (event: Event) => { if (event instanceof StorageEvent && event.key !== storageKey) return; if (event instanceof CustomEvent && event.detail?.key !== storageKey) return; diff --git a/components/PluginAIContextHost.test.tsx b/components/PluginAIContextHost.test.tsx index df762bfa1..3322f46d4 100644 --- a/components/PluginAIContextHost.test.tsx +++ b/components/PluginAIContextHost.test.tsx @@ -147,8 +147,8 @@ test('cold plugin host reaches the local fixture through the actual main provide await service.manager.initialize(); const staging = path.join(fixtureRoot, 'package'); fs.mkdirSync(path.join(staging, 'dist'), { recursive: true }); const sample = path.join(rootPath, 'examples/plugins/assistant'); - for (const file of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(staging, file)); - fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(staging, 'dist/index.js')); + for (const file of ['netcatty.plugin.json', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(staging, file)); + fs.copyFileSync(path.join(sample, 'dist/host.js'), path.join(staging, 'dist/host.js')); const { buildPluginPackage } = await import('@netcatty/plugin-cli'); const archive = path.join(fixtureRoot, 'assistant.ncpkg'); await buildPluginPackage(staging, archive); service.database.setPermissionMode('com.netcatty.assistant', 'context.selected.read', 'ask'); @@ -161,13 +161,13 @@ test('cold plugin host reaches the local fixture through the actual main provide await act(async () => { await new Promise((resolve) => setTimeout(resolve, 5)); }); } }; - panel = new JSDOM(fs.readFileSync(path.join(sample, 'panel.html'), 'utf8'), { runScripts: 'outside-only' }); - Object.defineProperty(panel.window, 'netcattyView', { value: { + panel = new JSDOM(fs.readFileSync(path.join(sample, 'view.html'), 'utf8'), { runScripts: 'outside-only' }); + Object.defineProperty(panel.window, 'pluginContext', { value: { commands: { executeCommand: async (command: string, args: unknown) => structuredClone(await service!.contributionService.executeCommand(command, structuredClone(args))), - onDidReceiveMessage: () => ({ dispose() {} }), + }, views: { onDidReceiveMessage: () => ({ dispose() {} }) } } }); diagnosticPhase = 'initial-selection'; - await act(async () => panel!.window.eval(fs.readFileSync(path.join(sample, 'panel.js'), 'utf8'))); + await act(async () => panel!.window.eval(fs.readFileSync(path.join(sample, 'panel.js'), 'utf8').replace('export function mount', 'function mount') + '\nwindow.disposePanel = mount(document.body, window.pluginContext, "test", "test");')); await waitFor(() => document.getElementById('plugin-ai-note') !== null); const noteChoice = document.getElementById('plugin-ai-note') as HTMLSelectElement; assert.equal(noteChoice.options.length, 2); @@ -209,7 +209,7 @@ test('cold plugin host reaches the local fixture through the actual main provide console.error = originalConsoleError; // JSDOM.close does not deliver the browser pagehide lifecycle. Invalidate // the sample's pending callbacks before teardown closes its document. - if (panel) { panel.window.dispatchEvent(new panel.window.Event('pagehide')); panel.window.close(); } + if (panel) { panel.window.disposePanel(); panel.window.close(); } await act(async () => root.unmount()); await service?.manager.shutdown(); aiBridge.cleanup(); publishNotesSnapshot(oldNotes); registerAppAppLockRuntime(oldLock); diff --git a/components/PluginGlobalAgentHost.test.tsx b/components/PluginGlobalAgentHost.test.tsx index 20538600c..6b5a31861 100644 --- a/components/PluginGlobalAgentHost.test.tsx +++ b/components/PluginGlobalAgentHost.test.tsx @@ -90,8 +90,8 @@ test('installed global Chat UI reuses actual Catty runtime, configured HTTP tran electron: { ipcMain }, getInteractionWindow: () => mainWindow, isAppLocked: () => false, getTerminalWorkerManager: () => worker }); service.runtimeSupervisor.runtimeFactories.browser = inProcessBrowserRuntime; await service.manager.initialize(); const sample = path.join(rootPath, 'examples/plugins/global-agent'); const staging = path.join(directory, 'package'); fs.mkdirSync(path.join(staging, 'dist'), { recursive: true }); - for (const file of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(staging, file)); - fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(staging, 'dist/index.js')); + for (const file of ['netcatty.plugin.json', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(staging, file)); + fs.copyFileSync(path.join(sample, 'dist/host.js'), path.join(staging, 'dist/host.js')); const { buildPluginPackage } = await import('@netcatty/plugin-cli'); const archive = path.join(directory, 'global-agent.ncpkg'); await buildPluginPackage(staging, archive); await service.manager.install(archive, { enable: true }); await act(async () => root.render( { - panel = new JSDOM(fs.readFileSync(path.join(sample, 'panel.html'), 'utf8'), { runScripts: 'outside-only' }); - Object.defineProperty(panel.window, 'netcattyView', { value: { executeCommand: async (name: string, params: unknown) => { + panel = new JSDOM(fs.readFileSync(path.join(sample, 'view.html'), 'utf8'), { runScripts: 'outside-only' }); + Object.defineProperty(panel.window, 'pluginContext', { value: { commands: { executeCommand: async (name: string, params: unknown) => { // PluginViewHost.close removes sender authority before WebContents // closes. A pagehide RPC cannot be relied on to reach this relay. if (!viewOpen) throw Error('Untrusted plugin view sender'); const result = structuredClone(await service!.contributionService.executeCommand(name, structuredClone(params))); pluginReplies.push(result); return result; - }, onDidReceiveMessage: () => ({ dispose() {} }), onDidChangeEnvironment: () => ({ dispose() {} }) } }); - await act(async () => panel!.window.eval(fs.readFileSync(path.join(sample, 'panel.js'), 'utf8'))); + } }, views: { onDidReceiveMessage: () => ({ dispose() {} }) } } }); + await act(async () => panel!.window.eval(fs.readFileSync(path.join(sample, 'panel.js'), 'utf8').replace('export function mount', 'function mount') + '\nwindow.disposePanel = mount(document.body, window.pluginContext, "test", "test");')); }; await mountPanel(); const element = (id: string) => panel!.window.document.getElementById(id)!; @@ -135,7 +135,7 @@ test('installed global Chat UI reuses actual Catty runtime, configured HTTP tran const reference = pluginReplies.find((value) => value && typeof value === 'object' && 'conversationRef' in value && 'chatHandle' in value) as { conversationRef: string }; const beforeReopen = counts.requests; viewOpen = false; - panel!.window.dispatchEvent(new panel!.window.Event('pagehide')); panel!.window.close(); + panel!.window.disposePanel(); panel!.window.close(); viewOpen = true; await mountPanel(); await waitFor(() => element('status').textContent!.startsWith('Choose terminals')); (element('conversation') as HTMLSelectElement).value = reference.conversationRef; @@ -182,7 +182,7 @@ test('installed global Chat UI reuses actual Catty runtime, configured HTTP tran assert.deepEqual(errors, []); } finally { console.error = originalError; - if (panel) { panel.window.dispatchEvent(new panel.window.Event('pagehide')); panel.window.close(); } + if (panel) { panel.window.disposePanel(); panel.window.close(); } await act(async () => root.unmount()); await service?.manager.shutdown(); mcp.setPermissionMode('confirm'); mcp.cleanup(); aiBridge.cleanup(); privacy.configure({ enabled: false }); registerAppAppLockRuntime(oldLock); server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); dom.window.close(); diff --git a/components/PluginPermissionHost.test.tsx b/components/PluginPermissionHost.test.tsx index 1916e153c..810585e9b 100644 --- a/components/PluginPermissionHost.test.tsx +++ b/components/PluginPermissionHost.test.tsx @@ -5,6 +5,27 @@ import { JSDOM } from 'jsdom'; import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); +// Test-only observer preserves the security-surface visibility assertions. +function observePluginHostSecurityVisibility(mount: HTMLElement, publish: (visible: boolean) => void): () => void { + const document = mount.ownerDocument; + let visible = true; + const update = () => { + const blocked = [...document.querySelectorAll('[data-host-security-surface]')].some((surface) => { + const style = document.defaultView!.getComputedStyle(surface); + return style.display !== 'none' && style.visibility !== 'hidden' + && !surface.closest('[hidden], [inert], [aria-hidden="true"]'); + }); + if (visible === !blocked) return; + visible = !blocked; + publish(visible); + }; + const observer = new document.defaultView!.MutationObserver(update); + observer.observe(document.body, { childList: true, subtree: true, attributes: true, + attributeFilter: ['class', 'style', 'hidden', 'inert', 'aria-hidden', 'data-host-security-surface'] }); + update(); + return () => observer.disconnect(); +} + test('registered Ask uses one in-app dialog; policy controls apply Allow and Deny with no hidden prompt', async () => { const dom = new JSDOM('
', { pretendToBeVisual: true, url: 'http://localhost' }); const previous = new Map(); @@ -25,7 +46,6 @@ test('registered Ask uses one in-app dialog; policy controls apply Allow and Den const { I18nProvider } = await import('../application/i18n/I18nProvider'); const { PluginPermissionHost } = await import('./plugins/PluginPermissionHost'); const { PluginPermissionPanel } = await import('./settings/tabs/PluginPermissionPanel'); - const { observePluginHostSecurityVisibility } = await import('../application/state/pluginHostSecurityVisibility'); const { PluginPermissionDecisionHost } = require('../electron/plugins/permissionDecisionHost.cjs'); const { PluginPermissionEngine } = require('../electron/plugins/permissionEngine.cjs'); const { PluginHostRpcRegistry } = require('../electron/plugins/hostRpcRegistry.cjs'); diff --git a/components/PluginSelectedContextPermission.entrypoint.test.tsx b/components/PluginSelectedContextPermission.entrypoint.test.tsx index b06abb550..c322f5f59 100644 --- a/components/PluginSelectedContextPermission.entrypoint.test.tsx +++ b/components/PluginSelectedContextPermission.entrypoint.test.tsx @@ -69,8 +69,8 @@ test('registered selected-summary Ask is one host chooser; Allow still selects a await service.manager.initialize(); const stage = path.join(fixtureRoot, 'package'); fs.mkdirSync(path.join(stage, 'dist'), { recursive: true }); const sample = path.resolve('examples/plugins/assistant'); - for (const file of ['netcatty.plugin.json', 'panel.html', 'panel.css', 'panel.js', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(stage, file)); - fs.copyFileSync(path.join(sample, 'src/index.js'), path.join(stage, 'dist/index.js')); + for (const file of ['netcatty.plugin.json', 'README.md']) fs.copyFileSync(path.join(sample, file), path.join(stage, file)); + fs.copyFileSync(path.join(sample, 'dist/host.js'), path.join(stage, 'dist/host.js')); const { buildPluginPackage } = await import('@netcatty/plugin-cli'); const archive = path.join(fixtureRoot, 'assistant.ncpkg'); await buildPluginPackage(stage, archive); await service.manager.install(archive, { enable: true }); await act(async () => root.render()); diff --git a/components/PluginTerminalSidebar.test.tsx b/components/PluginTerminalSidebar.test.tsx index 92eb8588e..87b6e7488 100644 --- a/components/PluginTerminalSidebar.test.tsx +++ b/components/PluginTerminalSidebar.test.tsx @@ -14,11 +14,12 @@ test('terminal extension pages use actual split panes, focus and session ownersh install('PointerEvent', dom.window.MouseEvent); install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window)); install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window)); install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window)); install('IS_REACT_ACT_ENVIRONMENT', true); - let rectX = 200; + const rectX = 200; dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(rectX, 100, 400, 300); const { default: React, act, useCallback, useRef, useState } = await import('react'); const { createRoot } = await import('react-dom/client'); const { I18nProvider } = await import('../application/i18n/I18nProvider'); + const { TooltipProvider } = await import('./ui/tooltip'); const { activeTabStore } = await import('../application/state/activeTabStore'); const { sidePanelLiveStore, SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT } = await import('../application/state/sidePanelLiveStore'); const { useTerminalSidePanelLayoutState } = await import('../application/state/useTerminalSidePanelLayoutState'); @@ -30,22 +31,17 @@ test('terminal extension pages use actual split panes, focus and session ownersh type Tool = import('../domain/sidePanelLayout').SidePanelTool; let selectedSession = 'synthetic-session-a'; const getSession = () => selectedSession; - const a = { id: 'com.example.sidebar.first', title: 'First page', location: 'terminal-sidebar', entry: 'page.html', visible: true }; + const a = { id: 'com.example.sidebar.first', title: 'First page', location: 'terminal-sidebar', visible: true }; const b = { ...a, id: 'com.example.sidebar.second', title: 'Second page' }; let snapshot = { locale: 'en', plugins: [{ id: 'com.example.sidebar', displayName: 'Synthetic plugin', version: '1.0.0', commands: [], keybindings: [], menus: [], settings: [], views: [a, b] }] }; - const changed = new Set<() => void>(), focusListeners = new Set<(event: { instanceId: string }) => void>(); - const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [], focus: string[] = [], bounds: Array<{ instanceId: string; x: number }> = []; - const visible = new Map(); + const changed = new Set<() => void>(); + const opens: NetcattyPluginViewOpenRequest[] = []; Object.assign(dom.window, { netcatty: { async getPluginRuntimeStatus() { return { available: true }; }, async getPluginContributions() { return snapshot; }, onPluginContributionsChanged(fn: () => void) { changed.add(fn); return () => { changed.delete(fn); }; }, - onPluginViewClosed() { return () => {}; }, - onPluginViewFocused(fn: (event: { instanceId: string }) => void) { focusListeners.add(fn); return () => { focusListeners.delete(fn); }; }, - async openPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; }, - async closePluginView(id: string) { closes.push(id); }, - async setPluginViewBounds(id: string, rect: { x: number }) { bounds.push({ instanceId: id, x: rect.x }); }, - async setPluginViewVisibility(id: string, value: boolean) { visible.set(id, value); }, - async focusPluginView(event: { instanceId: string }) { focus.push(event.instanceId); for (const fn of focusListeners) fn(event); }, + onPluginViewClosed() { return () => {}; }, onHostDrawnPluginViewUpdate() { return () => {}; }, + async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; }, + async closeHostDrawnPluginView() {}, } }); let split!: () => void; function Fixture() { @@ -75,54 +71,44 @@ test('terminal extension pages use actual split panes, focus and session ownersh const page = model.pages.find((item) => item.tool === pane.tool); const target = hosts.get(pane.tool) ?? parking.current; if (!page || !target) return null; return - focusPane(pane.id)} unavailable={() => closePane(pane.id)} /> + focusPane(pane.id)} unavailable={() => closePane(pane.id)} /> ; })}; } const root = createRoot(document.getElementById('root')!); const settle = () => new Promise((resolve) => setTimeout(resolve, 40)); try { activeTabStore.setActiveTabId('workspace-synthetic'); sidePanelLiveStore.update({ ...SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT, focusedSessionId: selectedSession }); - await act(async () => { root.render(); await settle(); }); - await act(async () => { document.querySelector('button[aria-label="Extension pages"]')!.click(); await settle(); }); - const firstButton = [...document.querySelectorAll('button')].find((button) => button.textContent?.includes('First page'))!; + await act(async () => { root.render(); await settle(); }); + assert.equal(document.querySelector('button[aria-label="Extension pages"]'), null, 'pages do not require opening a grouped menu'); + assert.ok(document.querySelector('button[aria-label="Second page — Synthetic plugin"]'), 'each contributed page has a direct toolbar button'); + const firstButton = document.querySelector('button[aria-label="First page — Synthetic plugin"]')!; await act(async () => { firstButton.click(); await settle(); }); assert.equal(document.querySelectorAll('[data-section="terminal-side-panel-pane"]').length, 1); assert.ok(document.querySelector('[data-pane-tool] [data-plugin-view-slot="terminal-sidebar"]')); + assert.equal(document.querySelectorAll('[data-plugin-terminal-sidebar] header').length, 1); assert.equal(opens.length, 1); assert.deepEqual(opens[0].context, { 'netcatty.surface': 'terminal-sidebar' }); await act(async () => { split(); await settle(); }); assert.equal(document.querySelectorAll('[data-section="terminal-side-panel-pane"]').length, 2); + assert.equal(document.querySelectorAll('[data-plugin-terminal-sidebar] header').length, 0, 'split pane headers already identify both pages'); assert.equal(opens.length, 2); - const firstId = opens.find((item) => item.viewId === a.id)!.instanceId!; - await act(async () => { for (const fn of focusListeners) fn({ instanceId: firstId }); await settle(); }); + await act(async () => { document.querySelector(`[data-pane-tool="plugin-view:${a.id}"] [data-plugin-view-slot]`)!.dispatchEvent(new dom.window.FocusEvent('focusin', { bubbles: true })); await settle(); }); assert.equal(document.querySelector(`[data-pane-tool="plugin-view:${a.id}"]`)?.getAttribute('data-focused'), 'true'); - const dialog = document.createElement('div'); dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-modal', 'true'); - await act(async () => { document.body.append(dialog); await settle(); }); - assert.ok(opens.every((item) => visible.get(item.instanceId!) === false)); - focus.length = 0; - await act(async () => { dialog.remove(); await settle(); }); - assert.ok(focus.length > 0); assert.ok(focus.every((id) => id === firstId), 'restoring panes focuses only the host-selected pane'); - const old = opens.map((item) => item.instanceId!); - await act(async () => { selectedSession = 'synthetic-session-b'; sidePanelLiveStore.update({ ...SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT, focusedSessionId: selectedSession }); - assert.ok(old.every((id) => closes.includes(id)), 'workspace focus cancels old native owners synchronously'); await settle(); }); + await act(async () => { selectedSession = 'synthetic-session-b'; sidePanelLiveStore.update({ ...SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT, focusedSessionId: selectedSession }); await settle(); }); assert.equal(opens.length, 4); assert.notEqual(opens[0].scopeId, opens[2].scopeId); assert.ok(opens.every((item) => JSON.stringify(item.context) === JSON.stringify({ 'netcatty.surface': 'terminal-sidebar' }))); - await act(async () => { rectX = 260; snapshot = { ...snapshot, plugins: [{ ...snapshot.plugins[0], views: [{ ...a, visible: false }, b] }] }; for (const fn of changed) fn(); await settle(); }); + await act(async () => { snapshot = { ...snapshot, plugins: [{ ...snapshot.plugins[0], views: [{ ...a, visible: false }, b] }] }; for (const fn of changed) fn(); await settle(); }); assert.equal(document.querySelectorAll('[data-section="terminal-side-panel-pane"]').length, 1); assert.equal(document.querySelector('[data-pane-tool]')?.getAttribute('data-pane-tool'), `plugin-view:${b.id}`); - assert.ok(bounds.some((item) => item.x === 260), 'portal relocation updates native geometry'); - const last = opens.at(-1)!.instanceId!; - await act(async () => { activeTabStore.setActiveTabId('vault'); assert.ok(closes.includes(last)); await settle(); }); + await act(async () => { activeTabStore.setActiveTabId('vault'); await settle(); }); assert.equal(document.querySelector('[data-plugin-terminal-sidebar]'), null); await act(async () => { selectedSession = 'synthetic-local-terminal'; activeTabStore.setActiveTabId(selectedSession); await settle(); }); - await act(async () => { document.querySelector('button[aria-label="Extension pages"]')!.click(); await settle(); }); - const localPage = [...document.querySelectorAll('button')].find((button) => button.textContent?.includes('Second page'))!; + const localPage = document.querySelector('button[aria-label="Second page — Synthetic plugin"]')!; await act(async () => { localPage.click(); await settle(); }); assert.ok(document.querySelector('[data-plugin-view-slot="terminal-sidebar"]'), 'standalone Local Terminal is a valid navigation owner'); assert.deepEqual(opens.at(-1)!.context, { 'netcatty.surface': 'terminal-sidebar' }); } finally { - await act(async () => { root.unmount(); await settle(); }); dom.window.close(); + await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close(); for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } } }); diff --git a/components/PluginVaultPages.test.tsx b/components/PluginVaultPages.test.tsx index 4d2bb27c1..c23951477 100644 --- a/components/PluginVaultPages.test.tsx +++ b/components/PluginVaultPages.test.tsx @@ -21,24 +21,19 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w const { activeTabStore } = await import('../application/state/activeTabStore'); const { requestOpenPluginView } = await import('../application/state/usePluginViewLifecycle'); const { I18nProvider } = await import('../application/i18n/I18nProvider'); - const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', entry: 'page.html', visible: true }; + const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true }; let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; let changed: (() => void) | undefined; const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>(); - const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [], visibility: boolean[] = []; - let defer: ((value: { instanceId: string }) => void) | undefined; - let deferOpen = false; - let delayLayout = false; - const rejectOldLayout: Array<(error: Error) => void> = []; - const layoutResult = () => delayLayout ? new Promise((_resolve, reject) => { rejectOldLayout.push(reject); }) : Promise.resolve(); + const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = []; Object.assign(dom.window, { netcatty: { async getPluginRuntimeStatus() { return { available: true }; }, async getPluginContributions() { return snapshot; }, onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; }, onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; }, - async openPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return deferOpen ? new Promise<{ instanceId: string }>((resolve) => { defer = resolve; }) : { instanceId: payload.instanceId! }; }, - async closePluginView(id: string) { closes.push(id); }, async setPluginViewBounds() { await layoutResult(); }, - async setPluginViewVisibility(_id: string, visible: boolean) { visibility.push(visible); await layoutResult(); }, + onHostDrawnPluginViewUpdate() { return () => {}; }, + async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; }, + async closeHostDrawnPluginView(id: string) { closes.push(id); }, } }); let selectSection!: (section: 'hosts' | `plugin-vault:${string}`) => void; function Fixture() { @@ -58,44 +53,26 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w assert.ok(document.querySelector('[data-section="vault-main"] [data-plugin-view-slot="vault-page"]')); assert.equal(opens.length, 1); assert.deepEqual(opens[0].context, { 'netcatty.surface': 'vault-page' }, 'no Vault/session data accompanies navigation'); - assert.equal(visibility.at(-1), true); - const dialog = document.createElement('div'); dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-modal', 'true'); - await act(async () => { document.body.append(dialog); await settle(); }); - assert.equal(visibility.at(-1), false, 'native content yields to host security/settings dialogs'); - await act(async () => { dialog.remove(); await settle(); }); - assert.equal(visibility.at(-1), true); - await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); assert.ok(closes.includes(opens[0].instanceId!)); await settle(); }); + await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); }); + assert.equal(closes.length, 0, 'hiding keeps the logical view available'); await act(async () => { activeTabStore.setActiveTabId('vault'); await settle(); }); - assert.equal(opens.length, 2); + assert.equal(opens.length, 1, 'returning to Vault reuses the same plugin state'); await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); }); await act(async () => { await settle(); }); - assert.ok(closes.includes(opens[1].instanceId!)); + // The main process owns immediate invalidation on disable/uninstall. + await act(async () => { for (const listener of listeners) listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'plugin-disabled' }); }); + assert.ok(closes.includes(opens[0].instanceId!)); assert.equal(document.querySelector('[data-plugin-vault-page]'), null); assert.equal(document.activeElement?.textContent, 'Hosts'); await act(async () => { selectSection('plugin-vault:missing'); await settle(); }); assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/); await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); }); - deferOpen = true; await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); }); - assert.equal(opens.length, 3); + assert.equal(opens.length, 2); await act(async () => { selectSection('hosts'); await settle(); }); - assert.ok(closes.includes(opens[2].instanceId!), 'cancel reserved instance before its open response'); - await act(async () => { defer!({ instanceId: opens[2].instanceId! }); await settle(); }); - assert.equal(document.querySelector('[data-plugin-vault-page]'), null, 'late open cannot restore withdrawn page'); - assert.ok(closes.filter((id) => id === opens[2].instanceId).length >= 2, 'late native response is also closed'); - deferOpen = false; - const second = { ...page, id: 'com.example.page.second', title: 'Second page' }; - await act(async () => { snapshot = { ...snapshot, plugins: [{ ...snapshot.plugins[0], views: [page, second] }] }; changed?.(); await settle(); }); - delayLayout = true; - await clickPage(); - assert.ok(rejectOldLayout.length >= 2, 'old page has both bounds and visibility IPC in flight'); - await act(async () => { selectSection('hosts'); await settle(); }); - delayLayout = false; - await act(async () => { document.querySelector('button[aria-label="Second page — Synthetic plugin"]')!.click(); await settle(); }); - await act(async () => { for (const reject of rejectOldLayout) reject(new Error('old page layout failed')); await settle(); }); - assert.equal(document.querySelector('[data-plugin-vault-page]')?.getAttribute('aria-label'), 'Second page', 'old bounds/visibility failures cannot withdraw the newly selected page'); + assert.equal(document.querySelector('[data-plugin-vault-page]'), null); } finally { - await act(async () => { root.unmount(); await settle(); }); dom.window.close(); + await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close(); for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } } }); diff --git a/components/plugins/PluginContributionHost.tsx b/components/plugins/PluginContributionHost.tsx index 606b8887f..16d7d5df5 100644 --- a/components/plugins/PluginContributionHost.tsx +++ b/components/plugins/PluginContributionHost.tsx @@ -7,9 +7,12 @@ import { } from '../../application/state/usePluginViewLifecycle'; import { Button } from '../ui/button'; import { PluginContributionIcon } from './PluginContributionIcon'; +import { PluginHostDrawnPage } from './PluginHostDrawnPage'; export { requestOpenPluginView }; +const subscribeNoop = () => () => {}; + const DEFAULT_KEYBINDING_CONTEXT = Object.freeze({ 'netcatty.surface': 'keybinding' }); export function PluginContributionHost({ @@ -28,7 +31,7 @@ export function PluginContributionHost({ activeView, close, effectiveRequested, - mountRef, + viewQueryContext, } = usePluginViewLifecycle({ locale, theme, @@ -38,18 +41,24 @@ export function PluginContributionHost({ if (!effectiveRequested || !activeView) return null; const location = activeView.view.location; + const content = void close()} loadingLabel={t('plugins.vault.loading')} />; const containerClass = location === 'aside' ? 'absolute inset-y-0 right-0 z-40 w-[420px] border-l border-border bg-background shadow-2xl' + : location === 'tab' + ? 'absolute inset-0 z-40 flex p-2 pt-0' : location === 'panel' ? 'absolute inset-x-0 bottom-0 z-40 h-[42%] border-t border-border bg-background shadow-2xl' : location === 'modal' - ? 'fixed left-1/2 top-1/2 z-50 h-[70vh] w-[min(800px,85vw)] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-background shadow-2xl' + ? 'fixed left-1/2 top-1/2 z-40 h-[70vh] w-[min(800px,85vw)] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-background shadow-2xl' : 'absolute inset-0 z-40 bg-background'; if (location === 'tab') { return ( -
-
+
+
+ {content} +
); } @@ -58,6 +67,7 @@ export function PluginContributionHost({
@@ -80,7 +90,9 @@ export function PluginContributionHost({ -
+
+ {content} +
); } diff --git a/components/plugins/PluginHostDrawnPage.tsx b/components/plugins/PluginHostDrawnPage.tsx new file mode 100644 index 000000000..f11d053da --- /dev/null +++ b/components/plugins/PluginHostDrawnPage.tsx @@ -0,0 +1,15 @@ +import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView'; +import { PluginSettingsEntry } from './PluginSettingsEntry'; +import { PluginRemoteSurface } from './PluginRemoteSurface'; + +export function PluginHostDrawnPage(props: Parameters[0] & { loadingLabel: string; pluginId: string }) { + const view = useHostDrawnPluginView(props); + if (!view.visible) return null; + if (view.loading) return

{props.loadingLabel}

; + return
+ +
+ +
+
; +} diff --git a/components/plugins/PluginRemoteSurface.test.tsx b/components/plugins/PluginRemoteSurface.test.tsx new file mode 100644 index 000000000..7517520cb --- /dev/null +++ b/components/plugins/PluginRemoteSurface.test.tsx @@ -0,0 +1,130 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { JSDOM } from 'jsdom'; + +test('plugin surface forwards its own input and contains malformed updates and render errors', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'ShadowRoot']) { + saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] }); + } + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true }); + let captured: ShadowRoot | undefined; + const nativeAttach = dom.window.Element.prototype.attachShadow; + dom.window.Element.prototype.attachShadow = function (options) { captured = nativeAttach.call(this, options) as unknown as ShadowRoot; return captured as unknown as globalThis.ShadowRoot; }; + const { default: React, act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { PluginRemoteSurface } = await import('./PluginRemoteSurface'); + const events: unknown[] = []; + const tree = { children: [{ id: '1', type: 1, element: 'div', attributes: { class: 'card', style: 'display:grid;gap:8px' }, children: [ + { id: '2', type: 1, element: 'button', attributes: { type: 'button', 'data-netcatty-remote-node': 'forged' }, children: [{ id: '3', type: 3, data: 'Hello' }] }, + { id: '4', type: 1, element: 'input', attributes: { type: 'text', value: '' }, children: [] }, + ] }] }; + const root = createRoot(document.getElementById('root')!); + try { + await act(async () => { root.render( events.push(event)} />); }); + assert.ok(captured); assert.equal(document.querySelector('[data-plugin-remote-surface]')?.querySelector('button'), null); + assert.equal(captured!.querySelector('button')?.textContent, 'Hello'); + assert.equal(captured!.querySelector('button')?.getAttribute('data-netcatty-remote-node'), '2'); + await act(async () => { captured!.querySelector('button')!.click(); }); + assert.deepEqual(events, [{ nodeId: '2', type: 'click' }]); + const input = captured!.querySelector('input')!; input.value = 'typed'; + await act(async () => { input.dispatchEvent(new dom.window.Event('input', { bubbles: true })); }); + assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed' }); + await act(async () => { document.getElementById('host')!.dispatchEvent(new dom.window.Event('input', { bubbles: true })); }); + assert.equal(events.length, 2); + await act(async () => { root.render( {}} />); }); + assert.equal(document.querySelector('[role=alert]')?.textContent, 'Unable to display plugin view.'); + let clicks = 0; + const renderView = async (nextTree: unknown) => act(async () => root.render(<> + {}} /> + + {}} /> + )); + await renderView(tree); + await renderView({ children: [{ id: 'bad', type: 1, element: 'input', attributes: {}, children: [{ id: 'text', type: 3, data: 'invalid' }] }] }); + assert.equal(document.querySelectorAll('[data-plugin-remote-surface]').length, 1); + assert.ok(document.querySelector('[role=alert]')); + await act(async () => document.getElementById('canary')!.click()); + assert.equal(clicks, 1); + // Validated data can still hit a React rendering constraint. Contain that + // descendant throw too, independently of the policy rejection above. + const originalError = console.error; + try { + console.error = () => {}; + await renderView({ children: [{ id: 'bad', type: 1, element: 'textarea', attributes: {}, children: [ + { id: 'a', type: 3, data: 'one' }, { id: 'b', type: 3, data: 'two' }, + ] }] }); + } finally { console.error = originalError; } + assert.equal(document.querySelectorAll('[data-plugin-remote-surface]').length, 1); + assert.ok(document.querySelector('[role=alert]')); + await act(async () => document.getElementById('canary')!.click()); + assert.equal(clicks, 2); + } finally { + await act(async () => { root.unmount(); }); + for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); } + Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); dom.window.close(); + } +}); + +test('closed-shadow editing keeps app close shortcuts in Vault, sidebar, tabs and popovers', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const [key, value] of Object.entries({ window: dom.window, document: dom.window.document, navigator: dom.window.navigator, + HTMLElement: dom.window.HTMLElement, Element: dom.window.Element, Node: dom.window.Node, IS_REACT_ACT_ENVIRONMENT: true })) { + saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + } + dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 20, y: 20, width: 240, height: 30, top: 20, left: 20, right: 260, bottom: 50, toJSON() {} }); + Object.assign(dom.window, { ResizeObserver: class { observe() {} disconnect() {} } }); + const shadows: ShadowRoot[] = []; + const nativeAttach = dom.window.Element.prototype.attachShadow; + dom.window.Element.prototype.attachShadow = function (options) { + const shadow = nativeAttach.call(this, options); shadows.push(shadow as unknown as ShadowRoot); return shadow; + }; + const { act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { PluginRemoteSurface } = await import('./PluginRemoteSurface'); + const { handleGlobalHotkeyKeyDownImpl } = await import('../../application/app/AppHandlers'); + const { isPluginViewEditingTarget, isPluginShortcutEditableEvent } = await import('../../application/state/pluginKeybindings'); + const { matchesKeyBinding } = await import('../../domain/models'); + const { DEFAULT_KEY_BINDINGS } = await import('../../domain/models/keyBindings'); + const actions: string[] = []; + const capture = (event: KeyboardEvent) => handleGlobalHotkeyKeyDownImpl(() => ({ + HOTKEY_DEBUG: false, closeTabKeyStr: 'Ctrl + W', hotkeyScheme: 'pc', keyBindings: DEFAULT_KEY_BINDINGS, matchesKeyBinding, + executeHotkeyAction: (action: string) => actions.push(action), + }), event); + dom.window.addEventListener('keydown', capture as unknown as EventListener, true); + const control = (id: string, element: string, attributes = {}) => ({ id, type: 1, element, attributes, children: [] }); + const tree = { children: [control('input', 'input'), control('textarea', 'textarea'), control('anchor', 'button', { id: 'anchor' }), + { ...control('popover', 'div', { 'data-plugin-popover': 'true', 'data-plugin-anchor': 'anchor', open: '' }), children: [control('pop-input', 'input'), control('pop-textarea', 'textarea')] }, + ] }; + const root = createRoot(document.getElementById('root')!); + try { + for (const slot of ['vault-page', 'terminal-sidebar', 'plugin-tab']) { + shadows.length = 0; + await act(async () => root.render(
{}} />
)); + assert.equal(shadows.length, 2, 'includes the portaled popover surface'); + for (const shadow of shadows) { + for (const element of shadow.querySelectorAll('input,textarea')) { + await act(async () => element.focus()); + // Native menu IPC sees this same retargeted document.activeElement. + assert.equal(isPluginViewEditingTarget(document.activeElement), true, `${slot}: ${element.tagName}`); + let editable = false; + const observe = (event: Event) => { editable = isPluginShortcutEditableEvent(event); assert.equal(event.target, shadow.host); }; + dom.window.addEventListener('keydown', observe, { once: true }); + await act(async () => element.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'w', code: 'KeyW', ctrlKey: true, bubbles: true, composed: true, cancelable: true }))); + assert.equal(editable, true); + assert.deepEqual(actions, []); + } + } + await act(async () => (shadows[0].querySelector('button') as HTMLButtonElement).focus()); + assert.equal(isPluginViewEditingTarget(document.activeElement), false, 'focus marker clears when editing ends'); + } + } finally { + dom.window.removeEventListener('keydown', capture as unknown as EventListener, true); + await act(async () => root.unmount()); dom.window.close(); + for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); } + } +}); diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx new file mode 100644 index 000000000..1dcf96afb --- /dev/null +++ b/components/plugins/PluginRemoteSurface.tsx @@ -0,0 +1,120 @@ +import React, { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { LazyLoadBoundary } from '../ui/lazy-load-boundary'; +import { PluginViewPopover } from './PluginViewPopover'; +import { createPortal } from 'react-dom'; +import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs'; +import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs'; + +type RemoteNode = { id: string; type: 3; data: string } | { id: string; type: 8; data: string } | { + id: string; type: 1; element: string; attributes: Record; children: RemoteNode[]; +}; +export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnViewEvent; +const ATTRIBUTE_NAMES: Record = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' }; +const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']); + +const SurfaceContext = createContext<{ css: string; onEvent(event: PluginSurfaceEvent): void; depth: number }>({ css: '', onEvent: () => {}, depth: 0 }); +const ResourceLoader = createContext<((path: string) => Promise) | undefined>(undefined); + +function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }): React.ReactNode { + const attrs = node.type === 1 ? node.attributes : {}; + const surface = useContext(SurfaceContext); + const loadImage = useContext(ResourceLoader); + const imagePath = node.type === 1 && node.element === 'img' ? attrs.src?.slice(6) : undefined; + const [imageUrl, setImageUrl] = useState(); + useEffect(() => { + let cancelled = false; setImageUrl(undefined); + if (imagePath && loadImage) void loadImage(imagePath).then((url) => { if (!cancelled) setImageUrl(url); }).catch(() => {}); + return () => { cancelled = true; }; + }, [imagePath, loadImage]); + const remoteSelection = JSON.stringify(node.type === 1 && node.element === 'select' + ? node.children.filter((child) => child.type === 1 && child.element === 'option' && Object.hasOwn(child.attributes, 'selected')).map((child) => child.type === 1 ? child.attributes.value ?? '' : '') : []); + const [localSelection, setLocalSelection] = useState(() => JSON.parse(remoteSelection)); + useEffect(() => { if (settled) setLocalSelection(JSON.parse(remoteSelection)); }, [remoteSelection, settled]); + const remoteValue = attrs.value; + const remoteChecked = Object.hasOwn(attrs, 'checked'); + const [localValue, setLocalValue] = useState(remoteValue ?? ''); + const [localChecked, setLocalChecked] = useState(remoteChecked); + useEffect(() => { if (settled && remoteValue !== undefined) setLocalValue(remoteValue); }, [remoteValue, settled]); + useEffect(() => { if (settled) setLocalChecked(remoteChecked); }, [remoteChecked, settled]); + if (node.type === 3) return node.data; + if (node.type === 8) return null; + if (attrs['data-plugin-popover'] === 'true') return surface.depth < 1 ? surface.onEvent({ nodeId: node.id, type: 'dismiss' })}> : null; + const props: Record = { 'data-netcatty-remote-node': node.id }; + let inlineStyle: string | undefined; + for (const [name, value] of Object.entries(node.attributes)) { + if (name === 'src' || (node.element === 'option' && name === 'selected')) continue; + if (name === 'style') { inlineStyle = value; continue; } + if (name === 'data-netcatty-remote-node') continue; + props[ATTRIBUTE_NAMES[name] ?? name] = BOOLEAN_ATTRIBUTES.has(name) ? true : value; + } + // The policy validated this declaration list before this component rendered. + props.ref = (el: HTMLElement | null) => { if (el) { if (inlineStyle === undefined) el.removeAttribute('style'); else el.setAttribute('style', inlineStyle); } }; + if (node.element === 'img') props.src = imageUrl; + if (node.element === 'form') props.onSubmit = (event: React.FormEvent) => event.preventDefault(); + if (['input', 'select', 'textarea'].includes(node.element)) { + if (node.element === 'select' && Object.hasOwn(attrs, 'multiple')) props.value = localSelection; + else if (remoteValue !== undefined) props.value = localValue; + props.autoComplete = 'off'; + if (node.element === 'input' && ['checkbox', 'radio'].includes(attrs.type ?? '')) props.checked = localChecked; + props.onChange = (event: React.ChangeEvent) => { + setLocalValue(event.currentTarget.value); + if (event.currentTarget instanceof event.currentTarget.ownerDocument.defaultView!.HTMLSelectElement && event.currentTarget.multiple) setLocalSelection([...event.currentTarget.selectedOptions].map((option) => option.value)); + if (event.currentTarget instanceof event.currentTarget.ownerDocument.defaultView!.HTMLInputElement) setLocalChecked(event.currentTarget.checked); + }; + } + return React.createElement(node.element, props, ...(node.element === 'textarea' && remoteValue !== undefined ? [] : node.children).map((child) => )); +} + +/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */ +export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise; onEvent(event: PluginSurfaceEvent): void }) { + const checked = useMemo(() => { + try { + validatePluginRemoteTree(tree); + return { tree: tree as { children: RemoteNode[] }, css: validatePluginStylesheet(css) }; + } catch { return null; } + }, [tree, css]); + if (!checked) return

Unable to display plugin view.

; + return Unable to display plugin view.

}>
; +} + +function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled: boolean; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) { + const hostRef = useRef(null); + const onEventRef = useRef(onEvent); onEventRef.current = onEvent; + const shadowRef = useRef(null); + const [shadow, setShadow] = useState(null); + useLayoutEffect(() => { + const host = hostRef.current; + if (!host) return; + // The same DOM node can be mounted twice in React Strict Mode. + const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' }); + shadowRef.current = root; + setShadow(root); + }, []); + useEffect(() => { + if (!shadow) return; + const listener = (event: Event) => { + const target = event.target; + const view = shadow.ownerDocument.defaultView; + if (!view || !(target instanceof view.HTMLElement) || !['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset'].includes(event.type)) return; + // Closed-shadow events hide their editable target from window capture. + if (event.type === 'focusin') hostRef.current?.toggleAttribute('data-plugin-editing', target.matches('input, textarea, select, [contenteditable]')); + if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing'); + if (event.type === 'submit') event.preventDefault(); + const nodeId = target.dataset.netcattyRemoteNode; + if (!nodeId) return; + const value = target instanceof view.HTMLInputElement || target instanceof view.HTMLTextAreaElement || target instanceof view.HTMLSelectElement ? target.value : undefined; + const values = target instanceof view.HTMLSelectElement && target.multiple ? [...target.selectedOptions].map((option) => option.value) : undefined; + const checkedValue = target instanceof view.HTMLInputElement && ['checkbox', 'radio'].includes(target.type) ? target.checked : undefined; + if (value !== undefined && value.length > 8192) return; + const keyboard = event instanceof view.KeyboardEvent && event.key.length <= 64 + ? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey } : {}; + onEventRef.current({ nodeId, type: event.type as PluginSurfaceEvent['type'], ...(value === undefined ? {} : { value }), ...(checkedValue === undefined ? {} : { checked: checkedValue }), ...keyboard, ...(values ? { values } : {}), ...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}) }); + }; + for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.addEventListener(event, listener, true); + return () => { for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.removeEventListener(event, listener, true); }; + }, [shadow]); + return
+
+ {shadow && createPortal(<>{tree.children.map((node) => )}, shadow)} +
; +} diff --git a/components/plugins/PluginSettingsEntry.tsx b/components/plugins/PluginSettingsEntry.tsx new file mode 100644 index 000000000..f38705595 --- /dev/null +++ b/components/plugins/PluginSettingsEntry.tsx @@ -0,0 +1,85 @@ +import { Settings } from 'lucide-react'; +import { useEffect, useRef, useState, type RefObject } from 'react'; +import { useI18n } from '../../application/i18n/I18nProvider'; +import { usePluginContributions } from '../../application/state/usePluginContributions'; +import { usePluginSettingsModel } from '../../application/state/usePluginSettingsModel'; +import { useAvailableFonts } from '../../application/state/fontStore'; +import { Button } from '../ui/button'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog'; +import { PluginSettingGroups } from './PluginSettingsForm'; + +export const pluginSettingsButtonClass = 'h-8 w-8 shrink-0 rounded-full border border-border/60 bg-background/95 shadow-sm hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2'; + +export function PluginSettingsDialog({ pluginId, onClose, restoreFocusTo }: { + pluginId: string; + onClose: () => void; + restoreFocusTo: RefObject; +}) { + const { t } = useI18n(); + const model = usePluginSettingsModel(pluginId); + const fonts = useAvailableFonts(); + useEffect(() => { + if (!model.loading && !model.error && !model.settings.length) onClose(); + }, [model.loading, model.error, model.settings.length, onClose]); + return { if (!open) onClose(); }}> + event.stopPropagation()} + onCloseAutoFocus={event => { + const element = restoreFocusTo.current; + if (element?.isConnected && !element.matches(':disabled')) { + event.preventDefault(); element.focus({ preventScroll: true }); + } + }}> + + + + +
+ {model.loading &&

{t('settings.plugins.loading')}

} + {model.error &&

{model.error.message}

} + {model.contextualScopes.length > 0 &&
+ {model.contextualScopes.map(kind => )} +
} +
+ +
+
+
+
; +} + +function AvailableSettingsEntry({ pluginId, name }: { pluginId: string; name: string }) { + const { t } = useI18n(); + const [open, setOpen] = useState(false); + const opener = useRef(null); + return <> +
+ +
+ {open && setOpen(false)} restoreFocusTo={opener} />} + ; +} + +export function PluginSettingsEntry({ pluginId }: { pluginId: string }) { + const { locale } = useI18n(); + const contributions = usePluginContributions({ locale, context: { 'netcatty.surface': 'settings' } }); + const plugin = contributions.snapshot.plugins.find(item => item.id === pluginId); + if (!plugin?.settings.some(setting => setting.visible)) return null; + // Removing or replacing the owning contribution also discards its open dialog. + return ; +} diff --git a/components/plugins/PluginSettingsForm.tsx b/components/plugins/PluginSettingsForm.tsx new file mode 100644 index 000000000..01bda9b18 --- /dev/null +++ b/components/plugins/PluginSettingsForm.tsx @@ -0,0 +1,275 @@ +import React, { useEffect, useState } from 'react'; +import { FolderOpen, RotateCcw } from 'lucide-react'; +import { normalizePluginKeyboardEvent } from '../../application/state/pluginKeybindings'; +import { usePluginContributions } from '../../application/state/usePluginContributions'; +import { useI18n } from '../../application/i18n/I18nProvider'; +import { useAvailableFonts } from '../../application/state/fontStore'; +import { Button } from '../ui/button'; +import { Input } from '../ui/input'; +import { Toggle } from '../settings/settings-ui'; +import { parsePluginStructuredSettingValue } from '../settings/tabs/pluginSettingValues'; +import { PluginStructuredSettingEditor } from '../settings/tabs/PluginStructuredSettingEditor'; +import { TerminalFontSelect } from '../settings/TerminalFontSelect'; + +export function PluginSettingField({ + pluginId, + setting, + updateSetting, + resetSetting, + selectSettingPath, + availableFonts, +}: { + pluginId: string; + setting: NetcattyPluginSettingContribution; + updateSetting: ReturnType['updateSetting']; + resetSetting: ReturnType['resetSetting']; + selectSettingPath: ReturnType['selectSettingPath']; + availableFonts: ReturnType; +}) { + const { t } = useI18n(); + const [value, setValue] = useState(setting.secret ? '' : setting.value ?? ''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const itemLabel = (key: 'settings.plugins.moveItemUp' | 'settings.plugins.moveItemDown', index: number) => ( + t(key).replace('{label}', setting.label).replace('{index}', String(index + 1)) + ); + + useEffect(() => { + setValue(setting.secret ? '' : setting.value ?? ''); + }, [setting.secret, setting.value]); + + const save = async (nextValue: unknown) => { + setSaving(true); + setError(null); + try { + await updateSetting(pluginId, setting.id, nextValue, setting.scopeId ?? undefined); + if (setting.secret) setValue(''); + } catch (cause) { + setError(cause instanceof Error ? cause.message : String(cause)); + } finally { + setSaving(false); + } + }; + + const control = (() => { + if (setting.scopeId == null) { + return
{t('settings.plugins.scopeContext').replace('{scope}', setting.scope)}
; + } + if (setting.control === 'switch') { + return { setValue(next); void save(next); }} />; + } + if (setting.control === 'radio') { + return ( +
+ {setting.label} + {setting.options?.map((option) => ( + + ))} +
+ ); + } + if (setting.control === 'select') { + return ( + + ); + } + if (setting.control === 'multiselect') { + const selected = Array.isArray(value) ? value.map(String) : []; + return ( + + ); + } + if (setting.control === 'textarea') { + return ( +
Loading configured backends…
-
Actions follow this plugin's Allow / Ask / Deny setting.
+
Actions follow this plugin's Allow / Ask / Deny setting.
diff --git a/examples/plugins/hello-react-host/LICENSE b/examples/plugins/hello-react-host/LICENSE new file mode 100644 index 000000000..2ed3ce57d --- /dev/null +++ b/examples/plugins/hello-react-host/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Netcatty example contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/examples/plugins/hello-react-host/README.md b/examples/plugins/hello-react-host/README.md new file mode 100644 index 000000000..502e35e6a --- /dev/null +++ b/examples/plugins/hello-react-host/README.md @@ -0,0 +1,22 @@ +# Hello React: host-rendered plugin UI + +This example uses ordinary React and custom CSS. Netcatty draws its visible UI; +the script runs in the isolated runtime and requests `views` and `settings.read` (its own settings only). + +Build: `npm run build --workspace @netcatty/example-hello-react-host`. +Package this folder with the plugin CLI and install the `.ncpkg` from Settings. +No development environment flag is needed for this browser example. + +It declares Vault, terminal sidebar, tab, aside, panel and modal views. +Its Settings entry is a standard Netcatty form with greeting, appearance and +content groups. Name, greeting enabled, accent color and default note are saved +by the host and applied to new pages and already-open pages. Demo edits inside +a page remain local; use Settings to change persistent defaults. +Try text/Chinese input, reset, checkbox, select, a package image and the custom +menu. Close and reopen a sidebar: its registered tool remains available. Hidden +views retain their own state within the host's five-minute/16-instance cache. + +The view permission grants no host data. User-entered text is handled by the +plugin. Unsafe elements, external resources and escaping styles are rejected; +ordinary React support does not guarantee every third-party browser library. +See `docs/plugin-platform/host-rendered-ui.md` for the supported contract. diff --git a/examples/plugins/hello-react-host/build.mjs b/examples/plugins/hello-react-host/build.mjs new file mode 100644 index 000000000..5ab5a6e33 --- /dev/null +++ b/examples/plugins/hello-react-host/build.mjs @@ -0,0 +1,5 @@ +import { build } from 'esbuild'; +import { fileURLToPath, URL } from 'node:url'; +await build({ entryPoints: [fileURLToPath(new URL('./src/index.tsx', import.meta.url))], outfile: fileURLToPath(new URL('./dist/index.js', import.meta.url)), bundle: true, platform: 'browser', format: 'esm', + plugins: [{ name: 'host-sdk', setup(buildApi) { buildApi.onResolve({ filter: /^@netcatty\/plugin-sdk$/ }, (args) => ({ path: args.path, external: true })); } }], + define: { 'process.env.NODE_ENV': '"production"' }, minify: true }); diff --git a/examples/plugins/hello-react-host/mark.svg b/examples/plugins/hello-react-host/mark.svg new file mode 100644 index 000000000..e796a563d --- /dev/null +++ b/examples/plugins/hello-react-host/mark.svg @@ -0,0 +1 @@ + diff --git a/examples/plugins/hello-react-host/netcatty.plugin.json b/examples/plugins/hello-react-host/netcatty.plugin.json new file mode 100644 index 000000000..9b8e8cd16 --- /dev/null +++ b/examples/plugins/hello-react-host/netcatty.plugin.json @@ -0,0 +1,173 @@ +{ + "manifestVersion": 1, + "id": "com.netcatty.hello-react-host", + "name": "hello-react-host", + "displayName": { + "en": "Hello React", + "zh-CN": "你好,React" + }, + "description": "Freely styled pages with standard, persistent Netcatty settings. No host data access.", + "version": "0.2.0", + "publisher": "netcatty", + "license": "MIT", + "engines": { + "netcatty": ">=0.0.0", + "api": ">=0.1.0-internal.1 <0.2.0" + }, + "features": { + "required": [ + "views.vault-pages", + "views.terminal-sidebar", + "views.host-drawn" + ] + }, + "main": { + "browser": "dist/index.js" + }, + "activationEvents": [ + "onView:com.netcatty.hello-react-host.vault", + "onView:com.netcatty.hello-react-host.sidebar", + "onView:com.netcatty.hello-react-host.tab", + "onView:com.netcatty.hello-react-host.aside", + "onView:com.netcatty.hello-react-host.panel", + "onView:com.netcatty.hello-react-host.modal" + ], + "permissions": { + "required": [ + "views", + "settings.read" + ] + }, + "contributes": { + "views": [ + { + "id": "com.netcatty.hello-react-host.vault", + "title": { + "en": "Hello · Vault", + "zh-CN": "你好 · Vault 页面" + }, + "location": "vault-page" + }, + { + "id": "com.netcatty.hello-react-host.sidebar", + "title": { + "en": "Hello · Sidebar", + "zh-CN": "你好 · 终端侧栏" + }, + "location": "terminal-sidebar" + }, + { + "id": "com.netcatty.hello-react-host.tab", + "title": { + "en": "Hello · Tab", + "zh-CN": "你好 · 独立标签页" + }, + "location": "tab" + }, + { + "id": "com.netcatty.hello-react-host.aside", + "title": { + "en": "Hello · Aside", + "zh-CN": "你好 · 侧边面板" + }, + "location": "aside" + }, + { + "id": "com.netcatty.hello-react-host.panel", + "title": { + "en": "Hello · Panel", + "zh-CN": "你好 · 底部面板" + }, + "location": "panel" + }, + { + "id": "com.netcatty.hello-react-host.modal", + "title": { + "en": "Hello · Modal", + "zh-CN": "你好 · 弹窗" + }, + "location": "modal" + } + ], + "settings": [ + { + "id": "com.netcatty.hello-react-host.name", + "label": { + "en": "Default name", + "zh-CN": "默认称呼" + }, + "group": { + "en": "Greeting", + "zh-CN": "问候" + }, + "description": { + "en": "Used when opening a new plugin page.", + "zh-CN": "用于新打开的插件页面。" + }, + "control": "text", + "scope": "application", + "default": "", + "pattern": "^.{0,40}$" + }, + { + "id": "com.netcatty.hello-react-host.enabled", + "label": { + "en": "Enable greeting", + "zh-CN": "启用问候" + }, + "group": { + "en": "Greeting", + "zh-CN": "问候" + }, + "control": "switch", + "scope": "application", + "default": true + }, + { + "id": "com.netcatty.hello-react-host.color", + "label": { + "en": "Accent color", + "zh-CN": "强调颜色" + }, + "group": { + "en": "Appearance", + "zh-CN": "外观" + }, + "control": "select", + "scope": "application", + "default": "blue", + "options": [ + { + "value": "blue", + "label": { + "en": "Blue", + "zh-CN": "蓝色" + } + }, + { + "value": "green", + "label": { + "en": "Green", + "zh-CN": "绿色" + } + } + ] + }, + { + "id": "com.netcatty.hello-react-host.note", + "label": { + "en": "Default note", + "zh-CN": "默认便签" + }, + "group": { + "en": "Content", + "zh-CN": "内容" + }, + "control": "textarea", + "scope": "application", + "default": "", + "pattern": "^[\\s\\S]{0,500}$" + } + ] + } +} diff --git a/examples/plugins/hello-react-host/package.json b/examples/plugins/hello-react-host/package.json new file mode 100644 index 000000000..d05c91c43 --- /dev/null +++ b/examples/plugins/hello-react-host/package.json @@ -0,0 +1,8 @@ +{ + "name": "@netcatty/example-hello-react-host", + "version": "0.2.0", + "private": true, + "type": "module", + "scripts": { "build": "node build.mjs" }, + "dependencies": { "@netcatty/plugin-sdk": "0.1.0-internal.1", "react": "^19.2.1", "react-dom": "^19.2.1" } +} diff --git a/examples/plugins/hello-react-host/src/index.tsx b/examples/plugins/hello-react-host/src/index.tsx new file mode 100644 index 000000000..f04cc2331 --- /dev/null +++ b/examples/plugins/hello-react-host/src/index.tsx @@ -0,0 +1,67 @@ +import React, { useEffect, useState } from 'react'; +import { definePlugin, type PluginContext } from '@netcatty/plugin-sdk'; +import { registerHostReactView, PluginPopover } from '@netcatty/plugin-sdk/host-react'; + +const css = ` +.page { max-width: 760px; padding: 24px; margin: 0 auto; color: hsl(var(--foreground)); font: 14px/1.5 system-ui, sans-serif; } +.badge { color: hsl(var(--primary)); font-size: 11px; font-weight: 700; letter-spacing: .12em; } +h1 { font-size: 26px; margin: 8px 0; } p { color: hsl(var(--muted-foreground)); } +.card { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; margin-top: 24px; padding: 20px; border: 1px solid hsl(var(--border)); border-radius: 12px; background: hsl(var(--muted)); } +textarea, select { padding: 9px; background: hsl(var(--background)); color: inherit; border: 1px solid hsl(var(--border)); border-radius: 6px; } +.check { display: flex; align-items: center; gap: 8px; } .check input { width: 16px; height: 16px; padding: 0; } +label { display: grid; gap: 8px; } input { padding: 9px; border: 1px solid hsl(var(--border)); border-radius: 6px; background: hsl(var(--background)); color: inherit; } +button { border: 0; border-radius: 6px; padding: 10px 16px; background: hsl(var(--primary)); color: hsl(var(--primary-foreground)); cursor: pointer; } +button:hover { opacity: .85; } button:disabled { opacity: .45; cursor: default; } +.page[data-color="green"] { --plugin-accent: 145 65% 36%; } +.page[data-color="green"] button { background: hsl(var(--plugin-accent)); } .result { grid-column: 1 / -1; margin: 0; } +@container (max-width: 420px) { .card { grid-template-columns: 1fr; } } +`; +function Hello({ settings }: { settings: PluginContext['settings'] }) { + const [name, setName] = useState(''); const [greeting, setGreeting] = useState(''); + const [enabled, setEnabled] = useState(true); const [color, setColor] = useState('blue'); const [note, setNote] = useState(''); const [menu, setMenu] = useState(false); + const [settingsError, setSettingsError] = useState(''); + const [settingsReady, setSettingsReady] = useState(false); + useEffect(() => { + let disposed = false; + const revisions = new Map(); + const apply = async (key: string) => { + const revision = (revisions.get(key) ?? 0) + 1; + revisions.set(key, revision); + try { + const value = await settings.get(`com.netcatty.hello-react-host.${key}`); + if (disposed || revisions.get(key) !== revision) return; + if (key === 'name') setName(typeof value === 'string' ? value : ''); + if (key === 'enabled') setEnabled(value !== false); + if (key === 'color') setColor(value === 'green' ? 'green' : 'blue'); + if (key === 'note') setNote(typeof value === 'string' ? value : ''); + } catch { + if (!disposed) setSettingsError('无法读取插件设置,请检查该插件的设置读取权限。'); + } + }; + const subscription = settings.onDidChange(({ settingId }) => { + const key = settingId.slice('com.netcatty.hello-react-host.'.length); + if (['name', 'enabled', 'color', 'note'].includes(key)) void apply(key); + }); + void Promise.all(['name', 'enabled', 'color', 'note'].map(apply)).then(() => { + if (!disposed) setSettingsReady(true); + }); + return () => { disposed = true; subscription.dispose(); }; + }, [settings]); + if (!settingsReady) return

正在读取插件设置…

; + return
Example markNETCATTY · HELLO

你好,世界!

一个融入 Netcatty 的小工作台。试试问候、便签和菜单。

+ {settingsError &&

{settingsError}

} +
+

{greeting}

+
+ +
diff --git a/examples/plugins/session-scratchpad/page.js b/examples/plugins/session-scratchpad/page.js index ebf3590eb..7697263ef 100644 --- a/examples/plugins/session-scratchpad/page.js +++ b/examples/plugins/session-scratchpad/page.js @@ -1,25 +1,28 @@ -"use strict"; -/* global document, window */ -const draft = document.getElementById("draft"); -const status = document.getElementById("status"); +export function mount(root, context, viewId, stateScope) { + const cleanup = []; +const draft = root.querySelector("#" + "draft"); +const status = root.querySelector("#" + "status"); let busy = false; async function save(clear) { if (busy) return; busy = true; try { const text = clear ? "" : draft.value; - await window.netcattyView.setState({ version: 1, text }); + await context.views.setState(viewId, stateScope, { version: 1, text }); if (clear) draft.value = ""; status.textContent = clear ? "Draft cleared." : "Draft saved in this plugin only."; } catch { status.textContent = "Could not save this draft."; } finally { busy = false; } } -document.getElementById("save").addEventListener("click", () => { void save(false); }); -document.getElementById("clear").addEventListener("click", () => { void save(true); }); -window.netcattyView.getState().then((state) => { +root.querySelector("#" + "save").addEventListener("click", () => { void save(false); }); +root.querySelector("#" + "clear").addEventListener("click", () => { void save(true); }); +context.views.getState(viewId, stateScope).then((state) => { if (state?.version === 1 && typeof state.text === "string" && state.text.length <= 4096) draft.value = state.text; status.textContent = "Ready. Use synthetic text for this example."; draft.disabled = false; - document.getElementById("save").disabled = false; - document.getElementById("clear").disabled = false; + root.querySelector("#" + "save").disabled = false; + root.querySelector("#" + "clear").disabled = false; }).catch(() => { status.textContent = "Could not load this plugin draft."; }); + + return () => { for (const stop of cleanup) stop(); }; +} diff --git a/examples/plugins/session-scratchpad/theme.js b/examples/plugins/session-scratchpad/theme.js deleted file mode 100644 index b1809b4bb..000000000 --- a/examples/plugins/session-scratchpad/theme.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* global document, window */ -// This page owns its DOM. Only the host's public semantic colors are copied. -(() => { - const names = ["--background", "--foreground", "--muted", "--muted-foreground", "--border", "--primary", "--primary-foreground"]; - let subscription; - const subscribe = () => { - if (subscription) return; - subscription = window.netcattyView.onDidChangeEnvironment((environment) => { - const root = document.documentElement; - root.style.colorScheme = environment.theme === "system" ? "light dark" : environment.theme; - root.dataset.reducedMotion = String(Boolean(environment.reducedMotion)); - root.dataset.highContrast = String(Boolean(environment.highContrast)); - for (const name of names) { - const value = environment.themeTokens?.[name]; - if (typeof value === "string" && value.length <= 96) root.style.setProperty(name, value); - else root.style.removeProperty(name); - } - }); - }; - subscribe(); - window.addEventListener("pagehide", () => { subscription?.dispose(); subscription = undefined; }); - window.addEventListener("pageshow", subscribe); -})(); diff --git a/examples/plugins/starter-netcatty/panel.css b/examples/plugins/session-scratchpad/view.css similarity index 76% rename from examples/plugins/starter-netcatty/panel.css rename to examples/plugins/session-scratchpad/view.css index 2d9eec62e..f199be4b2 100644 --- a/examples/plugins/starter-netcatty/panel.css +++ b/examples/plugins/session-scratchpad/view.css @@ -1,6 +1,7 @@ -:root { color-scheme: light dark; font: 14px/1.6 system-ui, sans-serif; } + .plugin-page { min-height:100%; color:hsl(var(--foreground)); background:hsl(var(--background)); font:14px/1.5 system-ui,sans-serif; } +.plugin-page { color-scheme: light dark; font: 14px/1.6 system-ui, sans-serif; } * { box-sizing: border-box; } -body { margin: 0; padding: 24px; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 12%)); } +.plugin-page { margin: 0; padding: 24px; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 12%)); } main { min-width: 0; overflow-wrap: anywhere; max-width: 720px; margin: auto; } h1 { margin: 0 0 8px; font-size: 22px; line-height: 1.3; letter-spacing: -.02em; } p { color: hsl(var(--muted-foreground, 215 20% 35%)); } @@ -14,7 +15,7 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid hsl(var(--prim #status { min-height: 1.5em; font-size: 12px; } #result { white-space: pre-wrap; overflow-wrap: anywhere; padding: 16px; border-radius: 10px; background: hsl(var(--muted, 210 20% 96%)); min-height: 48px; } .eyebrow { color: hsl(var(--muted-foreground, 215 20% 35%)); font-size: 11px; letter-spacing: .1em; } -@media (max-width: 360px) { body { padding: 16px; } } +@media (max-width: 360px) { .plugin-page { padding: 16px; } } @media (forced-colors: active) { button, textarea { border: 1px solid ButtonText; } } -@media (prefers-color-scheme: dark) { :root { --background: 221 39% 11%; --foreground: 210 20% 98%; --muted: 219 27% 21%; --muted-foreground: 220 13% 91%; --border: 218 11% 65%; --primary: 213 97% 87%; --primary-foreground: 221 39% 11%; } } +@media (prefers-color-scheme: dark) { .plugin-page { } } diff --git a/examples/plugins/session-scratchpad/view.html b/examples/plugins/session-scratchpad/view.html new file mode 100644 index 000000000..02148a9ac --- /dev/null +++ b/examples/plugins/session-scratchpad/view.html @@ -0,0 +1,4 @@ +

Session scratchpad

This page stores only text you type here, in this plugin's own view state. It cannot read Vault hosts, notes, credentials, sessions or the clipboard.

+ + +

Loading your plugin draft…

diff --git a/examples/plugins/settings-view-fixture/README.md b/examples/plugins/settings-view-fixture/README.md index d56725021..a1a859a2c 100644 --- a/examples/plugins/settings-view-fixture/README.md +++ b/examples/plugins/settings-view-fixture/README.md @@ -1,23 +1,6 @@ -# Settings view handoff fixture +# Settings fixture -First-party synthetic native QA fixture, compatible with the manager-dialog -baseline `614b7c997a75afff2c64b796a9f11c3eec804b43`. This is not a marketplace -release. It declares only `views`, has an empty browser activation function and -one static `location: settings` HTML panel. It has no commands, host, terminal, -network, filesystem, secret or sync operation. Declarations are not grants. - -```sh -node packages/plugin-cli/dist/cli.js validate examples/plugins/settings-view-fixture -node packages/plugin-cli/dist/cli.js pack examples/plugins/settings-view-fixture --out /tmp/settings-view-fixture.ncpkg -``` - -In a synthetic Electron profile, import disabled, inspect the manifest, then -Enable. In Installed, find **Static Settings View** and click its **Open** button -(the command palette is not this regression path). Review the normal permission -prompt; use only a specifically approved temporary grant. Denying must not open -a view. If allowed, the plugin manager must close before the external Settings -view appears. Verify its host-provided title/close button is clickable and can -receive focus; close it, then reopen plugin management. Do not use existing -Starter modal permission approval as authorization for this separate fixture. - -Version 0.1.1 corrects the default-export entrypoint contract. It retains the same sole `views` declaration and static HTML. Version 0.1.0 failed before activation and must not be used for successful native acceptance. +This example declares a standard host-owned greeting setting and a separate +modal preview page. Settings never render plugin HTML or CSS. It requests +`settings.read` for its own declared setting and `views` for the preview. +Build with `node build.mjs`; package `.package` using the plugin CLI. diff --git a/examples/plugins/settings-view-fixture/build.mjs b/examples/plugins/settings-view-fixture/build.mjs new file mode 100644 index 000000000..900c466e6 --- /dev/null +++ b/examples/plugins/settings-view-fixture/build.mjs @@ -0,0 +1,3 @@ +import { URL } from 'node:url'; +import { buildHostViewExample } from '../../../scripts/build-plugin-view-example.mjs'; +await buildHostViewExample(new URL('./', import.meta.url)); diff --git a/examples/plugins/settings-view-fixture/host.js b/examples/plugins/settings-view-fixture/host.js new file mode 100644 index 000000000..99dea9518 --- /dev/null +++ b/examples/plugins/settings-view-fixture/host.js @@ -0,0 +1,16 @@ +import { registerHostDomView } from '@netcatty/plugin-sdk/host-dom'; +import plugin from './index.js'; +import { mount } from './view.js'; +import html from './view.html'; +import css from './view.css'; +import manifest from './netcatty.plugin.json'; +export default { + async activate(context) { + await plugin.activate(context); + for (const view of manifest.contributes.views) context.subscriptions.add(registerHostDomView(context.views, view.id, (root, stateScope) => { + root.innerHTML = html; + return mount(root, context, view.id, stateScope); + }, css)); + }, + deactivate: plugin.deactivate, +}; diff --git a/examples/plugins/settings-view-fixture/netcatty.plugin.json b/examples/plugins/settings-view-fixture/netcatty.plugin.json index 3ecd3aeb1..6ca7b260f 100644 --- a/examples/plugins/settings-view-fixture/netcatty.plugin.json +++ b/examples/plugins/settings-view-fixture/netcatty.plugin.json @@ -2,20 +2,51 @@ "manifestVersion": 1, "id": "com.netcatty.settings-view-fixture", "name": "settings-view-fixture", - "displayName": { "en": "Settings View QA", "zh-CN": "设置视图验收" }, + "displayName": { + "en": "Settings View QA", + "zh-CN": "设置视图验收" + }, "version": "0.1.1", "publisher": "netcatty", "license": "GPL-3.0-or-later", - "engines": { "netcatty": ">=0.0.0", "api": ">=0.1.0-internal <0.2.0" }, - "main": { "browser": "index.js" }, - "activationEvents": ["onView:com.netcatty.settings-view-fixture.panel"], - "permissions": { "required": ["views"] }, + "engines": { + "netcatty": ">=0.0.0", + "api": ">=0.1.0-internal <0.2.0" + }, + "main": { + "browser": "dist/host.js" + }, + "activationEvents": [ + "onView:com.netcatty.settings-view-fixture.panel" + ], + "permissions": { + "required": [ + "views", + "settings.read" + ] + }, "contributes": { - "views": [{ - "id": "com.netcatty.settings-view-fixture.panel", - "title": { "en": "Static Settings View", "zh-CN": "静态设置视图" }, - "location": "settings", - "entry": "view.html" - }] + "views": [ + { + "id": "com.netcatty.settings-view-fixture.panel", + "title": { + "en": "Example preview", + "zh-CN": "示例预览" + }, + "location": "modal" + } + ], + "settings": [ + { + "id": "com.netcatty.settings-view-fixture.greeting", + "label": { + "en": "Greeting", + "zh-CN": "问候语" + }, + "control": "text", + "scope": "application", + "default": "Hello" + } + ] } } diff --git a/examples/plugins/settings-view-fixture/view.css b/examples/plugins/settings-view-fixture/view.css new file mode 100644 index 000000000..6a6aadda4 --- /dev/null +++ b/examples/plugins/settings-view-fixture/view.css @@ -0,0 +1 @@ + .plugin-page { min-height:100%; color:hsl(var(--foreground)); background:hsl(var(--background)); font:14px/1.5 system-ui,sans-serif; } diff --git a/examples/plugins/settings-view-fixture/view.html b/examples/plugins/settings-view-fixture/view.html index ae9cefb5b..2b861781c 100644 --- a/examples/plugins/settings-view-fixture/view.html +++ b/examples/plugins/settings-view-fixture/view.html @@ -1,3 +1 @@ - -Static Settings View -

Settings view handoff / 设置视图交接

This first-party static panel has no script, external resource or host data.

Close this view with Netcatty's header button. The manager should already be dismissed.

+

Example preview / 示例预览

This is an ordinary plugin page. Its greeting setting is edited in Netcatty’s standard plugin settings form.

diff --git a/examples/plugins/settings-view-fixture/view.js b/examples/plugins/settings-view-fixture/view.js new file mode 100644 index 000000000..2eefed74b --- /dev/null +++ b/examples/plugins/settings-view-fixture/view.js @@ -0,0 +1 @@ +export function mount() {} diff --git a/examples/plugins/starter-netcatty/README.md b/examples/plugins/starter-netcatty/README.md index 9abe0f1d8..f93bbd6a2 100644 --- a/examples/plugins/starter-netcatty/README.md +++ b/examples/plugins/starter-netcatty/README.md @@ -10,7 +10,7 @@ From the repository root: ```sh npm run build:plugin-packages node packages/plugin-cli/dist/cli.js validate examples/plugins/starter-netcatty -node packages/plugin-cli/dist/cli.js pack examples/plugins/starter-netcatty --out /tmp/starter-netcatty.ncpkg +node packages/plugin-cli/dist/cli.js pack examples/plugins/starter-netcatty/.package --out /tmp/starter-netcatty.ncpkg ``` Start the actual app normally with a fresh test profile; no development flag is @@ -36,4 +36,11 @@ requires API `>=0.1.0-internal.1 <0.2.0` and `metadata.brand-icon`. Older Starter 0.1.1 packages remain compatible with the new host. See [brand icon author instructions](../../../docs/plugin-platform/plugin-icons.md). -The page subscribes to `window.netcattyView.onDidChangeEnvironment()` in `theme.js`. It follows the seven public HSL theme variables, including accent changes, without reading host settings or DOM. The subscription is disposed on page hide. + +## Current UI build + +The page now uses the host-rendered contract. Run `node build.mjs` in this +example directory, then package `.package/` with the plugin CLI. `host.js` +registers ordinary DOM views; `view.html` and `view.css` are bundled source +templates. Theme values are inherited from Netcatty. There is no separate page +preload or `window.netcattyView` API. See `docs/plugin-platform/host-rendered-ui.md`. diff --git a/examples/plugins/starter-netcatty/build.mjs b/examples/plugins/starter-netcatty/build.mjs new file mode 100644 index 000000000..900c466e6 --- /dev/null +++ b/examples/plugins/starter-netcatty/build.mjs @@ -0,0 +1,3 @@ +import { URL } from 'node:url'; +import { buildHostViewExample } from '../../../scripts/build-plugin-view-example.mjs'; +await buildHostViewExample(new URL('./', import.meta.url)); diff --git a/examples/plugins/starter-netcatty/host.js b/examples/plugins/starter-netcatty/host.js new file mode 100644 index 000000000..fa13d5bb1 --- /dev/null +++ b/examples/plugins/starter-netcatty/host.js @@ -0,0 +1,16 @@ +import { registerHostDomView } from '@netcatty/plugin-sdk/host-dom'; +import plugin from './src/index.ts'; +import { mount } from './panel.js'; +import html from './view.html'; +import css from './view.css'; +import manifest from './netcatty.plugin.json'; +export default { + async activate(context) { + await plugin.activate(context); + for (const view of manifest.contributes.views) context.subscriptions.add(registerHostDomView(context.views, view.id, (root, stateScope) => { + root.innerHTML = html; + return mount(root, context, view.id, stateScope); + }, css)); + }, + deactivate: plugin.deactivate, +}; diff --git a/examples/plugins/starter-netcatty/netcatty.plugin.json b/examples/plugins/starter-netcatty/netcatty.plugin.json index f47c5f96d..7ef2b7a6c 100644 --- a/examples/plugins/starter-netcatty/netcatty.plugin.json +++ b/examples/plugins/starter-netcatty/netcatty.plugin.json @@ -15,7 +15,7 @@ "api": ">=0.1.0-internal.1 <0.2.0" }, "main": { - "browser": "dist/index.js" + "browser": "dist/host.js" }, "activationEvents": [ "onCommand:com.netcatty.starter.greet", @@ -67,8 +67,7 @@ "en": "Starter: Greeting Panel", "zh-CN": "入门:问候面板" }, - "location": "modal", - "entry": "panel.html" + "location": "modal" } ] }, diff --git a/examples/plugins/starter-netcatty/package.json b/examples/plugins/starter-netcatty/package.json index cd54d4a43..3f9179537 100644 --- a/examples/plugins/starter-netcatty/package.json +++ b/examples/plugins/starter-netcatty/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "scripts": { - "build": "tsc -p tsconfig.json" + "build": "node build.mjs" }, "dependencies": { "@netcatty/plugin-sdk": "0.1.0-internal.1" diff --git a/examples/plugins/starter-netcatty/panel.html b/examples/plugins/starter-netcatty/panel.html deleted file mode 100644 index 545898895..000000000 --- a/examples/plugins/starter-netcatty/panel.html +++ /dev/null @@ -1,3 +0,0 @@ - -Plugin Starter -

NETCATTY · PLUGIN STARTER

Your first plugin

Read your Greeting preference and show it here. No hosts, terminals or secrets are accessed.

diff --git a/examples/plugins/starter-netcatty/panel.js b/examples/plugins/starter-netcatty/panel.js index e8f207600..38cc9b888 100644 --- a/examples/plugins/starter-netcatty/panel.js +++ b/examples/plugins/starter-netcatty/panel.js @@ -1,22 +1,26 @@ -const button = document.getElementById('greet'); -const result = document.getElementById('result'); +export function mount(root, context, viewId) { + const cleanup = []; + const subscribeEnvironment = (listener) => { const sub = context.environment.onDidChange(listener); cleanup.push(() => sub.dispose()); listener(context.environment); return sub; }; + const subscribeMessage = (listener) => { const sub = context.views.onDidReceiveMessage(viewId, listener); cleanup.push(() => sub.dispose()); return sub; }; +const button = root.querySelector("#" + 'greet'); +const result = root.querySelector("#" + 'result'); let chinese = false; -window.netcattyView.onDidChangeEnvironment((environment) => { +subscribeEnvironment((environment) => { chinese = environment.locale.startsWith('zh'); - document.documentElement.lang = chinese ? 'zh-CN' : 'en'; - document.documentElement.style.colorScheme = environment.theme === 'light' ? 'light' : 'dark'; - document.getElementById('title').textContent = chinese ? '你的第一个插件' : 'Your first plugin'; - document.getElementById('description').textContent = chinese ? '读取并显示你设置的问候语。不访问主机、终端或秘密。' : 'Read your Greeting preference and show it here. No hosts, terminals or secrets are accessed.'; + root.lang = chinese ? 'zh-CN' : 'en'; + root.style.colorScheme = environment.theme === 'light' ? 'light' : 'dark'; + root.querySelector("#" + 'title').textContent = chinese ? '你的第一个插件' : 'Your first plugin'; + root.querySelector("#" + 'description').textContent = chinese ? '读取并显示你设置的问候语。不访问主机、终端或秘密。' : 'Read your Greeting preference and show it here. No hosts, terminals or secrets are accessed.'; button.textContent = chinese ? '显示问候语' : 'Show greeting'; }); -window.netcattyView.onDidReceiveMessage((message) => { +subscribeMessage((message) => { if (typeof message?.greeting === 'string') result.textContent = message.greeting; }); button.addEventListener('click', async () => { button.disabled = true; result.textContent = chinese ? '正在读取…' : 'Reading…'; try { - const response = await window.netcattyView.executeCommand('com.netcatty.starter.greet'); + const response = await context.commands.executeCommand('com.netcatty.starter.greet'); result.textContent = response.greeting; } catch { result.textContent = chinese ? '未能读取问候语,请检查权限授权。' : 'Could not read the greeting. Check permission approval.'; @@ -24,3 +28,6 @@ button.addEventListener('click', async () => { button.disabled = false; } }); + + return () => { for (const stop of cleanup) stop(); }; +} diff --git a/examples/plugins/starter-netcatty/theme.js b/examples/plugins/starter-netcatty/theme.js deleted file mode 100644 index b1809b4bb..000000000 --- a/examples/plugins/starter-netcatty/theme.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* global document, window */ -// This page owns its DOM. Only the host's public semantic colors are copied. -(() => { - const names = ["--background", "--foreground", "--muted", "--muted-foreground", "--border", "--primary", "--primary-foreground"]; - let subscription; - const subscribe = () => { - if (subscription) return; - subscription = window.netcattyView.onDidChangeEnvironment((environment) => { - const root = document.documentElement; - root.style.colorScheme = environment.theme === "system" ? "light dark" : environment.theme; - root.dataset.reducedMotion = String(Boolean(environment.reducedMotion)); - root.dataset.highContrast = String(Boolean(environment.highContrast)); - for (const name of names) { - const value = environment.themeTokens?.[name]; - if (typeof value === "string" && value.length <= 96) root.style.setProperty(name, value); - else root.style.removeProperty(name); - } - }); - }; - subscribe(); - window.addEventListener("pagehide", () => { subscription?.dispose(); subscription = undefined; }); - window.addEventListener("pageshow", subscribe); -})(); diff --git a/examples/plugins/vault-scratchpad/page.css b/examples/plugins/starter-netcatty/view.css similarity index 76% rename from examples/plugins/vault-scratchpad/page.css rename to examples/plugins/starter-netcatty/view.css index 2d9eec62e..f199be4b2 100644 --- a/examples/plugins/vault-scratchpad/page.css +++ b/examples/plugins/starter-netcatty/view.css @@ -1,6 +1,7 @@ -:root { color-scheme: light dark; font: 14px/1.6 system-ui, sans-serif; } + .plugin-page { min-height:100%; color:hsl(var(--foreground)); background:hsl(var(--background)); font:14px/1.5 system-ui,sans-serif; } +.plugin-page { color-scheme: light dark; font: 14px/1.6 system-ui, sans-serif; } * { box-sizing: border-box; } -body { margin: 0; padding: 24px; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 12%)); } +.plugin-page { margin: 0; padding: 24px; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 12%)); } main { min-width: 0; overflow-wrap: anywhere; max-width: 720px; margin: auto; } h1 { margin: 0 0 8px; font-size: 22px; line-height: 1.3; letter-spacing: -.02em; } p { color: hsl(var(--muted-foreground, 215 20% 35%)); } @@ -14,7 +15,7 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid hsl(var(--prim #status { min-height: 1.5em; font-size: 12px; } #result { white-space: pre-wrap; overflow-wrap: anywhere; padding: 16px; border-radius: 10px; background: hsl(var(--muted, 210 20% 96%)); min-height: 48px; } .eyebrow { color: hsl(var(--muted-foreground, 215 20% 35%)); font-size: 11px; letter-spacing: .1em; } -@media (max-width: 360px) { body { padding: 16px; } } +@media (max-width: 360px) { .plugin-page { padding: 16px; } } @media (forced-colors: active) { button, textarea { border: 1px solid ButtonText; } } -@media (prefers-color-scheme: dark) { :root { --background: 221 39% 11%; --foreground: 210 20% 98%; --muted: 219 27% 21%; --muted-foreground: 220 13% 91%; --border: 218 11% 65%; --primary: 213 97% 87%; --primary-foreground: 221 39% 11%; } } +@media (prefers-color-scheme: dark) { .plugin-page { } } diff --git a/examples/plugins/starter-netcatty/view.html b/examples/plugins/starter-netcatty/view.html new file mode 100644 index 000000000..5495bc21a --- /dev/null +++ b/examples/plugins/starter-netcatty/view.html @@ -0,0 +1 @@ +

NETCATTY · PLUGIN STARTER

Your first plugin

Read your Greeting preference and show it here. No hosts, terminals or secrets are accessed.

diff --git a/examples/plugins/vault-scratchpad/README.md b/examples/plugins/vault-scratchpad/README.md index cabcb4d83..90fd8854a 100644 --- a/examples/plugins/vault-scratchpad/README.md +++ b/examples/plugins/vault-scratchpad/README.md @@ -7,7 +7,7 @@ Text explicitly typed here is stored in this plugin's own bounded view state; it is not a Netcatty Note and is not automatically cloud-synced. ```sh -node packages/plugin-cli/dist/cli.js pack examples/plugins/vault-scratchpad --out /tmp/vault-scratchpad.ncpkg +node packages/plugin-cli/dist/cli.js pack examples/plugins/vault-scratchpad/.package --out /tmp/vault-scratchpad.ncpkg ``` Import disabled through normal Settings, inspect and enable it. Under Vault's @@ -26,4 +26,11 @@ modal or overlapping menu must hide the native view while it is present. This source example is not independent/native acceptance evidence. Parent QA records the precise tested commit and package hash separately. -The page subscribes to `window.netcattyView.onDidChangeEnvironment()` in `theme.js`. It follows the seven public HSL theme variables, including accent changes, without reading host settings or DOM. The subscription is disposed on page hide. + +## Current UI build + +The page now uses the host-rendered contract. Run `node build.mjs` in this +example directory, then package `.package/` with the plugin CLI. `host.js` +registers ordinary DOM views; `view.html` and `view.css` are bundled source +templates. Theme values are inherited from Netcatty. There is no separate page +preload or `window.netcattyView` API. See `docs/plugin-platform/host-rendered-ui.md`. diff --git a/examples/plugins/vault-scratchpad/build.mjs b/examples/plugins/vault-scratchpad/build.mjs new file mode 100644 index 000000000..900c466e6 --- /dev/null +++ b/examples/plugins/vault-scratchpad/build.mjs @@ -0,0 +1,3 @@ +import { URL } from 'node:url'; +import { buildHostViewExample } from '../../../scripts/build-plugin-view-example.mjs'; +await buildHostViewExample(new URL('./', import.meta.url)); diff --git a/examples/plugins/vault-scratchpad/host.js b/examples/plugins/vault-scratchpad/host.js new file mode 100644 index 000000000..656d20f92 --- /dev/null +++ b/examples/plugins/vault-scratchpad/host.js @@ -0,0 +1,16 @@ +import { registerHostDomView } from '@netcatty/plugin-sdk/host-dom'; +import plugin from './browser.js'; +import { mount } from './page.js'; +import html from './view.html'; +import css from './view.css'; +import manifest from './netcatty.plugin.json'; +export default { + async activate(context) { + await plugin.activate(context); + for (const view of manifest.contributes.views) context.subscriptions.add(registerHostDomView(context.views, view.id, (root, stateScope) => { + root.innerHTML = html; + return mount(root, context, view.id, stateScope); + }, css)); + }, + deactivate: plugin.deactivate, +}; diff --git a/examples/plugins/vault-scratchpad/netcatty.plugin.json b/examples/plugins/vault-scratchpad/netcatty.plugin.json index c5b51f3ba..2405ada77 100644 --- a/examples/plugins/vault-scratchpad/netcatty.plugin.json +++ b/examples/plugins/vault-scratchpad/netcatty.plugin.json @@ -2,22 +2,44 @@ "manifestVersion": 1, "id": "com.netcatty.vault-scratchpad", "name": "vault-scratchpad", - "displayName": { "en": "Vault Scratchpad", "zh-CN": "Vault 草稿板" }, + "displayName": { + "en": "Vault Scratchpad", + "zh-CN": "Vault 草稿板" + }, "version": "0.1.1", "publisher": "netcatty", "license": "GPL-3.0-or-later", - "engines": { "netcatty": ">=0.0.0", "api": ">=0.1.0-internal.1 <0.2.0" }, - "features": { "required": ["views.vault-pages"] }, - "main": { "browser": "browser.js" }, - "activationEvents": ["onView:com.netcatty.vault-scratchpad.page"], - "permissions": { "required": ["views"] }, + "engines": { + "netcatty": ">=0.0.0", + "api": ">=0.1.0-internal.1 <0.2.0" + }, + "features": { + "required": [ + "views.vault-pages" + ] + }, + "main": { + "browser": "dist/host.js" + }, + "activationEvents": [ + "onView:com.netcatty.vault-scratchpad.page" + ], + "permissions": { + "required": [ + "views" + ] + }, "contributes": { - "views": [{ - "id": "com.netcatty.vault-scratchpad.page", - "title": { "en": "Scratchpad", "zh-CN": "草稿板" }, - "location": "vault-page", - "entry": "page.html", - "order": 10 - }] + "views": [ + { + "id": "com.netcatty.vault-scratchpad.page", + "title": { + "en": "Scratchpad", + "zh-CN": "草稿板" + }, + "location": "vault-page", + "order": 10 + } + ] } } diff --git a/examples/plugins/vault-scratchpad/page.html b/examples/plugins/vault-scratchpad/page.html deleted file mode 100644 index 8eb9202f9..000000000 --- a/examples/plugins/vault-scratchpad/page.html +++ /dev/null @@ -1,7 +0,0 @@ - - -Vault Scratchpad -

Scratchpad

This page stores only text you type here, in this plugin's own view state. It cannot read Vault hosts, notes, credentials, sessions or the clipboard.

- - -

Loading your plugin draft…

diff --git a/examples/plugins/vault-scratchpad/page.js b/examples/plugins/vault-scratchpad/page.js index ebf3590eb..7697263ef 100644 --- a/examples/plugins/vault-scratchpad/page.js +++ b/examples/plugins/vault-scratchpad/page.js @@ -1,25 +1,28 @@ -"use strict"; -/* global document, window */ -const draft = document.getElementById("draft"); -const status = document.getElementById("status"); +export function mount(root, context, viewId, stateScope) { + const cleanup = []; +const draft = root.querySelector("#" + "draft"); +const status = root.querySelector("#" + "status"); let busy = false; async function save(clear) { if (busy) return; busy = true; try { const text = clear ? "" : draft.value; - await window.netcattyView.setState({ version: 1, text }); + await context.views.setState(viewId, stateScope, { version: 1, text }); if (clear) draft.value = ""; status.textContent = clear ? "Draft cleared." : "Draft saved in this plugin only."; } catch { status.textContent = "Could not save this draft."; } finally { busy = false; } } -document.getElementById("save").addEventListener("click", () => { void save(false); }); -document.getElementById("clear").addEventListener("click", () => { void save(true); }); -window.netcattyView.getState().then((state) => { +root.querySelector("#" + "save").addEventListener("click", () => { void save(false); }); +root.querySelector("#" + "clear").addEventListener("click", () => { void save(true); }); +context.views.getState(viewId, stateScope).then((state) => { if (state?.version === 1 && typeof state.text === "string" && state.text.length <= 4096) draft.value = state.text; status.textContent = "Ready. Use synthetic text for this example."; draft.disabled = false; - document.getElementById("save").disabled = false; - document.getElementById("clear").disabled = false; + root.querySelector("#" + "save").disabled = false; + root.querySelector("#" + "clear").disabled = false; }).catch(() => { status.textContent = "Could not load this plugin draft."; }); + + return () => { for (const stop of cleanup) stop(); }; +} diff --git a/examples/plugins/vault-scratchpad/theme.js b/examples/plugins/vault-scratchpad/theme.js deleted file mode 100644 index b1809b4bb..000000000 --- a/examples/plugins/vault-scratchpad/theme.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* global document, window */ -// This page owns its DOM. Only the host's public semantic colors are copied. -(() => { - const names = ["--background", "--foreground", "--muted", "--muted-foreground", "--border", "--primary", "--primary-foreground"]; - let subscription; - const subscribe = () => { - if (subscription) return; - subscription = window.netcattyView.onDidChangeEnvironment((environment) => { - const root = document.documentElement; - root.style.colorScheme = environment.theme === "system" ? "light dark" : environment.theme; - root.dataset.reducedMotion = String(Boolean(environment.reducedMotion)); - root.dataset.highContrast = String(Boolean(environment.highContrast)); - for (const name of names) { - const value = environment.themeTokens?.[name]; - if (typeof value === "string" && value.length <= 96) root.style.setProperty(name, value); - else root.style.removeProperty(name); - } - }); - }; - subscribe(); - window.addEventListener("pagehide", () => { subscription?.dispose(); subscription = undefined; }); - window.addEventListener("pageshow", subscribe); -})(); diff --git a/examples/plugins/session-scratchpad/page.css b/examples/plugins/vault-scratchpad/view.css similarity index 76% rename from examples/plugins/session-scratchpad/page.css rename to examples/plugins/vault-scratchpad/view.css index 2d9eec62e..f199be4b2 100644 --- a/examples/plugins/session-scratchpad/page.css +++ b/examples/plugins/vault-scratchpad/view.css @@ -1,6 +1,7 @@ -:root { color-scheme: light dark; font: 14px/1.6 system-ui, sans-serif; } + .plugin-page { min-height:100%; color:hsl(var(--foreground)); background:hsl(var(--background)); font:14px/1.5 system-ui,sans-serif; } +.plugin-page { color-scheme: light dark; font: 14px/1.6 system-ui, sans-serif; } * { box-sizing: border-box; } -body { margin: 0; padding: 24px; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 12%)); } +.plugin-page { margin: 0; padding: 24px; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 12%)); } main { min-width: 0; overflow-wrap: anywhere; max-width: 720px; margin: auto; } h1 { margin: 0 0 8px; font-size: 22px; line-height: 1.3; letter-spacing: -.02em; } p { color: hsl(var(--muted-foreground, 215 20% 35%)); } @@ -14,7 +15,7 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid hsl(var(--prim #status { min-height: 1.5em; font-size: 12px; } #result { white-space: pre-wrap; overflow-wrap: anywhere; padding: 16px; border-radius: 10px; background: hsl(var(--muted, 210 20% 96%)); min-height: 48px; } .eyebrow { color: hsl(var(--muted-foreground, 215 20% 35%)); font-size: 11px; letter-spacing: .1em; } -@media (max-width: 360px) { body { padding: 16px; } } +@media (max-width: 360px) { .plugin-page { padding: 16px; } } @media (forced-colors: active) { button, textarea { border: 1px solid ButtonText; } } -@media (prefers-color-scheme: dark) { :root { --background: 221 39% 11%; --foreground: 210 20% 98%; --muted: 219 27% 21%; --muted-foreground: 220 13% 91%; --border: 218 11% 65%; --primary: 213 97% 87%; --primary-foreground: 221 39% 11%; } } +@media (prefers-color-scheme: dark) { .plugin-page { } } diff --git a/examples/plugins/vault-scratchpad/view.html b/examples/plugins/vault-scratchpad/view.html new file mode 100644 index 000000000..fbcc63a80 --- /dev/null +++ b/examples/plugins/vault-scratchpad/view.html @@ -0,0 +1,4 @@ +

Scratchpad

This page stores only text you type here, in this plugin's own view state. It cannot read Vault hosts, notes, credentials, sessions or the clipboard.

+ + +

Loading your plugin draft…

diff --git a/global.d.ts b/global.d.ts index 570b16b12..7bb17a752 100644 --- a/global.d.ts +++ b/global.d.ts @@ -641,16 +641,13 @@ declare global { onPluginAuthenticationChallenge?(callback: (event: NetcattyPluginAuthenticationChallengeEvent) => void): () => void; onPluginConnectionData?(callback: (event: { sessionId: string; data: Uint8Array }) => void): () => void; onPluginConnectionClosed?(callback: (event: { sessionId: string; reason: string }) => void): () => void; - openPluginView?(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>; - closePluginView?(instanceId: string): Promise; - setPluginViewBounds?(instanceId: string, bounds: { x: number; y: number; width: number; height: number }): Promise; - setPluginViewVisibility?(instanceId: string, visible: boolean): Promise; - focusPluginView?(payload: import('@netcatty/plugin-contract').PluginViewFocusRequest): Promise; - postPluginViewMessage?(instanceId: string, message: unknown): Promise; + getPluginViewResource?(payload: import('@netcatty/plugin-contract').PluginViewResourceRequest): Promise; + openHostDrawnPluginView?(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>; + closeHostDrawnPluginView?(instanceId: string): Promise; + sendHostDrawnPluginViewEvent?(instanceId: string, event: import('@netcatty/plugin-contract').HostDrawnViewEvent): Promise; + onHostDrawnPluginViewUpdate?(callback: (event: import('@netcatty/plugin-contract').HostDrawnViewMessage & { viewId: string }) => void): () => void; onPluginContributionsChanged?(callback: (event: { reason: string; pluginId: string | null; revision: number }) => void): () => void; - onPluginViewMessage?(callback: (event: { pluginId: string; viewId: string; message: unknown }) => void): () => void; onPluginViewClosed?(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void; - onPluginViewFocused?(callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void): () => void; getPluginScopeCatalog?(): Promise; setPluginScopeCatalog?(catalog: NetcattyPluginScopeCatalog): Promise; onPluginScopeCatalogChanged?(callback: (catalog: NetcattyPluginScopeCatalog) => void): () => void; @@ -664,6 +661,7 @@ declare global { } interface NetcattyPluginSettingContribution { + group?: string; id: string; label: string; description?: string; @@ -714,7 +712,7 @@ declare global { icon?: NetcattyPluginIconReference; }>; settings: ReadonlyArray; - views: ReadonlyArray<{ id: string; title: string; location: string; entry: string; icon?: NetcattyPluginIconReference; order?: number; visible: boolean; retainContextWhenHidden?: boolean }>; + views: ReadonlyArray<{ id: string; title: string; location: string; icon?: NetcattyPluginIconReference; order?: number; visible: boolean }>; }>; } @@ -828,13 +826,7 @@ declare global { error: { code: number; message: string; data?: unknown }; }; - interface NetcattyPluginViewOpenRequest { - viewId: string; - instanceId?: string; - scopeId: string; - bounds?: { x: number; y: number; width: number; height: number }; - context?: Record; - } + type NetcattyPluginViewOpenRequest = import('@netcatty/plugin-contract').HostDrawnViewOpenRequest; interface NetcattyPluginViewClosedEvent { instanceId: string; diff --git a/infrastructure/ai/plugin/modelInvocationAdapter.test.ts b/infrastructure/ai/plugin/modelInvocationAdapter.test.ts index e66f7c1fe..b22d671a5 100644 --- a/infrastructure/ai/plugin/modelInvocationAdapter.test.ts +++ b/infrastructure/ai/plugin/modelInvocationAdapter.test.ts @@ -120,7 +120,7 @@ test('broker -> existing model factory -> existing host HTTP transport -> loopba assert.doesNotMatch(JSON.stringify({ chat, turn, text, usage, sentBodies }), /synthetic-not-a-paid-api-key/); // Exercise the actual page handlers through its existing command-only view // surface. This is DOM QA, not installed-plugin or native Electron evidence. - const dom = new JSDOM(fs.readFileSync(new URL('../../../examples/plugins/assistant/panel.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' }); + const dom = new JSDOM(fs.readFileSync(new URL('../../../examples/plugins/assistant/view.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' }); t.after(() => dom.window.close()); const commandHandlers: Record) => unknown> = { open: () => broker.open(context), contexts: () => contexts.summaries(context), @@ -129,15 +129,16 @@ test('broker -> existing model factory -> existing host HTTP transport -> loopba stop: (params) => broker.stop(params.turnHandle, context), close: (params) => broker.close(params.chatHandle, context), }; - Object.defineProperty(dom.window, 'netcattyView', { value: { + const commands = { executeCommand: async (id: string, params: Record) => { const operation = id.replace('com.netcatty.assistant.', ''); assert.ok(Object.hasOwn(commandHandlers, operation)); return structuredClone(await commandHandlers[operation](structuredClone(params))); }, - onDidReceiveMessage: () => () => {}, - } }); - dom.window.eval(fs.readFileSync(new URL('../../../examples/plugins/assistant/panel.js', import.meta.url), 'utf8')); + }; + const mount = dom.window.eval('(' + fs.readFileSync(new URL('../../../examples/plugins/assistant/panel.js', import.meta.url), 'utf8').replace('export function mount', 'function mount') + ')'); + const dispose = mount(dom.window.document.body, { commands, views: { onDidReceiveMessage: () => ({ dispose() {} }) } }, 'com.netcatty.assistant.panel'); + t.after(dispose); const waitFor = async (condition: () => boolean) => { const deadline = Date.now() + 3000; while (!condition()) { diff --git a/package-lock.json b/package-lock.json index 0b163ad06..993cea139 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,10 +22,12 @@ "@netcatty/plugin-sdk": "0.1.0-internal.1", "@noble/ciphers": "2.4.0", "@openai/codex-sdk": "0.144.3", + "@remote-dom/core": "^1.12.0", "@smithy/node-http-handler": "^4.4.9", "@withfig/autocomplete": "^2.692.3", "ajv": "8.18.0", "ajv-formats": "3.0.1", + "css-tree": "^3.2.1", "electron-updater": "^6.8.3", "http-proxy-agent": "^7.0.2", "https-proxy-agent": "^7.0.6", @@ -149,6 +151,15 @@ "@netcatty/plugin-sdk": "0.1.0-internal.1" } }, + "examples/plugins/hello-react-host": { + "name": "@netcatty/example-hello-react-host", + "version": "0.2.0", + "dependencies": { + "@netcatty/plugin-sdk": "0.1.0-internal.1", + "react": "^19.2.1", + "react-dom": "^19.2.1" + } + }, "examples/plugins/starter-netcatty": { "name": "@netcatty/example-starter-plugin", "version": "0.1.3", @@ -4696,6 +4707,10 @@ "resolved": "examples/plugins/hello-netcatty", "link": true }, + "node_modules/@netcatty/example-hello-react-host": { + "resolved": "examples/plugins/hello-react-host", + "link": true + }, "node_modules/@netcatty/example-starter-plugin": { "resolved": "examples/plugins/starter-netcatty", "link": true @@ -7018,6 +7033,39 @@ "dev": true, "license": "MIT" }, + "node_modules/@remote-dom/core": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@remote-dom/core/-/core-1.12.0.tgz", + "integrity": "sha512-mK+vo7aHLklGWLtFP0zCP8Itb4cNWcvRvErGLJvg/oGBF4ChuLEexdDtbZPQ5plJoRNhkwSDOwZcFmA/A9O/yA==", + "license": "MIT", + "dependencies": { + "@remote-dom/polyfill": "^1.6.0", + "htm": "^3.1.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "@preact/signals-core": "^1.3.0" + }, + "peerDependenciesMeta": { + "@preact/signals-core": { + "optional": true + }, + "preact": { + "optional": true + } + } + }, + "node_modules/@remote-dom/polyfill": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@remote-dom/polyfill/-/polyfill-1.6.0.tgz", + "integrity": "sha512-o2kb/cgJfqomrVOJLegsiHCIIRGwxlRp3G11gWmlUReDh51uRsI1eJVsyVDyHH3h8j7SxwaLSBZAr191akSGng==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@rolldown/pluginutils": { "version": "1.0.0-rc.2", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz", @@ -11206,7 +11254,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", - "dev": true, "license": "MIT", "dependencies": { "mdn-data": "2.27.1", @@ -13525,6 +13572,12 @@ "integrity": "sha512-ECg1JFG0YzehicQaogenlcs2qg6WsXQsxtnbr1i696u5tLUjtJdQAh0u2g0Q5YV45f263Ta1GnUJsc8WIfJf4Q==", "license": "MIT" }, + "node_modules/htm": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/htm/-/htm-3.1.1.tgz", + "integrity": "sha512-983Vyg8NwUE7JkZ6NmOqpCZ+sh1bKv2iYTlUkzlWmA5JD2acKoxd4KVxbMmxX/85mtfdnDmTFoNKcg5DGAvxNQ==", + "license": "Apache-2.0" + }, "node_modules/html-encoding-sniffer": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", @@ -15321,7 +15374,6 @@ "version": "2.27.1", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", - "dev": true, "license": "CC0-1.0" }, "node_modules/media-typer": { @@ -17667,7 +17719,6 @@ "version": "19.2.4", "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -17677,7 +17728,6 @@ "version": "19.2.4", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", - "dev": true, "license": "MIT", "dependencies": { "scheduler": "^0.27.0" @@ -18339,7 +18389,6 @@ "version": "0.27.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "dev": true, "license": "MIT" }, "node_modules/semver": { @@ -18806,7 +18855,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -20762,7 +20810,36 @@ "version": "0.1.0-internal.1", "license": "GPL-3.0-or-later", "dependencies": { - "@netcatty/plugin-contract": "0.1.0-internal.1" + "@netcatty/plugin-contract": "0.1.0-internal.1", + "@remote-dom/core": "^1.12.0" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0" + }, + "peerDependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0" + } + }, + "packages/plugin-sdk/node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "packages/plugin-sdk/node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" } } } diff --git a/package.json b/package.json index fce67f5f5..833692788 100644 --- a/package.json +++ b/package.json @@ -58,8 +58,9 @@ "test": "node --test --import tsx electron/*.test.cjs electron/preload/*.test.cjs electron/mcp/*.test.cjs electron/shared/*Privacy*.test.cjs electron/scripts/*.test.cjs electron/terminalWorker/*.test.cjs electron/capabilities/*.test.cjs electron/capabilities/*/*.test.cjs electron/capabilities/*/*/*.test.cjs electron/cli/*.test.cjs electron/hostBrowser/*Store.test.cjs electron/hostBrowser/hostBrowserManager.test.cjs electron/bridges/*.test.cjs electron/bridges/*/*.test.cjs electron/bridges/aiBridge/codexAppServer/*.test.cjs electron/bridges/aiBridge/sdk/*.test.cjs scripts/*.test.cjs application/*.test.ts application/app/*.test.ts application/i18n/locales/*.test.ts application/state/*.test.ts application/state/*/*.test.ts components/*.test.ts components/*.test.tsx components/editor/*.test.ts components/editor/*.test.tsx components/notes/*.test.ts components/notes/*.test.tsx components/port-forwarding/*.test.ts components/scripts/*.test.tsx components/systemManager/*.test.ts components/terminalLayer/*.test.ts components/settings/*.test.tsx components/settings/tabs/*.test.ts components/settings/tabs/ai/*.test.ts components/settings/tabs/ai/*.test.tsx components/ai/*.test.ts components/ai/*.test.tsx components/ai/toolArtifacts/*.test.ts components/ai/toolArtifacts/*.test.tsx components/ai-elements/*.test.tsx components/sftp/*.test.ts components/terminal/*.test.ts components/terminal/*.test.tsx components/terminal/runtime/*.test.ts components/vault/*.test.ts components/vault/*.test.tsx domain/*.test.ts domain/*/*.test.ts domain/*/*.test.cjs infrastructure/ai/*.test.ts infrastructure/ai/*/*.test.ts infrastructure/ai/sdk/*.test.ts infrastructure/config/*.test.ts infrastructure/monaco/*.test.ts infrastructure/persistence/*.test.ts infrastructure/services/*.test.ts infrastructure/services/*/*.test.ts lib/*.test.ts packages/*/src/*.test.ts", "test:plugin-contract": "node --test --import tsx packages/*/src/*.test.ts", "test:plugin-examples": "node --test examples/plugins/database-minimal/*.test.cjs examples/plugins/database-rfam-readonly/*.test.cjs examples/plugins/terminal-selection-draft/prepare.test.cjs examples/plugins/global-agent/*.test.cjs", - "pretest:plugin-runtime": "npm run build:plugin-runtime-deps && npm run build --workspace @netcatty/example-starter-plugin", + "pretest:plugin-runtime": "npm run build:plugin-runtime-deps && npm run build:plugin-view-examples", "test:plugin-runtime": "node --test electron/plugins/*.test.cjs domain/pluginRuntimePolicy.test.cjs domain/pluginPermissionDescriptions.test.cjs domain/pluginThemePack.test.cjs", + "test:plugin-host-drawn": "node --test --import tsx domain/pluginRemoteTreePolicy.test.cjs domain/pluginViewStylePolicy.test.cjs electron/plugins/hostDrawnViewHost.test.cjs application/state/pluginRemoteTree.test.tsx components/plugins/PluginRemoteSurface.test.tsx packages/plugin-sdk/src/hostReact.test.tsx application/state/pluginViewSession.test.ts application/state/terminalSidePanelPluginTabs.test.tsx components/PluginVaultPages.test.tsx components/PluginTerminalSidebar.test.tsx electron/plugins/viewResourceService.test.cjs", "pretest:plugin-runtime:electron": "npm run build:plugin-runtime-deps", "test:plugin-runtime:electron": "electron electron/plugins/electronRuntime.live.test.cjs", "test:sync-crdt": "node --test --import tsx domain/convergentSync/*.test.ts", @@ -77,7 +78,9 @@ "test:xterm-webgl-overflow": "electron scripts/xterm-webgl-atlas-overflow.live.test.cjs", "test:xterm-macos-selection": "electron scripts/xterm-macos-column-selection.live.test.cjs", "test:xterm-keyword-highlight-performance": "electron scripts/xterm-keyword-highlight-performance.live.test.cjs", - "test:xterm-keyword-highlight-throughput": "electron scripts/xterm-keyword-highlight-throughput.live.test.cjs" + "test:xterm-keyword-highlight-throughput": "electron scripts/xterm-keyword-highlight-throughput.live.test.cjs", + "build:plugin-view-examples": "node scripts/build-plugin-view-examples.mjs", + "test:plugin-host-drawn:electron": "electron electron/plugins/hostReactUi.live.test.cjs" }, "dependencies": { "@aws-sdk/client-s3": "^3.956.0", @@ -88,10 +91,12 @@ "@netcatty/plugin-sdk": "0.1.0-internal.1", "@noble/ciphers": "2.4.0", "@openai/codex-sdk": "0.144.3", + "@remote-dom/core": "^1.12.0", "@smithy/node-http-handler": "^4.4.9", "@withfig/autocomplete": "^2.692.3", "ajv": "8.18.0", "ajv-formats": "3.0.1", + "css-tree": "^3.2.1", "electron-updater": "^6.8.3", "http-proxy-agent": "^7.0.2", "https-proxy-agent": "^7.0.6", diff --git a/packages/plugin-cli/src/archive.ts b/packages/plugin-cli/src/archive.ts index edc07a778..0b29b59c8 100644 --- a/packages/plugin-cli/src/archive.ts +++ b/packages/plugin-cli/src/archive.ts @@ -296,7 +296,6 @@ async function scanPackageDirectory( ...packageIconPaths(manifest.icon), manifest.main.browser, manifest.main.node, - ...(manifest.contributes?.views ?? []).map(({ entry }) => entry), ...(manifest.contributes?.themes ?? []).map(({ entry }) => entry), ...(manifest.contributes?.commands ?? []).flatMap(({ icon }) => packageIconPaths(icon)), ...(manifest.contributes?.menus ?? []).flatMap(({ icon }) => packageIconPaths(icon)), @@ -754,7 +753,6 @@ async function inspectPluginPackage( ...packageIconPaths(manifest.icon), manifest.main.browser, manifest.main.node, - ...(manifest.contributes?.views ?? []).map(({ entry }) => entry), ...(manifest.contributes?.themes ?? []).map(({ entry }) => entry), ...(manifest.contributes?.commands ?? []).flatMap(({ icon }) => packageIconPaths(icon)), ...(manifest.contributes?.menus ?? []).flatMap(({ icon }) => packageIconPaths(icon)), diff --git a/packages/plugin-cli/src/manifest.ts b/packages/plugin-cli/src/manifest.ts index 93df185a2..3c03dec06 100644 --- a/packages/plugin-cli/src/manifest.ts +++ b/packages/plugin-cli/src/manifest.ts @@ -705,7 +705,6 @@ function validateSemantics(manifest: PluginManifest): string[] { ...packageIconPaths(manifest.icon), manifest.main.browser, manifest.main.node, - ...(manifest.contributes?.views ?? []).map(({ entry }) => entry), ...(manifest.contributes?.themes ?? []).map(({ entry }) => entry), ...(manifest.contributes?.commands ?? []).flatMap(({ icon }) => packageIconPaths(icon)), ...(manifest.contributes?.menus ?? []).flatMap(({ icon }) => packageIconPaths(icon)), diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index fbf097307..4a94e34e0 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -7,19 +7,36 @@ "$defs": { "JsonPrimitive": { "oneOf": [ - { "type": "string" }, - { "type": "number" }, - { "type": "boolean" }, - { "type": "null" } + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } ] }, "JsonValue": { "oneOf": [ - { "$ref": "#/$defs/JsonPrimitive" }, - { "type": "array", "items": { "$ref": "#/$defs/JsonValue" } }, + { + "$ref": "#/$defs/JsonPrimitive" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/JsonValue" + } + }, { "type": "object", - "additionalProperties": { "$ref": "#/$defs/JsonValue" } + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + } } ] }, @@ -143,10 +160,20 @@ "SecretRef": { "description": "A host-issued reference to secret material. The random identifier is opaque and never sufficient authority on its own. The non-secret key binds permission authorization to the packaged manifest resource; privileged consumers must revalidate identifier ownership, key binding, and operation scope.", "type": "object", - "required": ["kind", "id", "key"], + "required": [ + "kind", + "id", + "key" + ], "properties": { - "kind": { "const": "secret" }, - "id": { "type": "string", "minLength": 16, "maxLength": 256 }, + "kind": { + "const": "secret" + }, + "id": { + "type": "string", + "minLength": 16, + "maxLength": 256 + }, "key": { "type": "string", "minLength": 1, @@ -159,22 +186,48 @@ "CredentialRef": { "description": "An opaque host-issued reference to a Netcatty-owned credential. The host validates ownership and provider-operation scope before issuing a plaintext lease.", "type": "object", - "required": ["kind", "id"], + "required": [ + "kind", + "id" + ], "properties": { - "kind": { "const": "credential" }, - "id": { "type": "string", "minLength": 16, "maxLength": 256 } + "kind": { + "const": "credential" + }, + "id": { + "type": "string", + "minLength": 16, + "maxLength": 256 + } }, "additionalProperties": false }, "SecretLeaseRef": { "description": "An opaque, operation-bound, single-consumption lease. Only a host capability broker can consume it after revalidating runtime identity and operation scope.", "type": "object", - "required": ["kind", "id", "operationId", "expiresAt"], + "required": [ + "kind", + "id", + "operationId", + "expiresAt" + ], "properties": { - "kind": { "const": "secret-lease" }, - "id": { "type": "string", "minLength": 32, "maxLength": 256 }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "expiresAt": { "$ref": "#/$defs/SafePositiveInteger" } + "kind": { + "const": "secret-lease" + }, + "id": { + "type": "string", + "minLength": 32, + "maxLength": 256 + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "expiresAt": { + "$ref": "#/$defs/SafePositiveInteger" + } }, "additionalProperties": false }, @@ -755,7 +808,9 @@ "const": "commands.interactive" }, "InteractiveCommandLimits": { - "const": { "timeoutMs": 180000 } + "const": { + "timeoutMs": 180000 + } }, "HostQuickPickItem": { "type": "object", @@ -831,7 +886,9 @@ "maxLength": 128, "pattern": "^[^\\u0000-\\u001f\\u007f]*$" }, - "initialValue": { "$ref": "#/$defs/HostSingleLineInputText" } + "initialValue": { + "$ref": "#/$defs/HostSingleLineInputText" + } }, "additionalProperties": false }, @@ -1042,7 +1099,13 @@ "request" ], "properties": { - "permissionMode": { "enum": ["allow", "ask", "deny"] }, + "permissionMode": { + "enum": [ + "allow", + "ask", + "deny" + ] + }, "requestId": { "type": "string", "maxLength": 128 @@ -1684,12 +1747,22 @@ }, "LocalizedText": { "oneOf": [ - { "type": "string", "minLength": 1, "maxLength": 512 }, + { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, { "type": "object", "minProperties": 1, - "propertyNames": { "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$" }, - "additionalProperties": { "type": "string", "minLength": 1, "maxLength": 512 } + "propertyNames": { + "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$" + }, + "additionalProperties": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } } ] }, @@ -1801,53 +1874,115 @@ "type": "string", "minLength": 1, "maxLength": 8192, - "not": { "const": "*" } + "not": { + "const": "*" + } }, "PermissionResourceKind": { "description": "Whether a canonical resource grant covers only that resource or a filesystem directory subtree.", "type": "string", - "enum": ["exact", "directory"] + "enum": [ + "exact", + "directory" + ] }, "PermissionResourceDeclaration": { "type": "object", - "required": ["permission", "resources"], + "required": [ + "permission", + "resources" + ], "properties": { - "permission": { "$ref": "#/$defs/PluginPermission" }, + "permission": { + "$ref": "#/$defs/PluginPermission" + }, "resources": { "type": "array", "minItems": 1, "maxItems": 128, "uniqueItems": true, - "items": { "$ref": "#/$defs/PermissionResource" } + "items": { + "$ref": "#/$defs/PermissionResource" + } }, - "reason": { "type": "string", "maxLength": 1024 } + "reason": { + "type": "string", + "maxLength": 1024 + } + }, + "if": { + "properties": { + "permission": { + "const": "network.stream" + } + } + }, + "then": { + "properties": { + "resources": { + "type": "array", + "items": { + "$ref": "#/$defs/ByteStreamEndpoint" + } + } + } }, - "if": { "properties": { "permission": { "const": "network.stream" } } }, - "then": { "properties": { "resources": { "type": "array", "items": { "$ref": "#/$defs/ByteStreamEndpoint" } } } }, "additionalProperties": false }, "PermissionDeclaration": { "oneOf": [ - { "$ref": "#/$defs/PluginPermission", "not": { "const": "network.stream" } }, - { "$ref": "#/$defs/PermissionResourceDeclaration" } + { + "$ref": "#/$defs/PluginPermission", + "not": { + "const": "network.stream" + } + }, + { + "$ref": "#/$defs/PermissionResourceDeclaration" + } ] }, "RequiredPermissionResourceDeclaration": { "type": "object", - "required": ["permission", "resources"], + "required": [ + "permission", + "resources" + ], "properties": { - "permission": { "$ref": "#/$defs/ResourceScopedPermission" }, + "permission": { + "$ref": "#/$defs/ResourceScopedPermission" + }, "resources": { "type": "array", "minItems": 1, "maxItems": 128, "uniqueItems": true, - "items": { "$ref": "#/$defs/BoundedPermissionResource" } + "items": { + "$ref": "#/$defs/BoundedPermissionResource" + } }, - "reason": { "type": "string", "maxLength": 1024 } + "reason": { + "type": "string", + "maxLength": 1024 + } + }, + "if": { + "properties": { + "permission": { + "const": "network.stream" + } + } + }, + "then": { + "properties": { + "resources": { + "type": "array", + "items": { + "$ref": "#/$defs/ByteStreamEndpoint" + } + } + } }, - "if": { "properties": { "permission": { "const": "network.stream" } } }, - "then": { "properties": { "resources": { "type": "array", "items": { "$ref": "#/$defs/ByteStreamEndpoint" } } } }, "additionalProperties": false }, "RequiredPermissionDeclaration": { @@ -1873,12 +2008,16 @@ "required": { "type": "array", "maxItems": 64, - "items": { "$ref": "#/$defs/RequiredPermissionDeclaration" } + "items": { + "$ref": "#/$defs/RequiredPermissionDeclaration" + } }, "optional": { "type": "array", "maxItems": 64, - "items": { "$ref": "#/$defs/PermissionDeclaration" } + "items": { + "$ref": "#/$defs/PermissionDeclaration" + } } }, "additionalProperties": false @@ -1915,19 +2054,33 @@ }, "PluginEngines": { "type": "object", - "required": ["netcatty", "api"], + "required": [ + "netcatty", + "api" + ], "properties": { - "netcatty": { "$ref": "#/$defs/SemverRange" }, - "api": { "$ref": "#/$defs/SemverRange" } + "netcatty": { + "$ref": "#/$defs/SemverRange" + }, + "api": { + "$ref": "#/$defs/SemverRange" + } }, "additionalProperties": false }, "PluginEngineHeader": { "type": "object", - "required": ["netcatty", "api"], + "required": [ + "netcatty", + "api" + ], "properties": { - "netcatty": { "$ref": "#/$defs/SemverRange" }, - "api": { "$ref": "#/$defs/SemverRange" } + "netcatty": { + "$ref": "#/$defs/SemverRange" + }, + "api": { + "$ref": "#/$defs/SemverRange" + } }, "additionalProperties": true }, @@ -1938,20 +2091,26 @@ "type": "array", "maxItems": 128, "uniqueItems": true, - "items": { "$ref": "#/$defs/FeatureId" } + "items": { + "$ref": "#/$defs/FeatureId" + } }, "optional": { "type": "array", "maxItems": 128, "uniqueItems": true, - "items": { "$ref": "#/$defs/FeatureId" } + "items": { + "$ref": "#/$defs/FeatureId" + } } }, "additionalProperties": false }, "ActivationEvent": { "oneOf": [ - { "const": "onStartupFinished" }, + { + "const": "onStartupFinished" + }, { "type": "string", "maxLength": 256, @@ -1967,9 +2126,14 @@ }, "ThemeIcon": { "type": "object", - "required": ["kind", "name"], + "required": [ + "kind", + "name" + ], "properties": { - "kind": { "const": "theme" }, + "kind": { + "const": "theme" + }, "name": { "type": "string", "minLength": 1, @@ -1981,23 +2145,42 @@ }, "PackageIcon": { "type": "object", - "required": ["kind", "light"], + "required": [ + "kind", + "light" + ], "properties": { - "kind": { "const": "package" }, - "light": { "$ref": "#/$defs/RelativePackagePath" }, - "dark": { "$ref": "#/$defs/RelativePackagePath" } + "kind": { + "const": "package" + }, + "light": { + "$ref": "#/$defs/RelativePackagePath" + }, + "dark": { + "$ref": "#/$defs/RelativePackagePath" + } }, "additionalProperties": false }, "IconReference": { "oneOf": [ - { "$ref": "#/$defs/ThemeIcon" }, - { "$ref": "#/$defs/PackageIcon" } + { + "$ref": "#/$defs/ThemeIcon" + }, + { + "$ref": "#/$defs/PackageIcon" + } ] }, "SettingScope": { "type": "string", - "enum": ["application", "workspace", "host", "session", "device"] + "enum": [ + "application", + "workspace", + "host", + "session", + "device" + ] }, "SettingControl": { "type": "string", @@ -2022,69 +2205,177 @@ }, "SettingOption": { "type": "object", - "required": ["value", "label"], + "required": [ + "value", + "label" + ], "properties": { - "value": { "type": "string", "maxLength": 256 }, - "label": { "$ref": "#/$defs/LocalizedText" }, - "description": { "$ref": "#/$defs/LocalizedText" } + "value": { + "type": "string", + "maxLength": 256 + }, + "label": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + } }, "additionalProperties": false }, "SettingContribution": { "type": "object", - "required": ["id", "label", "control", "scope"], + "required": [ + "id", + "label", + "control", + "scope" + ], "properties": { - "id": { "$ref": "#/$defs/ContributionId" }, - "label": { "$ref": "#/$defs/LocalizedText" }, - "description": { "$ref": "#/$defs/LocalizedText" }, - "control": { "$ref": "#/$defs/SettingControl" }, - "scope": { "$ref": "#/$defs/SettingScope" }, - "default": { "$ref": "#/$defs/JsonValue" }, - "secret": { "type": "boolean", "default": false }, - "required": { "type": "boolean", "default": false }, + "id": { + "$ref": "#/$defs/ContributionId" + }, + "label": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "control": { + "$ref": "#/$defs/SettingControl" + }, + "scope": { + "$ref": "#/$defs/SettingScope" + }, + "default": { + "$ref": "#/$defs/JsonValue" + }, + "secret": { + "type": "boolean", + "default": false + }, + "required": { + "type": "boolean", + "default": false + }, "options": { "type": "array", "maxItems": 256, - "items": { "$ref": "#/$defs/SettingOption" } + "items": { + "$ref": "#/$defs/SettingOption" + } }, - "minimum": { "type": "number" }, - "maximum": { "type": "number" }, - "step": { "type": "number", "exclusiveMinimum": 0 }, - "pattern": { "type": "string", "maxLength": 512 }, - "placeholder": { "$ref": "#/$defs/LocalizedText" }, - "when": { "$ref": "#/$defs/ContextKeyExpression" }, - "restartRequired": { "type": "boolean", "default": false }, - "sync": { "type": "boolean", "default": false }, - "sortable": { "type": "boolean", "default": false }, - "valueSchema": { "$ref": "#/$defs/JsonValue" } + "minimum": { + "type": "number" + }, + "maximum": { + "type": "number" + }, + "step": { + "type": "number", + "exclusiveMinimum": 0 + }, + "pattern": { + "type": "string", + "maxLength": 512 + }, + "placeholder": { + "$ref": "#/$defs/LocalizedText" + }, + "when": { + "$ref": "#/$defs/ContextKeyExpression" + }, + "restartRequired": { + "type": "boolean", + "default": false + }, + "sync": { + "type": "boolean", + "default": false + }, + "sortable": { + "type": "boolean", + "default": false + }, + "valueSchema": { + "$ref": "#/$defs/JsonValue" + }, + "group": { + "$ref": "#/$defs/LocalizedText", + "description": "Host-rendered section heading. Settings and groups retain declaration order; no custom markup or styles." + } }, "additionalProperties": false }, "CommandContribution": { "type": "object", - "required": ["id", "title"], + "required": [ + "id", + "title" + ], "properties": { - "id": { "$ref": "#/$defs/ContributionId" }, - "title": { "$ref": "#/$defs/LocalizedText" }, - "category": { "$ref": "#/$defs/LocalizedText" }, - "description": { "$ref": "#/$defs/LocalizedText" }, - "icon": { "$ref": "#/$defs/IconReference" }, - "enablement": { "$ref": "#/$defs/ContextKeyExpression" }, - "interactive": { "type": "boolean", "default": false, "description": "Require commands.interactive for this command's fixed bounded host interaction budget. Does not grant UI or clipboard permissions." } + "id": { + "$ref": "#/$defs/ContributionId" + }, + "title": { + "$ref": "#/$defs/LocalizedText" + }, + "category": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "icon": { + "$ref": "#/$defs/IconReference" + }, + "enablement": { + "$ref": "#/$defs/ContextKeyExpression" + }, + "interactive": { + "type": "boolean", + "default": false, + "description": "Require commands.interactive for this command's fixed bounded host interaction budget. Does not grant UI or clipboard permissions." + } }, "additionalProperties": false }, "KeybindingContribution": { "type": "object", - "required": ["command", "key"], + "required": [ + "command", + "key" + ], "properties": { - "command": { "$ref": "#/$defs/ContributionId" }, - "key": { "type": "string", "minLength": 1, "maxLength": 128 }, - "mac": { "type": "string", "minLength": 1, "maxLength": 128 }, - "linux": { "type": "string", "minLength": 1, "maxLength": 128 }, - "windows": { "type": "string", "minLength": 1, "maxLength": 128 }, - "when": { "$ref": "#/$defs/ContextKeyExpression" }, - "args": { "$ref": "#/$defs/JsonValue" } + "command": { + "$ref": "#/$defs/ContributionId" + }, + "key": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "mac": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "linux": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "windows": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "when": { + "$ref": "#/$defs/ContextKeyExpression" + }, + "args": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, @@ -2101,25 +2392,59 @@ }, "MenuContribution": { "type": "object", - "required": ["command", "location"], + "required": [ + "command", + "location" + ], "properties": { - "command": { "$ref": "#/$defs/ContributionId" }, - "alt": { "$ref": "#/$defs/ContributionId" }, - "location": { "$ref": "#/$defs/MenuLocation" }, - "title": { "$ref": "#/$defs/LocalizedText" }, - "icon": { "$ref": "#/$defs/IconReference" }, - "group": { "type": "string", "maxLength": 128 }, - "order": { "type": "number" }, - "when": { "$ref": "#/$defs/ContextKeyExpression" }, - "enablement": { "$ref": "#/$defs/ContextKeyExpression" }, - "checked": { "$ref": "#/$defs/ContextKeyExpression" }, - "showKeybinding": { "type": "boolean", "default": true } + "command": { + "$ref": "#/$defs/ContributionId" + }, + "alt": { + "$ref": "#/$defs/ContributionId" + }, + "location": { + "$ref": "#/$defs/MenuLocation" + }, + "title": { + "$ref": "#/$defs/LocalizedText" + }, + "icon": { + "$ref": "#/$defs/IconReference" + }, + "group": { + "type": "string", + "maxLength": 128 + }, + "order": { + "type": "number" + }, + "when": { + "$ref": "#/$defs/ContextKeyExpression" + }, + "enablement": { + "$ref": "#/$defs/ContextKeyExpression" + }, + "checked": { + "$ref": "#/$defs/ContextKeyExpression" + }, + "showKeybinding": { + "type": "boolean", + "default": true + } }, "additionalProperties": false }, "ViewLocation": { "type": "string", - "enum": ["aside", "panel", "tab", "modal", "settings", "vault-page", "terminal-sidebar"] + "enum": [ + "aside", + "panel", + "tab", + "modal", + "vault-page", + "terminal-sidebar" + ] }, "VaultPagesFeature": { "const": "views.vault-pages" @@ -2127,25 +2452,264 @@ "TerminalSidebarFeature": { "const": "views.terminal-sidebar" }, - "PluginViewFocusEvent": { + "PluginViewResourceRequest": { "type": "object", - "required": ["instanceId"], - "properties": { "instanceId": { "type": "string", "minLength": 1, "maxLength": 128 } }, + "required": [ + "instanceId", + "path" + ], + "properties": { + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "path": { + "$ref": "#/$defs/RelativePackagePath" + } + }, "additionalProperties": false }, - "PluginViewFocusRequest": { "$ref": "#/$defs/PluginViewFocusEvent" }, + "PluginViewResourceResult": { + "type": "object", + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "maxLength": 5592500, + "pattern": "^data:image/png;base64," + } + }, + "additionalProperties": false + }, + "HostDrawnViewsFeature": { + "const": "views.host-drawn" + }, + "HostDrawnViewMessage": { + "oneOf": [ + { + "type": "object", + "required": [ + "kind", + "instanceId" + ], + "properties": { + "kind": { + "const": "host-ui.open" + }, + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "stateScope": { + "type": "string", + "maxLength": 128 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "instanceId" + ], + "properties": { + "kind": { + "const": "host-ui.close" + }, + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "instanceId", + "sequence", + "mutations", + "css" + ], + "properties": { + "kind": { + "const": "host-ui.update" + }, + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sequence": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "acknowledgedEvent": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "mutations": { + "type": "array", + "maxItems": 2048, + "items": { + "$ref": "#/$defs/JsonValue" + } + }, + "css": { + "type": "string", + "maxLength": 65536 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "instanceId", + "event" + ], + "properties": { + "kind": { + "const": "host-ui.event" + }, + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "event": { + "$ref": "#/$defs/HostDrawnViewEvent" + } + }, + "additionalProperties": false + } + ] + }, + "HostDrawnViewEvent": { + "type": "object", + "required": [ + "nodeId", + "type" + ], + "properties": { + "nodeId": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "type": { + "enum": [ + "click", + "input", + "change", + "keydown", + "keyup", + "focusin", + "focusout", + "compositionstart", + "compositionupdate", + "compositionend", + "dismiss", + "submit", + "reset" + ] + }, + "value": { + "type": "string", + "maxLength": 8192 + }, + "checked": { + "type": "boolean" + }, + "eventId": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "data": { + "type": "string", + "maxLength": 8192 + }, + "key": { + "type": "string", + "maxLength": 64 + }, + "ctrlKey": { + "type": "boolean" + }, + "metaKey": { + "type": "boolean" + }, + "altKey": { + "type": "boolean" + }, + "shiftKey": { + "type": "boolean" + }, + "values": { + "type": "array", + "maxItems": 128, + "items": { + "type": "string", + "maxLength": 8192 + } + } + }, + "additionalProperties": false + }, + "PluginViewFocusEvent": { + "type": "object", + "required": [ + "instanceId" + ], + "properties": { + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "PluginViewFocusRequest": { + "$ref": "#/$defs/PluginViewFocusEvent" + }, "ViewContribution": { "type": "object", - "required": ["id", "title", "location", "entry"], + "required": [ + "id", + "title", + "location" + ], "properties": { - "id": { "$ref": "#/$defs/ContributionId" }, - "title": { "$ref": "#/$defs/LocalizedText" }, - "location": { "$ref": "#/$defs/ViewLocation" }, - "entry": { "$ref": "#/$defs/RelativePackagePath" }, - "icon": { "$ref": "#/$defs/IconReference" }, - "order": { "type": "number" }, - "when": { "$ref": "#/$defs/ContextKeyExpression" }, - "retainContextWhenHidden": { "type": "boolean", "default": false } + "id": { + "$ref": "#/$defs/ContributionId" + }, + "title": { + "$ref": "#/$defs/LocalizedText" + }, + "location": { + "$ref": "#/$defs/ViewLocation" + }, + "icon": { + "$ref": "#/$defs/IconReference" + }, + "order": { + "type": "number" + }, + "when": { + "$ref": "#/$defs/ContextKeyExpression" + } }, "additionalProperties": false }, @@ -2171,120 +2735,292 @@ }, "ProviderContribution": { "type": "object", - "required": ["id", "label", "kind"], + "required": [ + "id", + "label", + "kind" + ], "properties": { - "id": { "$ref": "#/$defs/ContributionId" }, - "label": { "$ref": "#/$defs/LocalizedText" }, - "description": { "$ref": "#/$defs/LocalizedText" }, - "kind": { "$ref": "#/$defs/ProviderKind" }, + "id": { + "$ref": "#/$defs/ContributionId" + }, + "label": { + "$ref": "#/$defs/LocalizedText" + }, + "description": { + "$ref": "#/$defs/LocalizedText" + }, + "kind": { + "$ref": "#/$defs/ProviderKind" + }, "capabilities": { "type": "array", "maxItems": 64, "uniqueItems": true, - "items": { "$ref": "#/$defs/FeatureId" } + "items": { + "$ref": "#/$defs/FeatureId" + } }, - "configurationSchema": { "$ref": "#/$defs/JsonValue" } + "configurationSchema": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, "ProviderValidationIssue": { "type": "object", - "required": ["severity", "message"], + "required": [ + "severity", + "message" + ], "properties": { - "path": { "type": "string", "maxLength": 1024 }, - "severity": { "type": "string", "enum": ["warning", "error"] }, - "message": { "type": "string", "minLength": 1, "maxLength": 2048 } + "path": { + "type": "string", + "maxLength": 1024 + }, + "severity": { + "type": "string", + "enum": [ + "warning", + "error" + ] + }, + "message": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + } }, "additionalProperties": false }, "ConnectionConfigurationPayload": { "type": "object", - "required": ["configuration"], - "properties": { "configuration": { "$ref": "#/$defs/JsonValue" } }, + "required": [ + "configuration" + ], + "properties": { + "configuration": { + "$ref": "#/$defs/JsonValue" + } + }, "additionalProperties": false }, "ConnectionValidateResult": { "type": "object", - "required": ["valid", "issues"], + "required": [ + "valid", + "issues" + ], "properties": { - "valid": { "type": "boolean" }, - "issues": { "type": "array", "maxItems": 256, "items": { "$ref": "#/$defs/ProviderValidationIssue" } } + "valid": { + "type": "boolean" + }, + "issues": { + "type": "array", + "maxItems": 256, + "items": { + "$ref": "#/$defs/ProviderValidationIssue" + } + } }, "additionalProperties": false }, "ConnectionProbeResult": { "type": "object", - "required": ["available"], + "required": [ + "available" + ], "properties": { - "available": { "type": "boolean" }, - "message": { "type": "string", "maxLength": 2048 }, + "available": { + "type": "boolean" + }, + "message": { + "type": "string", + "maxLength": 2048 + }, "capabilities": { "type": "object", "maxProperties": 64, - "additionalProperties": { "$ref": "#/$defs/JsonValue" } + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + } } }, "additionalProperties": false }, "ConnectionOpenPayload": { "type": "object", - "required": ["configuration", "operationId", "columns", "rows", "inputStreamId", "outputStreamId", "windowBytes"], + "required": [ + "configuration", + "operationId", + "columns", + "rows", + "inputStreamId", + "outputStreamId", + "windowBytes" + ], "properties": { - "configuration": { "$ref": "#/$defs/JsonValue" }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "columns": { "type": "integer", "minimum": 1, "maximum": 16384 }, - "rows": { "type": "integer", "minimum": 1, "maximum": 16384 }, - "inputStreamId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "outputStreamId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "windowBytes": { "type": "integer", "minimum": 1024, "maximum": 16777216 }, + "configuration": { + "$ref": "#/$defs/JsonValue" + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "columns": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "rows": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "inputStreamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "outputStreamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "windowBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 16777216 + }, "credential": { "oneOf": [ - { "$ref": "#/$defs/SecretRef" }, - { "$ref": "#/$defs/CredentialRef" }, - { "$ref": "#/$defs/SecretLeaseRef" } + { + "$ref": "#/$defs/SecretRef" + }, + { + "$ref": "#/$defs/CredentialRef" + }, + { + "$ref": "#/$defs/SecretLeaseRef" + } ] }, - "authenticationProviderId": { "$ref": "#/$defs/ContributionId" } + "authenticationProviderId": { + "$ref": "#/$defs/ContributionId" + } }, "additionalProperties": false }, "ConnectionOpenResult": { "type": "object", - "required": ["connectionId", "status"], + "required": [ + "connectionId", + "status" + ], "properties": { - "connectionId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "status": { "type": "string", "enum": ["connecting", "connected"] }, - "diagnostics": { "type": "array", "maxItems": 256, "items": { "$ref": "#/$defs/ProviderValidationIssue" } } + "connectionId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "status": { + "type": "string", + "enum": [ + "connecting", + "connected" + ] + }, + "diagnostics": { + "type": "array", + "maxItems": 256, + "items": { + "$ref": "#/$defs/ProviderValidationIssue" + } + } }, "additionalProperties": false }, "ConnectionControlPayload": { "type": "object", - "required": ["connectionId", "operationId"], + "required": [ + "connectionId", + "operationId" + ], "properties": { - "connectionId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "connectionId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, "ConnectionResizePayload": { "type": "object", - "required": ["connectionId", "operationId", "columns", "rows"], + "required": [ + "connectionId", + "operationId", + "columns", + "rows" + ], "properties": { - "connectionId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "columns": { "type": "integer", "minimum": 1, "maximum": 16384 }, - "rows": { "type": "integer", "minimum": 1, "maximum": 16384 } + "connectionId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "columns": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "rows": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + } }, "additionalProperties": false }, "ConnectionSignalPayload": { "type": "object", - "required": ["connectionId", "operationId", "signal"], + "required": [ + "connectionId", + "operationId", + "signal" + ], "properties": { - "connectionId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "signal": { "type": "string", "enum": ["interrupt", "terminate", "kill", "eof", "break"] } + "connectionId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "signal": { + "type": "string", + "enum": [ + "interrupt", + "terminate", + "kill", + "eof", + "break" + ] + } }, "additionalProperties": false }, @@ -2294,12 +3030,34 @@ }, "ConnectionStatusResult": { "type": "object", - "required": ["status"], + "required": [ + "status" + ], "properties": { - "status": { "type": "string", "enum": ["connecting", "connected", "reconnecting", "closed", "error"] }, - "message": { "type": "string", "maxLength": 2048 }, - "retryable": { "type": "boolean" }, - "diagnostics": { "type": "array", "maxItems": 256, "items": { "$ref": "#/$defs/ProviderValidationIssue" } } + "status": { + "type": "string", + "enum": [ + "connecting", + "connected", + "reconnecting", + "closed", + "error" + ] + }, + "message": { + "type": "string", + "maxLength": 2048 + }, + "retryable": { + "type": "boolean" + }, + "diagnostics": { + "type": "array", + "maxItems": 256, + "items": { + "$ref": "#/$defs/ProviderValidationIssue" + } + } }, "additionalProperties": false }, @@ -2307,76 +3065,217 @@ "oneOf": [ { "type": "object", - "required": ["id", "kind", "title"], + "required": [ + "id", + "kind", + "title" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 128 }, - "kind": { "type": "string", "enum": ["text", "password", "otp"] }, - "title": { "type": "string", "minLength": 1, "maxLength": 512 }, - "message": { "type": "string", "maxLength": 2048 }, - "placeholder": { "type": "string", "maxLength": 512 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "kind": { + "type": "string", + "enum": [ + "text", + "password", + "otp" + ] + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "message": { + "type": "string", + "maxLength": 2048 + }, + "placeholder": { + "type": "string", + "maxLength": 512 + } }, "additionalProperties": false }, { "type": "object", - "required": ["id", "kind", "title", "choices"], + "required": [ + "id", + "kind", + "title", + "choices" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 128 }, - "kind": { "const": "choice" }, - "title": { "type": "string", "minLength": 1, "maxLength": 512 }, - "message": { "type": "string", "maxLength": 2048 }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "kind": { + "const": "choice" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "message": { + "type": "string", + "maxLength": 2048 + }, "choices": { - "type": "array", "minItems": 1, "maxItems": 64, + "type": "array", + "minItems": 1, + "maxItems": 64, "items": { - "type": "object", "required": ["id", "label"], + "type": "object", + "required": [ + "id", + "label" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 128 }, - "label": { "type": "string", "minLength": 1, "maxLength": 512 }, - "description": { "type": "string", "maxLength": 2048 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "description": { + "type": "string", + "maxLength": 2048 + } }, "additionalProperties": false } }, - "multiple": { "type": "boolean" } + "multiple": { + "type": "boolean" + } }, "additionalProperties": false }, { "type": "object", - "required": ["id", "kind", "title"], + "required": [ + "id", + "kind", + "title" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 128 }, - "kind": { "const": "confirmation" }, - "title": { "type": "string", "minLength": 1, "maxLength": 512 }, - "message": { "type": "string", "maxLength": 2048 }, - "confirmLabel": { "type": "string", "maxLength": 128 }, - "cancelLabel": { "type": "string", "maxLength": 128 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "kind": { + "const": "confirmation" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "message": { + "type": "string", + "maxLength": 2048 + }, + "confirmLabel": { + "type": "string", + "maxLength": 128 + }, + "cancelLabel": { + "type": "string", + "maxLength": 128 + } }, "additionalProperties": false }, { "type": "object", - "required": ["id", "kind", "title", "url"], + "required": [ + "id", + "kind", + "title", + "url" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 128 }, - "kind": { "const": "browser" }, - "title": { "type": "string", "minLength": 1, "maxLength": 512 }, - "url": { "type": "string", "format": "uri", "maxLength": 8192 }, - "callbackUri": { "type": "string", "format": "uri", "maxLength": 8192 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "kind": { + "const": "browser" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "url": { + "type": "string", + "format": "uri", + "maxLength": 8192 + }, + "callbackUri": { + "type": "string", + "format": "uri", + "maxLength": 8192 + } }, "additionalProperties": false }, { "type": "object", - "required": ["id", "kind", "title", "verificationUri", "userCode", "expiresAt"], + "required": [ + "id", + "kind", + "title", + "verificationUri", + "userCode", + "expiresAt" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 128 }, - "kind": { "const": "deviceCode" }, - "title": { "type": "string", "minLength": 1, "maxLength": 512 }, - "verificationUri": { "type": "string", "format": "uri", "maxLength": 8192 }, - "userCode": { "type": "string", "minLength": 1, "maxLength": 256 }, - "expiresAt": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, - "intervalMs": { "type": "integer", "minimum": 100, "maximum": 300000 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "kind": { + "const": "deviceCode" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "verificationUri": { + "type": "string", + "format": "uri", + "maxLength": 8192 + }, + "userCode": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "expiresAt": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "intervalMs": { + "type": "integer", + "minimum": 100, + "maximum": 300000 + } }, "additionalProperties": false } @@ -2384,27 +3283,79 @@ }, "AuthenticationBeginPayload": { "type": "object", - "required": ["operationId", "connectionProviderId", "configuration"], + "required": [ + "operationId", + "connectionProviderId", + "configuration" + ], "properties": { - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "connectionProviderId": { "$ref": "#/$defs/ContributionId" }, - "configuration": { "$ref": "#/$defs/JsonValue" }, - "credential": { "oneOf": [{ "$ref": "#/$defs/SecretRef" }, { "$ref": "#/$defs/CredentialRef" }, { "$ref": "#/$defs/SecretLeaseRef" }] } + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "connectionProviderId": { + "$ref": "#/$defs/ContributionId" + }, + "configuration": { + "$ref": "#/$defs/JsonValue" + }, + "credential": { + "oneOf": [ + { + "$ref": "#/$defs/SecretRef" + }, + { + "$ref": "#/$defs/CredentialRef" + }, + { + "$ref": "#/$defs/SecretLeaseRef" + } + ] + } }, "additionalProperties": false }, "AuthenticationResponsePayload": { "type": "object", - "required": ["operationId", "challengeId", "response"], + "required": [ + "operationId", + "challengeId", + "response" + ], "properties": { - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "challengeId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "challengeId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, "response": { "oneOf": [ - { "type": "string", "minLength": 1, "maxLength": 8192 }, - { "type": "boolean" }, - { "type": "array", "maxItems": 64, "uniqueItems": true, "items": { "type": "string", "maxLength": 128 } }, - { "$ref": "#/$defs/SecretLeaseRef" } + { + "type": "string", + "minLength": 1, + "maxLength": 8192 + }, + { + "type": "boolean" + }, + { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "maxLength": 128 + } + }, + { + "$ref": "#/$defs/SecretLeaseRef" + } ] } }, @@ -2414,37 +3365,71 @@ "oneOf": [ { "type": "object", - "required": ["status", "challenge"], + "required": [ + "status", + "challenge" + ], "properties": { - "status": { "const": "challenge" }, - "challenge": { "$ref": "#/$defs/AuthenticationChallenge" } + "status": { + "const": "challenge" + }, + "challenge": { + "$ref": "#/$defs/AuthenticationChallenge" + } }, "additionalProperties": false }, { "type": "object", - "required": ["status"], + "required": [ + "status" + ], "properties": { - "status": { "const": "authenticated" }, - "credential": { "oneOf": [{ "$ref": "#/$defs/SecretRef" }, { "$ref": "#/$defs/CredentialRef" }] } + "status": { + "const": "authenticated" + }, + "credential": { + "oneOf": [ + { + "$ref": "#/$defs/SecretRef" + }, + { + "$ref": "#/$defs/CredentialRef" + } + ] + } }, "additionalProperties": false }, { "type": "object", - "required": ["status"], + "required": [ + "status" + ], "properties": { - "status": { "const": "cancelled" }, - "message": { "type": "string", "maxLength": 2048 } + "status": { + "const": "cancelled" + }, + "message": { + "type": "string", + "maxLength": 2048 + } }, "additionalProperties": false }, { "type": "object", - "required": ["status"], + "required": [ + "status" + ], "properties": { - "status": { "const": "failed" }, - "message": { "type": "string", "maxLength": 2048 } + "status": { + "const": "failed" + }, + "message": { + "type": "string", + "maxLength": 2048 + } }, "additionalProperties": false } @@ -2452,15 +3437,32 @@ }, "ImporterDetectPayload": { "type": "object", - "required": ["sample"], + "required": [ + "sample" + ], "properties": { - "fileName": { "type": "string", "maxLength": 1024 }, - "mediaType": { "type": "string", "maxLength": 256 }, + "fileName": { + "type": "string", + "maxLength": 1024 + }, + "mediaType": { + "type": "string", + "maxLength": 256 + }, "sample": { - "type": "object", "required": ["encoding", "data"], + "type": "object", + "required": [ + "encoding", + "data" + ], "properties": { - "encoding": { "const": "base64" }, - "data": { "type": "string", "maxLength": 174764 } + "encoding": { + "const": "base64" + }, + "data": { + "type": "string", + "maxLength": 174764 + } }, "additionalProperties": false } @@ -2469,45 +3471,111 @@ }, "ImporterDetectResult": { "type": "object", - "required": ["confidence"], + "required": [ + "confidence" + ], "properties": { - "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, - "format": { "type": "string", "maxLength": 256 }, - "reason": { "type": "string", "maxLength": 2048 } + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "format": { + "type": "string", + "maxLength": 256 + }, + "reason": { + "type": "string", + "maxLength": 2048 + } }, "additionalProperties": false }, "ImporterParsePayload": { "type": "object", - "required": ["operationId", "inputStreamId", "outputStreamId", "windowBytes"], + "required": [ + "operationId", + "inputStreamId", + "outputStreamId", + "windowBytes" + ], "properties": { - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "fileName": { "type": "string", "maxLength": 1024 }, - "mediaType": { "type": "string", "maxLength": 256 }, - "inputStreamId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "outputStreamId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "windowBytes": { "type": "integer", "minimum": 1024, "maximum": 16777216 }, - "options": { "$ref": "#/$defs/JsonValue" } + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "fileName": { + "type": "string", + "maxLength": 1024 + }, + "mediaType": { + "type": "string", + "maxLength": 256 + }, + "inputStreamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "outputStreamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "windowBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 16777216 + }, + "options": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, "ImporterParseResult": { "type": "object", - "required": ["parsed", "warnings", "errors"], + "required": [ + "parsed", + "warnings", + "errors" + ], "properties": { - "parsed": { "type": "integer", "minimum": 0, "maximum": 10000 }, - "warnings": { "type": "integer", "minimum": 0, "maximum": 10000 }, - "errors": { "type": "integer", "minimum": 0, "maximum": 10000 } + "parsed": { + "type": "integer", + "minimum": 0, + "maximum": 10000 + }, + "warnings": { + "type": "integer", + "minimum": 0, + "maximum": 10000 + }, + "errors": { + "type": "integer", + "minimum": 0, + "maximum": 10000 + } }, "additionalProperties": false }, "ImporterPluginConnectionDraft": { "type": "object", - "required": ["providerId", "configuration"], + "required": [ + "providerId", + "configuration" + ], "properties": { - "providerId": { "$ref": "#/$defs/ContributionId" }, - "configuration": { "$ref": "#/$defs/JsonValue" }, - "authenticationProviderId": { "$ref": "#/$defs/ContributionId" }, + "providerId": { + "$ref": "#/$defs/ContributionId" + }, + "configuration": { + "$ref": "#/$defs/JsonValue" + }, + "authenticationProviderId": { + "$ref": "#/$defs/ContributionId" + }, "credentialId": { "type": "string", "minLength": 1, @@ -2522,166 +3590,461 @@ "type": "object", "anyOf": [ { - "required": ["hostname"], + "required": [ + "hostname" + ], "properties": { - "hostname": { "type": "string", "minLength": 1, "maxLength": 1024 } + "hostname": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + } } }, { - "required": ["protocol", "pluginConnection"], + "required": [ + "protocol", + "pluginConnection" + ], "properties": { - "protocol": { "$ref": "#/$defs/PluginHostProtocol" }, - "pluginConnection": { "$ref": "#/$defs/ImporterPluginConnectionDraft" } + "protocol": { + "$ref": "#/$defs/PluginHostProtocol" + }, + "pluginConnection": { + "$ref": "#/$defs/ImporterPluginConnectionDraft" + } } } ], "if": { "type": "object", - "required": ["protocol"], - "properties": { "protocol": { "$ref": "#/$defs/PluginHostProtocol" } } + "required": [ + "protocol" + ], + "properties": { + "protocol": { + "$ref": "#/$defs/PluginHostProtocol" + } + } + }, + "then": { + "required": [ + "pluginConnection" + ] }, - "then": { "required": ["pluginConnection"] }, "dependentRequired": { - "pluginConnection": ["protocol"] + "pluginConnection": [ + "protocol" + ] }, "dependentSchemas": { "pluginConnection": { "type": "object", - "required": ["protocol"], - "properties": { "protocol": { "$ref": "#/$defs/PluginHostProtocol" } } + "required": [ + "protocol" + ], + "properties": { + "protocol": { + "$ref": "#/$defs/PluginHostProtocol" + } + } } }, "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 256 }, - "label": { "type": "string", "minLength": 1, "maxLength": 512 }, - "hostname": { "type": "string", "minLength": 1, "maxLength": 1024 }, - "username": { "type": "string", "maxLength": 512 }, - "group": { "type": "string", "minLength": 1, "maxLength": 512 }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "hostname": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "username": { + "type": "string", + "maxLength": 512 + }, + "group": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, "tags": { "type": "array", "maxItems": 128, "uniqueItems": true, - "items": { "type": "string", "minLength": 1, "maxLength": 256 } + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } }, - "os": { "type": "string", "enum": ["linux", "windows", "macos"] }, - "deviceType": { "type": "string", "enum": ["general", "network"] }, - "identityId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "identityFileId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "telnetIdentityId": { "type": "string", "minLength": 1, "maxLength": 256 }, - "protocol": { - "oneOf": [ - { "type": "string", "enum": ["ssh", "telnet", "mosh", "et", "local", "serial"] }, - { "$ref": "#/$defs/PluginHostProtocol" } + "os": { + "type": "string", + "enum": [ + "linux", + "windows", + "macos" ] }, - "pluginConnection": { "$ref": "#/$defs/ImporterPluginConnectionDraft" }, - "notes": { "type": "string", "maxLength": 65536 }, - "theme": { "type": "string", "minLength": 1, "maxLength": 256 }, - "sftpEncoding": { "type": "string", "minLength": 1, "maxLength": 64 }, - "sftpFileProtocol": { "type": "string", "enum": ["auto", "sftp", "scp"] }, - "moshEnabled": { "type": "boolean" }, - "etEnabled": { "type": "boolean" }, - "telnetEnabled": { "type": "boolean" }, - "sftpSudo": { "type": "boolean" }, - "requiresMfa": { "type": "boolean" }, - "useSshAgent": { "type": "boolean" }, - "identitiesOnly": { "type": "boolean" }, - "agentForwarding": { "type": "boolean" }, - "x11Forwarding": { "type": "boolean" }, - "showLineTimestamps": { "type": "boolean" }, - "disableDynamicTabTitle": { "type": "boolean" }, - "pinned": { "type": "boolean" }, - "autoOpenSftpPanel": { "type": "boolean" }, - "sftpFollowTerminalCwd": { "type": "boolean" }, - "port": { "type": "integer", "minimum": 1, "maximum": 65535 }, - "telnetPort": { "type": "integer", "minimum": 1, "maximum": 65535 }, - "etPort": { "type": "integer", "minimum": 1, "maximum": 65535 }, - "keepaliveInterval": { "type": "integer", "minimum": 0, "maximum": 3600 }, - "keepaliveCountMax": { "type": "integer", "minimum": 1, "maximum": 100 } + "deviceType": { + "type": "string", + "enum": [ + "general", + "network" + ] + }, + "identityId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "identityFileId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "telnetIdentityId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "protocol": { + "oneOf": [ + { + "type": "string", + "enum": [ + "ssh", + "telnet", + "mosh", + "et", + "local", + "serial" + ] + }, + { + "$ref": "#/$defs/PluginHostProtocol" + } + ] + }, + "pluginConnection": { + "$ref": "#/$defs/ImporterPluginConnectionDraft" + }, + "notes": { + "type": "string", + "maxLength": 65536 + }, + "theme": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "sftpEncoding": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "sftpFileProtocol": { + "type": "string", + "enum": [ + "auto", + "sftp", + "scp" + ] + }, + "moshEnabled": { + "type": "boolean" + }, + "etEnabled": { + "type": "boolean" + }, + "telnetEnabled": { + "type": "boolean" + }, + "sftpSudo": { + "type": "boolean" + }, + "requiresMfa": { + "type": "boolean" + }, + "useSshAgent": { + "type": "boolean" + }, + "identitiesOnly": { + "type": "boolean" + }, + "agentForwarding": { + "type": "boolean" + }, + "x11Forwarding": { + "type": "boolean" + }, + "showLineTimestamps": { + "type": "boolean" + }, + "disableDynamicTabTitle": { + "type": "boolean" + }, + "pinned": { + "type": "boolean" + }, + "autoOpenSftpPanel": { + "type": "boolean" + }, + "sftpFollowTerminalCwd": { + "type": "boolean" + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "telnetPort": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "etPort": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "keepaliveInterval": { + "type": "integer", + "minimum": 0, + "maximum": 3600 + }, + "keepaliveCountMax": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } }, "additionalProperties": false }, "ImporterIdentityDraft": { "type": "object", - "required": ["label", "username", "authMethod"], + "required": [ + "label", + "username", + "authMethod" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 256 }, - "label": { "type": "string", "minLength": 1, "maxLength": 512 }, - "username": { "type": "string", "minLength": 1, "maxLength": 512 }, - "authMethod": { "type": "string", "enum": ["password", "key", "certificate"] }, - "password": { "type": "string", "maxLength": 65536 }, - "keyId": { "type": "string", "minLength": 1, "maxLength": 256 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "username": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "authMethod": { + "type": "string", + "enum": [ + "password", + "key", + "certificate" + ] + }, + "password": { + "type": "string", + "maxLength": 65536 + }, + "keyId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } }, "additionalProperties": false }, "ImporterKeyDraft": { "type": "object", - "required": ["label", "type"], + "required": [ + "label", + "type" + ], "oneOf": [ { - "required": ["privateKey"], + "required": [ + "privateKey" + ], "properties": { - "privateKey": { "type": "string", "minLength": 1, "maxLength": 2097152 } + "privateKey": { + "type": "string", + "minLength": 1, + "maxLength": 2097152 + } } }, { - "required": ["filePath"], + "required": [ + "filePath" + ], "properties": { - "filePath": { "type": "string", "minLength": 1, "maxLength": 8192 } + "filePath": { + "type": "string", + "minLength": 1, + "maxLength": 8192 + } } } ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 256 }, - "label": { "type": "string", "minLength": 1, "maxLength": 512 }, - "type": { "type": "string", "enum": ["RSA", "ECDSA", "ED25519"] }, - "privateKey": { "type": "string", "minLength": 1, "maxLength": 2097152 }, - "publicKey": { "type": "string", "maxLength": 1048576 }, - "certificate": { "type": "string", "maxLength": 1048576 }, - "passphrase": { "type": "string", "maxLength": 65536 }, - "filePath": { "type": "string", "minLength": 1, "maxLength": 8192 }, - "category": { "type": "string", "enum": ["key", "certificate", "identity"] } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "type": { + "type": "string", + "enum": [ + "RSA", + "ECDSA", + "ED25519" + ] + }, + "privateKey": { + "type": "string", + "minLength": 1, + "maxLength": 2097152 + }, + "publicKey": { + "type": "string", + "maxLength": 1048576 + }, + "certificate": { + "type": "string", + "maxLength": 1048576 + }, + "passphrase": { + "type": "string", + "maxLength": 65536 + }, + "filePath": { + "type": "string", + "minLength": 1, + "maxLength": 8192 + }, + "category": { + "type": "string", + "enum": [ + "key", + "certificate", + "identity" + ] + } }, "additionalProperties": false }, "ImporterSnippetDraft": { "type": "object", - "required": ["label", "command"], + "required": [ + "label", + "command" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 256 }, - "label": { "type": "string", "minLength": 1, "maxLength": 512 }, - "command": { "type": "string", "minLength": 1, "maxLength": 1048576 }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "command": { + "type": "string", + "minLength": 1, + "maxLength": 1048576 + }, "tags": { "type": "array", "maxItems": 128, "uniqueItems": true, - "items": { "type": "string", "minLength": 1, "maxLength": 256 } + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } }, - "kind": { "type": "string", "enum": ["snippet", "script"] }, - "description": { "type": "string", "maxLength": 4096 } + "kind": { + "type": "string", + "enum": [ + "snippet", + "script" + ] + }, + "description": { + "type": "string", + "maxLength": 4096 + } }, "additionalProperties": false }, "ImporterGroupDraft": { "oneOf": [ - { "type": "string", "minLength": 1, "maxLength": 512 }, + { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, { "type": "object", "properties": { - "path": { "type": "string", "minLength": 1, "maxLength": 512 }, - "label": { "type": "string", "minLength": 1, "maxLength": 512 } + "path": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } }, "anyOf": [ { - "required": ["path"], + "required": [ + "path" + ], "properties": { - "path": { "type": "string", "minLength": 1, "maxLength": 512 } + "path": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } } }, { - "required": ["label"], + "required": [ + "label" + ], "properties": { - "label": { "type": "string", "minLength": 1, "maxLength": 512 } + "label": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } } } ], @@ -2692,48 +4055,94 @@ "ImporterRecord": { "oneOf": [ { - "type": "object", "required": ["type", "draft"], + "type": "object", + "required": [ + "type", + "draft" + ], "properties": { - "type": { "const": "draft" }, + "type": { + "const": "draft" + }, "draft": { "oneOf": [ { - "type": "object", "required": ["kind", "value"], + "type": "object", + "required": [ + "kind", + "value" + ], "properties": { - "kind": { "const": "host" }, - "value": { "$ref": "#/$defs/ImporterHostDraft" } + "kind": { + "const": "host" + }, + "value": { + "$ref": "#/$defs/ImporterHostDraft" + } }, "additionalProperties": false }, { - "type": "object", "required": ["kind", "value"], + "type": "object", + "required": [ + "kind", + "value" + ], "properties": { - "kind": { "const": "identity" }, - "value": { "$ref": "#/$defs/ImporterIdentityDraft" } + "kind": { + "const": "identity" + }, + "value": { + "$ref": "#/$defs/ImporterIdentityDraft" + } }, "additionalProperties": false }, { - "type": "object", "required": ["kind", "value"], + "type": "object", + "required": [ + "kind", + "value" + ], "properties": { - "kind": { "const": "key" }, - "value": { "$ref": "#/$defs/ImporterKeyDraft" } + "kind": { + "const": "key" + }, + "value": { + "$ref": "#/$defs/ImporterKeyDraft" + } }, "additionalProperties": false }, { - "type": "object", "required": ["kind", "value"], + "type": "object", + "required": [ + "kind", + "value" + ], "properties": { - "kind": { "const": "snippet" }, - "value": { "$ref": "#/$defs/ImporterSnippetDraft" } + "kind": { + "const": "snippet" + }, + "value": { + "$ref": "#/$defs/ImporterSnippetDraft" + } }, "additionalProperties": false }, { - "type": "object", "required": ["kind", "value"], + "type": "object", + "required": [ + "kind", + "value" + ], "properties": { - "kind": { "const": "group" }, - "value": { "$ref": "#/$defs/ImporterGroupDraft" } + "kind": { + "const": "group" + }, + "value": { + "$ref": "#/$defs/ImporterGroupDraft" + } }, "additionalProperties": false } @@ -2743,28 +4152,64 @@ "additionalProperties": false }, { - "type": "object", "required": ["type", "message"], + "type": "object", + "required": [ + "type", + "message" + ], "properties": { - "type": { "type": "string", "enum": ["warning", "error"] }, - "code": { "type": "string", "maxLength": 128 }, - "message": { "type": "string", "minLength": 1, "maxLength": 2048 }, - "path": { "type": "string", "maxLength": 1024 } + "type": { + "type": "string", + "enum": [ + "warning", + "error" + ] + }, + "code": { + "type": "string", + "maxLength": 128 + }, + "message": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + "path": { + "type": "string", + "maxLength": 1024 + } }, "additionalProperties": false }, { - "type": "object", "required": ["type", "completed"], + "type": "object", + "required": [ + "type", + "completed" + ], "properties": { - "type": { "const": "progress" }, - "completed": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, - "total": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, - "message": { "type": "string", "maxLength": 2048 } + "type": { + "const": "progress" + }, + "completed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "total": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "message": { + "type": "string", + "maxLength": 2048 + } }, "additionalProperties": false } ] }, - "SyncObjectKey": { "type": "string", "minLength": 1, @@ -2777,26 +4222,56 @@ }, "SyncAccount": { "type": "object", - "required": ["id"], + "required": [ + "id" + ], "properties": { - "id": { "type": "string", "minLength": 1, "maxLength": 512 }, - "email": { "type": "string", "maxLength": 512 }, - "name": { "type": "string", "maxLength": 512 }, - "avatarUrl": { "type": "string", "maxLength": 2048 } + "id": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "email": { + "type": "string", + "maxLength": 512 + }, + "name": { + "type": "string", + "maxLength": 512 + }, + "avatarUrl": { + "type": "string", + "maxLength": 2048 + } }, "additionalProperties": false }, "SyncConnectPayload": { "type": "object", - "required": ["configuration", "operationId"], + "required": [ + "configuration", + "operationId" + ], "properties": { - "configuration": { "$ref": "#/$defs/JsonValue" }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "configuration": { + "$ref": "#/$defs/JsonValue" + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, "credential": { "oneOf": [ - { "$ref": "#/$defs/SecretRef" }, - { "$ref": "#/$defs/CredentialRef" }, - { "$ref": "#/$defs/SecretLeaseRef" } + { + "$ref": "#/$defs/SecretRef" + }, + { + "$ref": "#/$defs/CredentialRef" + }, + { + "$ref": "#/$defs/SecretLeaseRef" + } ] } }, @@ -2804,16 +4279,24 @@ }, "SyncConnectResult": { "type": "object", - "required": ["account"], + "required": [ + "account" + ], "properties": { - "account": { "$ref": "#/$defs/SyncAccount" } + "account": { + "$ref": "#/$defs/SyncAccount" + } }, "additionalProperties": false }, "SyncDisconnectPayload": { "type": "object", "properties": { - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, @@ -2823,18 +4306,28 @@ "SyncGetAccountPayload": { "type": "object", "properties": { - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, "SyncGetAccountResult": { "type": "object", - "required": ["account"], + "required": [ + "account" + ], "properties": { "account": { "oneOf": [ - { "$ref": "#/$defs/SyncAccount" }, - { "type": "null" } + { + "$ref": "#/$defs/SyncAccount" + }, + { + "type": "null" + } ] } }, @@ -2843,30 +4336,69 @@ "SyncGetCapabilitiesPayload": { "type": "object", "properties": { - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, "SyncCapabilitiesResult": { "type": "object", - "required": ["revisions", "conditionalWrites", "atomicReplacement"], + "required": [ + "revisions", + "conditionalWrites", + "atomicReplacement" + ], "properties": { - "revisions": { "type": "boolean" }, - "conditionalWrites": { "type": "boolean" }, - "atomicReplacement": { "type": "boolean" }, - "maxObjectBytes": { "type": "integer", "minimum": 1, "maximum": 67108864 }, - "maxObjects": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } + "revisions": { + "type": "boolean" + }, + "conditionalWrites": { + "type": "boolean" + }, + "atomicReplacement": { + "type": "boolean" + }, + "maxObjectBytes": { + "type": "integer", + "minimum": 1, + "maximum": 67108864 + }, + "maxObjects": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } }, "additionalProperties": false }, "SyncReadObjectPayload": { "type": "object", - "required": ["key", "operationId"], + "required": [ + "key", + "operationId" + ], "properties": { - "key": { "$ref": "#/$defs/SyncObjectKey" }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "outputStreamId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "windowBytes": { "type": "integer", "minimum": 1024, "maximum": 16777216 } + "key": { + "$ref": "#/$defs/SyncObjectKey" + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "outputStreamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "windowBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 16777216 + } }, "additionalProperties": false }, @@ -2874,34 +4406,76 @@ "oneOf": [ { "type": "object", - "required": ["found"], + "required": [ + "found" + ], "properties": { - "found": { "const": false } + "found": { + "const": false + } }, "additionalProperties": false }, { "type": "object", - "required": ["found", "byteLength", "encoding", "data"], + "required": [ + "found", + "byteLength", + "encoding", + "data" + ], "properties": { - "found": { "const": true }, - "byteLength": { "type": "integer", "minimum": 0, "maximum": 67108864 }, - "encoding": { "const": "base64" }, - "data": { "type": "string", "maxLength": 9007199254740991 }, - "revision": { "$ref": "#/$defs/SyncObjectRevision" }, - "contentType": { "type": "string", "maxLength": 256 } + "found": { + "const": true + }, + "byteLength": { + "type": "integer", + "minimum": 0, + "maximum": 67108864 + }, + "encoding": { + "const": "base64" + }, + "data": { + "type": "string", + "maxLength": 9007199254740991 + }, + "revision": { + "$ref": "#/$defs/SyncObjectRevision" + }, + "contentType": { + "type": "string", + "maxLength": 256 + } }, "additionalProperties": false }, { "type": "object", - "required": ["found", "byteLength", "streamed"], + "required": [ + "found", + "byteLength", + "streamed" + ], "properties": { - "found": { "const": true }, - "byteLength": { "type": "integer", "minimum": 0, "maximum": 67108864 }, - "streamed": { "const": true }, - "revision": { "$ref": "#/$defs/SyncObjectRevision" }, - "contentType": { "type": "string", "maxLength": 256 } + "found": { + "const": true + }, + "byteLength": { + "type": "integer", + "minimum": 0, + "maximum": 67108864 + }, + "streamed": { + "const": true + }, + "revision": { + "$ref": "#/$defs/SyncObjectRevision" + }, + "contentType": { + "type": "string", + "maxLength": 256 + } }, "additionalProperties": false } @@ -2909,48 +4483,100 @@ }, "SyncWriteObjectPayload": { "type": "object", - "required": ["key", "operationId", "byteLength"], + "required": [ + "key", + "operationId", + "byteLength" + ], "properties": { - "key": { "$ref": "#/$defs/SyncObjectKey" }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "byteLength": { "type": "integer", "minimum": 0, "maximum": 67108864 }, + "key": { + "$ref": "#/$defs/SyncObjectKey" + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "byteLength": { + "type": "integer", + "minimum": 0, + "maximum": 67108864 + }, "expectedRevision": { "oneOf": [ - { "$ref": "#/$defs/SyncObjectRevision" }, - { "type": "null" } + { + "$ref": "#/$defs/SyncObjectRevision" + }, + { + "type": "null" + } ] }, - "encoding": { "const": "base64" }, - "data": { "type": "string", "maxLength": 9007199254740991 }, - "inputStreamId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "windowBytes": { "type": "integer", "minimum": 1024, "maximum": 16777216 } + "encoding": { + "const": "base64" + }, + "data": { + "type": "string", + "maxLength": 9007199254740991 + }, + "inputStreamId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "windowBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 16777216 + } }, "additionalProperties": false }, "SyncWriteObjectResult": { "type": "object", - "required": ["created"], + "required": [ + "created" + ], "properties": { - "created": { "type": "boolean" }, - "revision": { "$ref": "#/$defs/SyncObjectRevision" } + "created": { + "type": "boolean" + }, + "revision": { + "$ref": "#/$defs/SyncObjectRevision" + } }, "additionalProperties": false }, "SyncDeleteObjectPayload": { "type": "object", - "required": ["key", "operationId"], + "required": [ + "key", + "operationId" + ], "properties": { - "key": { "$ref": "#/$defs/SyncObjectKey" }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "expectedRevision": { "$ref": "#/$defs/SyncObjectRevision" } + "key": { + "$ref": "#/$defs/SyncObjectKey" + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "expectedRevision": { + "$ref": "#/$defs/SyncObjectRevision" + } }, "additionalProperties": false }, "SyncDeleteObjectResult": { "type": "object", - "required": ["deleted"], + "required": [ + "deleted" + ], "properties": { - "deleted": { "type": "boolean" } + "deleted": { + "type": "boolean" + } }, "additionalProperties": false }, @@ -2967,36 +4593,56 @@ }, "CompanionExecutableVariant": { "type": "object", - "required": ["path", "platforms", "sha256"], + "required": [ + "path", + "platforms", + "sha256" + ], "properties": { - "path": { "$ref": "#/$defs/RelativePackagePath" }, + "path": { + "$ref": "#/$defs/RelativePackagePath" + }, "platforms": { "type": "array", "minItems": 1, "maxItems": 6, "uniqueItems": true, - "items": { "$ref": "#/$defs/CompanionPlatform" } + "items": { + "$ref": "#/$defs/CompanionPlatform" + } }, - "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" } + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } }, "additionalProperties": false }, "CompanionExecutable": { "type": "object", - "required": ["id", "variants"], + "required": [ + "id", + "variants" + ], "properties": { - "id": { "$ref": "#/$defs/ContributionId" }, + "id": { + "$ref": "#/$defs/ContributionId" + }, "variants": { "type": "array", "minItems": 1, "maxItems": 12, - "items": { "$ref": "#/$defs/CompanionExecutableVariant" } + "items": { + "$ref": "#/$defs/CompanionExecutableVariant" + } }, "permissions": { "type": "array", "maxItems": 32, "uniqueItems": true, - "items": { "$ref": "#/$defs/PluginPermission" } + "items": { + "$ref": "#/$defs/PluginPermission" + } } }, "additionalProperties": false @@ -3059,13 +4705,31 @@ }, "PluginManifestHeader": { "type": "object", - "required": ["manifestVersion", "id", "version", "engines"], + "required": [ + "manifestVersion", + "id", + "version", + "engines" + ], "properties": { - "$schema": { "type": "string", "format": "uri-reference" }, - "manifestVersion": { "type": "integer", "minimum": 1, "maximum": 65535 }, - "id": { "$ref": "#/$defs/PluginId" }, - "version": { "$ref": "#/$defs/SemanticVersion" }, - "engines": { "$ref": "#/$defs/PluginEngineHeader" } + "$schema": { + "type": "string", + "format": "uri-reference" + }, + "manifestVersion": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "id": { + "$ref": "#/$defs/PluginId" + }, + "version": { + "$ref": "#/$defs/SemanticVersion" + }, + "engines": { + "$ref": "#/$defs/PluginEngineHeader" + } }, "additionalProperties": true }, @@ -3204,32 +4868,73 @@ }, "RpcId": { "oneOf": [ - { "type": "string", "minLength": 1, "maxLength": 128 }, - { "$ref": "#/$defs/SafeUnsignedInteger" } + { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + { + "$ref": "#/$defs/SafeUnsignedInteger" + } ] }, "NullableRpcId": { "oneOf": [ - { "$ref": "#/$defs/RpcId" }, - { "type": "null" } + { + "$ref": "#/$defs/RpcId" + }, + { + "type": "null" + } ] }, "RpcRequest": { "type": "object", "description": "A generic request. Reserved methods with dedicated schemas are excluded and must validate against their exact contract.", - "required": ["jsonrpc", "id", "method"], + "required": [ + "jsonrpc", + "id", + "method" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/RpcId" }, - "method": { "type": "string", "minLength": 1, "maxLength": 256 }, - "params": { "$ref": "#/$defs/JsonValue" }, - "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, - "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "method": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "params": { + "$ref": "#/$defs/JsonValue" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "not": { - "required": ["method"], + "required": [ + "method" + ], "properties": { - "method": { "enum": ["plugin.initialize", "plugin.terminal.interceptor.attach", "$/cancelRequest", "$/progress"] } + "method": { + "enum": [ + "plugin.initialize", + "plugin.terminal.interceptor.attach", + "$/cancelRequest", + "$/progress" + ] + } } }, "additionalProperties": false @@ -3237,37 +4942,90 @@ "RpcNotification": { "type": "object", "description": "A generic notification. Reserved notifications with dedicated schemas are excluded and must validate against their exact contract.", - "required": ["jsonrpc", "method"], + "required": [ + "jsonrpc", + "method" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "method": { "type": "string", "minLength": 1, "maxLength": 256 }, - "params": { "$ref": "#/$defs/JsonValue" } + "jsonrpc": { + "const": "2.0" + }, + "method": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "params": { + "$ref": "#/$defs/JsonValue" + } }, "not": { - "required": ["method"], + "required": [ + "method" + ], "properties": { - "method": { "enum": ["plugin.initialize", "plugin.terminal.interceptor.attach", "$/cancelRequest", "$/progress"] } + "method": { + "enum": [ + "plugin.initialize", + "plugin.terminal.interceptor.attach", + "$/cancelRequest", + "$/progress" + ] + } } }, "additionalProperties": false }, "RpcSuccess": { "type": "object", - "required": ["jsonrpc", "id", "result"], + "required": [ + "jsonrpc", + "id", + "result" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/RpcId" }, - "result": { "$ref": "#/$defs/JsonValue" } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "result": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, "JsonRpcStandardErrorCode": { "type": "integer", - "enum": [-32700, -32600, -32601, -32602, -32603] + "enum": [ + -32700, + -32600, + -32601, + -32602, + -32603 + ] }, "PluginWireErrorCode": { "type": "integer", - "enum": [-32001, -32002, -32003, -32004, -32005, -32006, -32007, -32008, -32009, -32010, -32011, -32012, -32013, -32014, -32015, -32016] + "enum": [ + -32001, + -32002, + -32003, + -32004, + -32005, + -32006, + -32007, + -32008, + -32009, + -32010, + -32011, + -32012, + -32013, + -32014, + -32015, + -32016 + ] }, "PluginErrorName": { "type": "string", @@ -3292,36 +5050,67 @@ }, "PluginErrorData": { "type": "object", - "required": ["pluginCode"], + "required": [ + "pluginCode" + ], "properties": { - "pluginCode": { "$ref": "#/$defs/PluginErrorName" }, - "details": { "$ref": "#/$defs/JsonValue" } + "pluginCode": { + "$ref": "#/$defs/PluginErrorName" + }, + "details": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, "RpcErrorCode": { "oneOf": [ - { "$ref": "#/$defs/JsonRpcStandardErrorCode" }, - { "$ref": "#/$defs/PluginWireErrorCode" } + { + "$ref": "#/$defs/JsonRpcStandardErrorCode" + }, + { + "$ref": "#/$defs/PluginWireErrorCode" + } ] }, "RpcErrorObject": { "type": "object", - "required": ["code", "message"], + "required": [ + "code", + "message" + ], "properties": { - "code": { "$ref": "#/$defs/RpcErrorCode" }, - "message": { "type": "string", "minLength": 1, "maxLength": 2048 }, - "data": { "$ref": "#/$defs/JsonValue" } + "code": { + "$ref": "#/$defs/RpcErrorCode" + }, + "message": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + "data": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, "RpcFailure": { "type": "object", - "required": ["jsonrpc", "id", "error"], + "required": [ + "jsonrpc", + "id", + "error" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/NullableRpcId" }, - "error": { "$ref": "#/$defs/RpcErrorObject" } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/NullableRpcId" + }, + "error": { + "$ref": "#/$defs/RpcErrorObject" + } }, "additionalProperties": false }, @@ -3330,27 +5119,63 @@ }, "ProgressBegin": { "type": "object", - "required": ["kind", "title"], + "required": [ + "kind", + "title" + ], "properties": { - "kind": { "const": "begin" }, - "title": { "type": "string", "minLength": 1, "maxLength": 256 }, - "message": { "type": "string", "maxLength": 1024 }, - "percentage": { "type": "number", "minimum": 0, "maximum": 100 }, - "cancellable": { "type": "boolean" } + "kind": { + "const": "begin" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "message": { + "type": "string", + "maxLength": 1024 + }, + "percentage": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "cancellable": { + "type": "boolean" + } }, "additionalProperties": false }, "ProgressReport": { "type": "object", - "required": ["kind"], + "required": [ + "kind" + ], "properties": { - "kind": { "const": "report" }, - "message": { "type": "string", "maxLength": 1024 }, - "percentage": { "type": "number", "minimum": 0, "maximum": 100 }, - "increment": { "type": "number", "minimum": 0, "maximum": 100 } + "kind": { + "const": "report" + }, + "message": { + "type": "string", + "maxLength": 1024 + }, + "percentage": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "increment": { + "type": "number", + "minimum": 0, + "maximum": 100 + } }, "not": { - "required": ["percentage", "increment"], + "required": [ + "percentage", + "increment" + ], "properties": { "percentage": true, "increment": true @@ -3360,32 +5185,60 @@ }, "ProgressEnd": { "type": "object", - "required": ["kind"], + "required": [ + "kind" + ], "properties": { - "kind": { "const": "end" }, - "message": { "type": "string", "maxLength": 1024 } + "kind": { + "const": "end" + }, + "message": { + "type": "string", + "maxLength": 1024 + } }, "additionalProperties": false }, "ProgressValue": { "oneOf": [ - { "$ref": "#/$defs/ProgressBegin" }, - { "$ref": "#/$defs/ProgressReport" }, - { "$ref": "#/$defs/ProgressEnd" } + { + "$ref": "#/$defs/ProgressBegin" + }, + { + "$ref": "#/$defs/ProgressReport" + }, + { + "$ref": "#/$defs/ProgressEnd" + } ] }, "RpcProgressNotification": { "type": "object", - "required": ["jsonrpc", "method", "params"], + "required": [ + "jsonrpc", + "method", + "params" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "method": { "const": "$/progress" }, + "jsonrpc": { + "const": "2.0" + }, + "method": { + "const": "$/progress" + }, "params": { "type": "object", - "required": ["token", "value"], + "required": [ + "token", + "value" + ], "properties": { - "token": { "$ref": "#/$defs/ProgressToken" }, - "value": { "$ref": "#/$defs/ProgressValue" } + "token": { + "$ref": "#/$defs/ProgressToken" + }, + "value": { + "$ref": "#/$defs/ProgressValue" + } }, "additionalProperties": false } @@ -3394,15 +5247,29 @@ }, "RpcCancel": { "type": "object", - "required": ["jsonrpc", "method", "params"], + "required": [ + "jsonrpc", + "method", + "params" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "method": { "const": "$/cancelRequest" }, + "jsonrpc": { + "const": "2.0" + }, + "method": { + "const": "$/cancelRequest" + }, "params": { "type": "object", - "required": ["cancellationId"], + "required": [ + "cancellationId" + ], "properties": { - "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false } @@ -3413,34 +5280,59 @@ "oneOf": [ { "type": "object", - "required": ["encoding", "value", "byteLength"], + "required": [ + "encoding", + "value", + "byteLength" + ], "properties": { - "encoding": { "const": "json" }, - "value": { "$ref": "#/$defs/JsonValue" }, - "byteLength": { "$ref": "#/$defs/StreamChunkByteLength" } + "encoding": { + "const": "json" + }, + "value": { + "$ref": "#/$defs/JsonValue" + }, + "byteLength": { + "$ref": "#/$defs/StreamChunkByteLength" + } }, "additionalProperties": false }, { "type": "object", - "required": ["encoding", "value", "byteLength"], + "required": [ + "encoding", + "value", + "byteLength" + ], "properties": { - "encoding": { "const": "base64" }, + "encoding": { + "const": "base64" + }, "value": { "type": "string", "maxLength": 22369624, "contentEncoding": "base64" }, - "byteLength": { "$ref": "#/$defs/StreamChunkByteLength" } + "byteLength": { + "$ref": "#/$defs/StreamChunkByteLength" + } }, "additionalProperties": false }, { "type": "object", - "required": ["encoding", "byteLength"], + "required": [ + "encoding", + "byteLength" + ], "properties": { - "encoding": { "const": "transfer" }, - "byteLength": { "$ref": "#/$defs/StreamChunkByteLength" } + "encoding": { + "const": "transfer" + }, + "byteLength": { + "$ref": "#/$defs/StreamChunkByteLength" + } }, "additionalProperties": false } @@ -3450,55 +5342,120 @@ "oneOf": [ { "type": "object", - "required": ["streamId", "sequence", "kind", "windowBytes"], + "required": [ + "streamId", + "sequence", + "kind", + "windowBytes" + ], "properties": { - "streamId": { "$ref": "#/$defs/StreamId" }, - "sequence": { "const": 0 }, - "kind": { "const": "open" }, - "windowBytes": { "$ref": "#/$defs/StreamWindowBytes" } + "streamId": { + "$ref": "#/$defs/StreamId" + }, + "sequence": { + "const": 0 + }, + "kind": { + "const": "open" + }, + "windowBytes": { + "$ref": "#/$defs/StreamWindowBytes" + } }, "additionalProperties": false }, { "type": "object", - "required": ["streamId", "sequence", "kind", "data"], + "required": [ + "streamId", + "sequence", + "kind", + "data" + ], "properties": { - "streamId": { "$ref": "#/$defs/StreamId" }, - "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, - "kind": { "const": "chunk" }, - "data": { "$ref": "#/$defs/StreamChunkData" } + "streamId": { + "$ref": "#/$defs/StreamId" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "kind": { + "const": "chunk" + }, + "data": { + "$ref": "#/$defs/StreamChunkData" + } }, "additionalProperties": false }, { "type": "object", - "required": ["streamId", "sequence", "kind"], + "required": [ + "streamId", + "sequence", + "kind" + ], "properties": { - "streamId": { "$ref": "#/$defs/StreamId" }, - "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, - "kind": { "enum": ["end", "cancel"] } + "streamId": { + "$ref": "#/$defs/StreamId" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "kind": { + "enum": [ + "end", + "cancel" + ] + } }, "additionalProperties": false }, { "type": "object", - "required": ["streamId", "sequence", "kind", "error"], + "required": [ + "streamId", + "sequence", + "kind", + "error" + ], "properties": { - "streamId": { "$ref": "#/$defs/StreamId" }, - "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, - "kind": { "const": "error" }, - "error": { "$ref": "#/$defs/RpcErrorObject" } + "streamId": { + "$ref": "#/$defs/StreamId" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "kind": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/RpcErrorObject" + } }, "additionalProperties": false }, { "type": "object", - "required": ["streamId", "sequence", "kind", "creditBytes"], + "required": [ + "streamId", + "sequence", + "kind", + "creditBytes" + ], "properties": { - "streamId": { "$ref": "#/$defs/StreamId" }, - "sequence": { "$ref": "#/$defs/SafeUnsignedInteger" }, - "kind": { "const": "windowUpdate" }, - "creditBytes": { "$ref": "#/$defs/StreamCreditBytes" } + "streamId": { + "$ref": "#/$defs/StreamId" + }, + "sequence": { + "$ref": "#/$defs/SafeUnsignedInteger" + }, + "kind": { + "const": "windowUpdate" + }, + "creditBytes": { + "$ref": "#/$defs/StreamCreditBytes" + } }, "additionalProperties": false } @@ -3506,7 +5463,10 @@ }, "TerminalInterceptorDirection": { "type": "string", - "enum": ["input", "output"] + "enum": [ + "input", + "output" + ] }, "TerminalInterceptorChunkByteLength": { "type": "integer", @@ -3525,261 +5485,612 @@ }, "TerminalInterceptorReadyFrame": { "type": "object", - "required": ["type", "sessionId", "direction", "windowBytes"], + "required": [ + "type", + "sessionId", + "direction", + "windowBytes" + ], "properties": { - "type": { "const": "netcatty:terminal-interceptor:ready" }, - "sessionId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, - "direction": { "$ref": "#/$defs/TerminalInterceptorDirection" }, - "windowBytes": { "$ref": "#/$defs/TerminalInterceptorWindowBytes" } + "type": { + "const": "netcatty:terminal-interceptor:ready" + }, + "sessionId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "direction": { + "$ref": "#/$defs/TerminalInterceptorDirection" + }, + "windowBytes": { + "$ref": "#/$defs/TerminalInterceptorWindowBytes" + } }, "additionalProperties": false }, "TerminalInterceptorChunkFrame": { "type": "object", - "required": ["type", "sequence", "direction", "creditBytes", "byteLength"], + "required": [ + "type", + "sequence", + "direction", + "creditBytes", + "byteLength" + ], "properties": { - "type": { "const": "netcatty:terminal-interceptor:chunk" }, - "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, - "direction": { "$ref": "#/$defs/TerminalInterceptorDirection" }, - "creditBytes": { "$ref": "#/$defs/TerminalInterceptorCreditBytes" }, - "byteLength": { "$ref": "#/$defs/TerminalInterceptorChunkByteLength" } + "type": { + "const": "netcatty:terminal-interceptor:chunk" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "direction": { + "$ref": "#/$defs/TerminalInterceptorDirection" + }, + "creditBytes": { + "$ref": "#/$defs/TerminalInterceptorCreditBytes" + }, + "byteLength": { + "$ref": "#/$defs/TerminalInterceptorChunkByteLength" + } }, "additionalProperties": false }, "TerminalInterceptorOkResultFrame": { "type": "object", - "required": ["type", "sequence", "status", "creditBytes", "byteLength"], + "required": [ + "type", + "sequence", + "status", + "creditBytes", + "byteLength" + ], "properties": { - "type": { "const": "netcatty:terminal-interceptor:result" }, - "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, - "status": { "const": "ok" }, - "creditBytes": { "$ref": "#/$defs/TerminalInterceptorChunkByteLength" }, - "byteLength": { "$ref": "#/$defs/TerminalInterceptorChunkByteLength" } + "type": { + "const": "netcatty:terminal-interceptor:result" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "status": { + "const": "ok" + }, + "creditBytes": { + "$ref": "#/$defs/TerminalInterceptorChunkByteLength" + }, + "byteLength": { + "$ref": "#/$defs/TerminalInterceptorChunkByteLength" + } }, "additionalProperties": false }, "TerminalInterceptorFailedResultFrame": { "type": "object", - "required": ["type", "sequence", "status"], + "required": [ + "type", + "sequence", + "status" + ], "properties": { - "type": { "const": "netcatty:terminal-interceptor:result" }, - "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, - "status": { "const": "failed" } + "type": { + "const": "netcatty:terminal-interceptor:result" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "status": { + "const": "failed" + } }, "additionalProperties": false }, "TerminalInterceptorFrame": { "oneOf": [ - { "$ref": "#/$defs/TerminalInterceptorReadyFrame" }, - { "$ref": "#/$defs/TerminalInterceptorChunkFrame" }, - { "$ref": "#/$defs/TerminalInterceptorOkResultFrame" }, - { "$ref": "#/$defs/TerminalInterceptorFailedResultFrame" } + { + "$ref": "#/$defs/TerminalInterceptorReadyFrame" + }, + { + "$ref": "#/$defs/TerminalInterceptorChunkFrame" + }, + { + "$ref": "#/$defs/TerminalInterceptorOkResultFrame" + }, + { + "$ref": "#/$defs/TerminalInterceptorFailedResultFrame" + } ] }, "RuntimeInitializeParams": { "type": "object", - "required": ["netcattyVersion", "apiVersion", "supportedFeatures"], + "required": [ + "netcattyVersion", + "apiVersion", + "supportedFeatures" + ], "properties": { - "netcattyVersion": { "$ref": "#/$defs/SemanticVersion" }, - "apiVersion": { "$ref": "#/$defs/SemanticVersion" }, + "netcattyVersion": { + "$ref": "#/$defs/SemanticVersion" + }, + "apiVersion": { + "$ref": "#/$defs/SemanticVersion" + }, "supportedFeatures": { "type": "array", "maxItems": 256, "uniqueItems": true, - "items": { "$ref": "#/$defs/FeatureId" } + "items": { + "$ref": "#/$defs/FeatureId" + } } }, "additionalProperties": false }, "RuntimeInitializeResult": { "type": "object", - "required": ["pluginId", "pluginVersion", "apiVersion", "enabledFeatures"], + "required": [ + "pluginId", + "pluginVersion", + "apiVersion", + "enabledFeatures" + ], "properties": { - "pluginId": { "$ref": "#/$defs/PluginId" }, - "pluginVersion": { "$ref": "#/$defs/SemanticVersion" }, - "apiVersion": { "$ref": "#/$defs/SemanticVersion" }, + "pluginId": { + "$ref": "#/$defs/PluginId" + }, + "pluginVersion": { + "$ref": "#/$defs/SemanticVersion" + }, + "apiVersion": { + "$ref": "#/$defs/SemanticVersion" + }, "enabledFeatures": { "type": "array", "maxItems": 256, "uniqueItems": true, - "items": { "$ref": "#/$defs/FeatureId" } + "items": { + "$ref": "#/$defs/FeatureId" + } } }, "additionalProperties": false }, "RuntimeInitializeRequest": { "type": "object", - "required": ["jsonrpc", "id", "method", "params"], + "required": [ + "jsonrpc", + "id", + "method", + "params" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/RpcId" }, - "method": { "const": "plugin.initialize" }, - "params": { "$ref": "#/$defs/RuntimeInitializeParams" }, - "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, - "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "method": { + "const": "plugin.initialize" + }, + "params": { + "$ref": "#/$defs/RuntimeInitializeParams" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, "RuntimeInitializeSuccess": { "type": "object", - "required": ["jsonrpc", "id", "result"], + "required": [ + "jsonrpc", + "id", + "result" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/RpcId" }, - "result": { "$ref": "#/$defs/RuntimeInitializeResult" } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "result": { + "$ref": "#/$defs/RuntimeInitializeResult" + } }, "additionalProperties": false }, "TerminalSessionSnapshot": { "type": "object", - "required": ["sessionId", "protocol", "status"], + "required": [ + "sessionId", + "protocol", + "status" + ], "properties": { - "sessionId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, - "hostId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, - "workspaceId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, + "sessionId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "hostId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, "protocol": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" }, - "status": { "type": "string", "enum": ["connecting", "connected", "disconnected"] }, - "cwd": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[^\\u0000]+$" }, - "title": { "type": "string", "minLength": 1, "maxLength": 1024, "pattern": "^[^\\u0000]+$" }, - "shellType": { "type": "string", "enum": ["posix", "fish", "powershell", "cmd", "unknown"] }, - "cols": { "type": "integer", "minimum": 1, "maximum": 16384 }, - "rows": { "type": "integer", "minimum": 1, "maximum": 16384 }, - "alternateScreen": { "type": "boolean" } + "status": { + "type": "string", + "enum": [ + "connecting", + "connected", + "disconnected" + ] + }, + "cwd": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "pattern": "^[^\\u0000]+$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^[^\\u0000]+$" + }, + "shellType": { + "type": "string", + "enum": [ + "posix", + "fish", + "powershell", + "cmd", + "unknown" + ] + }, + "cols": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "rows": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "alternateScreen": { + "type": "boolean" + } }, "additionalProperties": false }, "TerminalInterceptorAttachmentDescriptor": { "type": "object", - "required": ["providerId", "direction", "session"], + "required": [ + "providerId", + "direction", + "session" + ], "properties": { - "providerId": { "$ref": "#/$defs/ContributionId" }, - "direction": { "type": "string", "enum": ["input", "output"] }, - "session": { "$ref": "#/$defs/TerminalSessionSnapshot" } + "providerId": { + "$ref": "#/$defs/ContributionId" + }, + "direction": { + "type": "string", + "enum": [ + "input", + "output" + ] + }, + "session": { + "$ref": "#/$defs/TerminalSessionSnapshot" + } }, "additionalProperties": false }, "TerminalInterceptorAttachmentParams": { "type": "object", - "required": ["descriptor"], + "required": [ + "descriptor" + ], "properties": { - "descriptor": { "$ref": "#/$defs/TerminalInterceptorAttachmentDescriptor" } + "descriptor": { + "$ref": "#/$defs/TerminalInterceptorAttachmentDescriptor" + } }, "additionalProperties": false }, "TerminalInterceptorAttachmentResult": { "type": "object", - "required": ["accepted"], + "required": [ + "accepted" + ], "properties": { - "accepted": { "const": true } + "accepted": { + "const": true + } }, "additionalProperties": false }, "TerminalInterceptorAttachmentRequest": { "type": "object", - "required": ["jsonrpc", "id", "method", "params"], + "required": [ + "jsonrpc", + "id", + "method", + "params" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/RpcId" }, - "method": { "const": "plugin.terminal.interceptor.attach" }, - "params": { "$ref": "#/$defs/TerminalInterceptorAttachmentParams" }, - "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, - "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "method": { + "const": "plugin.terminal.interceptor.attach" + }, + "params": { + "$ref": "#/$defs/TerminalInterceptorAttachmentParams" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, "TerminalInterceptorAttachmentSuccess": { "type": "object", - "required": ["jsonrpc", "id", "result"], + "required": [ + "jsonrpc", + "id", + "result" + ], "properties": { - "jsonrpc": { "const": "2.0" }, - "id": { "$ref": "#/$defs/RpcId" }, - "result": { "$ref": "#/$defs/TerminalInterceptorAttachmentResult" } + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "result": { + "$ref": "#/$defs/TerminalInterceptorAttachmentResult" + } }, "additionalProperties": false }, "RpcMessage": { "description": "A mutually exclusive RPC wire envelope. Reserved inbound methods use their exact schemas. Successful responses require method-specific validation through request correlation.", "oneOf": [ - { "$ref": "#/$defs/RpcRequest" }, - { "$ref": "#/$defs/RpcNotification" }, - { "$ref": "#/$defs/RpcSuccess" }, - { "$ref": "#/$defs/RpcFailure" }, - { "$ref": "#/$defs/RpcCancel" }, - { "$ref": "#/$defs/RpcProgressNotification" }, - { "$ref": "#/$defs/RuntimeInitializeRequest" }, - { "$ref": "#/$defs/TerminalInterceptorAttachmentRequest" } + { + "$ref": "#/$defs/RpcRequest" + }, + { + "$ref": "#/$defs/RpcNotification" + }, + { + "$ref": "#/$defs/RpcSuccess" + }, + { + "$ref": "#/$defs/RpcFailure" + }, + { + "$ref": "#/$defs/RpcCancel" + }, + { + "$ref": "#/$defs/RpcProgressNotification" + }, + { + "$ref": "#/$defs/RuntimeInitializeRequest" + }, + { + "$ref": "#/$defs/TerminalInterceptorAttachmentRequest" + } ] }, "PermissionGrantScope": { "type": "string", - "enum": ["once", "session", "application", "always"] + "enum": [ + "once", + "session", + "application", + "always" + ] }, "PermissionRequest": { "type": "object", - "required": ["requestId", "pluginId", "permission", "reason"], + "required": [ + "requestId", + "pluginId", + "permission", + "reason" + ], "properties": { - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "pluginId": { "$ref": "#/$defs/PluginId" }, - "pluginVersion": { "$ref": "#/$defs/SemanticVersion" }, - "pluginName": { "type": "string", "minLength": 1, "maxLength": 128 }, - "publisher": { "type": "string", "minLength": 1, "maxLength": 128 }, - "runtimeId": { "type": ["string", "null"], "minLength": 1, "maxLength": 128 }, - "runtimeKind": { "type": ["string", "null"], "enum": ["browser", "utility", null] }, - "permission": { "$ref": "#/$defs/PluginPermission" }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "pluginId": { + "$ref": "#/$defs/PluginId" + }, + "pluginVersion": { + "$ref": "#/$defs/SemanticVersion" + }, + "pluginName": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "publisher": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "runtimeId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 128 + }, + "runtimeKind": { + "type": [ + "string", + "null" + ], + "enum": [ + "browser", + "utility", + null + ] + }, + "permission": { + "$ref": "#/$defs/PluginPermission" + }, "resources": { "type": "array", "maxItems": 128, "uniqueItems": true, - "items": { "$ref": "#/$defs/PermissionResource" } + "items": { + "$ref": "#/$defs/PermissionResource" + } }, "resourceKinds": { "type": "array", "maxItems": 128, - "items": { "$ref": "#/$defs/PermissionResourceKind" } + "items": { + "$ref": "#/$defs/PermissionResourceKind" + } }, "displayContext": { - "type": "object", "additionalProperties": false, + "type": "object", + "additionalProperties": false, "properties": { - "action": { "$ref": "#/$defs/PluginAgentActionPreview" }, - "modelLabel": { "type": "string", "minLength": 1, "maxLength": 160 }, + "action": { + "$ref": "#/$defs/PluginAgentActionPreview" + }, + "modelLabel": { + "type": "string", + "minLength": 1, + "maxLength": 160 + }, "selections": { - "type": "array", "maxItems": 32, + "type": "array", + "maxItems": 32, "items": { - "type": "object", "required": ["title", "scope", "version"], "additionalProperties": false, + "type": "object", + "required": [ + "title", + "scope", + "version" + ], + "additionalProperties": false, "properties": { - "title": { "type": "string", "maxLength": 160 }, - "scope": { "enum": ["workspace", "tab", "session", "host", "note"] }, - "version": { "type": "string", "minLength": 1, "maxLength": 128 } + "title": { + "type": "string", + "maxLength": 160 + }, + "scope": { + "enum": [ + "workspace", + "tab", + "session", + "host", + "note" + ] + }, + "version": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } } } } } }, "relatedPermissions": { - "type": "array", "maxItems": 5, + "type": "array", + "maxItems": 5, "items": { - "type": "object", "required": ["permission", "resources"], + "type": "object", + "required": [ + "permission", + "resources" + ], "properties": { - "permission": { "$ref": "#/$defs/PluginPermission" }, - "resources": { "type": "array", "minItems": 1, "maxItems": 128, "uniqueItems": true, "items": { "$ref": "#/$defs/PermissionResource" } } + "permission": { + "$ref": "#/$defs/PluginPermission" + }, + "resources": { + "type": "array", + "minItems": 1, + "maxItems": 128, + "uniqueItems": true, + "items": { + "$ref": "#/$defs/PermissionResource" + } + } }, "additionalProperties": false } }, - "reason": { "type": "string", "minLength": 1, "maxLength": 1024 }, - "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "sessionId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sessionId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, "allowedScopes": { "type": "array", "minItems": 1, "maxItems": 4, "uniqueItems": true, - "items": { "$ref": "#/$defs/PermissionGrantScope" } + "items": { + "$ref": "#/$defs/PermissionGrantScope" + } } }, "additionalProperties": false @@ -3788,26 +6099,52 @@ "oneOf": [ { "type": "object", - "required": ["requestId", "decision", "scope"], + "required": [ + "requestId", + "decision", + "scope" + ], "properties": { - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "decision": { "const": "allow" }, - "scope": { "$ref": "#/$defs/PermissionGrantScope" }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "decision": { + "const": "allow" + }, + "scope": { + "$ref": "#/$defs/PermissionGrantScope" + }, "resources": { "type": "array", "maxItems": 128, "uniqueItems": true, - "items": { "$ref": "#/$defs/PermissionResource" } + "items": { + "$ref": "#/$defs/PermissionResource" + } } }, "additionalProperties": false }, { "type": "object", - "required": ["requestId", "decision"], + "required": [ + "requestId", + "decision" + ], "properties": { - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "decision": { "enum": ["deny", "cancel"] } + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "decision": { + "enum": [ + "deny", + "cancel" + ] + } }, "additionalProperties": false } @@ -3815,14 +6152,38 @@ }, "ProviderRequest": { "type": "object", - "required": ["providerId", "operation", "requestId"], + "required": [ + "providerId", + "operation", + "requestId" + ], "properties": { - "providerId": { "$ref": "#/$defs/ContributionId" }, - "operation": { "type": "string", "minLength": 1, "maxLength": 128 }, - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "payload": { "$ref": "#/$defs/JsonValue" }, - "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, - "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + "providerId": { + "$ref": "#/$defs/ContributionId" + }, + "operation": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "payload": { + "$ref": "#/$defs/JsonValue" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } }, "additionalProperties": false }, @@ -3830,30 +6191,63 @@ "oneOf": [ { "type": "object", - "required": ["requestId", "status", "result"], + "required": [ + "requestId", + "status", + "result" + ], "properties": { - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "status": { "const": "ok" }, - "result": { "$ref": "#/$defs/JsonValue" } + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "status": { + "const": "ok" + }, + "result": { + "$ref": "#/$defs/JsonValue" + } }, "additionalProperties": false }, { "type": "object", - "required": ["requestId", "status"], + "required": [ + "requestId", + "status" + ], "properties": { - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "status": { "const": "cancelled" } + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "status": { + "const": "cancelled" + } }, "additionalProperties": false }, { "type": "object", - "required": ["requestId", "status", "error"], + "required": [ + "requestId", + "status", + "error" + ], "properties": { - "requestId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "status": { "const": "failed" }, - "error": { "$ref": "#/$defs/RpcErrorObject" } + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "status": { + "const": "failed" + }, + "error": { + "$ref": "#/$defs/RpcErrorObject" + } }, "additionalProperties": false } @@ -6193,6 +8587,45 @@ "maxLength": 98304 } } + }, + "HostDrawnViewOpenRequest": { + "type": "object", + "additionalProperties": false, + "required": [ + "viewId", + "instanceId", + "scopeId" + ], + "properties": { + "viewId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "instanceId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "scopeId": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "context": { + "type": "object", + "maxProperties": 64, + "additionalProperties": { + "type": [ + "string", + "number", + "boolean", + "null" + ], + "maxLength": 8192 + } + } + } } } } diff --git a/packages/plugin-contract/src/contract.test.ts b/packages/plugin-contract/src/contract.test.ts index 79addabe2..54274765d 100644 --- a/packages/plugin-contract/src/contract.test.ts +++ b/packages/plugin-contract/src/contract.test.ts @@ -907,7 +907,7 @@ test("UI contribution shapes cover conditional menus, icons, and platform keybin id: "com.example.contract-test.panel", title: "Panel", location: "panel", - entry: "dist/panel.html", + icon: { kind: "package", light: "assets/panel.svg" }, order: 20, }), true, JSON.stringify(view.errors)); @@ -1154,7 +1154,7 @@ test("semantic namespacing covers every contribution registry and near-prefix co id: "com.example.contract-test.panel", title: "Panel", location: "panel", - entry: "dist/panel.html", + }], providers: [{ id: "com.example.contract-test.completion", @@ -1220,7 +1220,7 @@ test("contribution IDs are globally unique across registry kinds", async () => { id: sharedId, title: "Shared view", location: "panel", - entry: "dist/shared.html", + }], providers: validManifest.contributes.providers, }, @@ -1336,7 +1336,7 @@ test("planned phase consumers are representable without private application type id: "com.example.contract-test.panel", title: "Panel", location: "panel", - entry: "dist/panel.html", + }], }, }, @@ -1477,3 +1477,18 @@ test("planned phase consumers are representable without private application type assert.equal(result.valid, true, result.errors.join("\n")); } }); + + +test("settings accept host-owned groups but reject custom rendering and settings view placement", () => { + const validate = validator("SettingContribution"); + const setting = { id: "com.example.contract-test.name", label: "Name", group: { en: "General", "zh-CN": "常规" }, control: "text", scope: "application", default: "" }; + assert.equal(validate(setting), true, JSON.stringify(validate.errors)); + for (const field of ["html", "css", "render", "entry"]) { + assert.equal(validate({ ...setting, [field]: "plugin controlled" }), false, field); + } + const view = validator("ViewContribution"); + assert.equal(view({ id: "com.example.contract-test.view", title: "Custom", location: "settings" }), false); + for (const location of ["vault-page", "terminal-sidebar", "tab", "aside", "panel", "modal"]) { + assert.equal(view({ id: "com.example.contract-test.view", title: "Custom", location }), true, JSON.stringify(view.errors)); + } +}); diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index 9e773ba2a..74d0f3897 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -207,6 +207,50 @@ export type HostClipboardWriteRequest = { text: string; }; +export type HostDrawnViewEvent = { + nodeId: string; + type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset"; + value?: string; + checked?: boolean; + eventId?: number; + data?: string; + key?: string; + ctrlKey?: boolean; + metaKey?: boolean; + altKey?: boolean; + shiftKey?: boolean; + values?: Array; +}; + +export type HostDrawnViewMessage = ({ + kind: "host-ui.open"; + instanceId: string; + stateScope?: string; +}) | ({ + kind: "host-ui.close"; + instanceId: string; +}) | ({ + kind: "host-ui.update"; + instanceId: string; + sequence: number; + acknowledgedEvent?: number; + mutations: Array; + css: string; +}) | ({ + kind: "host-ui.event"; + instanceId: string; + event: HostDrawnViewEvent; +}); + +export type HostDrawnViewOpenRequest = { + viewId: string; + instanceId: string; + scopeId: string; + context?: { [key: string]: string | number | boolean | null }; +}; + +export type HostDrawnViewsFeature = "views.host-drawn"; + export type HostInputRequest = { kind: "input"; title: string; @@ -1124,6 +1168,15 @@ export type PluginViewFocusEvent = { export type PluginViewFocusRequest = PluginViewFocusEvent; +export type PluginViewResourceRequest = { + instanceId: string; + path: RelativePackagePath; +}; + +export type PluginViewResourceResult = { + url: string; +}; + export type PluginWireErrorCode = -32001 | -32002 | -32003 | -32004 | -32005 | -32006 | -32007 | -32008 | -32009 | -32010 | -32011 | -32012 | -32013 | -32014 | -32015 | -32016; export type ProgressBegin = { @@ -1328,6 +1381,7 @@ export type SettingContribution = { sync?: boolean; sortable?: boolean; valueSchema?: JsonValue; + group?: LocalizedText; }; export type SettingControl = "switch" | "radio" | "select" | "multiselect" | "text" | "textarea" | "number" | "slider" | "password" | "color" | "font" | "file" | "directory" | "keybinding" | "list" | "table"; @@ -1786,13 +1840,11 @@ export type ViewContribution = { id: ContributionId; title: LocalizedText; location: ViewLocation; - entry: RelativePackagePath; icon?: IconReference; order?: number; when?: ContextKeyExpression; - retainContextWhenHidden?: boolean; }; -export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "settings" | "vault-page" | "terminal-sidebar"; +export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "vault-page" | "terminal-sidebar"; export type WireIntegerLimits = {"maxSafeInteger":9007199254740991}; diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index 59acfafa6..60f91b5a6 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -4,17 +4,38 @@ "private": true, "type": "module", "license": "GPL-3.0-or-later", - "files": ["dist"], + "files": [ + "dist", + "view" + ], "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" + }, + "./view/netcatty.css": "./view/netcatty.css", + "./host-react": { + "types": "./dist/hostReact.d.ts", + "import": "./dist/hostReact.js" + }, + "./host-dom": { + "types": "./dist/hostDom.d.ts", + "import": "./dist/hostDom.js" } }, "scripts": { "build": "tsc -p tsconfig.build.json" }, "dependencies": { - "@netcatty/plugin-contract": "0.1.0-internal.1" + "@netcatty/plugin-contract": "0.1.0-internal.1", + "@remote-dom/core": "^1.12.0" + }, + "peerDependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0" } } diff --git a/packages/plugin-sdk/src/hostDom.ts b/packages/plugin-sdk/src/hostDom.ts new file mode 100644 index 000000000..94abd1de8 --- /dev/null +++ b/packages/plugin-sdk/src/hostDom.ts @@ -0,0 +1,109 @@ +import { RemoteMutationObserver, remoteId } from '@remote-dom/core/elements'; +import type { HostDrawnViewEvent, JsonValue } from '@netcatty/plugin-contract'; +import type { Disposable, PluginViews } from './index.js'; + +/** Build ordinary DOM in the isolated runtime; only validated data reaches the visible host. */ +export function registerHostDomView(views: PluginViews, viewId: string, mount: (container: HTMLElement, stateScope: string) => (() => void) | void, css = ''): Disposable { + if (css.length > 65536) throw new TypeError('Plugin CSS exceeds the view limit'); + type View = { container: HTMLDivElement; unmount: () => void; observer: RemoteMutationObserver; sequence: number; acknowledgedEvent: number; sentAck: number; poll: ReturnType; controls: Map }; + const instances = new Map(); + const close = (id: string) => { + const view = instances.get(id); if (!view) return; + instances.delete(id); clearInterval(view.poll); view.observer.disconnect(); view.unmount(); view.container.remove(); + }; + const sendEvent = (view: View, event: HostDrawnViewEvent) => { + const element = [...view.container.querySelectorAll('*')].find((item) => remoteId(item) === event.nodeId); + if (!element || !(element instanceof HTMLElement)) return; + if (event.type === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; } + if (event.type === 'click') { + // The host already performed native checkbox/label behavior. Reproduce it + // once for React's click-based change handler, without a second toggle. + if (element instanceof HTMLInputElement && ['checkbox', 'radio'].includes(element.type) && event.checked !== undefined) { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked')?.set?.call(element, !event.checked); + } + if (element instanceof HTMLInputElement && ['checkbox', 'radio'].includes(element.type)) element.click(); + else { + // The visible host performs label and form defaults. Dispatch callbacks + // here with defaults cancelled, so one user action runs only once. + const click = new MouseEvent('click', { bubbles: true, cancelable: true }); + const preventDefault = (action: Event) => action.preventDefault(); + view.container.addEventListener('click', preventDefault, { once: true }); + try { element.dispatchEvent(click); } finally { view.container.removeEventListener('click', preventDefault); } + } + return; + } + if (event.type === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; } + if (event.type === 'submit') { const action = new Event(event.type, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; } + if (event.type === 'keydown' || event.type === 'keyup') { + element.dispatchEvent(new KeyboardEvent(event.type, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return; + } + if (event.type.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(event.type, { data: event.data ?? '', bubbles: true })); return; } + if (event.type === 'focusin' || event.type === 'focusout') { element.dispatchEvent(new FocusEvent(event.type, { bubbles: true })); return; } + if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) { + if (element instanceof HTMLSelectElement && element.multiple && event.values) { + for (const option of element.options) option.selected = event.values.includes(option.value); + } + if (!(element instanceof HTMLSelectElement && element.multiple) && event.value !== undefined && event.value.length <= 8192) { + const prototype = element instanceof HTMLInputElement ? HTMLInputElement.prototype + : element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLSelectElement.prototype; + Object.getOwnPropertyDescriptor(prototype, 'value')?.set?.call(element, event.value); + } + if (element instanceof HTMLInputElement && typeof event.checked === 'boolean') { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked')?.set?.call(element, event.checked); + } + element.dispatchEvent(new Event(event.type, { bubbles: true, cancelable: true })); + } + }; + const subscription = views.onDidReceiveMessage(viewId, (message) => { + if (!message || typeof message !== 'object' || Array.isArray(message) || typeof message.instanceId !== 'string') return; + const id = message.instanceId; + if (message.kind === 'host-ui.open') { + if (instances.has(id)) return; + const container = document.createElement('div'); document.body.appendChild(container); + let view: View; + const send = (mutations: readonly unknown[]) => { + if (instances.get(id) !== view) return; + const records = [...mutations]; const live = new Set(); + for (const control of container.querySelectorAll('input,textarea,select,option')) { + const node = control as HTMLInputElement; + const nodeId = remoteId(node); live.add(nodeId); + const properties: Record = node.tagName === 'OPTION' + ? { selected: (node as unknown as HTMLOptionElement).selected ? '' : null } + : { value: node.value, ...(node.tagName === 'INPUT' && ['checkbox', 'radio'].includes(node.type) ? { checked: node.checked ? '' : null } : {}) }; + const signature = JSON.stringify(properties); + if (view.controls.get(nodeId) === signature) continue; + view.controls.set(nodeId, signature); + for (const [name, value] of Object.entries(properties)) records.push([3, nodeId, name, value, 2]); + } + for (const nodeId of view.controls.keys()) if (!live.has(nodeId)) view.controls.delete(nodeId); + if (!records.length && view.sentAck === view.acknowledgedEvent) return; + view.sentAck = view.acknowledgedEvent; + views.postMessage(viewId, JSON.parse(JSON.stringify({ kind: 'host-ui.update', instanceId: id, sequence: ++view.sequence, acknowledgedEvent: view.acknowledgedEvent, css, mutations: records })) as JsonValue); + }; + const observer = new RemoteMutationObserver({ + mutate(mutations) { send(mutations); }, + call() { throw new Error('Direct host methods are unavailable'); }, + }); + view = { container, unmount: () => {}, observer, sequence: 0, acknowledgedEvent: 0, sentAck: 0, controls: new Map(), poll: setInterval(() => send([]), 50) }; + instances.set(id, view); + observer.observe(container); + // A valid component may render nothing; complete initial loading even when + // React makes no DOM mutations. + views.postMessage(viewId, { kind: 'host-ui.update', instanceId: id, sequence: ++view.sequence, css, mutations: [] }); + const mountRoot = document.createElement('div'); + mountRoot.setAttribute('style', 'min-height:100%;height:100%'); + container.appendChild(mountRoot); + const cleanup = mount(mountRoot, typeof message.stateScope === 'string' ? message.stateScope : viewId); + if (typeof cleanup === 'function') view.unmount = cleanup; + } else if (message.kind === 'host-ui.close') close(id); + else if (message.kind === 'host-ui.event') { + const view = instances.get(id); + if (view && message.event && typeof message.event === 'object' && !Array.isArray(message.event)) { + const event = message.event as unknown as HostDrawnViewEvent; + view.acknowledgedEvent = event.eventId ?? view.acknowledgedEvent; + sendEvent(view, event); + } + } + }); + return { dispose() { subscription.dispose(); for (const id of [...instances.keys()]) close(id); } }; +} diff --git a/packages/plugin-sdk/src/hostReact.test.tsx b/packages/plugin-sdk/src/hostReact.test.tsx new file mode 100644 index 000000000..48538ce80 --- /dev/null +++ b/packages/plugin-sdk/src/hostReact.test.tsx @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import type { JsonValue, HostDrawnViewMessage } from '@netcatty/plugin-contract'; +import { JSDOM } from 'jsdom'; + +test('ordinary React view renders data updates and responds to its own forwarded clicks', async () => { + const dom = new JSDOM('', { url: 'http://localhost', pretendToBeVisual: true }); + const saved = new Map(); + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) { + saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] }); + } + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true }); + const { default: React, act, useState } = await import('react'); + const { registerHostReactView } = await import('./hostReact.js'); + let receive: (value: JsonValue) => void = () => {}; + const messages: Array> = []; + const views = { onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) { receive = listener; return { dispose() {} }; }, + postMessage(_id: string, value: JsonValue) { messages.push(value as unknown as Extract); }, getState: async () => undefined, setState: async () => {} }; + let submissions = 0; let selected: string[] = []; + function Example() { + const [count, setCount] = useState(0); const [name, setName] = useState(''); + return
+ setName(event.currentTarget.value)} /> + +
{ event.preventDefault(); submissions++; }}> + + +
+
; + } + const registration = registerHostReactView(views, 'com.example.view', () => , '.my-button{display:grid}'); + try { + await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'i1' }); await new Promise((resolve) => setTimeout(resolve, 20)); }); + assert.equal(messages[0].sequence, 1); assert.deepEqual(messages[0].mutations, []); + const first = messages.at(-1)!; assert.equal(first.kind, 'host-ui.update'); assert.ok(first.sequence >= 2); + const container = (first.mutations[0] as unknown[])[2] as { children: Array<{ id: string; element: string; attributes: Record }> }; const input = container.children[0]; const button = container.children[1]; assert.equal(button.element, 'button'); + await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'i1', event: { type: 'input', nodeId: input.id, value: 'Catty' } }); await new Promise((resolve) => setTimeout(resolve, 20)); }); + assert.match(JSON.stringify(messages.at(-1)), /Catty/); assert.equal(button.attributes.class, 'my-button'); + await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'i1', event: { type: 'click', nodeId: button.id } }); await new Promise((resolve) => setTimeout(resolve, 20)); }); + assert.match(JSON.stringify(messages.at(-1)), /"1"/); assert.ok(messages.at(-1)!.sequence >= 2); + const form = container.children[2] as unknown as { id: string; children: Array<{ id: string }> }; + await act(async () => { + receive({ kind: 'host-ui.event', instanceId: 'i1', event: { type: 'click', nodeId: form.children[0].id } }); + receive({ kind: 'host-ui.event', instanceId: 'i1', event: { type: 'submit', nodeId: form.id } }); + receive({ kind: 'host-ui.event', instanceId: 'i1', event: { type: 'change', nodeId: form.children[1].id, values: ['a', 'c'] } }); + }); + assert.equal(submissions, 1, 'forwarded click and host submit must not submit twice'); + assert.deepEqual(selected, ['a', 'c'], 'multiple selection reaches ordinary React handlers'); + await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'i1' }); }); + assert.equal(document.querySelector('button'), null); + } finally { + registration.dispose(); + for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); } + Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); dom.window.close(); + } +}); diff --git a/packages/plugin-sdk/src/hostReact.ts b/packages/plugin-sdk/src/hostReact.ts new file mode 100644 index 000000000..023bf3509 --- /dev/null +++ b/packages/plugin-sdk/src/hostReact.ts @@ -0,0 +1,22 @@ +import { createRoot } from 'react-dom/client'; +import { createElement, useEffect, useRef, type ReactNode } from 'react'; +import type { Disposable, PluginViews } from './index.js'; +import { registerHostDomView } from './hostDom.js'; + +/** Author ordinary React while Netcatty owns the visible DOM. */ +export function registerHostReactView(views: PluginViews, viewId: string, render: () => ReactNode, css = ''): Disposable { + return registerHostDomView(views, viewId, (container) => { + const root = createRoot(container); root.render(render()); return () => root.unmount(); + }, css); +} + +/** A host-positioned popup with freely authored content. */ +export function PluginPopover({ anchor, open, onClose, children }: { anchor: string; open: boolean; onClose(): void; children: ReactNode }) { + const ref = useRef(null); + useEffect(() => { + const node = ref.current; if (!node) return; + node.addEventListener('netcatty-dismiss', onClose); + return () => node.removeEventListener('netcatty-dismiss', onClose); + }, [onClose]); + return createElement('div', { ref, 'data-plugin-popover': 'true', 'data-plugin-anchor': anchor, ...(open ? { open: true } : {}) }, children); +} diff --git a/packages/plugin-sdk/view/netcatty.css b/packages/plugin-sdk/view/netcatty.css new file mode 100644 index 000000000..407caa665 --- /dev/null +++ b/packages/plugin-sdk/view/netcatty.css @@ -0,0 +1,15 @@ +/* Optional class-based foundation for host-rendered Netcatty plugin pages. */ +* { box-sizing: border-box; } +.nc-page { font: 14px/1.5 system-ui, sans-serif; background: hsl(var(--background)); color: hsl(var(--foreground)); min-width: 0; padding: 24px; overflow-wrap: anywhere; } +.nc-page h1 { margin: 0 0 8px; font-size: 20px; line-height: 1.3; font-weight: 600; } +.nc-muted { color: hsl(var(--muted-foreground, 215 20% 35%)); } +.nc-button, .nc-input { font: inherit; color: inherit; border: 1px solid hsl(var(--border, 215 20% 75%)); border-radius: 6px; background: hsl(var(--background, 0 0% 100%)); } +.nc-button { padding: 7px 12px; cursor: pointer; } +.nc-button:hover:not(:disabled) { background: hsl(var(--muted, 210 20% 96%)); } +.nc-button:disabled { opacity: .5; cursor: default; } +.nc-button-primary { background: hsl(var(--primary, 221 83% 45%)); color: hsl(var(--primary-foreground, 0 0% 100%)); border-color: transparent; } +.nc-button-primary:hover:not(:disabled) { background: hsl(var(--primary, 221 83% 45%) / .9); } +.nc-input { padding: 7px 10px; max-width: 100%; } +.nc-button:focus-visible, .nc-input:focus-visible { outline: 2px solid hsl(var(--primary, 221 83% 45%)); outline-offset: 2px; } +@media (max-width: 360px) { .nc-page { font: 14px/1.5 system-ui, sans-serif; background: hsl(var(--background)); color: hsl(var(--foreground)); padding: 16px; } } +@media (forced-colors: active) { .nc-button, .nc-input { border: 1px solid ButtonText; } } diff --git a/scripts/build-plugin-view-example.mjs b/scripts/build-plugin-view-example.mjs new file mode 100644 index 000000000..21987ac9d --- /dev/null +++ b/scripts/build-plugin-view-example.mjs @@ -0,0 +1,16 @@ +import { build } from 'esbuild'; +import { mkdir, readFile, rm, copyFile, cp, stat } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +export async function buildHostViewExample(directory) { + const root = fileURLToPath(directory); + await build({ entryPoints: [path.join(root, 'host.js')], outfile: path.join(root, 'dist/host.js'), bundle: true, platform: 'browser', format: 'esm', loader: { '.html': 'text', '.css': 'text' }, minify: true }); + const staging = path.join(root, '.package'); + await rm(staging, { recursive: true, force: true }); + await mkdir(path.join(staging, 'dist'), { recursive: true }); + for (const file of ['netcatty.plugin.json', 'dist/host.js']) await copyFile(path.join(root, file), path.join(staging, file)); + if (await stat(path.join(root, 'assets')).then((info) => info.isDirectory(), () => false)) await cp(path.join(root, 'assets'), path.join(staging, 'assets'), { recursive: true }); + // Parse at build time so a forgotten view declaration fails before packaging. + const manifest = JSON.parse(await readFile(path.join(root, 'netcatty.plugin.json'), 'utf8')); + if (!manifest.contributes?.views?.length) throw new Error('Example has no declared view'); +} diff --git a/scripts/build-plugin-view-examples.mjs b/scripts/build-plugin-view-examples.mjs new file mode 100644 index 000000000..70579d1c0 --- /dev/null +++ b/scripts/build-plugin-view-examples.mjs @@ -0,0 +1,5 @@ +import { buildHostViewExample } from './build-plugin-view-example.mjs'; +for (const name of ['hello-vault', 'hello-world-v2', 'session-scratchpad', 'vault-scratchpad', 'settings-view-fixture', 'starter-netcatty', 'assistant', 'global-agent']) { + await buildHostViewExample(new URL(`../examples/plugins/${name}/`, import.meta.url)); +} +await import('../examples/plugins/hello-react-host/build.mjs'); diff --git a/scripts/fixtures/host-plugin-react.html b/scripts/fixtures/host-plugin-react.html new file mode 100644 index 000000000..a1f8d5d2b --- /dev/null +++ b/scripts/fixtures/host-plugin-react.html @@ -0,0 +1 @@ +Host React fixture
diff --git a/scripts/fixtures/host-plugin-react.tsx b/scripts/fixtures/host-plugin-react.tsx new file mode 100644 index 000000000..a5ec01dc0 --- /dev/null +++ b/scripts/fixtures/host-plugin-react.tsx @@ -0,0 +1,43 @@ +import React, { useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import { PluginHostDrawnPage } from '../../components/plugins/PluginHostDrawnPage'; +import '../../index.css'; +import { I18nProvider } from '../../application/i18n/I18nProvider'; +import { usePluginContributions } from '../../application/state/usePluginContributions'; +import { PluginSettingGroups } from '../../components/plugins/PluginSettingsForm'; +import { useAvailableFonts } from '../../application/state/fontStore'; +for (const [name, value] of Object.entries({ '--radius': '0.6rem', '--input': '0 0% 30%', '--background': '0 0% 10%', '--foreground': '0 0% 95%', '--muted': '0 0% 16%', '--muted-foreground': '0 0% 70%', '--border': '0 0% 30%', '--primary': '210 90% 55%', '--primary-foreground': '0 0% 100%' })) document.documentElement.style.setProperty(name, value); +document.body.style.background = 'hsl(var(--background))'; +const attached = Element.prototype.attachShadow; +Element.prototype.attachShadow = function (init) { + const root = attached.call(this, init); + if (!this.closest('[data-plugin-view-popover]')) (window as typeof window & { testPluginShadow?: ShadowRoot }).testPluginShadow = root; + return root; +}; +const name = new URLSearchParams(location.search).get('view') || 'vault'; +const surface = name === 'vault' ? 'vault-page' : name === 'sidebar' ? 'terminal-sidebar' : name; +const context = Object.freeze({ 'netcatty.surface': surface }); +const subscribeHidden = () => () => {}; +const unavailable = () => { document.body.dataset.failure = 'true'; }; +const settingsQuery = { locale: 'zh-CN', context: { 'netcatty.surface': 'settings' } }; +function SettingsFixture() { + const contributions = usePluginContributions(settingsQuery); + const fonts = useAvailableFonts(); + const plugin = contributions.snapshot.plugins[0]; + return
+

你好,React · 插件设置

+ {plugin && } + {contributions.error &&

{contributions.error.message}

} +
; +} +function Fixture() { + const [visible, setVisible] = useState(true); + return
+ {visible && } +
Host menu
+ + +
; +} +createRoot(document.getElementById('root')!).render({name === 'settings-form' ? : }); diff --git a/scripts/plugin-assistant-panel.test.cjs b/scripts/plugin-assistant-panel.test.cjs index 92453cc78..b2dcce5cf 100644 --- a/scripts/plugin-assistant-panel.test.cjs +++ b/scripts/plugin-assistant-panel.test.cjs @@ -7,26 +7,17 @@ const { JSDOM } = require("jsdom"); async function fixture(t, options = {}) { const root = path.resolve(__dirname, "../examples/plugins/assistant"); - const dom = new JSDOM(fs.readFileSync(path.join(root, "panel.html"), "utf8"), { runScripts: "outside-only" }); + const dom = new JSDOM(fs.readFileSync(path.join(root, "view.html"), "utf8"), { runScripts: "outside-only" }); t.after(() => dom.window.close()); const stylesheet = dom.window.document.createElement("style"); - stylesheet.textContent = fs.readFileSync(path.join(root, "panel.css"), "utf8"); + stylesheet.textContent = fs.readFileSync(path.join(root, "view.css"), "utf8"); dom.window.document.head.append(stylesheet); let now = 0; let opens = 0; let modelCalls = 0; let changed = false; const calls = []; - const environmentListeners = new Set(); let environment; + let messageListeners = 0; const element = (id) => dom.window.document.getElementById(id); dom.window.Date.now = options.clock ?? (() => now); - Object.defineProperty(dom.window, "netcattyView", { value: { - onDidReceiveMessage: () => () => {}, - onDidChangeEnvironment: (listener) => { - environmentListeners.add(listener); - if (environment) { - const replay = environment; - queueMicrotask(() => { if (environmentListeners.has(listener) && replay === environment) listener(replay); }); - } - return { dispose: () => environmentListeners.delete(listener) }; - }, + const commands = { executeCommand: async (id, params) => { const operation = id.replace("com.netcatty.assistant.", ""); calls.push({ operation, params }); if (options.commands) return options.commands(operation, structuredClone(params)); @@ -46,7 +37,7 @@ async function fixture(t, options = {}) { if (operation === "read") return { kind: "end", sequence: 0 }; throw Error(`Unexpected operation ${operation}`); }, - } }); + }; const waitFor = async (condition) => { const deadline = Date.now() + 2_000; while (!condition()) { @@ -54,44 +45,25 @@ async function fixture(t, options = {}) { await new Promise(setImmediate); } }; - dom.window.eval(fs.readFileSync(path.join(root, "panel.js"), "utf8")); + const mount = dom.window.eval('(' + fs.readFileSync(path.join(root, "panel.js"), "utf8").replace('export function mount', 'function mount') + ')'); + const unmount = mount(dom.window.document.body, { commands, views: { onDidReceiveMessage() { messageListeners++; return { dispose() { messageListeners--; } }; } } }, 'com.netcatty.assistant.panel'); + let disposed = false; + const dispose = () => { if (!disposed) { disposed = true; unmount(); } }; + t.after(dispose); await waitFor(() => element("status").textContent === "Ready"); element("prompt").value = "Synthetic draft must survive session recovery"; return { element, calls, waitFor, window: dom.window, opens: () => opens, modelCalls: () => modelCalls, - emitEnvironment: (value) => { environment = value; for (const listener of environmentListeners) listener(value); }, - environmentListeners: () => environmentListeners.size, + dispose, messageListeners: () => messageListeners, timeTo: (value) => { now = value; }, changeModel: () => { changed = true; }, send: () => element("compose").dispatchEvent(new dom.window.Event("submit", { cancelable: true })) }; } -test("assistant follows host light/dark and accent updates with safe fallbacks and subscription cleanup", async (t) => { - const f = await fixture(t); const root = f.window.document.documentElement; - const computed = () => f.window.getComputedStyle(root); - const calls = f.calls.length; - assert.equal(computed().colorScheme, "light dark"); - assert.equal(computed().getPropertyValue("--background").trim(), "0 0% 100%"); - assert.equal(f.environmentListeners(), 1); - f.emitEnvironment({ theme: "light", themeTokens: { "--background": "20 20% 98%", "--primary": "145 60% 35%", "--muted": "30 10% 90%", "--private-token": "ignored" } }); - assert.equal(root.style.colorScheme, "light"); assert.equal(root.dataset.theme, "light"); - assert.equal(root.style.getPropertyValue("--primary"), "145 60% 35%"); - assert.equal(root.style.getPropertyValue("--private-token"), ""); - f.emitEnvironment({ theme: "dark", themeTokens: { "--background": "220 20% 10%", "--primary": "280 80% 75%" } }); - assert.equal(root.style.colorScheme, "dark"); - assert.equal(root.style.getPropertyValue("--primary"), "280 80% 75%"); - assert.equal(root.style.getPropertyValue("--muted"), ""); - assert.equal(computed().getPropertyValue("--muted").trim(), "219 27% 21%"); - f.emitEnvironment({ theme: "light", themeTokens: { "--primary": "x".repeat(97) } }); - assert.equal(root.style.colorScheme, "light"); assert.equal(root.style.getPropertyValue("--primary"), ""); - assert.equal(computed().getPropertyValue("--background").trim(), "0 0% 100%"); - f.emitEnvironment({ theme: "system" }); assert.equal(root.style.colorScheme, "light dark"); - assert.equal(f.calls.length, calls); assert.equal(f.modelCalls(), 0); - f.window.dispatchEvent(new f.window.Event("pagehide")); assert.equal(f.environmentListeners(), 0); - f.emitEnvironment({ theme: "dark", themeTokens: { "--primary": "210 90% 70%" } }); - assert.equal(root.style.colorScheme, "light dark"); - f.window.dispatchEvent(new f.window.Event("pageshow")); - await new Promise(setImmediate); - assert.equal(f.environmentListeners(), 1); assert.equal(root.style.colorScheme, "dark"); - assert.equal(root.style.getPropertyValue("--primary"), "210 90% 70%"); +test("assistant mount cleanup unsubscribes messages and closes its own chat", async (t) => { + const f = await fixture(t); + assert.equal(f.messageListeners(), 1); + f.dispose(); + assert.equal(f.messageListeners(), 0); + assert.equal(f.calls.filter(call => call.operation === 'close' && call.params.chatHandle === 'chat-1').length, 1); }); test("expired sample chat reopens before one explicit send and preserves the draft", async (t) => { diff --git a/scripts/plugin-global-agent-layout.live.test.cjs b/scripts/plugin-global-agent-layout.live.test.cjs index 40dadf719..b8942aec1 100644 --- a/scripts/plugin-global-agent-layout.live.test.cjs +++ b/scripts/plugin-global-agent-layout.live.test.cjs @@ -28,10 +28,10 @@ if (!process.versions.electron) { void app.whenReady().then(async () => { // Inline the real stylesheet and omit panel.js: even a broken layout has no // path to execute plugin commands or initiate model/credential requests. - const html = fs.readFileSync(path.join(sample, "panel.html"), "utf8") - .replace('', ``) - .replace('', "") - .replace("", ''); + const html = ` + + + ${fs.readFileSync(path.join(sample, "view.html"), "utf8")}`; const isolatedSession = session.fromPartition("agent-layout-synthetic"); isolatedSession.webRequest.onBeforeRequest({ urls: ["http://*/*", "https://*/*"] }, (_details, callback) => callback({ cancel: true })); win = new BrowserWindow({ show: false, useContentSize: true, width: 798, height: 548, diff --git a/vite.config.ts b/vite.config.ts index 2ec57ed84..f0f1c255c 100755 --- a/vite.config.ts +++ b/vite.config.ts @@ -85,7 +85,7 @@ export default defineConfig(() => { build: { // The shared runtime is also required by Electron; convert it for browser builds. commonjsOptions: { - include: [/node_modules/, /domain\/systemManager\/containerRuntime\.shared\.cjs$/, /domain\/plugin(?:RuntimePolicy|PermissionDescriptions|ThemePack)\.cjs$/], + include: [/node_modules/, /domain\/systemManager\/containerRuntime\.shared\.cjs$/, /domain\/plugin(?:RuntimePolicy|PermissionDescriptions|ThemePack|RemoteTreePolicy|ViewStylePolicy)\.cjs$/], }, chunkSizeWarningLimit: 3000, target: 'esnext', // Required for top-level await in WASM modules @@ -133,6 +133,8 @@ export default defineConfig(() => { '@/domain/pluginRuntimePolicy.cjs', '@/domain/pluginPermissionDescriptions.cjs', '@/domain/pluginThemePack.cjs', + '@/domain/pluginRemoteTreePolicy.cjs', + '@/domain/pluginViewStylePolicy.cjs', 'ai', '@ai-sdk/openai', '@ai-sdk/anthropic',