Skip to content

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

fix(desktop): resync plugin view bounds after layout

今天不加班d1752de2751f
diff --git a/apps/desktop/src/components/workpanel/PluginViewTab.tsx b/apps/desktop/src/components/workpanel/PluginViewTab.tsx
index 17c1e431e..2bce1ff85 100644
--- a/apps/desktop/src/components/workpanel/PluginViewTab.tsx
+++ b/apps/desktop/src/components/workpanel/PluginViewTab.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { api } from "../../lib/api";
import { pluginViewIcon } from "../../lib/plugin-view-icons";
@@ -41,6 +41,29 @@ export function PluginViewTab({
locationRef.current = location;
const viewLocation = pluginId === "pi.browser" && viewId === "browser" ? undefined : location;
const [failed, setFailed] = useState(false);
+ const boundsFrameRef = useRef(0);
+ const reportBounds = useCallback(() => {
+ // Replacing a pending frame on every commit can starve bounds updates.
+ if (boundsFrameRef.current) return;
+ boundsFrameRef.current = requestAnimationFrame(() => {
+ boundsFrameRef.current = 0;
+ const surface = surfaceRef.current;
+ if (!surface || failed) return;
+ const rect = surface.getBoundingClientRect();
+ void api.pluginViewSetBounds({
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ });
+ });
+ }, [failed]);
+
+ // ResizeObserver does not cover position-only movement caused by an ancestor
+ // layout or transform. Every React layout commit supplies the final rect.
+ useLayoutEffect(() => {
+ reportBounds();
+ });
// Create the view, and re-create it whenever the plugin's lifecycle changed
// underneath us: a crash, a development reload, or a re-enable all destroy
@@ -80,29 +103,17 @@ export function PluginViewTab({
useEffect(() => {
const surface = surfaceRef.current;
if (!surface || failed) return;
- let frame = 0;
- const report = () => {
- cancelAnimationFrame(frame);
- frame = requestAnimationFrame(() => {
- const rect = surface.getBoundingClientRect();
- void api.pluginViewSetBounds({
- x: rect.x,
- y: rect.y,
- width: rect.width,
- height: rect.height,
- });
- });
- };
- const observer = new ResizeObserver(report);
+ const observer = new ResizeObserver(reportBounds);
observer.observe(surface);
- window.addEventListener("resize", report);
- report();
+ window.addEventListener("resize", reportBounds);
+ reportBounds();
return () => {
observer.disconnect();
- window.removeEventListener("resize", report);
- cancelAnimationFrame(frame);
+ window.removeEventListener("resize", reportBounds);
+ cancelAnimationFrame(boundsFrameRef.current);
+ boundsFrameRef.current = 0;
};
- }, [pluginId, viewId, failed]);
+ }, [pluginId, viewId, failed, reportBounds]);
if (failed) {
return (
diff --git a/apps/desktop/test/plugin-view-bounds-sync.test.mjs b/apps/desktop/test/plugin-view-bounds-sync.test.mjs
new file mode 100644
index 000000000..f3024fe06
--- /dev/null
+++ b/apps/desktop/test/plugin-view-bounds-sync.test.mjs
@@ -0,0 +1,208 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+import { resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "../../..");
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+
+const fixture = String.raw`
+import React from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { IPC } from "@pi-desktop/shared";
+import { PluginViewTab } from "./src/components/workpanel/PluginViewTab";
+
+const calls = [];
+window.piDesktop = {
+ channels: IPC,
+ platform: "darwin",
+ invoke: async (channel, ...args) => {
+ calls.push({ channel, args });
+ return { ok: true, data: undefined };
+ },
+ on: () => () => undefined,
+};
+
+document.body.style.cssText = "margin:0;display:flex;align-items:flex-start";
+const sidebar = document.createElement("div");
+sidebar.style.cssText = "flex:0 0 0;height:240px";
+const host = document.createElement("div");
+host.style.cssText = "flex:0 0 320px;width:320px;height:240px";
+const style = document.createElement("style");
+style.textContent = ".work-plugin-view,.work-plugin-view-surface{width:100%;height:100%}";
+document.head.append(style);
+document.body.append(sidebar, host);
+
+const i18n = createInstance();
+const ready = i18n.init({
+ lng: "en",
+ resources: { en: { translation: catalogs.en } },
+ interpolation: { escapeValue: false },
+});
+const root = createRoot(host);
+const view = () => (
+ <I18nextProvider i18n={i18n}>
+ <PluginViewTab pluginId="fixture.plugin" viewId="surface" title="Fixture" />
+ </I18nextProvider>
+);
+const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));
+const boundsCalls = () => calls
+ .filter((entry) => entry.channel === IPC.invoke.pluginViewSetBounds)
+ .map((entry) => entry.args[0]);
+const settledBounds = async () => {
+ let previousCount = -1;
+ for (let frame = 0; frame < 8; frame += 1) {
+ await nextFrame();
+ const current = boundsCalls();
+ if (current.length > 0 && current.length === previousCount) return current.at(-1);
+ previousCount = current.length;
+ }
+ return undefined;
+};
+
+globalThis.pluginViewBoundsProbe = async () => {
+ await ready;
+ flushSync(() => root.render(view()));
+ const initial = await settledBounds();
+ if (!initial) throw new Error("plugin view did not report initial bounds");
+
+ calls.length = 0;
+ host.style.transform = "translateX(180px)";
+ let churnFrame = 0;
+ const churn = () => {
+ churnFrame = requestAnimationFrame(churn);
+ flushSync(() => root.render(view()));
+ };
+ churnFrame = requestAnimationFrame(churn);
+ flushSync(() => root.render(view()));
+ const moved = await settledBounds();
+ cancelAnimationFrame(churnFrame);
+ const surface = document.querySelector(".work-plugin-view-surface").getBoundingClientRect();
+ if (!moved) throw new Error("plugin view bounds were starved by repeated layout commits");
+ if (Math.round(moved.x) !== Math.round(surface.x)) {
+ throw new Error("reported x does not match the moved surface: " + JSON.stringify({ moved, x: surface.x }));
+ }
+ if (Math.round(initial.width) !== Math.round(moved.width)) {
+ throw new Error("fixture changed surface width: " + JSON.stringify({ initial, moved }));
+ }
+ return { initial, moved };
+};
+`;
+
+test(
+ "plugin native bounds follow position-only renderer layout changes",
+ {
+ skip:
+ process.platform === "linux" && !process.env.DISPLAY
+ ? "Electron requires a display"
+ : false,
+ },
+ async () => {
+ const temp = await mkdtemp(join(tmpdir(), "pi-plugin-view-bounds-"));
+ try {
+ await build({
+ stdin: {
+ contents: fixture,
+ resolveDir: join(root, "apps/desktop"),
+ loader: "tsx",
+ },
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "iife",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(
+ join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><body><script src="renderer.js"></script>',
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({
+ show: false,
+ width: 800,
+ height: 600,
+ webPreferences: {
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ backgroundThrottling: false,
+ },
+ });
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ const result = await window.webContents.executeJavaScript("globalThis.pluginViewBoundsProbe()");
+ console.log("PLUGIN_VIEW_BOUNDS_PROBE " + JSON.stringify({ ok: true, result }));
+ app.exit(0);
+ } catch (error) {
+ console.error("PLUGIN_VIEW_BOUNDS_PROBE " + JSON.stringify({ ok: false, error: String(error) }));
+ app.exit(1);
+ }
+});
+`,
+ );
+
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(
+ resolveElectronBinary(root).electronBinary,
+ [join(temp, "main.cjs")],
+ { env, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => {
+ output += chunk;
+ });
+ }
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+
+ const line = output
+ .split(/\r?\n/)
+ .find((item) => item.startsWith("PLUGIN_VIEW_BOUNDS_PROBE "));
+ assert.ok(line, output.slice(-6000));
+ assert.equal(code, 0, output.slice(-6000));
+ const report = JSON.parse(line.slice("PLUGIN_VIEW_BOUNDS_PROBE ".length));
+ assert.equal(report.ok, true, output.slice(-6000));
+ assert.equal(report.result.initial.x, 0);
+ assert.equal(report.result.moved.x, 180);
+ assert.equal(report.result.initial.width, report.result.moved.width);
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/apps/desktop/test/plugin-work-panel-views.test.mjs b/apps/desktop/test/plugin-work-panel-views.test.mjs
index f6837a180..c802ac0f1 100644
--- a/apps/desktop/test/plugin-work-panel-views.test.mjs
+++ b/apps/desktop/test/plugin-work-panel-views.test.mjs
@@ -96,20 +96,26 @@ test("plugin views reach the panel body and the empty state", () => {
assert.doesNotMatch(panelSource, /openPluginView\(view\)/);
});
-test("the native surface keeps its full bounds while the launcher is active", () => {
+test("the native surface keeps its full and current bounds while the launcher is active", () => {
assert.match(panelSource, /blocked=\{\s*exiting \|\| panelBlocked \|\| blockingOverlayActive\s*\}/s);
assert.doesNotMatch(panelSource, /avoid: pluginSurface/);
assert.doesNotMatch(panelSource, /menuOpen|work-panel-new-menu|placeWorkPanelMenu/);
assert.doesNotMatch(viewTabSource, /occludedById/);
assert.match(viewTabSource, /y: rect\.y/);
assert.match(viewTabSource, /height: rect\.height/);
- // Visibility and bounds are separate effects: only panel-wide blocking and
- // lifecycle transitions hide the native page, so creating a New tab cannot
- // alter the active surface's measured rectangle.
+ // Visibility and bounds are separate effects: blocking controls attachment,
+ // while renderer layout commits and element resizes keep the complete native
+ // rectangle current without changing the active tab.
assert.match(
viewTabSource,
- /pluginViewSetVisible\(pluginId, viewId, !blocked, sessionId\)[\s\S]*pluginViewSetBounds/s,
+ /pluginViewSetVisible\(pluginId, viewId, !blocked, sessionId\)/,
);
+ assert.match(
+ viewTabSource,
+ /useLayoutEffect\(\(\) => \{\s*reportBounds\(\);\s*\}\)/s,
+ );
+ assert.match(viewTabSource, /new ResizeObserver\(reportBounds\)/);
+ assert.match(viewTabSource, /void api\.pluginViewSetBounds\(\{/);
});
test("an unknown icon token degrades instead of rendering plugin markup", () => {
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index d760c7a05..f3d4ddc56 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1129,6 +1129,12 @@ entirely inside the plugin's isolated page:
### 5.4 Interactions
+- Native plugin bounds follow the placeholder's complete viewport-relative
+ rectangle after every renderer layout commit, not only after the placeholder
+ changes size. Sidebar collapse/expand, preview mode, and ancestor transforms
+ therefore cannot leave the host `WebContentsView` at an earlier horizontal
+ position or expose an uncovered strip beside Browser or another plugin view.
+
- Trigger: file/URL references and BrowserPreview create/activate their
resource tab in the originating session's runtime context. BrowserPreview
events carry `sessionId`, and the renderer retains that session's preview
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e9357dd67..08265474e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -15644,15 +15644,19 @@ plugin-form fixtures in an isolated temporary directory at runtime.
#### E2E-LAYOUT-work-panel-maximize
-- **Preconditions**: A desktop session is open with the work panel visible.
+- **Preconditions**: A desktop session is open with the work panel visible and
+ the bundled Browser plugin active on a loaded page.
1. Note the current panel width. If the sidebar is expanded, collapse it;
then click the panel header's `+` action to open a real work-panel tab.
2. Click the panel header's preview toggle.
- 3. Inspect the header border box and tab alignment with the sidebar collapsed
+ 3. While preview remains active, collapse and reopen the sidebar. Compare the
+ Browser/plugin placeholder's viewport-relative rectangle with the latest
+ native bounds report after each layout settles.
+ 4. Inspect the header border box and tab alignment with the sidebar collapsed
and expanded on macOS windowed/fullscreen and Windows/Linux. Confirm the
overlay row and spacer declare neither drag nor no-drag and do not cover
the panel controls with opaque paint.
- 4. Using native pointer input, click the centers and edges of sidebar and
+ 5. Using native pointer input, click the centers and edges of sidebar and
New Task controls; confirm sidebar toggles and New Task exits preview to
an editable composer. Reenter preview, operate tabs, close, add, restore,
panel toggle and native controls, then drag empty header space and confirm
@@ -15661,7 +15665,10 @@ plugin-form fixtures in an isolated temporary directory at runtime.
width to the panel, so the panel spans the client area minus the expanded
sidebar (the whole client area when the sidebar is collapsed). The native
window never changes size. The divider is inert while preview mode is on
- (`aria-disabled`). Leaving preview mode restores the previous panel width and
+ (`aria-disabled`). The native Browser/plugin surface matches the complete
+ renderer placeholder rect after both sidebar transitions, including when
+ only its absolute position changes; no stale page edge or uncovered strip
+ remains beside it. Leaving preview mode restores the previous panel width and
keeps whatever sidebar state the user chose last. The mode is transient: it is
not persisted and ends when the panel closes. Preview mode keeps the shell's
new-task, sidebar, and system-window actions reachable while MainChat is
@@ -15683,9 +15690,12 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Status**: Partially automated (`scripts/e2e-three-column-layout.mjs` —
preview entry/exit, DOM action behavior, header border-box exclusion, row/spacer
drag ownership, and all-platform/fullscreen CSS fixtures in both sidebar
- states). DOM clicks and CDP input are not native hit-test proof; native pointer,
- window-drag and visual checks remain required on each platform. Branch runs
- are exploratory and do not satisfy the integrated-main gate.
+ states). `plugin-view-bounds-sync.test.mjs` mounts the production
+ `PluginViewTab` in Electron and covers a position-only layout commit with
+ unchanged surface dimensions. DOM clicks and CDP input are not native hit-test
+ proof; native pointer, window-drag, and visual checks remain required on each
+ platform. Branch runs are exploratory and do not satisfy the integrated-main
+ gate.
### E2E-WORK-PANEL-overflow-tab-drag-exclusion