Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(plugins): resolve automatic JSX against the host runtime
Zengwenqie1283bbd648e
diff --git a/apps/desktop/src/plugins/renderer-host/import-map.ts b/apps/desktop/src/plugins/renderer-host/import-map.tsindex f304c362c..87b6b3f1c 100644--- a/apps/desktop/src/plugins/renderer-host/import-map.ts+++ b/apps/desktop/src/plugins/renderer-host/import-map.ts@@ -4,7 +4,7 @@* A plugin that brought its own React would break hooks and context in the* first component that mixed the two, and the failure looks like a plugin bug* rather than a duplicate module. The host therefore answers the bare- * specifiers `react`, `react-dom` and `react-dom/client` from here, through a+ * specifiers `react`, `react/jsx-runtime`, `react-dom` and `react-dom/client`, through a* document import map pointing at generated blob modules.** The shims are generated from the live namespaces rather than a hand-written@@ -14,18 +14,21 @@import * as ReactDom from "react-dom";import * as ReactDomClient from "react-dom/client";import * as React from "react";+import * as ReactJsxRuntime from "react/jsx-runtime";/** Where the generated shims read their modules from. Not a plugin API. */export const RENDERER_HOST_KEY = "__PI_RENDERER_HOST__";type RendererHostModules = {react: typeof React;+ reactJsxRuntime: typeof ReactJsxRuntime;reactDom: typeof ReactDom;reactDomClient: typeof ReactDomClient;};export const REACT_IMPORT_MAP: Readonly<Record<string, keyof RendererHostModules>> = {react: "react",+ "react/jsx-runtime": "reactJsxRuntime","react-dom": "reactDom","react-dom/client": "reactDomClient",};@@ -58,7 +61,7 @@ function blobModuleUrl(modules: RendererHostModules, key: keyof RendererHostModu}/**- * Publish the host's React and map the three bare specifiers onto it. Called+ * Publish the host's React and map the React bare specifiers onto it. Called* once, before the first plugin module is evaluated — a plugin imported first* would otherwise fail to resolve `react` at all.*/@@ -67,6 +70,7 @@ export function installRendererImportMap(): void {installed = true;const modules: RendererHostModules = {react: React,+ reactJsxRuntime: ReactJsxRuntime,reactDom: ReactDom,reactDomClient: ReactDomClient,};diff --git a/apps/desktop/test/plugin-renderer-import-map.test.mjs b/apps/desktop/test/plugin-renderer-import-map.test.mjsindex 4ad8e3c4e..9590863c8 100644--- a/apps/desktop/test/plugin-renderer-import-map.test.mjs+++ b/apps/desktop/test/plugin-renderer-import-map.test.mjs@@ -3,6 +3,8 @@ import { readFileSync } from "node:fs";import { register } from "node:module";import test from "node:test";import * as React from "react";+import * as ReactJsxRuntime from "react/jsx-runtime";+import { renderToStaticMarkup } from "react-dom/server";import * as ReactDom from "react-dom";import * as ReactDomClient from "react-dom/client";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));@@ -51,16 +53,16 @@ async function evaluate(blobs, url) {return import(`data:text/javascript,${encodeURIComponent(source)}`);}-test("react, react-dom and react-dom/client resolve to the host's own modules", async (t) => {+test("React and automatic JSX resolve to the host's own modules", async (t) => {const { scripts, blobs } = fakeDocument(t);installRendererImportMap();assert.equal(scripts.length, 1);assert.equal(scripts[0].type, "importmap");const { imports } = JSON.parse(scripts[0].textContent);- assert.deepEqual(Object.keys(imports), ["react", "react-dom", "react-dom/client"]);+ assert.deepEqual(Object.keys(imports), ["react", "react/jsx-runtime", "react-dom", "react-dom/client"]);- const expected = { react: React, "react-dom": ReactDom, "react-dom/client": ReactDomClient };+ const expected = { react: React, "react/jsx-runtime": ReactJsxRuntime, "react-dom": ReactDom, "react-dom/client": ReactDomClient };for (const [specifier, host] of Object.entries(expected)) {const shim = await evaluate(blobs, imports[specifier]);// Node's CommonJS interop adds a `module.exports` key, which no import@@ -86,3 +88,19 @@ test("the page lets the shims and plugin modules load", () => {assert.match(scriptSrc, /\bblob:/);assert.match(scriptSrc, /\bplugin-renderer:/);});++test("automatic JSX plugin components render with the host hooks and context", async (t) => {+ const { scripts, blobs } = fakeDocument(t);+ installRendererImportMap();+ const { imports } = JSON.parse(scripts[0].textContent);+ assert.ok(imports["react/jsx-runtime"], "automatic JSX entry must resolve before plugin activation");+ const runtime = await evaluate(blobs, imports["react/jsx-runtime"]);+ const hostReact = await evaluate(blobs, imports.react);+ const Context = hostReact.createContext("missing");+ function PluginChart() {+ const title = hostReact.useContext(Context);+ return runtime.jsx("figure", { children: title });+ }+ const html = renderToStaticMarkup(runtime.jsx(Context.Provider, { value: "Revenue chart", children: runtime.jsx(PluginChart, {}) }));+ assert.equal(html, "<figure>Revenue chart</figure>");+});diff --git a/docs/plugin-development.md b/docs/plugin-development.mdindex 14df50162..670416952 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -884,7 +884,8 @@ export function onLoad(pi) {A dialog you draw yourself is not a slot: `pi.ui.openLayer()` hands you a layerto render into, and the component draws inside it. Styles go through-`pi.ui.injectStyle`, and `react` / `react-dom` resolve to the app's copies+`pi.ui.injectStyle`, and `react`, `react/jsx-runtime`, `react-dom` and+`react-dom/client` resolve to the app's copiesthrough the window's import map, so no bundled React is needed.`rendererActions` whitelists what a component may dispatch — `plugin.call`,diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex b540c3b40..65935c743 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -17688,3 +17688,16 @@ host-created files. The full app's file-preview viewer is covered separately.- **Steps:** Save a 500K user context limit for a model whose catalog publishes 1M. Open the Composer model list, then send a short message and inspect context usage. Repeat with a catalog-owned limit and with discovery unavailable.- **Expected:** The user-configured row and context inspector show 500K; a catalog-owned row follows the published limit; a configured model without discovery retains its saved context label. Model selection remains unchanged.- **Status:** Automated unit regression in `apps/desktop/test/composer-models.test.mjs` covers user overrides, catalog inheritance, and missing discovery; the full save → picker → message → context-inspector path remains a manual validation scenario.++### E2E-PLUGIN-automatic-jsx-activation++- Preconditions: a granted renderer plugin whose compiled entry imports+ `react/jsx-runtime`, with React externalized to the host.+- Steps: activate the entry through the host import map; render an automatic+ JSX component that reads a host context with a hook.+- Expected: the entry resolves and renders the supplied context value without+ bundling a second React instance. Legacy React bindings remain unchanged.+- Automated regression: `apps/desktop/test/plugin-renderer-import-map.test.mjs`+ evaluates the generated shims and renders an automatic JSX component using+ the host hooks and context. Isolated Electron coverage uses+ `scripts/e2e-plugin-jsx-runtime.mjs`; no user profile or provider is used.diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 12a3dff4d..b9d721877 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -1394,3 +1394,8 @@ one at runtime.All high-risk entry points assert declared+granted permissions and emit audit log lines.Plugin panels no longer receive the full `pi` object; they use `window.pluginBridge.invoke`.++Renderer ES modules may import `react/jsx-runtime` for automatic JSX. The host+import map exposes its own runtime alongside `react`, `react-dom`, and+`react-dom/client`, before evaluating plugin entries. This keeps compiled JSX,+hooks and context on the host React instance.diff --git a/scripts/e2e-plugin-jsx-runtime.mjs b/scripts/e2e-plugin-jsx-runtime.mjsnew file mode 100644index 000000000..26f3684b7--- /dev/null+++ b/scripts/e2e-plugin-jsx-runtime.mjs@@ -0,0 +1,62 @@+#!/usr/bin/env node+/** Activate automatic JSX through the real host import map in isolated Electron. */+import assert from "node:assert/strict";+import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises";+import { createServer } from "node:http";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { join, resolve, dirname } from "node:path";+import { fileURLToPath } from "node:url";+import { spawn } from "node:child_process";+import { build } from "esbuild";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const scratch = await mkdtemp(join(tmpdir(), "pi-plugin-jsx-"));+const require = createRequire(join(root, "package.json"));+let server;+try {+ await build({ stdin: { contents: 'export {installRendererImportMap, REACT_IMPORT_MAP} from "./apps/desktop/src/plugins/renderer-host/import-map.ts"; export * as React from "react"; export {createRoot} from "react-dom/client";', resolveDir: root, loader: "ts" }, outfile: join(scratch, "host.mjs"), bundle: true, format: "esm", platform: "browser", define: { "process.env.NODE_ENV": '"production"' } });+ const page = `<!doctype html><html><head><meta charset="utf-8"></head><body><div id="root"></div><script type="module">+import {installRendererImportMap, REACT_IMPORT_MAP, React, createRoot} from '/host.mjs';+try {+ installRendererImportMap();+ const plugin = await import('/plugin.mjs');+ const Context = React.createContext('missing');+ const rootView = createRoot(document.querySelector('#root'));+ rootView.render(React.createElement(Context.Provider,{value:'Revenue chart'},React.createElement(plugin.Chart,{context:Context})));+ await new Promise((resolve,reject)=>{+ const observer=new MutationObserver(check);+ const timer=setTimeout(()=>{observer.disconnect();reject(new Error('automatic JSX plugin did not render'));},10000);+ function check(){if(document.querySelector('figure')?.textContent==='Revenue chart'){clearTimeout(timer);observer.disconnect();resolve();}}+ observer.observe(document.body,{childList:true,subtree:true});check();+ });+ window.__jsxSmoke={ok:true,text:document.querySelector('figure').textContent,imports:Object.keys(REACT_IMPORT_MAP)};+ rootView.unmount();+}catch(error){window.__jsxSmoke={ok:false,error:error.stack};}+</script></body></html>`;+ server = createServer(async (req, res) => {+ const path = new URL(req.url, "http://localhost").pathname;+ try {+ const bytes = path === "/" ? page : path === "/host.mjs" ? await readFile(join(scratch, "host.mjs")) : path === "/plugin.mjs" ? 'import {jsx} from "react/jsx-runtime"; import {useContext} from "react"; export function Chart({context}) {return jsx("figure", {children:useContext(context)});}' : null;+ if (bytes === null) { res.writeHead(404); res.end(); return; }+ res.setHeader("content-type", path === "/" ? "text/html" : "text/javascript"); res.end(bytes);+ } catch { res.writeHead(404); res.end(); }+ });+ await new Promise(done => server.listen(0, "127.0.0.1", done));+ await writeFile(join(scratch, "main.cjs"), `const {app,BrowserWindow}=require('electron');app.setPath('userData',${JSON.stringify(join(scratch, "profile"))});app.whenReady().then(async()=>{try{const win=new BrowserWindow({show:false,webPreferences:{sandbox:true}});await win.loadURL(${JSON.stringify(`http://127.0.0.1:${server.address().port}/`)});const result=await win.webContents.executeJavaScript('new Promise(resolve=>{function check(){if(window.__jsxSmoke)resolve(window.__jsxSmoke);else requestAnimationFrame(check);}check();})');console.log('JSX_SMOKE '+JSON.stringify(result));app.exit(result.ok?0:1);}catch(error){console.error(error);app.exit(1);}});`);+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(require("electron"), [join(scratch, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ child.stdout.on("data", chunk => { output += chunk; });+ child.stderr.on("data", chunk => { output += chunk; });+ const timer = setTimeout(() => child.kill(), 30000);+ const code = await new Promise((done, reject) => { child.on("error", reject); child.on("exit", done); });+ clearTimeout(timer);+ assert.equal(code, 0, output);+ const result = JSON.parse(output.split("\n").find(line => line.startsWith("JSX_SMOKE ")).slice(12));+ assert.equal(result.ok, true);+ console.log("PASS automatic JSX plugin activation with host hooks and context", JSON.stringify(result));+} finally {+ if (server) await new Promise(done => server.close(done));+ await rm(scratch, { recursive: true, force: true });+}