Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(plugin-panel): keep bridge calls attributed while a surface closes

vastsa5ef08cee1043
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.ts
index c636ff477..d0eab3a17 100644
--- a/apps/desktop/electron/main/bootstrap/shutdown.ts
+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts
@@ -147,11 +147,22 @@ export function registerShutdownHandlers({
persistenceOutbox,
logger,
});
+ // Panel windows and docked views are the only pages that call the plugin
+ // runtime over the panel bridge. They are torn down, and their pages are
+ // waited for, before the runtime and the host stop: a call such a page
+ // already sent while its surface was closing is otherwise answered by a
+ // runtime that is already shutting down, and surfaces as a bridge failure
+ // nobody can act on. The wait is bounded inside the hosts, so a page that
+ // refuses to close cannot hold up the quit.
+ const pluginSurfacesShutdown = Promise.allSettled([
+ pluginPanels.closeAll(),
+ pluginViews.dispose(),
+ ]);
+ logger.app("lifecycle", "info", "app shutdown");
+ await pluginSurfacesShutdown;
const hostShutdown = getHost()?.dispose();
const mcpShutdown = getMcpControl()?.stop();
- const pluginPanelShutdown = pluginPanels.closeAll();
updater.dispose();
- logger.app("lifecycle", "info", "app shutdown");
// Plugin hosts are stopped as a shutdown, not left for the process teardown
// to kill: an unannounced exit is indistinguishable from a crash, and would
// end every quit in error logs, toasts, and restarts into a closing app.
@@ -159,7 +170,6 @@ export function registerShutdownHandlers({
userMcp.disposeAll();
mcpOAuth?.disposeAll();
browserPane.dispose();
- pluginViews.dispose();
inflightCheckpointer.dispose();
const sidecarShutdown = getSidecar()?.dispose();
@@ -169,7 +179,6 @@ export function registerShutdownHandlers({
logger.app("lifecycle", "warn", "host shutdown failed", { data: String(error) });
}
await Promise.allSettled([
- pluginPanelShutdown,
pluginShutdown,
sidecarShutdown,
mcpShutdown,
diff --git a/apps/desktop/electron/main/plugin-panel-host.ts b/apps/desktop/electron/main/plugin-panel-host.ts
index 84a65850f..08c7ed7db 100644
--- a/apps/desktop/electron/main/plugin-panel-host.ts
+++ b/apps/desktop/electron/main/plugin-panel-host.ts
@@ -5,6 +5,7 @@ import { catalogs, resolveLocale } from "@pi-desktop/i18n";
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 {
isPluginPanelWindowControlAction,
PLUGIN_PANEL_MIN_SIZE,
@@ -182,6 +183,13 @@ export class PluginPanelHost {
* context menu it did not ask for.
*/
private widgetLocales = new Map<number, string>();
+ /**
+ * 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
+ * while `windows` still lists its surface as open, so a call that arrives
+ * while the host is closing that surface is still the panel's own call.
+ */
+ private senders = new PanelSenders();
constructor(
bridge: BridgeHandler,
@@ -206,8 +214,16 @@ export class PluginPanelHost {
ipcMain.handle(
"pi-plugin-panel-invoke",
async (event, rawChannel: unknown, rawPayload: unknown) => {
- const pluginId = this.pluginIdForSender(event.sender.id);
- if (!pluginId) throw new Error("invalid panel invoker");
+ const invocation = resolvePanelInvocation(
+ this.pluginIdForSender(event.sender.id),
+ event.sender.isDestroyed(),
+ );
+ if (invocation.kind === "foreign") throw new Error("invalid panel invoker");
+ // A page that is already gone can never read the answer: the call is the
+ // tail of the teardown that closed its surface. Settle it rather than
+ // dispatching into a plugin runtime that may already be stopping.
+ if (invocation.kind === "gone") return;
+ const pluginId = invocation.pluginId;
const channel = String(rawChannel ?? "");
const payload =
rawPayload && typeof rawPayload === "object"
@@ -262,7 +278,13 @@ export class PluginPanelHost {
PLUGIN_PANEL_WINDOW_CONTROL_CHANNEL,
async (event, rawAction: unknown) => {
const window = this.windowForSender(event.sender.id);
- if (!window) throw new Error("invalid panel window control invoker");
+ if (!window) {
+ // The capsule asks for `getState` on install and for `close` while the
+ // surface tears down; a page that is already gone cannot read either
+ // answer, so it is settled rather than reported as an invalid invoker.
+ if (event.sender.isDestroyed()) return;
+ throw new Error("invalid panel window control invoker");
+ }
if (!isPluginPanelWindowControlAction(rawAction)) {
throw new Error("unsupported panel window control action");
}
@@ -274,10 +296,14 @@ export class PluginPanelHost {
);
}
+ /**
+ * The plugin a bridge call belongs to. Panel identity comes from `senders`,
+ * which outlives the host's record of open windows; the resolvers cover the
+ * docked work-panel views owned by `PluginViewHost`.
+ */
private pluginIdForSender(senderId: number): string | null {
- for (const [pluginId, win] of this.windows) {
- if (!win.isDestroyed() && win.webContents.id === senderId) return pluginId;
- }
+ const own = this.senders.pluginFor(senderId);
+ if (own) return own;
for (const resolve of this.senderResolvers) {
const pluginId = resolve(senderId);
if (pluginId) return pluginId;
@@ -411,10 +437,15 @@ export class PluginPanelHost {
if (existing && !existing.isDestroyed()) {
this.applyEgressPolicy(existing.webContents.session, request);
await ensureOsMicrophone(request.allowMicrophone);
- if (existing.isMinimized()) existing.restore();
- existing.show();
- existing.focus();
- return;
+ // 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);
@@ -493,28 +524,55 @@ export class PluginPanelHost {
win.on("closed", () => {
this.pendingDrops.delete(webContentsId);
this.widgetLocales.delete(webContentsId);
- this.windows.delete(request.pluginId);
+ 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);
await win.loadURL(pathToFileURL(request.htmlPath).toString());
win.show();
}
+ /**
+ * Close the plugin's panel and resolve once its page is gone. Bounded, for two
+ * 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.
+ */
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();
- this.windows.delete(pluginId);
+ await pageGoneWithin(page);
}
+ /**
+ * Close every panel and wait for every one of those pages to be gone, so a
+ * caller can stop the plugin runtime and the host afterwards. Shutdown relies
+ * on that order: a call a closing page already sent is otherwise answered by a
+ * runtime that is already shutting down, and is reported as a bridge failure
+ * nobody can act on.
+ */
async closeAll(): Promise<void> {
- for (const pluginId of [...this.windows.keys()]) {
- await this.close(pluginId);
- }
+ await Promise.allSettled(
+ [...this.windows.keys()].map((pluginId) => this.close(pluginId)),
+ );
}
/**
diff --git a/apps/desktop/electron/main/plugin-panel-senders.ts b/apps/desktop/electron/main/plugin-panel-senders.ts
new file mode 100644
index 000000000..42b2cb4c5
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-panel-senders.ts
@@ -0,0 +1,89 @@
+/**
+ * Who may use the panel bridge, and what happens to a call that arrives while
+ * its page is going away.
+ *
+ * A panel surface (detached window, floating widget, docked work-panel view) is
+ * registered before its page loads and torn down after the page is gone, but the
+ * page can still call the bridge in between: a timer that fired as the host
+ * started closing it, or an unload handler. Identity therefore belongs to the
+ * page — the web contents — and not to the host's record of which surfaces are
+ * currently open, which is already being emptied by the time those calls arrive.
+ */
+
+export type PanelInvocation =
+ | { readonly kind: "bridge"; readonly pluginId: string }
+ | { readonly kind: "gone" }
+ | { readonly kind: "foreign" };
+
+const GONE: PanelInvocation = { kind: "gone" };
+
+/**
+ * What a panel bridge call from an already resolved sender has to do.
+ *
+ * `senderGone` means the page that sent the call no longer exists. Its answer
+ * can never be read, and the work it asks for would run against a plugin runtime
+ * or host that the same teardown is stopping, so the call is settled instead of
+ * failing: a rejection here is logged in the main process with no way to tell it
+ * apart from a panel reaching outside its own plugin.
+ */
+export function resolvePanelInvocation(
+ pluginId: string | null,
+ senderGone: boolean,
+): PanelInvocation {
+ if (senderGone) return GONE;
+ return pluginId ? { kind: "bridge", pluginId } : { kind: "foreign" };
+}
+
+/**
+ * Identity of the pages allowed to use the panel bridge, keyed by web contents
+ * id. Registration happens before the page can load, and release when that page
+ * is gone — never when its surface is merely asked to close.
+ */
+export class PanelSenders {
+ private pluginIds = new Map<number, string>();
+
+ register(senderId: number, pluginId: string): void {
+ this.pluginIds.set(senderId, pluginId);
+ }
+
+ release(senderId: number): void {
+ this.pluginIds.delete(senderId);
+ }
+
+ pluginFor(senderId: number): string | null {
+ return this.pluginIds.get(senderId) ?? null;
+ }
+}
+
+/**
+ * How long a page is given to disappear before a shutdown moves on without it.
+ * A page that refuses to close (`beforeunload`) must not hold up the quit.
+ */
+export const PLUGIN_PAGE_CLOSE_SETTLE_MS = 1_000;
+
+type ClosablePage = {
+ isDestroyed(): boolean;
+ once(event: "destroyed", listener: () => void): unknown;
+ removeListener(event: "destroyed", listener: () => void): unknown;
+};
+
+/**
+ * Resolve once a page is destroyed, or once it has had `budgetMs` to go. Used by
+ * shutdown to keep the plugin runtime and the host alive until the pages that
+ * call them are gone.
+ */
+export function pageGoneWithin(
+ page: ClosablePage,
+ budgetMs: number = PLUGIN_PAGE_CLOSE_SETTLE_MS,
+): Promise<void> {
+ if (page.isDestroyed()) return Promise.resolve();
+ return new Promise((resolve) => {
+ const timer = setTimeout(finish, budgetMs);
+ function finish(): void {
+ clearTimeout(timer);
+ page.removeListener("destroyed", finish);
+ resolve();
+ }
+ page.once("destroyed", finish);
+ });
+}
diff --git a/apps/desktop/electron/main/plugin-view-host.ts b/apps/desktop/electron/main/plugin-view-host.ts
index 394ef9726..94082b5e3 100644
--- a/apps/desktop/electron/main/plugin-view-host.ts
+++ b/apps/desktop/electron/main/plugin-view-host.ts
@@ -1,6 +1,7 @@
import { session, shell, WebContentsView, type BrowserWindow } from "electron";
import { join } from "node:path";
import { parseAllowedExternalUrl } from "./safe-open-external";
+import { PanelSenders, pageGoneWithin } from "./plugin-panel-senders";
import {
PLUGIN_VIEW_LOCATION_EVENT,
PLUGIN_VIEW_LOCATION_PARAM,
@@ -106,6 +107,13 @@ export class PluginViewHost {
private bounds: PluginViewBounds = { x: 0, y: 0, width: 0, height: 0 };
private clock = 0;
private onBlockedRequest?: PluginPanelBlockedRequest;
+ /**
+ * Identity of the pages allowed to use the bridge, keyed by web contents. A
+ * view keeps its plugin for as long as its page exists, not only while it is
+ * cached in `views`, so a call that arrives while the view is being dropped
+ * still belongs to its own plugin.
+ */
+ private senders = new PanelSenders();
constructor(onBlockedRequest?: PluginPanelBlockedRequest) {
this.onBlockedRequest = onBlockedRequest;
@@ -158,11 +166,7 @@ export class PluginViewHost {
* calls from docked views on the same channel it serves panel windows.
*/
pluginIdForSender(senderId: number): string | null {
- for (const entry of this.views.values()) {
- const wc = entry.view.webContents;
- if (!wc.isDestroyed() && wc.id === senderId) return entry.pluginId;
- }
- return null;
+ return this.senders.pluginFor(senderId);
}
/**
@@ -195,6 +199,12 @@ export class PluginViewHost {
loaded: false,
};
this.views.set(key, entry);
+ // A docked view 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 — never when the host merely drops the cached surface around it.
+ const senderId = view.webContents.id;
+ this.senders.register(senderId, request.pluginId);
+ view.webContents.once("destroyed", () => this.senders.release(senderId));
view.webContents.once("did-finish-load", () => {
entry.loaded = true;
});
@@ -286,8 +296,20 @@ export class PluginViewHost {
}
}
- dispose(): void {
- for (const key of [...this.views.keys()]) this.destroy(key);
+ /**
+ * Drop every view and wait, bounded, for the pages to be gone, so a caller
+ * that is about to stop the plugin runtime knows no view page can still call
+ * it. Shutdown sequences this before that stop.
+ */
+ async dispose(): Promise<void> {
+ await Promise.allSettled(
+ [...this.views.values()].map(async (entry) => {
+ // Captured while the view is alive; `destroy` closes the page below.
+ const page = entry.view.webContents;
+ this.destroy(entry.key);
+ await pageGoneWithin(page);
+ }),
+ );
}
private destroy(key: string): void {
diff --git a/apps/desktop/test/plugin-panel-invoker.test.mjs b/apps/desktop/test/plugin-panel-invoker.test.mjs
new file mode 100644
index 000000000..a65cdf5ab
--- /dev/null
+++ b/apps/desktop/test/plugin-panel-invoker.test.mjs
@@ -0,0 +1,205 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { register } from "node:module";
+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 panelHostSource = await readFile(
+ new URL("../electron/main/plugin-panel-host.ts", import.meta.url),
+ "utf8",
+);
+const viewHostSource = await readFile(
+ new URL("../electron/main/plugin-view-host.ts", import.meta.url),
+ "utf8",
+);
+
+/** A page double for `pageGoneWithin`: it only ends when the test says so. */
+function fakePage() {
+ const listeners = new Set();
+ return {
+ destroyed: false,
+ listeners,
+ isDestroyed() {
+ return this.destroyed;
+ },
+ once(event, listener) {
+ assert.equal(event, "destroyed");
+ listeners.add(listener);
+ return this;
+ },
+ removeListener(_event, listener) {
+ listeners.delete(listener);
+ return this;
+ },
+ die() {
+ this.destroyed = true;
+ for (const listener of [...listeners]) listener();
+ },
+ };
+}
+
+test("a panel keeps its plugin while its page is still there", () => {
+ const senders = new PanelSenders();
+ senders.register(41, "pi.todo");
+
+ // Closing the surface is the host's decision; a page that is still unloading
+ // keeps calling the bridge as its own plugin.
+ assert.equal(senders.pluginFor(41), "pi.todo");
+ assert.deepEqual(resolvePanelInvocation(senders.pluginFor(41), false), {
+ kind: "bridge",
+ pluginId: "pi.todo",
+ });
+
+ senders.release(41);
+ assert.equal(senders.pluginFor(41), null);
+});
+
+test("a call from a page that is already gone is settled, never reported", () => {
+ // Regression: the reported "invalid panel invoker" came from a panel page
+ // that called the bridge while the host was closing its surface, so its sender
+ // no longer matched any open window. A page that is gone can never read the
+ // answer, and the failure was logged in main as if a panel were reaching
+ // outside its own plugin.
+ assert.deepEqual(resolvePanelInvocation("pi.todo", true), { kind: "gone" });
+ assert.deepEqual(resolvePanelInvocation(null, true), { kind: "gone" });
+
+ // A live sender from outside the panel hosts is still a foreign invoker.
+ assert.deepEqual(resolvePanelInvocation(null, false), { kind: "foreign" });
+});
+
+test("releasing the page of a closed surface leaves late calls foreign", () => {
+ const senders = new PanelSenders();
+ senders.register(7, "pi.token-insights");
+ assert.equal(senders.pluginFor(7), "pi.token-insights");
+ // Release happens on the page's own end, which the hosts wire to the window's
+ // `closed` handler and to the view's web contents `destroyed` event.
+ senders.release(7);
+ assert.deepEqual(resolvePanelInvocation(senders.pluginFor(7), false), {
+ kind: "foreign",
+ });
+});
+
+test(
+ "shutdown waits for a page to go, then releases the listener",
+ { timeout: 5_000 },
+ async () => {
+ const page = fakePage();
+ let settled = false;
+ const pending = pageGoneWithin(page, 50).then(() => {
+ settled = true;
+ });
+
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(settled, false, "a live page must not settle the wait early");
+
+ page.die();
+ await pending;
+ assert.equal(page.listeners.size, 0, "the destroyed listener is released");
+ },
+);
+
+test(
+ "a page that refuses to close cannot hold up a shutdown",
+ { timeout: 5_000 },
+ async () => {
+ const page = fakePage();
+ // The page never goes away, so only the budget can end the wait: if the
+ // implementation waited for the event, this test would hit its own timeout.
+ let settled = false;
+ const pending = pageGoneWithin(page, 20).then(() => {
+ settled = true;
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(settled, false, "the wait is not over while the page lives");
+ await pending;
+ assert.equal(page.destroyed, false);
+ assert.ok(PLUGIN_PAGE_CLOSE_SETTLE_MS > 0);
+ },
+);
+
+test(
+ "an already destroyed page does not subscribe at all",
+ { timeout: 5_000 },
+ async () => {
+ const page = fakePage();
+ page.destroyed = true;
+ await pageGoneWithin(page);
+ assert.equal(page.listeners.size, 0);
+ },
+);
+
+test("panel windows and docked views bind bridge identity to the page", () => {
+ assert.match(
+ panelHostSource,
+ /import \{ PanelSenders, pageGoneWithin, resolvePanelInvocation \} from "\.\/plugin-panel-senders"/,
+ );
+ assert.match(panelHostSource, /private senders = new PanelSenders\(\)/);
+ // Registered before the document loads, released with the page — not with the
+ // host's record of which surfaces are open.
+ assert.match(panelHostSource, /this\.senders\.register\(webContentsId, request\.pluginId\)/);
+ assert.match(panelHostSource, /this\.senders\.release\(webContentsId\)/);
+ assert.match(panelHostSource, /const own = this\.senders\.pluginFor\(senderId\)/);
+
+ // A window that closes slowly must not remove the entry of a newer window for
+ // the same plugin, and reusing a panel re-checks it after the microphone prompt
+ // awaits: a destroyed window has no `show`.
+ assert.match(panelHostSource, /if \(this\.windows\.get\(request\.pluginId\) === win\) \{/);
+ const reuse = panelHostSource.slice(
+ panelHostSource.indexOf("async open(request: PluginPanelOpenRequest)"),
+ panelHostSource.indexOf("const partition = pluginSessionPartition("),
+ );
+ assert.match(
+ reuse,
+ /await ensureOsMicrophone\(request\.allowMicrophone\);[\s\S]*if \(!existing\.isDestroyed\(\)\) \{/,
+ );
+
+ // `close` must not unregister a page it is closing: the calls that page has
+ // already sent still have to resolve to its own plugin.
+ const close = panelHostSource.slice(
+ panelHostSource.indexOf("async close(pluginId"),
+ panelHostSource.indexOf("async closeAll("),
+ );
+ assert.ok(close.length > 0);
+ // The close waits for that page, so its bridge calls reach a live runtime.
+ assert.match(close, /await pageGoneWithin\(page\)/);
+ // Nothing is unregistered after `win.close()`: the `closed` handler owns the
+ // removal, so a page that refuses the close stays an open panel.
+ assert.doesNotMatch(close.slice(close.indexOf("win.close();")), /windows\.delete/);
+ // `closeAll` is the shutdown path: every panel's page is waited for.
+ const closeAll = panelHostSource.slice(panelHostSource.indexOf("async closeAll("));
+ assert.match(closeAll, /this\.close\(pluginId\)/);
+
+ assert.match(
+ viewHostSource,
+ /import \{ PanelSenders, pageGoneWithin \} from "\.\/plugin-panel-senders"/,
+ );
+ assert.match(viewHostSource, /this\.senders\.register\(senderId, request\.pluginId\)/);
+ assert.match(viewHostSource, /this\.senders\.release\(senderId\)/);
+ assert.match(viewHostSource, /return this\.senders\.pluginFor\(senderId\)/);
+ assert.match(viewHostSource, /async dispose\(\): Promise<void>/);
+});
+
+test("the bridge settles a call from a page that is gone", () => {
+ const handler = panelHostSource.slice(
+ panelHostSource.indexOf('"pi-plugin-panel-invoke"'),
+ panelHostSource.indexOf('ipcMain.on("pi-plugin-panel-drop"'),
+ );
+ assert.ok(handler.length > 0);
+ assert.match(handler, /resolvePanelInvocation\(/);
+ assert.match(handler, /event\.sender\.isDestroyed\(\)/);
+ assert.match(handler, /if \(invocation\.kind === "gone"\) return;/);
+ assert.match(
+ handler,
+ /if \(invocation\.kind === "foreign"\) throw new Error\("invalid panel invoker"\)/,
+ );
+ // The same rule covers the capsule channel: a page that is gone cannot read a
+ // window-control answer either, while a live sender still reads as invalid.
+ assert.match(
+ panelHostSource,
+ /if \(!window\) \{[\s\S]*?if \(event\.sender\.isDestroyed\(\)\) return;[\s\S]*?throw new Error\("invalid panel window control invoker"\)/,
+ );
+});
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index 6f3570d7d..6aaa5d2af 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -219,15 +219,25 @@ test("app quit waits for one idempotent teardown before allowing the follow-up q
shutdownSource.indexOf("if (state.shutdownPromise) return"),
"the first quit must be prevented before the idempotence guard returns",
);
+ // Panel windows and docked views are the only pages that call the host and the
+ // plugin runtime over the panel bridge. Their pages are gone before either
+ // stops: a call a page already sent while its surface was closing is otherwise
+ // answered by a runtime that is already shutting down, and is reported as a
+ // bridge failure nobody can act on.
assert.ok(
- shutdownSource.indexOf("getHost()?.dispose()") <
- shutdownSource.indexOf("pluginPanels.closeAll()"),
- "host disposal must start before other application teardown",
+ shutdownSource.indexOf("await pluginSurfacesShutdown") <
+ shutdownSource.indexOf("getHost()?.dispose()"),
+ "panel and view pages must be gone before the host stops",
+ );
+ assert.ok(
+ shutdownSource.indexOf("await pluginSurfacesShutdown") <
+ shutdownSource.indexOf("plugins.disposeAll()"),
+ "no panel page may still call a plugin runtime that is stopping",
);
assert.match(shutdownSource, /await hostShutdown/);
assert.match(
shutdownSource,
- /await Promise\.allSettled\(\[\s*pluginPanelShutdown,\s*pluginShutdown,\s*sidecarShutdown,\s*mcpShutdown,\s*remoteHostsShutdown,\s*\]\)/,
+ /await Promise\.allSettled\(\[\s*pluginShutdown,\s*sidecarShutdown,\s*mcpShutdown,\s*remoteHostsShutdown,\s*\]\)/,
);
const releaseQuit = shutdownSource.match(
/const releaseQuit = \(\) => \{[\s\S]*?shutdownComplete = true;[\s\S]*?app\.quit\(\);[\s\S]*?\};/,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 1f74ae544..b6e5964d0 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2731,8 +2731,8 @@ identify the platform validation still needed.
#### E2E-024D: Isolated plugin panel host bridge
- **Preconditions**: Plugin with `ui.panel` enabled.
-- **Steps**: 1) Set the app language to English and open a panel whose manifest declares localized `ui.title.en` and `ui.title.zh-CN`; confirm the native window/launcher identity remains available without a host-rendered title. 2) Set the app language to Simplified Chinese and reopen the panel; confirm the panel content remains plugin-owned. 3) While the panel stays open, switch the app language to Korean and confirm the live `appearance:changed` event updates the panel controls, safe-area reminder, and accessible labels without reopening it. 4) Open the panel on macOS, Windows, and Linux; confirm the same frameless 46px drag band, fixed top-right capsule fully contained inside that band, and exactly three accessible controls. 5) Exercise minimize, maximize, restore, close, keyboard focus, light/dark themes, page-defined light/dark backgrounds, and reduced motion on every platform. 6) Render a plugin-owned titlebar/toolbar; verify fixed/sticky UI uses `--pi-plugin-titlebar-height`, its interactive controls use `no-drag`, and clicks outside the capsule in the top 46px are treated as window dragging. 7) On Windows with classic scrollbars, scroll a panel with content overflow and inspect the right edge. 8) Open a development plugin and confirm the localized reminder explains that the top 46px is not clickable outside the capsule. 9) Reopen a minimized panel. 10) Invoke panel bridge APIs (`ui.showToast`, optional fs/net with grants). 11) Close the panel from the capsule and by disabling or uninstalling the plugin.
-- **Expected**: Panel runs in its sandboxed window/partition; all three platforms use one host-owned frameless chrome contract with no native traffic lights, host-rendered title, or application menu; the top drag band is exactly 46px, and the minimal capsule stays fixed at the top-right without exceeding it. The capsule contains minimize/maximize-or-restore/close, follows the plugin page's surface/text colors, and never forces a black surface onto a light page. A v2 page marked `pi-plugin-chrome` uses `--pi-plugin-titlebar-height` and starts its own content directly below the 46px band without an additive duplicate spacer; a legacy page keeps the compatibility offset. A panel's stable scrollbar gutter is scoped to its actual content scroller; Windows does not show a second root-level empty side rail outside the page surface. The plugin owns its title and toolbar; the host drag strip remains usable, blocks clicks outside the capsule, and development panels alone show the reminder. Reopening restores the existing panel; switching to Korean while the panel remains open updates the host capsule, reminder, and accessible labels in place; bridge calls remain permission-checked and the host remains stable on panel close. Closing a panel must not throw a main-process `TypeError: Object has been destroyed` or show an uncaught-exception dialog.
+- **Steps**: 1) Set the app language to English and open a panel whose manifest declares localized `ui.title.en` and `ui.title.zh-CN`; confirm the native window/launcher identity remains available without a host-rendered title. 2) Set the app language to Simplified Chinese and reopen the panel; confirm the panel content remains plugin-owned. 3) While the panel stays open, switch the app language to Korean and confirm the live `appearance:changed` event updates the panel controls, safe-area reminder, and accessible labels without reopening it. 4) Open the panel on macOS, Windows, and Linux; confirm the same frameless 46px drag band, fixed top-right capsule fully contained inside that band, and exactly three accessible controls. 5) Exercise minimize, maximize, restore, close, keyboard focus, light/dark themes, page-defined light/dark backgrounds, and reduced motion on every platform. 6) Render a plugin-owned titlebar/toolbar; verify fixed/sticky UI uses `--pi-plugin-titlebar-height`, its interactive controls use `no-drag`, and clicks outside the capsule in the top 46px are treated as window dragging. 7) On Windows with classic scrollbars, scroll a panel with content overflow and inspect the right edge. 8) Open a development plugin and confirm the localized reminder explains that the top 46px is not clickable outside the capsule. 9) Reopen a minimized panel. 10) Invoke panel bridge APIs (`ui.showToast`, optional fs/net with grants). 11) Close the panel from the capsule and by disabling or uninstalling the plugin. 12) Repeat with a panel and a docked work-panel view open and quit the app, then read the main-process log.
+- **Expected**: Panel runs in its sandboxed window/partition; all three platforms use one host-owned frameless chrome contract with no native traffic lights, host-rendered title, or application menu; the top drag band is exactly 46px, and the minimal capsule stays fixed at the top-right without exceeding it. The capsule contains minimize/maximize-or-restore/close, follows the plugin page's surface/text colors, and never forces a black surface onto a light page. A v2 page marked `pi-plugin-chrome` uses `--pi-plugin-titlebar-height` and starts its own content directly below the 46px band without an additive duplicate spacer; a legacy page keeps the compatibility offset. A panel's stable scrollbar gutter is scoped to its actual content scroller; Windows does not show a second root-level empty side rail outside the page surface. The plugin owns its title and toolbar; the host drag strip remains usable, blocks clicks outside the capsule, and development panels alone show the reminder. Reopening restores the existing panel; switching to Korean while the panel remains open updates the host capsule, reminder, and accessible labels in place; bridge calls remain permission-checked and the host remains stable on panel close. Closing a panel must not throw a main-process `TypeError: Object has been destroyed` or show an uncaught-exception dialog, and neither closing a panel nor quitting with panels and docked views open may log a panel-bridge failure for the page that is closing: a call from a page that is already gone is settled, and the panel and view pages are gone before the plugin runtime and the host stop.
- **Specs linked**: `03-runtime/01-ipc-protocol.md`, `04-ux/07-ui-design-system.md`, `07-plugins/01-plugin-system.md`, `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`, `07-plugins/12-plugin-ipc-and-host-services.md`, ADR 0081, ADR 0082, ADR 0092, ADR 0093
- **Acceptance**: G (isolated panel)
- **Status**: Documented
diff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
index cc30776cb..2e029fc18 100644
--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md
@@ -185,6 +185,14 @@ audit-operation names for the device service: `audio.input.open` /
`webContents` identity copies that id before the window is destroyed; the
`closed` handler must not read `webContents` on a destroyed window, or the
host surfaces an uncaught `TypeError: Object has been destroyed`.
+- Bridge identity belongs to the page, not to the host's list of open surfaces: a
+ panel window or a docked view registers its plugin before the document loads and
+ releases it only when that page is gone, so a call that arrives while the host is
+ closing the surface still reaches its own plugin. A call from a page that is
+ already destroyed is settled instead of rejected: its answer can never be read and
+ the plugin runtime may already be stopping, so rejecting it would only add an
+ `invalid panel invoker` failure to the main log. Shutdown closes the panel and
+ view pages, bounded, before `plugins.disposeAll()` and `host.dispose()`.
- The preload exposes `pluginBridge.getDroppedFilePath(file)` without exposing
Node to the page. A panel may call `fs.registerDropped` with that path; the
host consumes a sender-bound recent drop record once and issues a one-file