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 (
-
-
+
);
}
@@ -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 ;
+}
+
+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 (
+
+ );
+ }
+ if (setting.control === 'select') {
+ return (
+
+ );
+ }
+ if (setting.control === 'multiselect') {
+ const selected = Array.isArray(value) ? value.map(String) : [];
+ return (
+
+ );
+ }
+ if (setting.control === 'textarea') {
+ return (
+