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): repair #321 crash, blob CSP, token outlet, load race
Tioit-Wang94282cd7a990
diff --git a/apps/desktop/index.html b/apps/desktop/index.htmlindex b5e890034..9267565ff 100644--- a/apps/desktop/index.html+++ b/apps/desktop/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8" /><metahttp-equiv="Content-Security-Policy"- content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset: plugin-renderer:; media-src 'self' data: blob: https:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:;"+ content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset: plugin-renderer:; media-src 'self' data: blob: https:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:;"/><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>PI-Desktop</title>diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex 71a41dc95..57c55c198 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -74,6 +74,7 @@ import {useComposerPluginTokens,useComposerTriggerAcceptBridge,} from "../features/chat/composer/use-plugin-composer-slots";+import { ComposerTokenChip } from "../features/chat/composer/ComposerTokenChip";import { SlotBoundary } from "../plugins/renderer-slots/use-slots";import { dispatchFor } from "../plugins/renderer-host/dispatch";@@ -566,10 +567,6 @@ export function Composer({);};- // Keep the transcript's bottom reserve in sync with the composer's real- // height (it grows with multi-line input) so the last message sits just- // above the box instead of far below it.- useEffect(() => {// The insert bridge: plugin slot components reach the draft through// `composer.insertText`; this composer instance owns the live route while// it is mounted and clears it on unmount (last-writer-wins is the docked@@ -588,6 +585,10 @@ export function Composer({return () => registerComposerInsert(null);}, [draft, fileReferencesRef]);+ // Keep the transcript's bottom reserve in sync with the composer's real+ // height (it grows with multi-line input) so the last message sits just+ // above the box instead of far below it.+ useEffect(() => {const el = dockRef.current;if (!el) return;// Setting a custom property on documentElement invalidates style for the@@ -680,21 +681,11 @@ export function Composer({{pluginTokens.tokens.slice(0, 8).map((token) => (- <span+ <ComposerTokenChipkey={`${token.pluginId}:${token.label}`}- className="pi-plugin-token-chip"- role="listitem"- >- #{token.label}- <button- type="button"- className="pi-plugin-token-chip-remove"- aria-label={`remove #${token.label}`}- onClick={() => pluginTokens.removeToken(token.label)}- >- ×- </button>- </span>+ token={token}+ onRemove={pluginTokens.removeToken}+ />))}{pluginTokens.foldedCount > 0 ? (<spandiff --git a/apps/desktop/src/features/chat/composer/ComposerTokenChip.tsx b/apps/desktop/src/features/chat/composer/ComposerTokenChip.tsxnew file mode 100644index 000000000..7b7ec597d--- /dev/null+++ b/apps/desktop/src/features/chat/composer/ComposerTokenChip.tsx@@ -0,0 +1,63 @@+/**+ * One draft token chip (`docs/plugin-plan/ui/composer/`).+ *+ * A plugin that registered `composerToken` for this label draws the token's+ * face through its own component; without a registration the host chip+ * renders. The ✕ removal stays host-owned either way so the fold records+ * (折叠不丢弃) can never strand a token inside the draft.+ */+import { createElement, type ComponentType } from "react";+import type { PluginComposerTokenProps } from "@pi-desktop/plugin-sdk";+import {+ SlotBoundary,+ useSlotEntryForKey,+} from "../../../plugins/renderer-slots/use-slots";+import { dispatchFor } from "../../../plugins/renderer-host/dispatch";+import type { ComposerPluginToken } from "./plugin-trigger";++export function ComposerTokenChip({+ token,+ onRemove,+}: {+ token: ComposerPluginToken;+ onRemove: (label: string) => void;+}) {+ const entry = useSlotEntryForKey("composerToken", token.label);+ const removeButton = (+ <button+ type="button"+ className="pi-plugin-token-chip-remove"+ aria-label={`remove #${token.label}`}+ onClick={() => onRemove(token.label)}+ >+ ×+ </button>+ );+ if (!entry) {+ return (+ <span className="pi-plugin-token-chip" role="listitem">+ #{token.label}+ {removeButton}+ </span>+ );+ }+ return (+ <span+ className="pi-plugin-token-chip"+ role="listitem"+ data-pi-plugin={entry.pluginId}+ >+ <SlotBoundary entry={entry} slot="composerToken">+ {createElement(+ entry.component as ComponentType<PluginComposerTokenProps>,+ {+ label: token.label,+ send: token.send,+ dispatch: dispatchFor(entry.pluginId),+ },+ )}+ </SlotBoundary>+ {removeButton}+ </span>+ );+}diff --git a/apps/desktop/src/plugins/renderer-host/loader.ts b/apps/desktop/src/plugins/renderer-host/loader.tsindex 336efe47e..2e2cbaab9 100644--- a/apps/desktop/src/plugins/renderer-host/loader.ts+++ b/apps/desktop/src/plugins/renderer-host/loader.ts@@ -144,6 +144,15 @@ export function loadRendererModule(`onLoad for ${pluginId} failed: ${error instanceof Error ? error.message : String(error)}`,);}+ // Unload raced the async load: the plugin was torn down while `onLoad`+ // was still running, so its late registrations, styles, and dispatch+ // binding must not survive. The load memo was already deleted by+ // `unloadRendererModule`, which is the lost-race signal here.+ if (!loaded.has(pluginId)) {+ slotRegistry.unregisterPlugin(pluginId);+ removePluginStyles(pluginId);+ unbindDispatch(pluginId);+ }return { pluginId, module: mod as PiRendererModule };})();loaded.set(pluginId, promise);diff --git a/apps/desktop/test/plugin-composer-slots.test.mjs b/apps/desktop/test/plugin-composer-slots.test.mjsindex d81cc6042..9cd9c5a20 100644--- a/apps/desktop/test/plugin-composer-slots.test.mjs+++ b/apps/desktop/test/plugin-composer-slots.test.mjs@@ -209,3 +209,29 @@ test("the trigger menu and token chips have host chrome styles", () => {assert.match(shell, /\.pi-plugin-token-chip-remove \{/);assert.match(shell, /\.pi-plugin-token-chip\.is-fold \{/);});++test("the composer mounts a composerToken outlet keyed by label", () => {+ // The composerToken slot had no host outlet: registrations were dead.+ // The chip renders the claiming plugin's component and falls back to the+ // host chip when no registration covers the label.+ const chip = readFileSync(src("features/chat/composer/ComposerTokenChip.tsx"), "utf8");+ assert.match(chip, /useSlotEntryForKey\("composerToken", token\.label\)/);+ assert.match(chip, /createElement\(/);+ const composer = readFileSync(src("components/Composer.tsx"), "utf8");+ assert.match(composer, /<ComposerTokenChip\b/);+});++test("the composer's plugin effects stay top-level and independent", () => {+ // Regression: an earlier edit nested the insert-bridge effect inside the+ // dock-height effect, so React committed the outer effect and called+ // useEffect from within its setup — crash-on-boot React error #321.+ const composer = readFileSync(src("components/Composer.tsx"), "utf8");+ const bridgeAt = composer.indexOf("registerComposerInsert((text)");+ const dockAt = composer.indexOf("const el = dockRef.current;");+ assert.ok(bridgeAt > -1 && dockAt > bridgeAt, "insert-bridge effect precedes the dock effect");+ const bridgeHead = composer.lastIndexOf("useEffect(() => {", bridgeAt);+ assert.ok(+ bridgeHead > -1 && !composer.slice(bridgeHead + 17, bridgeAt).includes("useEffect(() => {"),+ "insert-bridge effect opens with its own useEffect, not one inherited from another effect",+ );+});diff --git a/apps/desktop/test/plugin-renderer-loader.test.mjs b/apps/desktop/test/plugin-renderer-loader.test.mjsnew file mode 100644index 000000000..a5cf54d3d--- /dev/null+++ b/apps/desktop/test/plugin-renderer-loader.test.mjs@@ -0,0 +1,26 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import test from "node:test";++const here = dirname(fileURLToPath(import.meta.url));+const src = (relative) => join(here, "..", "src", relative);++test("unload races the async load and late registrations are dropped", () => {+ // Contract (卸载摘注册): when a plugin is disabled/uninstalled while its+ // renderer module is still loading, the load must not leave orphan+ // registrations, injected styles, or a dispatch binding behind.+ const loader = readFileSync(src("plugins/renderer-host/loader.ts"), "utf8");+ // The lost-race check happens after onLoad resolves: the memo deleted by+ // unloadRendererModule is the signal, and every teardown surface runs.+ const checkAt = loader.indexOf("if (!loaded.has(pluginId)) {");+ const onLoadAt = loader.indexOf("await mod.onLoad(");+ const returnAt = loader.indexOf("return { pluginId, module: mod as PiRendererModule };");+ assert.ok(onLoadAt > -1 && checkAt > onLoadAt, "the race check follows onLoad");+ assert.ok(returnAt > checkAt, "the race check precedes the successful return");+ const guarded = loader.slice(checkAt, returnAt);+ assert.match(guarded, /slotRegistry\.unregisterPlugin\(pluginId\)/);+ assert.match(guarded, /removePluginStyles\(pluginId\)/);+ assert.match(guarded, /unbindDispatch\(pluginId\)/);+});diff --git a/apps/desktop/test/plugin-ui-slots-demo.test.mjs b/apps/desktop/test/plugin-ui-slots-demo.test.mjsindex 4e1028f24..e4f08b9f7 100644--- a/apps/desktop/test/plugin-ui-slots-demo.test.mjs+++ b/apps/desktop/test/plugin-ui-slots-demo.test.mjs@@ -25,7 +25,6 @@ test("the demo manifest declares the full renderer action vocabulary", () => {[...manifest.rendererActions].sort(),["composer.acceptTriggerItem", "composer.insertText", "plugin.call"],);- assert.ok(manifest.rendererCallMethods.includes("stats.summary"));assert.ok(manifest.permissions.includes("renderer.extension"));assert.ok(manifest.permissions.includes("agent.tool.register"));// toolCard ownership premise: the claimed tool is declared here.@@ -38,6 +37,19 @@ test("the demo manifest declares the full renderer action vocabulary", () => {assert.ok(manifest.renderer.endsWith("renderer/index.mjs"));});+test("the demo renderer stays valid ESM with every registration", () => {+ execFileSync(process.execPath, ["--check", join(demoDir, "renderer/index.mjs")]);+ assert.match(rendererSource, /import \{ createElement as h, useState \} from "react"/);+});++test("the page CSP lets the import map's blob shims load", () => {+ // The React import map serves shims from blob: URLs; a built page whose+ // script-src lacks blob: blocks every plugin module at load (seen live as+ // PLUGIN_SLOT_LOAD_FAILED after a CSP security error).+ const html = readFileSync(root("apps/desktop/index.html"), "utf8");+ assert.match(html, /script-src[^;]*\bblob:/);+});+test("the headless entry answers the declared renderer method", async () => {const entry = createRequire(import.meta.url)(join(demoDir, "main.js"));assert.equal(typeof entry.onLoad, "function");