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): support development JSX in renderer modules
vastsa23bc6e96f7e0
diff --git a/apps/desktop/src/plugins/renderer-host/import-map.ts b/apps/desktop/src/plugins/renderer-host/import-map.tsindex 87b6b3f1c..d69989256 100644--- a/apps/desktop/src/plugins/renderer-host/import-map.ts+++ b/apps/desktop/src/plugins/renderer-host/import-map.ts@@ -4,7 +4,8 @@* 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/jsx-runtime`, `react-dom` and `react-dom/client`, through a+ * specifiers `react`, `react/jsx-dev-runtime`, `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,6 +15,7 @@import * as ReactDom from "react-dom";import * as ReactDomClient from "react-dom/client";import * as React from "react";+import * as ReactJsxDevRuntime from "react/jsx-dev-runtime";import * as ReactJsxRuntime from "react/jsx-runtime";/** Where the generated shims read their modules from. Not a plugin API. */@@ -21,6 +23,7 @@ export const RENDERER_HOST_KEY = "__PI_RENDERER_HOST__";type RendererHostModules = {react: typeof React;+ reactJsxDevRuntime: typeof ReactJsxDevRuntime;reactJsxRuntime: typeof ReactJsxRuntime;reactDom: typeof ReactDom;reactDomClient: typeof ReactDomClient;@@ -28,11 +31,24 @@ type RendererHostModules = {export const REACT_IMPORT_MAP: Readonly<Record<string, keyof RendererHostModules>> = {react: "react",+ "react/jsx-dev-runtime": "reactJsxDevRuntime","react/jsx-runtime": "reactJsxRuntime","react-dom": "reactDom","react-dom/client": "reactDomClient",};+const ReactJsxDevRuntimeHost: typeof ReactJsxDevRuntime = {+ ...ReactJsxDevRuntime,+ // Production React omits jsxDEV; development-compiled plugins still need a+ // valid entry point when they run in a production host.+ jsxDEV: (...args) => {+ const [type, props, key] = args;+ return ReactJsxDevRuntime.jsxDEV+ ? ReactJsxDevRuntime.jsxDEV(...args)+ : ReactJsxRuntime.jsx(type, props, key);+ },+};+let installed = false;/**@@ -70,6 +86,7 @@ export function installRendererImportMap(): void {installed = true;const modules: RendererHostModules = {react: React,+ reactJsxDevRuntime: ReactJsxDevRuntimeHost,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 9590863c8..e1bddfd49 100644--- a/apps/desktop/test/plugin-renderer-import-map.test.mjs+++ b/apps/desktop/test/plugin-renderer-import-map.test.mjs@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";import { register } from "node:module";import test from "node:test";import * as React from "react";+import * as ReactJsxDevRuntime from "react/jsx-dev-runtime";import * as ReactJsxRuntime from "react/jsx-runtime";import { renderToStaticMarkup } from "react-dom/server";import * as ReactDom from "react-dom";@@ -60,16 +61,20 @@ test("React and automatic JSX resolve to the host's own modules", async (t) => {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/jsx-runtime", "react-dom", "react-dom/client"]);+ assert.deepEqual(Object.keys(imports), ["react", "react/jsx-dev-runtime", "react/jsx-runtime", "react-dom", "react-dom/client"]);- const expected = { react: React, "react/jsx-runtime": ReactJsxRuntime, "react-dom": ReactDom, "react-dom/client": ReactDomClient };+ const expected = { react: React, "react/jsx-dev-runtime": ReactJsxDevRuntime, "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// can name; everything else a plugin can import is the host's binding.const names = Object.keys(host).filter((name) => /^[A-Za-z_$][\w$]*$/.test(name));assert.ok(names.includes("default"), `${specifier} has a default export`);- for (const name of names) assert.equal(shim[name], host[name], `${specifier}.${name}`);+ for (const name of names) {+ if (specifier === "react/jsx-dev-runtime" && name === "jsxDEV") continue;+ assert.equal(shim[name], host[name], `${specifier}.${name}`);+ }+ if (specifier === "react/jsx-dev-runtime") assert.equal(typeof shim.jsxDEV, "function");}});@@ -94,13 +99,23 @@ test("automatic JSX plugin components render with the host hooks and context", ainstallRendererImportMap();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"]);+ assert.ok(imports["react/jsx-dev-runtime"], "development JSX entry must resolve before plugin activation");+ const runtimes = [+ { specifier: "react/jsx-runtime", runtime: await evaluate(blobs, imports["react/jsx-runtime"]), dev: false },+ { specifier: "react/jsx-dev-runtime", runtime: await evaluate(blobs, imports["react/jsx-dev-runtime"]), dev: true },+ ];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 source = { fileName: "plugin.tsx", lineNumber: 1, columnNumber: 1 };+ for (const { specifier, runtime, dev } of runtimes) {+ const render = (type, props) => dev+ ? runtime.jsxDEV(type, props, undefined, false, source)+ : runtime.jsx(type, props);+ function PluginChart() {+ const title = hostReact.useContext(Context);+ return render("figure", { children: title });+ }+ const tree = render(Context.Provider, { value: "Revenue chart", children: render(PluginChart, {}) });+ assert.equal(renderToStaticMarkup(tree), "<figure>Revenue chart</figure>", specifier);}- 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 670416952..208d33eda 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -884,8 +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/jsx-runtime`, `react-dom` and-`react-dom/client` resolve to the app's copies+`pi.ui.injectStyle`, and `react`, `react/jsx-dev-runtime`,+`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 579241201..f010adde2 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -17739,10 +17739,11 @@ host-created files. The full app's file-preview viewer is covered separately.### 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+ `react/jsx-runtime` or `react/jsx-dev-runtime`, with React externalized to the+ host.+- Steps: activate production and development entries through the host import+ map; render automatic JSX components that read a host context with a hook.+- Expected: both entries resolve and render the supplied context value withoutbundling 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 usingdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex b9d721877..42e4ab3ce 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -1395,7 +1395,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.+Renderer ES modules may import `react/jsx-runtime` or+`react/jsx-dev-runtime` for automatic JSX. The host import map exposes both of+its runtimes alongside `react`, `react-dom`, and `react-dom/client`, before+evaluating plugin entries. This keeps compiled JSX, hooks and context on the+host React instance in production and development builds.diff --git a/scripts/e2e-plugin-jsx-runtime.mjs b/scripts/e2e-plugin-jsx-runtime.mjsindex 3fbc79d11..6dee11d07 100644--- a/scripts/e2e-plugin-jsx-runtime.mjs+++ b/scripts/e2e-plugin-jsx-runtime.mjs@@ -23,21 +23,23 @@ try {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})));+ rootView.render(React.createElement(React.Fragment,null,+ React.createElement(Context.Provider,{value:'Production JSX'},React.createElement(plugin.Chart,{context:Context})),+ React.createElement(Context.Provider,{value:'Development JSX'},React.createElement(plugin.DevChart,{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();}}+ const timer=setTimeout(()=>{observer.disconnect();const figures=[...document.querySelectorAll('figure')].map(node=>node.textContent);reject(new Error('automatic JSX plugins did not render: '+JSON.stringify({figures,html:document.querySelector('#root')?.innerHTML})));},10000);+ function check(){const figures=[...document.querySelectorAll('figure')].map(node=>node.textContent);if(figures[0]==='Production JSX'&&figures[1]==='Development JSX'){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)};+ window.__jsxSmoke={ok:true,text:[...document.querySelectorAll('figure')].map(node=>node.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;+ const bytes = path === "/" ? page : path === "/host.mjs" ? await readFile(join(scratch, "host.mjs")) : path === "/plugin.mjs" ? 'import {jsx} from "react/jsx-runtime"; import {jsxDEV} from "react/jsx-dev-runtime"; import {useContext} from "react"; export function Chart({context}) {return jsx("figure", {children:useContext(context)});} export function DevChart({context}) {return jsxDEV("figure", {children:useContext(context)}, undefined, false, {fileName:"plugin.tsx",lineNumber:1,columnNumber:1});}' : 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(); }@@ -55,7 +57,7 @@ try {assert.equal(code, 0, output);const result = JSON.parse(output.split("\n").find(line => line.startsWith("JSX_SMOKE ")).slice("JSX_SMOKE ".length));assert.equal(result.ok, true);- console.log("PASS automatic JSX plugin activation with host hooks and context", JSON.stringify(result));+ console.log("PASS production and development 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 });