mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 16:42:19 +00:00
fix(plugins): preserve plugin tabs on overlay close and harden host surface controls (#4296)
This commit is contained in:
9 files changed
+144
-18
No files matched your search
@@ -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('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
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<typeof usePluginViewLifecycle>;
|
||||
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); }
|
||||
}
|
||||
});
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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(<PluginRemoteSurface tree={tree} css="@import 'https://bad.example/x';" onEvent={() => {}} />); });
|
||||
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(<PluginRemoteSurface tree={{ ...controls }} css="" onEvent={(event) => 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(<>
|
||||
<PluginRemoteSurface key="view" tree={nextTree} css="" onEvent={() => {}} />
|
||||
const renderView = async (nextTree: unknown, viewKey = 'view') => act(async () => root.render(<>
|
||||
<PluginRemoteSurface key={viewKey} tree={nextTree} css="" onEvent={() => {}} />
|
||||
<button id="canary" onClick={() => clicks++}>Host canary</button>
|
||||
<PluginRemoteSurface key="sibling" tree={tree} css="" onEvent={() => {}} />
|
||||
</>));
|
||||
@@ -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());
|
||||
|
||||
@@ -13,6 +13,10 @@ const ATTRIBUTE_NAMES: Record<string, string> = { 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<string>) | 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<string[]>(() => 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) => <RemoteElement key={child.id} node={child} settled={settled} />));
|
||||
// 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) => <RemoteElement key={child.id} node={child} settled={settled} />));
|
||||
}
|
||||
|
||||
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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';
|
||||
|
||||
@@ -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`;
|
||||
}
|
||||
|
||||
@@ -3,5 +3,5 @@
|
||||
<div><label for="conversation">Owned conversation</label><select id="conversation"><option value="">New conversation</option></select></div>
|
||||
<div class="actions"><button id="refresh" type="button">Refresh backends</button><button id="targets" type="button">Choose terminals</button><button id="open" type="button" disabled>Open conversation</button></div><p id="selection" class="hint">No targets selected yet.</p></section>
|
||||
<section class="card response"><pre id="transcript" aria-live="polite"></pre><p id="usage" class="hint"></p><p id="activity" class="hint"></p></section>
|
||||
<form id="compose"><label for="prompt">Message</label><textarea id="prompt" maxlength="16384" placeholder="Ask about the selected terminals"></textarea><div class="actions"><button id="send" type="submit" disabled>Send</button><button id="stop" type="button" disabled>Stop</button><span id="status" role="status">Loading configured backends…</span></div></form>
|
||||
<form id="compose"><label for="prompt">Message</label><textarea id="prompt" maxlength="8192" placeholder="Ask about the selected terminals"></textarea><div class="actions"><button id="send" type="submit" disabled>Send</button><button id="stop" type="button" disabled>Stop</button><span id="status" role="status">Loading configured backends…</span></div></form>
|
||||
<footer>Actions follow this plugin's Allow / Ask / Deny setting.</footer></main></div>
|
||||
Reference in new issue
Block a user