feat: rebuild plugin UI with host rendering and standard settings (#4053)

* feat: rebuild plugin pages with host rendering and native settings

* fix(plugins): contain host-view errors, isolate editing, and migrate fixtures

* fix(plugins): migrate remaining permission fixture hosts
This commit is contained in:
陈大猫 authored and GitHub committed 2026-10-28 23:08:31 -07:00
1 parent 7cd57adcea
commit d5a03606b7
227 files changed
+8298 -4172

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
import { build } from 'esbuild';
import { mkdir, readFile, rm, copyFile, cp, stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
export async function buildHostViewExample(directory) {
const root = fileURLToPath(directory);
await build({ entryPoints: [path.join(root, 'host.js')], outfile: path.join(root, 'dist/host.js'), bundle: true, platform: 'browser', format: 'esm', loader: { '.html': 'text', '.css': 'text' }, minify: true });
const staging = path.join(root, '.package');
await rm(staging, { recursive: true, force: true });
await mkdir(path.join(staging, 'dist'), { recursive: true });
for (const file of ['netcatty.plugin.json', 'dist/host.js']) await copyFile(path.join(root, file), path.join(staging, file));
if (await stat(path.join(root, 'assets')).then((info) => info.isDirectory(), () => false)) await cp(path.join(root, 'assets'), path.join(staging, 'assets'), { recursive: true });
// Parse at build time so a forgotten view declaration fails before packaging.
const manifest = JSON.parse(await readFile(path.join(root, 'netcatty.plugin.json'), 'utf8'));
if (!manifest.contributes?.views?.length) throw new Error('Example has no declared view');
}
+5
View File
@@ -0,0 +1,5 @@
import { buildHostViewExample } from './build-plugin-view-example.mjs';
for (const name of ['hello-vault', 'hello-world-v2', 'session-scratchpad', 'vault-scratchpad', 'settings-view-fixture', 'starter-netcatty', 'assistant', 'global-agent']) {
await buildHostViewExample(new URL(`../examples/plugins/${name}/`, import.meta.url));
}
await import('../examples/plugins/hello-react-host/build.mjs');
+1
View File
@@ -0,0 +1 @@
<!doctype html><html><head><meta charset="utf-8"><title>Host React fixture</title></head><body><div id="root"></div><script type="module" src="./host-plugin-react.tsx"></script></body></html>
+43
View File
@@ -0,0 +1,43 @@
import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { PluginHostDrawnPage } from '../../components/plugins/PluginHostDrawnPage';
import '../../index.css';
import { I18nProvider } from '../../application/i18n/I18nProvider';
import { usePluginContributions } from '../../application/state/usePluginContributions';
import { PluginSettingGroups } from '../../components/plugins/PluginSettingsForm';
import { useAvailableFonts } from '../../application/state/fontStore';
for (const [name, value] of Object.entries({ '--radius': '0.6rem', '--input': '0 0% 30%', '--background': '0 0% 10%', '--foreground': '0 0% 95%', '--muted': '0 0% 16%', '--muted-foreground': '0 0% 70%', '--border': '0 0% 30%', '--primary': '210 90% 55%', '--primary-foreground': '0 0% 100%' })) document.documentElement.style.setProperty(name, value);
document.body.style.background = 'hsl(var(--background))';
const attached = Element.prototype.attachShadow;
Element.prototype.attachShadow = function (init) {
const root = attached.call(this, init);
if (!this.closest('[data-plugin-view-popover]')) (window as typeof window & { testPluginShadow?: ShadowRoot }).testPluginShadow = root;
return root;
};
const name = new URLSearchParams(location.search).get('view') || 'vault';
const surface = name === 'vault' ? 'vault-page' : name === 'sidebar' ? 'terminal-sidebar' : name;
const context = Object.freeze({ 'netcatty.surface': surface });
const subscribeHidden = () => () => {};
const unavailable = () => { document.body.dataset.failure = 'true'; };
const settingsQuery = { locale: 'zh-CN', context: { 'netcatty.surface': 'settings' } };
function SettingsFixture() {
const contributions = usePluginContributions(settingsQuery);
const fonts = useAvailableFonts();
const plugin = contributions.snapshot.plugins[0];
return <main className="mx-auto max-w-2xl space-y-4 p-6 text-foreground" data-settings-fixture="" data-loading={contributions.loading} data-available={contributions.available} data-count={contributions.snapshot.plugins.length}>
<h2 className="text-xl font-semibold">你好,React · 插件设置</h2>
{plugin && <PluginSettingGroups pluginId={plugin.id} settings={plugin.settings} updateSetting={contributions.updateSetting}
resetSetting={contributions.resetSetting} selectSettingPath={contributions.selectSettingPath} availableFonts={fonts} />}
{contributions.error && <p role="alert">{contributions.error.message}</p>}
</main>;
}
function Fixture() {
const [visible, setVisible] = useState(true);
return <div style={{ width: 600, height: 500, position: 'relative' }}>
{visible && <PluginHostDrawnPage pluginId="com.netcatty.hello-react-host" viewId={new URLSearchParams(location.search).get('id') || `com.netcatty.hello-react-host.${name}`} version="0.2.0" slot={surface} active context={context} subscribeHidden={subscribeHidden} unavailable={unavailable} loadingLabel="Loading" />}
<div id="host-overlay" style={{ position: 'absolute', top: 20, left: 20, width: 100, height: 50, zIndex: 10, background: 'red' }}>Host menu</div>
<button id="toggle-plugin" style={{ position: 'absolute', left: 0, top: 520 }} onClick={() => setVisible(value => !value)}>Toggle plugin</button>
<input id="host-private-input" aria-label="Host-only input" style={{ position: 'absolute', left: 150, top: 520 }} />
</div>;
}
createRoot(document.getElementById('root')!).render(<I18nProvider locale="zh-CN">{name === 'settings-form' ? <SettingsFixture /> : <Fixture />}</I18nProvider>);
+17 -45
View File
@@ -7,26 +7,17 @@ const { JSDOM } = require("jsdom");
async function fixture(t, options = {}) {
const root = path.resolve(__dirname, "../examples/plugins/assistant");
const dom = new JSDOM(fs.readFileSync(path.join(root, "panel.html"), "utf8"), { runScripts: "outside-only" });
const dom = new JSDOM(fs.readFileSync(path.join(root, "view.html"), "utf8"), { runScripts: "outside-only" });
t.after(() => dom.window.close());
const stylesheet = dom.window.document.createElement("style");
stylesheet.textContent = fs.readFileSync(path.join(root, "panel.css"), "utf8");
stylesheet.textContent = fs.readFileSync(path.join(root, "view.css"), "utf8");
dom.window.document.head.append(stylesheet);
let now = 0; let opens = 0; let modelCalls = 0; let changed = false;
const calls = [];
const environmentListeners = new Set(); let environment;
let messageListeners = 0;
const element = (id) => dom.window.document.getElementById(id);
dom.window.Date.now = options.clock ?? (() => now);
Object.defineProperty(dom.window, "netcattyView", { value: {
onDidReceiveMessage: () => () => {},
onDidChangeEnvironment: (listener) => {
environmentListeners.add(listener);
if (environment) {
const replay = environment;
queueMicrotask(() => { if (environmentListeners.has(listener) && replay === environment) listener(replay); });
}
return { dispose: () => environmentListeners.delete(listener) };
},
const commands = {
executeCommand: async (id, params) => {
const operation = id.replace("com.netcatty.assistant.", ""); calls.push({ operation, params });
if (options.commands) return options.commands(operation, structuredClone(params));
@@ -46,7 +37,7 @@ async function fixture(t, options = {}) {
if (operation === "read") return { kind: "end", sequence: 0 };
throw Error(`Unexpected operation ${operation}`);
},
} });
};
const waitFor = async (condition) => {
const deadline = Date.now() + 2_000;
while (!condition()) {
@@ -54,44 +45,25 @@ async function fixture(t, options = {}) {
await new Promise(setImmediate);
}
};
dom.window.eval(fs.readFileSync(path.join(root, "panel.js"), "utf8"));
const mount = dom.window.eval('(' + fs.readFileSync(path.join(root, "panel.js"), "utf8").replace('export function mount', 'function mount') + ')');
const unmount = mount(dom.window.document.body, { commands, views: { onDidReceiveMessage() { messageListeners++; return { dispose() { messageListeners--; } }; } } }, 'com.netcatty.assistant.panel');
let disposed = false;
const dispose = () => { if (!disposed) { disposed = true; unmount(); } };
t.after(dispose);
await waitFor(() => element("status").textContent === "Ready");
element("prompt").value = "Synthetic draft must survive session recovery";
return { element, calls, waitFor, window: dom.window, opens: () => opens, modelCalls: () => modelCalls,
emitEnvironment: (value) => { environment = value; for (const listener of environmentListeners) listener(value); },
environmentListeners: () => environmentListeners.size,
dispose, messageListeners: () => messageListeners,
timeTo: (value) => { now = value; }, changeModel: () => { changed = true; },
send: () => element("compose").dispatchEvent(new dom.window.Event("submit", { cancelable: true })) };
}
test("assistant follows host light/dark and accent updates with safe fallbacks and subscription cleanup", async (t) => {
const f = await fixture(t); const root = f.window.document.documentElement;
const computed = () => f.window.getComputedStyle(root);
const calls = f.calls.length;
assert.equal(computed().colorScheme, "light dark");
assert.equal(computed().getPropertyValue("--background").trim(), "0 0% 100%");
assert.equal(f.environmentListeners(), 1);
f.emitEnvironment({ theme: "light", themeTokens: { "--background": "20 20% 98%", "--primary": "145 60% 35%", "--muted": "30 10% 90%", "--private-token": "ignored" } });
assert.equal(root.style.colorScheme, "light"); assert.equal(root.dataset.theme, "light");
assert.equal(root.style.getPropertyValue("--primary"), "145 60% 35%");
assert.equal(root.style.getPropertyValue("--private-token"), "");
f.emitEnvironment({ theme: "dark", themeTokens: { "--background": "220 20% 10%", "--primary": "280 80% 75%" } });
assert.equal(root.style.colorScheme, "dark");
assert.equal(root.style.getPropertyValue("--primary"), "280 80% 75%");
assert.equal(root.style.getPropertyValue("--muted"), "");
assert.equal(computed().getPropertyValue("--muted").trim(), "219 27% 21%");
f.emitEnvironment({ theme: "light", themeTokens: { "--primary": "x".repeat(97) } });
assert.equal(root.style.colorScheme, "light"); assert.equal(root.style.getPropertyValue("--primary"), "");
assert.equal(computed().getPropertyValue("--background").trim(), "0 0% 100%");
f.emitEnvironment({ theme: "system" }); assert.equal(root.style.colorScheme, "light dark");
assert.equal(f.calls.length, calls); assert.equal(f.modelCalls(), 0);
f.window.dispatchEvent(new f.window.Event("pagehide")); assert.equal(f.environmentListeners(), 0);
f.emitEnvironment({ theme: "dark", themeTokens: { "--primary": "210 90% 70%" } });
assert.equal(root.style.colorScheme, "light dark");
f.window.dispatchEvent(new f.window.Event("pageshow"));
await new Promise(setImmediate);
assert.equal(f.environmentListeners(), 1); assert.equal(root.style.colorScheme, "dark");
assert.equal(root.style.getPropertyValue("--primary"), "210 90% 70%");
test("assistant mount cleanup unsubscribes messages and closes its own chat", async (t) => {
const f = await fixture(t);
assert.equal(f.messageListeners(), 1);
f.dispose();
assert.equal(f.messageListeners(), 0);
assert.equal(f.calls.filter(call => call.operation === 'close' && call.params.chatHandle === 'chat-1').length, 1);
});
test("expired sample chat reopens before one explicit send and preserves the draft", async (t) => {
@@ -28,10 +28,10 @@ if (!process.versions.electron) {
void app.whenReady().then(async () => {
// Inline the real stylesheet and omit panel.js: even a broken layout has no
// path to execute plugin commands or initiate model/credential requests.
const html = fs.readFileSync(path.join(sample, "panel.html"), "utf8")
.replace('<link rel="stylesheet" href="panel.css">', `<style>${fs.readFileSync(path.join(sample, "panel.css"), "utf8")}</style>`)
.replace('<script src="panel.js"></script>', "")
.replace("<head>", '<head><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'">');
const html = `<!doctype html><html><head>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
<style>html,body{margin:0;height:100%}${fs.readFileSync(path.join(sample, "view.css"), "utf8")}</style>
</head><body>${fs.readFileSync(path.join(sample, "view.html"), "utf8")}</body></html>`;
const isolatedSession = session.fromPartition("agent-layout-synthetic");
isolatedSession.webRequest.onBeforeRequest({ urls: ["http://*/*", "https://*/*"] }, (_details, callback) => callback({ cancel: true }));
win = new BrowserWindow({ show: false, useContentSize: true, width: 798, height: 548,