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(desktop): serialize panel lifecycle and force teardown on reload
Totopo275a1e63015839
diff --git a/apps/desktop/electron/main/plugin-panel-host.ts b/apps/desktop/electron/main/plugin-panel-host.tsindex 15244454f..f90ff1cb5 100644--- a/apps/desktop/electron/main/plugin-panel-host.ts+++ b/apps/desktop/electron/main/plugin-panel-host.ts@@ -6,6 +6,7 @@ import { isNetUrlAllowed, THEME_ASSET_SCHEME } from "@pi-desktop/plugin-sdk";import { builtinWindowBackground } from "@pi-desktop/shared";import { suppressLinuxFramelessSystemMenu } from "./frameless-system-menu";import { PanelSenders, pageGoneWithin, resolvePanelInvocation } from "./plugin-panel-senders";+import { PanelOperationSerializer } from "./plugin-panel-senders";import {isPluginPanelWindowControlAction,PLUGIN_PANEL_MIN_SIZE,@@ -183,6 +184,7 @@ export class PluginPanelHost {* context menu it did not ask for.*/private widgetLocales = new Map<number, string>();+ private serializer = new PanelOperationSerializer();/*** Identity of the panel pages allowed to use the bridge, keyed by web* contents. A page belongs to its plugin for as long as it exists, not only@@ -433,122 +435,123 @@ export class PluginPanelHost {}async open(request: PluginPanelOpenRequest): Promise<void> {- const existing = this.windows.get(request.pluginId);- if (existing && !existing.isDestroyed()) {- this.applyEgressPolicy(existing.webContents.session, request);- await ensureOsMicrophone(request.allowMicrophone);- // The microphone prompt is asynchronous: the panel can be closed while the- // user answers it, and a destroyed window has no `show`. Fall through and- // build the requested panel instead of reusing a window that is gone.- if (!existing.isDestroyed()) {- if (existing.isMinimized()) existing.restore();- existing.show();- existing.focus();- return;+ return this.serializer.run(request.pluginId, async () => {+ const existing = this.windows.get(request.pluginId);+ if (existing && !existing.isDestroyed()) {+ this.applyEgressPolicy(existing.webContents.session, request);+ await ensureOsMicrophone(request.allowMicrophone);+ // The microphone prompt is asynchronous: the panel can be closed while the+ // user answers it, and a destroyed window has no `show`. Fall through and+ // build the requested panel instead of reusing a window that is gone.+ if (!existing.isDestroyed()) {+ if (existing.isMinimized()) existing.restore();+ existing.show();+ existing.focus();+ return;+ }}- }- const partition = pluginSessionPartition(request.pluginId);- const ses = session.fromPartition(partition, { cache: true });- this.applyEgressPolicy(ses, request);- await ensureOsMicrophone(request.allowMicrophone);--- const widget = request.shape === "widget";- const minSize = widget ? PLUGIN_PANEL_WIDGET_MIN_SIZE : PLUGIN_PANEL_MIN_SIZE;- const win = new BrowserWindow({- width: Math.max(minSize.width, request.width || (widget ? 220 : 480)),- height: Math.max(minSize.height, request.height || (widget ? 220 : 360)),- title: request.title,- show: false,- autoHideMenuBar: true,- // The host theme is only a fallback; the preload samples the actual- // plugin page colors after it has loaded and paints the chrome from them.- backgroundColor: widget ? "#00000000" : builtinWindowBackground(request.theme),- // Every platform uses the same frameless surface. A panel's visible window- // controls are the preload's three-button capsule; a floating widget has- // no chrome of its own — the plugin draws its silhouette edge to edge.- frame: false,- transparent: widget,- // A transparent window would otherwise carry a rectangular native shadow- // around an orb that is round; a widget draws its own glow instead.- hasShadow: !widget,- resizable: request.resizable ?? !widget,- alwaysOnTop: widget && request.alwaysOnTop === true,- // A floating widget is a desktop companion, not a taskbar entry, and it- // has no capsule to restore from a maximized state.- skipTaskbar: widget,- maximizable: !widget,- ...(widget ? { fullscreenable: false } : {}),- webPreferences: {- session: ses,- preload: join(__dirname, "../preload/plugin-panel.js"),- contextIsolation: true,- nodeIntegration: false,- sandbox: true,- webviewTag: false,- additionalArguments: [- `${PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX}${encodeURIComponent(request.locale)}`,- `--pi-plugin-panel-theme=${request.theme}`,- ...(widget ? [PLUGIN_PANEL_WIDGET_ARGUMENT] : []),- ...(request.development- ? ["--pi-plugin-panel-development=1"]- : []),- ],- },- });- // A panel owns its visible surface; do not add a native application menu- // to the window around the plugin's own UI.- win.setMenu(null);- suppressLinuxFramelessSystemMenu(win);-- // A panel gets exactly one web contents. `window.open` would otherwise mint- // a chromeless window outside the egress policy applied above.- win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));-- const sendWindowState = () => {- if (win.isDestroyed() || win.webContents.isDestroyed()) return;- win.webContents.send(PLUGIN_PANEL_WINDOW_STATE_CHANNEL, {- maximized: win.isMaximized(),+ const partition = pluginSessionPartition(request.pluginId);+ const ses = session.fromPartition(partition, { cache: true });+ this.applyEgressPolicy(ses, request);+ await ensureOsMicrophone(request.allowMicrophone);++ const widget = request.shape === "widget";+ const minSize = widget ? PLUGIN_PANEL_WIDGET_MIN_SIZE : PLUGIN_PANEL_MIN_SIZE;+ const win = new BrowserWindow({+ width: Math.max(minSize.width, request.width || (widget ? 220 : 480)),+ height: Math.max(minSize.height, request.height || (widget ? 220 : 360)),+ title: request.title,+ show: false,+ autoHideMenuBar: true,+ // The host theme is only a fallback; the preload samples the actual+ // plugin page colors after it has loaded and paints the chrome from them.+ backgroundColor: widget ? "#00000000" : builtinWindowBackground(request.theme),+ // Every platform uses the same frameless surface. A panel's visible window+ // controls are the preload's three-button capsule; a floating widget has+ // no chrome of its own — the plugin draws its silhouette edge to edge.+ frame: false,+ transparent: widget,+ // A transparent window would otherwise carry a rectangular native shadow+ // around an orb that is round; a widget draws its own glow instead.+ hasShadow: !widget,+ resizable: request.resizable ?? !widget,+ alwaysOnTop: widget && request.alwaysOnTop === true,+ // A floating widget is a desktop companion, not a taskbar entry, and it+ // has no capsule to restore from a maximized state.+ skipTaskbar: widget,+ maximizable: !widget,+ ...(widget ? { fullscreenable: false } : {}),+ webPreferences: {+ session: ses,+ preload: join(__dirname, "../preload/plugin-panel.js"),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ webviewTag: false,+ additionalArguments: [+ `${PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX}${encodeURIComponent(request.locale)}`,+ `--pi-plugin-panel-theme=${request.theme}`,+ ...(widget ? [PLUGIN_PANEL_WIDGET_ARGUMENT] : []),+ ...(request.development+ ? ["--pi-plugin-panel-development=1"]+ : []),+ ],+ },+ });+ // A panel owns its visible surface; do not add a native application menu+ // to the window around the plugin's own UI.+ win.setMenu(null);+ suppressLinuxFramelessSystemMenu(win);++ // A panel gets exactly one web contents. `window.open` would otherwise mint+ // a chromeless window outside the egress policy applied above.+ win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));++ const sendWindowState = () => {+ if (win.isDestroyed() || win.webContents.isDestroyed()) return;+ win.webContents.send(PLUGIN_PANEL_WINDOW_STATE_CHANNEL, {+ maximized: win.isMaximized(),+ });+ };+ win.on("maximize", sendWindowState);+ win.on("unmaximize", sendWindowState);+ win.webContents.on("did-finish-load", sendWindowState);++ // `closed` fires after the native window is gone. Copy the contents id+ // while the window is still alive; reading `webContents` later throws+ // "Object has been destroyed" and surfaces an uncaught main-process dialog.+ const webContentsId = win.webContents.id;+ if (widget) this.widgetLocales.set(webContentsId, request.locale);+ win.on("closed", () => {+ this.pendingDrops.delete(webContentsId);+ this.widgetLocales.delete(webContentsId);+ this.senders.release(webContentsId);+ // Only when this window is still the registered one: a page that closes+ // slowly can already have been replaced by a newer panel window for the+ // plugin, and that newer entry has to survive the predecessor's teardown.+ if (this.windows.get(request.pluginId) === win) {+ this.windows.delete(request.pluginId);+ }});- };- win.on("maximize", sendWindowState);- win.on("unmaximize", sendWindowState);- win.webContents.on("did-finish-load", sendWindowState);-- // `closed` fires after the native window is gone. Copy the contents id- // while the window is still alive; reading `webContents` later throws- // "Object has been destroyed" and surfaces an uncaught main-process dialog.- const webContentsId = win.webContents.id;- if (widget) this.widgetLocales.set(webContentsId, request.locale);- win.on("closed", () => {- this.pendingDrops.delete(webContentsId);- this.widgetLocales.delete(webContentsId);- this.senders.release(webContentsId);- // Only when this window is still the registered one: a page that closes- // slowly can already have been replaced by a newer panel window for the- // plugin, and that newer entry has to survive the predecessor's teardown.- if (this.windows.get(request.pluginId) === win) {- this.windows.delete(request.pluginId);- }- });- this.windows.set(request.pluginId, win);- // The page can call the bridge from its first script, so its identity is- // registered before the document loads and released only when the page is- // gone (see the `closed` handler above).- this.senders.register(webContentsId, request.pluginId);- try {- await win.loadURL(pathToFileURL(request.htmlPath).toString());- if (!win.isDestroyed()) {- win.show();- }- } catch (error) {- if (!win.isDestroyed()) {- win.destroy();+ this.windows.set(request.pluginId, win);+ // The page can call the bridge from its first script, so its identity is+ // registered before the document loads and released only when the page is+ // gone (see the `closed` handler above).+ this.senders.register(webContentsId, request.pluginId);+ try {+ await win.loadURL(pathToFileURL(request.htmlPath).toString());+ if (!win.isDestroyed()) {+ win.show();+ }+ } catch (error) {+ if (!win.isDestroyed()) {+ win.destroy();+ }+ throw error;}- throw error;- }+ });}/**@@ -556,19 +559,26 @@ export class PluginPanelHost {* reasons: the page may still be finishing, and its bridge calls have to reach* a live plugin runtime while it does; and a page that refuses to close* (`beforeunload`) must settle the call at the budget instead of holding it- * forever. A refused close leaves the panel registered: it is still open.+ * forever. A refused close leaves the panel registered: it is still open,+ * unless `force` is specified (such as during reload or teardown), which forcibly+ * destroys the window if it refuses to close.*/- async close(pluginId: string): Promise<void> {- const win = this.windows.get(pluginId);- if (!win || win.isDestroyed()) {- this.windows.delete(pluginId);- return;- }- // Captured while the window is alive; the close destroys its web contents,- // and the `closed` handler above owns the removal from `windows`.- const page = win.webContents;- win.close();- await pageGoneWithin(page);+ async close(pluginId: string, options?: { force?: boolean }): Promise<void> {+ return this.serializer.run(pluginId, async () => {+ const win = this.windows.get(pluginId);+ if (!win || win.isDestroyed()) {+ this.windows.delete(pluginId);+ return;+ }+ // Captured while the window is alive; the close destroys its web contents,+ // and the `closed` handler above owns the removal from `windows`.+ const page = win.webContents;+ win.close();+ await pageGoneWithin(page);+ if (options?.force && !win.isDestroyed()) {+ win.destroy();+ }+ });}/**diff --git a/apps/desktop/electron/main/plugin-panel-senders.ts b/apps/desktop/electron/main/plugin-panel-senders.tsindex 42b2cb4c5..ed94f44f6 100644--- a/apps/desktop/electron/main/plugin-panel-senders.ts+++ b/apps/desktop/electron/main/plugin-panel-senders.ts@@ -87,3 +87,51 @@ export function pageGoneWithin(page.once("destroyed", finish);});}++export type TeardownableWindow = {+ close(): void;+ destroy(): void;+ isDestroyed(): boolean;+ webContents: ClosablePage;+};++/**+ * Close a panel window and wait for its webContents to be destroyed.+ * When `force` is true (such as during plugin reload or host shutdown),+ * if the page refuses the close (e.g. `beforeunload`) or fails to exit+ * within `budgetMs`, the window is forcibly destroyed to prevent stale+ * surfaces from surviving across reloads.+ */+export async function teardownPanelWindow(+ window: TeardownableWindow,+ options: { force?: boolean; budgetMs?: number } = {},+): Promise<void> {+ if (window.isDestroyed()) return;+ const page = window.webContents;+ window.close();+ await pageGoneWithin(page, options.budgetMs);+ if (options.force && !window.isDestroyed()) {+ window.destroy();+ }+}++/**+ * Serializes async operations per plugin ID to prevent lifecycle races+ * between teardown/close and subsequent openPanel requests.+ */+export class PanelOperationSerializer {+ private inFlight = new Map<string, Promise<unknown>>();++ run<T>(pluginId: string, operation: () => Promise<T>): Promise<T> {+ const prior = this.inFlight.get(pluginId) ?? Promise.resolve();+ const current = prior.catch(() => undefined).then(operation);+ this.inFlight.set(pluginId, current);+ const cleanup = () => {+ if (this.inFlight.get(pluginId) === current) {+ this.inFlight.delete(pluginId);+ }+ };+ current.then(cleanup, cleanup);+ return current;+ }+}diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 0379931c1..22d22a06a 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -414,7 +414,7 @@ export type PluginHostServices = {name: string;ok: boolean;message?: string;- }) => void;+ }) => Promise<void> | void;/** Work-panel guest + CDP, gated by `browser.cdp` in the runtime. */browser?: {navigate: (@@ -2038,7 +2038,7 @@ export class PluginRuntime {ok: true,ts: Date.now(),});- this.services.onPluginReloaded?.({ pluginId, name: manifest.name, ok: true });+ await this.services.onPluginReloaded?.({ pluginId, name: manifest.name, ok: true });} catch (error) {const message = (error as Error).message;this.services.audit?.({@@ -2048,7 +2048,7 @@ export class PluginRuntime {message,ts: Date.now(),});- this.services.onPluginReloaded?.({ pluginId, name, ok: false, message });+ await this.services.onPluginReloaded?.({ pluginId, name, ok: false, message });} finally {this.reloading.delete(pluginId);}diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 43a8ecf3d..57768d288 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -453,7 +453,7 @@ export function createPluginServices({},// Hot reload happens without anyone asking for it, so it has to report// itself: the plugins page reads status from the host, not from the edit.- onPluginReloaded: ({ pluginId, name, ok, message }) => {+ onPluginReloaded: async ({ pluginId, name, ok, message }) => {logger.app("plugin", ok ? "info" : "error", "development plugin reloaded", {pluginId,data: { ok, message },@@ -461,9 +461,9 @@ export function createPluginServices({sendToRenderer(IPC.event.toast, {message: ok ? `Reloaded ${name}` : `Reload failed: ${name} — ${message ?? ""}`,});- // Views were loaded from the previous revision of the plugin's files.+ // Views and panels were loaded from the previous revision of the plugin's files.pluginViews.closePlugin(pluginId);- void pluginPanels.close(pluginId);+ await pluginPanels.close(pluginId, { force: true });if (pluginId === BROWSER_PLUGIN_ID) browserHost.disposeGuest();sendToRenderer(IPC.event.pluginChanged,{ reason: "reload", pluginId });},diff --git a/apps/desktop/test/plugin-hot-reload.test.mjs b/apps/desktop/test/plugin-hot-reload.test.mjsindex 59a6a0613..44658bf9a 100644--- a/apps/desktop/test/plugin-hot-reload.test.mjs+++ b/apps/desktop/test/plugin-hot-reload.test.mjs@@ -135,7 +135,12 @@ test("watchers are released on teardown and reloads reach the renderer", () => {pluginServicesSrc.indexOf("onPluginReloaded:"),);assert.match(reported, /IPC\.event\.toast/);+ assert.match(reported, /await pluginPanels\.close\(pluginId,\s*\{\s*force:\s*true\s*\}\)/);assert.match(reported, /IPC\.event\.pluginChanged,\s*\{ reason: "reload", pluginId \}/);- assert.match(reported, /pluginPanels\.close\(pluginId\)/);+ assert.ok(+ reported.indexOf("pluginPanels.close(pluginId, { force: true })") <+ reported.indexOf('IPC.event.pluginChanged,{ reason: "reload", pluginId }'),+ "panel teardown must precede notifying renderer of reload",+ );assert.match(reported, /Reload failed/);});diff --git a/apps/desktop/test/plugin-panel-invoker.test.mjs b/apps/desktop/test/plugin-panel-invoker.test.mjsindex a65cdf5ab..dd04b453c 100644--- a/apps/desktop/test/plugin-panel-invoker.test.mjs+++ b/apps/desktop/test/plugin-panel-invoker.test.mjs@@ -5,8 +5,14 @@ import test from "node:test";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));-const { PanelSenders, PLUGIN_PAGE_CLOSE_SETTLE_MS, pageGoneWithin, resolvePanelInvocation } =- await import("../electron/main/plugin-panel-senders.ts");+const {+ PanelOperationSerializer,+ PanelSenders,+ PLUGIN_PAGE_CLOSE_SETTLE_MS,+ pageGoneWithin,+ resolvePanelInvocation,+ teardownPanelWindow,+} = await import("../electron/main/plugin-panel-senders.ts");const panelHostSource = await readFile(new URL("../electron/main/plugin-panel-host.ts", import.meta.url),@@ -203,3 +209,122 @@ test("the bridge settles a call from a page that is gone", () => {/if \(!window\) \{[\s\S]*?if \(event\.sender\.isDestroyed\(\)\) return;[\s\S]*?throw new Error\("invalid panel window control invoker"\)/,);});++test("PanelOperationSerializer serializes operations on the same plugin ID", async () => {+ const serializer = new PanelOperationSerializer();+ const events = [];+ let unblockFirst;+ const firstBlock = new Promise((resolve) => {+ unblockFirst = resolve;+ });++ const op1 = serializer.run("plugin.a", async () => {+ events.push("op1:start");+ await firstBlock;+ events.push("op1:end");+ return "result-1";+ });++ const op2 = serializer.run("plugin.a", async () => {+ events.push("op2:start");+ events.push("op2:end");+ return "result-2";+ });++ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(events, ["op1:start"], "op2 must not start while op1 is pending");++ unblockFirst();+ const [res1, res2] = await Promise.all([op1, op2]);+ assert.equal(res1, "result-1");+ assert.equal(res2, "result-2");+ assert.deepEqual(events, ["op1:start", "op1:end", "op2:start", "op2:end"]);+});++test("PanelOperationSerializer runs operations for different plugins concurrently", async () => {+ const serializer = new PanelOperationSerializer();+ const events = [];+ let unblockA;+ const blockA = new Promise((resolve) => {+ unblockA = resolve;+ });++ const opA = serializer.run("plugin.a", async () => {+ events.push("a:start");+ await blockA;+ events.push("a:end");+ });++ const opB = serializer.run("plugin.b", async () => {+ events.push("b:start");+ events.push("b:end");+ });++ await new Promise((resolve) => setImmediate(resolve));+ assert.ok(events.includes("b:start"), "opB must not be blocked by opA");+ assert.ok(events.includes("b:end"), "opB completes while opA is blocked");++ unblockA();+ await opA;+ await opB;+});++test("PanelOperationSerializer continues processing after an operation failure", async () => {+ const serializer = new PanelOperationSerializer();+ const failed = serializer.run("plugin.a", async () => {+ throw new Error("failure");+ });+ await assert.rejects(failed, /failure/);++ const next = await serializer.run("plugin.a", async () => "recovered");+ assert.equal(next, "recovered");+});++test("teardownPanelWindow forces destruction when a page refuses to close", async () => {+ const page = fakePage();+ let closed = false;+ let destroyed = false;+ const win = {+ close() {+ closed = true;+ },+ destroy() {+ destroyed = true;+ page.die();+ },+ isDestroyed() {+ return destroyed;+ },+ webContents: page,+ };++ // The page never dies on win.close(), simulating beforeunload refusing close.+ await teardownPanelWindow(win, { force: true, budgetMs: 20 });+ assert.equal(closed, true, "win.close() must be called first");+ assert.equal(destroyed, true, "win.destroy() must be called when force is true");+ assert.equal(win.isDestroyed(), true);+});++test("teardownPanelWindow leaves window registered when not forced and page refuses close", async () => {+ const page = fakePage();+ let closed = false;+ let destroyed = false;+ const win = {+ close() {+ closed = true;+ },+ destroy() {+ destroyed = true;+ page.die();+ },+ isDestroyed() {+ return destroyed;+ },+ webContents: page,+ };++ await teardownPanelWindow(win, { force: false, budgetMs: 20 });+ assert.equal(closed, true, "win.close() was called");+ assert.equal(destroyed, false, "win.destroy() was not called without force");+ assert.equal(win.isDestroyed(), false);+});