From 2da20e6b2abef7b3d31ffc2bed9c1e78a69182e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:46:40 +0800 Subject: [PATCH] fix(plugins): preserve plugin tabs on overlay close and harden host surface controls (#4296) --- .../state/usePluginViewLifecycle.test.ts | 62 +++++++++++++++++++ application/state/usePluginViewLifecycle.ts | 6 +- .../plugins/PluginRemoteSurface.test.tsx | 39 +++++++++--- components/plugins/PluginRemoteSurface.tsx | 13 +++- domain/pluginRemoteTreePolicy.cjs | 1 + domain/pluginRemoteTreePolicy.test.cjs | 2 + examples/plugins/assistant/panel.js | 17 ++++- examples/plugins/global-agent/panel.js | 20 +++++- examples/plugins/global-agent/view.html | 2 +- 9 files changed, 144 insertions(+), 18 deletions(-) create mode 100644 application/state/usePluginViewLifecycle.test.ts diff --git a/application/state/usePluginViewLifecycle.test.ts b/application/state/usePluginViewLifecycle.test.ts new file mode 100644 index 000000000..c8fe002e3 --- /dev/null +++ b/application/state/usePluginViewLifecycle.test.ts @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { JSDOM } from 'jsdom'; + +test('closing plugin overlays preserves the underlying plugin tab and closing that tab still removes it', async () => { + const dom = new JSDOM('
', { url: 'http://localhost', pretendToBeVisual: true }); + const previous = new Map(); + const install = (name: string, value: unknown) => { + previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + Object.defineProperty(globalThis, name, { configurable: true, writable: true, value }); + }; + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MutationObserver']) { + install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]); + } + 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); + Object.assign(dom.window, { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), netcatty: { + async getPluginRuntimeStatus() { return { available: true }; }, + async getPluginContributions() { return { locale: 'en', plugins: [{ id: 'example.plugin', version: '1.0.0', displayName: 'Example', + commands: [], keybindings: [], menus: [], settings: [], views: ['tab', 'modal', 'aside', 'panel'].map(location => ({ + id: `example.plugin.${location}`, title: location, location, visible: true, + })) }] }; }, + onPluginContributionsChanged() { return () => {}; }, + async setPluginEnvironment() {}, + } }); + const { default: React, act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { usePluginViewLifecycle, requestOpenPluginView } = await import('./usePluginViewLifecycle'); + const { pluginViewTabStore } = await import('./pluginViewTabStore'); + const { activeTabStore } = await import('./activeTabStore'); + const context = { 'netcatty.surface': 'keybinding' }; + let model!: ReturnType; + function Fixture() { + model = usePluginViewLifecycle({ locale: 'en', theme: 'dark', keybindingContext: context }); + return React.createElement('button', { onClick: () => void model.close() }, model.activeView?.view.id ?? 'none'); + } + const root = createRoot(document.getElementById('root')!); + const settle = () => new Promise(resolve => setTimeout(resolve, 30)); + const perform = async (action: () => void) => act(async () => { action(); await settle(); }); + try { + activeTabStore.setActiveTabId('vault'); + const tab = pluginViewTabStore.open({ pluginId: 'example.plugin', pluginName: 'Example', viewId: 'example.plugin.tab', title: 'Tab' }); + await perform(() => root.render(React.createElement(Fixture))); + assert.equal(model.activeView?.view.id, tab.viewId); + for (const location of ['modal', 'aside', 'panel']) { + await perform(() => requestOpenPluginView({ viewId: `example.plugin.${location}` })); + assert.equal(model.activeView?.view.location, location); + await perform(() => document.querySelector('button')!.click()); + assert.equal(activeTabStore.getActiveTabId(), tab.id, `closing ${location} preserves the active tab`); + assert.equal(pluginViewTabStore.getTabs()[0]?.id, tab.id); + assert.equal(model.activeView?.view.id, tab.viewId, `closing ${location} returns to the underlying view`); + } + await perform(() => document.querySelector('button')!.click()); + assert.equal(pluginViewTabStore.getTabs().length, 0, 'closing the tab itself still removes it'); + } finally { + await act(async () => root.unmount()); + pluginViewTabStore.retain(new Set()); activeTabStore.setActiveTabId('vault'); dom.window.close(); + for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } + } +}); diff --git a/application/state/usePluginViewLifecycle.ts b/application/state/usePluginViewLifecycle.ts index 007ecaf12..14a5a87ed 100644 --- a/application/state/usePluginViewLifecycle.ts +++ b/application/state/usePluginViewLifecycle.ts @@ -144,7 +144,11 @@ export function usePluginViewLifecycle({ const close = useCallback(async () => { setRequested(null); if (activeView) pluginViewSessions.closeView(activeView.view.id); - if (activePluginTab) pluginViewTabStore.close(activePluginTab.id); + // An overlay can be requested while a different plugin tab stays active. + // Dismissing that overlay must not close the tab underneath it. + if (activeView?.view.location === 'tab' && activePluginTab?.viewId === activeView.view.id) { + pluginViewTabStore.close(activePluginTab.id); + } }, [activePluginTab, activeView]); useEffect(() => { diff --git a/components/plugins/PluginRemoteSurface.test.tsx b/components/plugins/PluginRemoteSurface.test.tsx index 7517520cb..cd81f87cd 100644 --- a/components/plugins/PluginRemoteSurface.test.tsx +++ b/components/plugins/PluginRemoteSurface.test.tsx @@ -36,9 +36,30 @@ test('plugin surface forwards its own input and contains malformed updates and r assert.equal(events.length, 2); await act(async () => { root.render( {}} />); }); assert.equal(document.querySelector('[role=alert]')?.textContent, 'Unable to display plugin view.'); + const optionA = { id: 'a', type: 1, element: 'option', attributes: { selected: '' }, children: [{ id: 'at', type: 3, data: ' First\n option ' }] }; + const optionB = { id: 'b', type: 1, element: 'option', attributes: {}, children: [{ id: 'bt', type: 3, data: 'Second' }] }; + const controls = { children: [ + { id: 'select', type: 1, element: 'select', attributes: { multiple: '' }, children: [optionA, optionB] }, + { id: 'textarea', type: 1, element: 'textarea', attributes: {}, children: [{ id: 'ta', type: 3, data: 'Hello' }, { id: 'tb', type: 3, data: ' world' }] }, + ] }; + const renderControls = async () => act(async () => root.render( events.push(event)} />)); + await renderControls(); + const select = captured!.querySelector('select')!; + assert.deepEqual([...select.selectedOptions].map((option) => option.value), ['First option']); + assert.equal(captured!.querySelector('textarea')!.value, 'Hello world'); + await act(async () => { + select.options[0].selected = false; select.options[1].selected = true; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + }); + assert.deepEqual(events.at(-1), { nodeId: 'select', type: 'change', value: 'Second', values: ['Second'] }); + optionA.attributes = {} as typeof optionA.attributes; + optionB.attributes = { selected: '' }; + await renderControls(); + assert.deepEqual([...select.selectedOptions].map((option) => option.value), ['Second'], 'acknowledgement keeps native option text values selected'); + let clicks = 0; - const renderView = async (nextTree: unknown) => act(async () => root.render(<> - {}} /> + const renderView = async (nextTree: unknown, viewKey = 'view') => act(async () => root.render(<> + {}} /> {}} /> )); @@ -48,15 +69,17 @@ test('plugin surface forwards its own input and contains malformed updates and r 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. + // Unexpected rendering failures stay within this plugin, including layout effects. const originalError = console.error; + const prevAttach = dom.window.Element.prototype.attachShadow; 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; } + dom.window.Element.prototype.attachShadow = () => { throw new Error('Synthetic surface failure'); }; + await renderView(tree, 'broken-surface'); + } finally { + dom.window.Element.prototype.attachShadow = prevAttach; + 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()); diff --git a/components/plugins/PluginRemoteSurface.tsx b/components/plugins/PluginRemoteSurface.tsx index 1dcf96afb..c82dcf28e 100644 --- a/components/plugins/PluginRemoteSurface.tsx +++ b/components/plugins/PluginRemoteSurface.tsx @@ -13,6 +13,10 @@ const ATTRIBUTE_NAMES: Record = { class: 'className', for: 'html 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 }); +function remoteText(nodes: RemoteNode[]): string { + return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join(''); +} + const ResourceLoader = createContext<((path: string) => Promise) | undefined>(undefined); function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }): React.ReactNode { @@ -27,10 +31,10 @@ function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean } 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 ?? '' : '') : []); + ? node.children.filter((child) => child.type === 1 && child.element === 'option' && Object.hasOwn(child.attributes, 'selected')).map((child) => child.type === 1 ? child.attributes.value ?? remoteText(child.children).replace(/[\t\n\f\r ]+/g, ' ').trim() : '') : []); const [localSelection, setLocalSelection] = useState(() => JSON.parse(remoteSelection)); useEffect(() => { if (settled) setLocalSelection(JSON.parse(remoteSelection)); }, [remoteSelection, settled]); - const remoteValue = attrs.value; + const remoteValue = attrs.value ?? (node.type === 1 && node.element === 'textarea' ? remoteText(node.children) : undefined); const remoteChecked = Object.hasOwn(attrs, 'checked'); const [localValue, setLocalValue] = useState(remoteValue ?? ''); const [localChecked, setLocalChecked] = useState(remoteChecked); @@ -62,7 +66,10 @@ function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean } 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) => )); + // React treats textarea/option text specially; do not wrap it in components. + if (node.element === 'textarea') return React.createElement(node.element, props); + if (node.element === 'option') return React.createElement(node.element, props, remoteText(node.children)); + return React.createElement(node.element, props, ...node.children.map((child) => )); } /** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */ diff --git a/domain/pluginRemoteTreePolicy.cjs b/domain/pluginRemoteTreePolicy.cjs index 88774e574..1f8da3e4b 100644 --- a/domain/pluginRemoteTreePolicy.cjs +++ b/domain/pluginRemoteTreePolicy.cjs @@ -44,6 +44,7 @@ function validatePluginRemoteTree(root) { || !Array.isArray(node.children) || !record(node.attributes) || Object.keys(node).some((key) => !["id", "type", "element", "attributes", "children"].includes(key))) throw new TypeError("Forbidden view element"); if (VOID_ELEMENTS.has(node.element) && node.children.length) throw new TypeError("Void view elements cannot have children"); + if (node.element === "textarea" && node.children.some((child) => !record(child) || ![3, 8].includes(child.type))) throw new TypeError("Textarea only accepts text"); const attributes = Object.entries(node.attributes); if (attributes.length > 64) throw new TypeError("Too many view attributes"); for (const [name, value] of attributes) { diff --git a/domain/pluginRemoteTreePolicy.test.cjs b/domain/pluginRemoteTreePolicy.test.cjs index c1b57baf0..57bfd3f73 100644 --- a/domain/pluginRemoteTreePolicy.test.cjs +++ b/domain/pluginRemoteTreePolicy.test.cjs @@ -43,4 +43,6 @@ test("void children are rejected in snapshots and mutation insertions", () => { assert.throws(() => validatePluginRemoteTree({ children: [node] }), /Void view elements/); assert.throws(() => validatePluginMutationBatch([[0, "~", node, 0]]), /Void view elements/); } + assert.throws(() => validatePluginRemoteTree({ children: [element("a", "textarea", {}, [element("b", "div")])] }), /Textarea/); + assert.equal(validatePluginRemoteTree({ children: [element("a", "textarea", {}, [text("b", "Hello"), text("c", " world")])] }), true); }); diff --git a/examples/plugins/assistant/panel.js b/examples/plugins/assistant/panel.js index 7e0c9c2b1..eb2157d5a 100644 --- a/examples/plugins/assistant/panel.js +++ b/examples/plugins/assistant/panel.js @@ -3,6 +3,19 @@ export function mount(root, context, viewId) { const onDispose = (stop) => cleanup.push(stop); const subscribeMessage = (listener) => { const sub = context.views.onDidReceiveMessage(viewId, listener); cleanup.push(() => sub.dispose()); return sub; }; const element = (id) => root.querySelector("#" + id); +// Keep the newest output visible within the host's per-node and total limits. +// Chunking avoids closing a healthy view when an ordinary response exceeds 8 KB. +let outputText = ''; let outputTruncated = false; +function showOutput(text, append = false) { + const combined = append ? outputText + text : text; + outputTruncated = (append && outputTruncated) || combined.length > 32768; + outputText = combined.slice(-32768); + const nodes = []; + if (outputTruncated) nodes.push(root.ownerDocument.createTextNode('[Earlier output omitted; showing the latest 32,768 characters.]\n\n')); + for (let offset = 0; offset < outputText.length; offset += 4096) nodes.push(root.ownerDocument.createTextNode(outputText.slice(offset, offset + 4096))); + element('response').replaceChildren(...nodes); +} + const invoke = (operation, params = {}) => context.commands.executeCommand(`com.netcatty.assistant.${operation}`, params); let chat; let turn; @@ -90,7 +103,7 @@ element('compose').addEventListener('submit', async (event) => { } const run = ++generation; busy(true); element('status').textContent = 'Streaming...'; - element('response').textContent = ''; element('usage').textContent = ''; + showOutput(''); element('usage').textContent = ''; try { // No inference has been requested yet, so an expired session can be // replaced before this explicit Send. Never retry a failed send/read. @@ -103,7 +116,7 @@ element('compose').addEventListener('submit', async (event) => { const chunk = await invoke('read', { turnHandle: turn }); if (run !== generation) return; if (chunk.kind === 'end') break; - if (chunk.kind === 'text') element('response').textContent += chunk.text; + if (chunk.kind === 'text') showOutput(chunk.text, true); if (chunk.kind === 'usage') element('usage').textContent = `${chunk.inputTokens ?? '?'} input tokens · ${chunk.outputTokens ?? '?'} output tokens`; } element('status').textContent = 'Complete'; diff --git a/examples/plugins/global-agent/panel.js b/examples/plugins/global-agent/panel.js index 40c0421c4..868d5cad2 100644 --- a/examples/plugins/global-agent/panel.js +++ b/examples/plugins/global-agent/panel.js @@ -3,6 +3,19 @@ export function mount(root, context, viewId) { const onDispose = (stop) => cleanup.push(stop); const subscribeMessage = (listener) => { const sub = context.views.onDidReceiveMessage(viewId, listener); cleanup.push(() => sub.dispose()); return sub; }; const element = (id) => root.querySelector("#" + id); +// Keep the newest output visible within the host's per-node and total limits. +// Chunking avoids closing a healthy view when an ordinary response exceeds 8 KB. +let outputText = ''; let outputTruncated = false; +function showOutput(text, append = false) { + const combined = append ? outputText + text : text; + outputTruncated = (append && outputTruncated) || combined.length > 32768; + outputText = combined.slice(-32768); + const nodes = []; + if (outputTruncated) nodes.push(root.ownerDocument.createTextNode('[Earlier output omitted; showing the latest 32,768 characters.]\n\n')); + for (let offset = 0; offset < outputText.length; offset += 4096) nodes.push(root.ownerDocument.createTextNode(outputText.slice(offset, offset + 4096))); + element('transcript').replaceChildren(...nodes); +} + const invoke = (name, params = {}) => context.commands.executeCommand(`com.netcatty.globalagent.${name}`, params); let chat; let selection; let turn; let busy = false; let generation = 0; let closed = false; const option = (value, text) => { const item = root.ownerDocument.createElement('option'); item.value = value; item.textContent = text; return item; }; @@ -53,7 +66,7 @@ element('open').addEventListener('click', async () => { if (closed || run !== generation) { await invoke('close', { chatHandle: result.chatHandle }).catch(() => {}); return; } chat = result; const history = await invoke('history', { chatHandle: chat.chatHandle }); if (closed || run !== generation) return; - element('transcript').textContent = history.items.map((item) => `${item.role}: ${item.text}`).join('\n\n'); + showOutput(history.items.map((item) => `${item.role}: ${item.text}`).join('\n\n')); element('usage').textContent = ''; element('activity').textContent = ''; status(`Ready · ${result.backendLabel}`); } catch { await closeChat(); if (!closed && run === generation) status('Conversation unavailable. Refresh backends or choose terminals again; your draft is kept.'); } @@ -62,8 +75,9 @@ element('open').addEventListener('click', async () => { element('compose').addEventListener('submit', async (event) => { event.preventDefault(); if (busy || !chat || !element('prompt').value.trim()) return; if (chat.expiresAt <= Date.now()) { status('Conversation targets expired. Choose terminals and reopen; your draft is kept.'); return; } + if (element('prompt').value.length > 8192) { status('Message is too long. Limit it to 8,192 characters before sending.'); return; } const run = ++generation; controls(true); status('Running…'); element('usage').textContent = ''; element('activity').textContent = ''; - const text = element('prompt').value; element('transcript').textContent += `\n\nuser: ${text}\n\nassistant: `; + const text = element('prompt').value; showOutput(`\n\nuser: ${text}\n\nassistant: `, true); try { const result = await invoke('send', { chatHandle: chat.chatHandle, text }); if (closed || run !== generation) { await invoke('stop', { turnHandle: result.turnHandle }).catch(() => {}); return; } @@ -71,7 +85,7 @@ element('compose').addEventListener('submit', async (event) => { for (;;) { const item = await invoke('read', { turnHandle: turn }); if (closed || run !== generation) return; if (item.kind === 'end') { status(item.reason === 'completed' ? 'Complete' : `Ended: ${item.reason}`); break; } - if (item.kind === 'text') element('transcript').textContent += item.text; + if (item.kind === 'text') showOutput(item.text, true); if (item.kind === 'activity') element('activity').textContent = `${item.capabilityId}: ${item.state}`; if (item.kind === 'usage') element('usage').textContent = `${item.inputTokens} input tokens · ${item.outputTokens} output tokens`; } diff --git a/examples/plugins/global-agent/view.html b/examples/plugins/global-agent/view.html index 790c8a5ef..bd3b557c5 100644 --- a/examples/plugins/global-agent/view.html +++ b/examples/plugins/global-agent/view.html @@ -3,5 +3,5 @@

No targets selected yet.

-
Loading configured backends…
+
Loading configured backends…