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(windows): smooth main window corner compositing (#1522)
Land3cdb4ff9c9a
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex 19c76c339..9b34ce729 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -34,7 +34,8 @@ import {import { readWindowState, writeWindowState } from "../window-preferences";import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";import { isWindowFullScreen } from "../window-fullscreen";-import { installWindowShape } from "../window-shape";+import { DEFAULT_WINDOW_CORNER_RADIUS, installWindowShape } from "../window-shape";+import { applyMainWindowBackground, mainWindowBackgroundOptions } from "../window-background";import { recoverRendererAfterGone } from "../renderer-recovery";function windowsIconPath(): string | undefined {@@ -163,6 +164,9 @@ export async function createWindow({{ width: windowMinWidth, height: windowMinHeight },restoreWorkArea,);+ const initialWindowBackground = builtinWindowBackground(+ nativeTheme.shouldUseDarkColors ? "dark" : "light",+ );windowState.mainWindow = new BrowserWindow({...(restoredBounds ?? { width: 1200, height: 800 }),minWidth: initialMinWidth,@@ -190,9 +194,7 @@ export async function createWindow({: {frame: false,...(process.platform === "win32" ? { thickFrame: false } : {}),- backgroundColor: builtinWindowBackground(- nativeTheme.shouldUseDarkColors ? "dark" : "light",- ),+ ...mainWindowBackgroundOptions(process.platform, initialWindowBackground),}),...(process.platform === "win32"? {@@ -211,7 +213,10 @@ export async function createWindow({},});const window = windowState.mainWindow;- if (process.platform === "win32") installWindowShape(window);+ if (process.platform === "win32") {+ installWindowShape(window, DEFAULT_WINDOW_CORNER_RADIUS, screen);+ }+ applyMainWindowBackground(window, process.platform, initialWindowBackground);suppressLinuxFramelessSystemMenu(window);const initialBounds = window.getBounds();windowState.workPanelBaseBounds = restoredBoundsdiff --git a/apps/desktop/electron/main/ipc/window-ipc.ts b/apps/desktop/electron/main/ipc/window-ipc.tsindex 266cdec62..692b81b7d 100644--- a/apps/desktop/electron/main/ipc/window-ipc.ts+++ b/apps/desktop/electron/main/ipc/window-ipc.ts@@ -22,6 +22,7 @@ import {DEFAULT_WINDOW_CORNER_RADIUS,setWindowCornerRadius,} from "../window-shape";+import { applyMainWindowBackground } from "../window-background";import type { IpcRegistrar } from "./types";export type WindowIpcDependencies = {@@ -141,7 +142,7 @@ export function registerWindowIpc({typeof requestedRadius === "number" ? requestedRadius : DEFAULT_WINDOW_CORNER_RADIUS,): null;- mainWindow.setBackgroundColor(color);+ applyMainWindowBackground(mainWindow, process.platform, color);return { applied: true, theme, color, cornerRadius };});diff --git a/apps/desktop/electron/main/window-background.ts b/apps/desktop/electron/main/window-background.tsnew file mode 100644index 000000000..1afee82ce--- /dev/null+++ b/apps/desktop/electron/main/window-background.ts@@ -0,0 +1,49 @@+import type { BrowserWindow, BrowserWindowConstructorOptions } from "electron";+import { isWindowBackgroundColor } from "@pi-desktop/plugin-sdk";++type BackgroundPlatform = NodeJS.Platform;+type BackgroundWindow = Pick<BrowserWindow, "contentView" | "setBackgroundColor">;++/** Convert the Plugin SDK's RRGGBBAA value to Electron's unambiguous CSS form. */+export function toElectronBackgroundColor(color: string): string {+ if (!isWindowBackgroundColor(color)) {+ throw new TypeError("invalid window background color");+ }++ const red = Number.parseInt(color.slice(1, 3), 16);+ const green = Number.parseInt(color.slice(3, 5), 16);+ const blue = Number.parseInt(color.slice(5, 7), 16);+ const alpha = color.length === 9+ ? Number.parseInt(color.slice(7, 9), 16) / 255+ : 1;+ return `rgba(${red}, ${green}, ${blue}, ${alpha})`;+}++/** Options needed before the main window is created to avoid a color flash. */+export function mainWindowBackgroundOptions(+ platform: BackgroundPlatform,+ color: string,+): Pick<BrowserWindowConstructorOptions, "backgroundColor" | "transparent"> {+ if (platform === "win32") {+ return { transparent: true, backgroundColor: "#00000000" };+ }+ if (platform === "darwin") return {};+ return { backgroundColor: toElectronBackgroundColor(color) };+}++/** Apply a theme background to its platform-owned surface. */+export function applyMainWindowBackground(+ window: BackgroundWindow,+ platform: BackgroundPlatform,+ color: string,+): boolean {+ if (platform === "darwin") return false;++ const electronColor = toElectronBackgroundColor(color);+ if (platform === "win32") {+ window.contentView.setBackgroundColor(electronColor);+ } else {+ window.setBackgroundColor(electronColor);+ }+ return true;+}diff --git a/apps/desktop/electron/main/window-shape.ts b/apps/desktop/electron/main/window-shape.tsindex fb3e086fc..029180cb1 100644--- a/apps/desktop/electron/main/window-shape.ts+++ b/apps/desktop/electron/main/window-shape.ts@@ -1,4 +1,4 @@-import type { BrowserWindow, Rectangle } from "electron";+import type { BrowserWindow, Rectangle, Screen } from "electron";import { MAX_WINDOW_CORNER_RADIUS } from "@pi-desktop/plugin-sdk";import { isWindowFullScreen } from "./window-fullscreen.ts";@@ -6,14 +6,27 @@ import { isWindowFullScreen } from "./window-fullscreen.ts";export const DEFAULT_WINDOW_CORNER_RADIUS = 12;const controllers = new WeakMap<BrowserWindow, { setRadius: (radius: number) => number }>();-/** Pixel rows approximate a quarter circle without changing window bounds. */-export function roundedWindowShape(width: number, height: number, radius: number): Rectangle[] {+type WindowShapeScreen = Pick<Screen, "getDisplayMatching" | "on" | "removeListener">;++/**+ * Build a native hit region that contains the antialiased edge painted by the+ * content view. The content view owns the visible curve; this region only+ * keeps clicks outside the rounded silhouette from reaching the window.+ */+export function roundedWindowHitRegion(width: number, height: number, radius: number): Rectangle[] {const corner = Math.min(Math.round(radius), Math.floor(width / 2), Math.floor(height / 2));if (corner <= 0) return [];+const rects: Rectangle[] = [];for (let row = 0; row < corner; row += 1) {- const distance = corner - row - 0.5;- const inset = Math.max(0, Math.ceil(corner - Math.sqrt(corner * corner - distance * distance) - 0.5));+ // Cover the full curve slice across this row, not only its midpoint. The+ // circle boundary moves inward as the row approaches the center, so use+ // its lower edge and round outward to keep antialiased coverage clickable.+ const distance = corner - row - 1;+ const inset = Math.max(+ 0,+ Math.floor(corner - Math.sqrt(corner * corner - distance * distance)),+ );const band = { x: inset, width: width - inset * 2, height: 1 };rects.push({ ...band, y: row }, { ...band, y: height - row - 1 });}@@ -23,30 +36,49 @@ export function roundedWindowShape(width: number, height: number, radius: numberreturn rects;}-/** Keep the native hit region matched to the current window dimensions. */-export function installWindowShape(window: BrowserWindow, initialRadius = DEFAULT_WINDOW_CORNER_RADIUS) {- let radius = initialRadius;+/** Keep the visible curve and native hit region synchronized with the window. */+export function installWindowShape(+ window: BrowserWindow,+ initialRadius = DEFAULT_WINDOW_CORNER_RADIUS,+ windowScreen?: WindowShapeScreen,+) {+ let radius = Math.max(0, Math.min(MAX_WINDOW_CORNER_RADIUS, Math.round(initialRadius)));let lastShape = "";const apply = (force = false) => {if (window.isDestroyed()) return;- const { width, height } = window.getBounds();+ const { width, height } = window.contentView.getBounds();const rectangular = window.isMaximized() || isWindowFullScreen(window);- const shapeKey = `${width}:${height}:${rectangular ? 0 : radius}`;+ const scaleFactor = windowScreen?.getDisplayMatching(window.getBounds()).scaleFactor ?? 1;+ const visibleRadius = rectangular ? 0 : radius;+ const shapeKey = `${width}:${height}:${scaleFactor}:${visibleRadius}`;if (!force && shapeKey === lastShape) return;- window.setShape(rectangular ? [] : roundedWindowShape(width, height, radius));++ window.contentView.setBorderRadius(visibleRadius);+ window.setShape(+ visibleRadius === 0 ? [] : roundedWindowHitRegion(width, height, visibleRadius),+ );lastShape = shapeKey;};- // Windows can reset the native window region during visibility transitions.++ // Windows can reset the native window region during visibility and monitor+ // transitions. Re-apply after those changes while retaining the chosen DIP+ // radius across maximized/fullscreen states.const reapply = () => apply(true);window.on("resize", apply);+ window.on("move", apply);window.on("maximize", apply);window.on("unmaximize", apply);window.on("enter-full-screen", apply);window.on("leave-full-screen", apply);window.on("show", reapply);window.on("restore", reapply);+ windowScreen?.on("display-metrics-changed", reapply);+ windowScreen?.on("display-added", reapply);+ windowScreen?.on("display-removed", reapply);+const dispose = () => {window.removeListener("resize", apply);+ window.removeListener("move", apply);window.removeListener("maximize", apply);window.removeListener("unmaximize", apply);window.removeListener("enter-full-screen", apply);@@ -54,9 +86,13 @@ export function installWindowShape(window: BrowserWindow, initialRadius = DEFAULwindow.removeListener("show", reapply);window.removeListener("restore", reapply);window.removeListener("closed", dispose);+ windowScreen?.removeListener("display-metrics-changed", reapply);+ windowScreen?.removeListener("display-added", reapply);+ windowScreen?.removeListener("display-removed", reapply);controllers.delete(window);};window.once("closed", dispose);+const controller = {setRadius(next: number) {radius = Math.max(0, Math.min(MAX_WINDOW_CORNER_RADIUS, Math.round(next)));diff --git a/apps/desktop/test/macos-sidebar-vibrancy.test.mjs b/apps/desktop/test/macos-sidebar-vibrancy.test.mjsindex 004fbebfb..836f3b438 100644--- a/apps/desktop/test/macos-sidebar-vibrancy.test.mjs+++ b/apps/desktop/test/macos-sidebar-vibrancy.test.mjs@@ -43,11 +43,16 @@ test("macOS main window enables native sidebar vibrancy only in its platform bra"non-mac branch must not set under-window vibrancy",);- // The shared opaque fallback remains in place for Windows/Linux, and comes- // from the built-in theme table rather than a local literal.+ // The platform helper receives the built-in fallback selected from the+ // native theme. Windows paints it inside the rounded content surface;+ // Linux keeps its native window background behavior.assert.match(mainWindowBlock,- /backgroundColor:\s*builtinWindowBackground\(\s*nativeTheme\.shouldUseDarkColors \? "dark" : "light",?\s*\)/,+ /\.\.\.mainWindowBackgroundOptions\(process\.platform, initialWindowBackground\)/,+ );+ assert.match(+ windowSource,+ /const initialWindowBackground = builtinWindowBackground\(\s*nativeTheme\.shouldUseDarkColors \? "dark" : "light",?\s*\)/,);assert.match(mainWindowBlock, /frame: false/);assert.doesNotMatch(diff --git a/apps/desktop/test/window-background-theme.test.mjs b/apps/desktop/test/window-background-theme.test.mjsindex dc36b16fb..33a5ef633 100644--- a/apps/desktop/test/window-background-theme.test.mjs+++ b/apps/desktop/test/window-background-theme.test.mjs@@ -25,8 +25,10 @@ test("theme changes synchronize the native non-macOS window background", () => {);assert.match(mainSource,- /handleWithEvent\(IPC\.invoke\.windowSetBackgroundColor,[\s\S]*?registrar\.assertMainWindowSender\(event\)[\s\S]*?!isWindowBackgroundColor\(requested\)[\s\S]*?mainWindow\.setBackgroundColor\(color\)/,+ /handleWithEvent\(IPC\.invoke\.windowSetBackgroundColor,[\s\S]*?registrar\.assertMainWindowSender\(event\)[\s\S]*?!isWindowBackgroundColor\(requested\)[\s\S]*?applyMainWindowBackground\(mainWindow, process\.platform, color\)/,);+ assert.match(mainSource, /mainWindowBackgroundOptions\(process\.platform, initialWindowBackground\)/);+ assert.match(mainSource, /applyMainWindowBackground\(window, process\.platform, initialWindowBackground\)/);// A malformed colour is refused; an omitted one falls back to the host// palette, which is what restores the default after a theme switch.assert.match(mainSource, /isWindowBackgroundColor\(requested\)\s*\n?\s*\? requested/);diff --git a/apps/desktop/test/window-background.test.mjs b/apps/desktop/test/window-background.test.mjsnew file mode 100644index 000000000..e13bd83c0--- /dev/null+++ b/apps/desktop/test/window-background.test.mjs@@ -0,0 +1,53 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ applyMainWindowBackground,+ mainWindowBackgroundOptions,+ toElectronBackgroundColor,+} from "../electron/main/window-background.ts";++function makeWindow() {+ const calls = [];+ return {+ calls,+ contentView: {+ setBackgroundColor: (color) => calls.push(["contentView", color]),+ },+ setBackgroundColor: (color) => calls.push(["window", color]),+ };+}++test("plugin colors convert from RRGGBBAA to an explicit CSS color", () => {+ assert.equal(toElectronBackgroundColor("#123456"), "rgba(18, 52, 86, 1)");+ assert.equal(+ toElectronBackgroundColor("#12345680"),+ "rgba(18, 52, 86, 0.5019607843137255)",+ );+ assert.equal(toElectronBackgroundColor("#abcdef00"), "rgba(171, 205, 239, 0)");+ assert.throws(() => toElectronBackgroundColor("#1234567"), /invalid window background color/);+});++test("constructor background options keep only the Windows outer surface transparent", () => {+ assert.deepEqual(mainWindowBackgroundOptions("win32", "#ffffff"), {+ transparent: true,+ backgroundColor: "#00000000",+ });+ assert.deepEqual(mainWindowBackgroundOptions("linux", "#12345680"), {+ backgroundColor: "rgba(18, 52, 86, 0.5019607843137255)",+ });+ assert.deepEqual(mainWindowBackgroundOptions("darwin", "#ffffff"), {});+});++test("background updates target the rounded content view on Windows and native window on Linux", () => {+ const windows = makeWindow();+ assert.equal(applyMainWindowBackground(windows, "win32", "#12345680"), true);+ assert.deepEqual(windows.calls, [["contentView", "rgba(18, 52, 86, 0.5019607843137255)"]]);++ const linux = makeWindow();+ assert.equal(applyMainWindowBackground(linux, "linux", "#123456"), true);+ assert.deepEqual(linux.calls, [["window", "rgba(18, 52, 86, 1)"]]);++ const mac = makeWindow();+ assert.equal(applyMainWindowBackground(mac, "darwin", "#123456"), false);+ assert.deepEqual(mac.calls, []);+});diff --git a/apps/desktop/test/window-shape.test.mjs b/apps/desktop/test/window-shape.test.mjsindex 94d74bffc..255ee0809 100644--- a/apps/desktop/test/window-shape.test.mjs+++ b/apps/desktop/test/window-shape.test.mjs@@ -5,83 +5,163 @@ import test from "node:test";import {DEFAULT_WINDOW_CORNER_RADIUS,installWindowShape,- roundedWindowShape,+ roundedWindowHitRegion,setWindowCornerRadius,} from "../electron/main/window-shape.ts";import { setWindowFullScreen } from "../electron/main/window-fullscreen.ts";-test("default native window radius matches the global medium radius token", () => {- const tokens = readFileSync(new URL("../src/styles/tokens.css", import.meta.url), "utf8");- const match = tokens.match(/^\s*--radius-md:\s*(\d+(?:\.\d+)?)px;/m);- assert.ok(match, "the global medium radius token is defined");- assert.equal(DEFAULT_WINDOW_CORNER_RADIUS, Number(match[1]));-});--test("global medium-radius shape cuts only the outer corner pixels", () => {- const rects = roundedWindowShape(100, 80, DEFAULT_WINDOW_CORNER_RADIUS);- assert.deepEqual(rects[0], { x: 9, y: 0, width: 82, height: 1 });- assert.deepEqual(rects[1], { x: 9, y: 79, width: 82, height: 1 });- assert.deepEqual(rects.at(-1), { x: 0, y: 12, width: 100, height: 56 });- assert.deepEqual(roundedWindowShape(100, 80, 0), []);-});--test("shape follows resize and becomes rectangular in maximized or fullscreen states", () => {+function makeWindow() {const window = new EventEmitter();let bounds = { x: 20, y: 30, width: 100, height: 80 };+ let contentBounds = { x: 0, y: 0, width: 100, height: 80 };let maximized = false;+ let borderRadius = null;let lastShape = null;+ const contentView = {+ getBounds: () => contentBounds,+ setBorderRadius: (radius) => { borderRadius = radius; },+ };+ window.contentView = contentView;window.getBounds = () => bounds;window.isDestroyed = () => false;window.isMaximized = () => maximized;window.isFullScreen = () => false;window.setFullScreen = (value) => window.emit(value ? "enter-full-screen" : "leave-full-screen");window.setShape = (rects) => { lastShape = rects; };- const shape = installWindowShape(window);- assert.deepEqual(lastShape[0], { x: 9, y: 0, width: 82, height: 1 });- bounds = { ...bounds, width: 120 };- window.emit("resize");- assert.equal(lastShape[0].width, 102);- maximized = true;- window.emit("maximize");- assert.deepEqual(lastShape, []);- maximized = false;- window.emit("unmaximize");- assert.equal(lastShape[0].width, 102);- setWindowFullScreen(window, true, true);- assert.deepEqual(lastShape, []);- setWindowFullScreen(window, false, true);- assert.equal(lastShape[0].width, 102);+ return {+ window,+ contentView,+ setBounds(next) {+ bounds = next;+ contentBounds = { x: 0, y: 0, width: next.width, height: next.height };+ },+ setMaximized(value) { maximized = value; },+ get borderRadius() { return borderRadius; },+ get lastShape() { return lastShape; },+ };+}++function makeScreen(scaleFactor = 1) {+ const screen = new EventEmitter();+ screen.getDisplayMatching = () => ({ scaleFactor });+ return {+ screen,+ setScaleFactor(next) { scaleFactor = next; },+ };+}++test("default window radius matches the global medium radius token", () => {+ const tokens = readFileSync(new URL("../src/styles/tokens.css", import.meta.url), "utf8");+ const match = tokens.match(/^\s*--radius-md:\s*(\d+(?:\.\d+)?)px;/m);+ assert.ok(match, "the global medium radius token is defined");+ assert.equal(DEFAULT_WINDOW_CORNER_RADIUS, Number(match[1]));+});++test("native hit region includes antialiased edge coverage for supported radii", () => {+ const defaultRegion = roundedWindowHitRegion(100, 80, DEFAULT_WINDOW_CORNER_RADIUS);+ assert.deepEqual(defaultRegion[0], { x: 7, y: 0, width: 86, height: 1 });+ assert.deepEqual(defaultRegion[1], { x: 7, y: 79, width: 86, height: 1 });+ assert.deepEqual(defaultRegion.at(-1), { x: 0, y: 12, width: 100, height: 56 });+ assert.deepEqual(roundedWindowHitRegion(100, 80, 0), []);+ assert.deepEqual(roundedWindowHitRegion(100, 80, 24)[0], {+ x: 17,+ y: 0,+ width: 66,+ height: 1,+ });+});++test("native hit region uses the actual content-view size", () => {+ const fixture = makeWindow();+ fixture.contentView.getBounds = () => ({ x: 0, y: 0, width: 96, height: 76 });++ installWindowShape(fixture.window, DEFAULT_WINDOW_CORNER_RADIUS);++ assert.deepEqual(fixture.lastShape[0], { x: 7, y: 0, width: 82, height: 1 });+ assert.deepEqual(fixture.lastShape.at(-1), { x: 0, y: 12, width: 96, height: 52 });+});++test("visible radius and native hit region follow size, DPI, and window state", () => {+ const fixture = makeWindow();+ const screen = makeScreen();+ let setShapeCalls = 0;+ const originalSetShape = fixture.window.setShape;+ fixture.window.setShape = (rects) => {+ setShapeCalls += 1;+ originalSetShape(rects);+ };++ const shape = installWindowShape(fixture.window, DEFAULT_WINDOW_CORNER_RADIUS, screen.screen);+ assert.equal(fixture.borderRadius, 12);+ assert.deepEqual(fixture.lastShape[0], { x: 7, y: 0, width: 86, height: 1 });++ fixture.setBounds({ x: 20, y: 30, width: 120, height: 90 });+ fixture.window.emit("resize");+ assert.equal(fixture.borderRadius, 12);+ assert.equal(fixture.lastShape[0].width, 106);++ screen.setScaleFactor(1.75);+ const callsBeforeDpiChange = setShapeCalls;+ screen.screen.emit("display-metrics-changed", {}, { scaleFactor: 1.75 }, ["scaleFactor"]);+ assert.equal(setShapeCalls, callsBeforeDpiChange + 1);+ assert.equal(fixture.borderRadius, 12);++ fixture.setMaximized(true);+ fixture.window.emit("maximize");+ assert.deepEqual(fixture.lastShape, []);+ assert.equal(fixture.borderRadius, 0);+ fixture.setMaximized(false);+ fixture.window.emit("unmaximize");+ assert.equal(fixture.borderRadius, 12);+ assert.equal(fixture.lastShape[0].width, 106);++ setWindowFullScreen(fixture.window, true, true);+ assert.deepEqual(fixture.lastShape, []);+ assert.equal(fixture.borderRadius, 0);+ setWindowFullScreen(fixture.window, false, true);+ assert.equal(fixture.borderRadius, 12);+assert.equal(shape.setRadius(100), 24);- assert.equal(lastShape[0].width < 102, true);- assert.equal(setWindowCornerRadius(window, 0), 0);- assert.deepEqual(lastShape, []);- assert.equal(setWindowCornerRadius(window, 4), 4);- assert.equal(lastShape[0].width, 116);- window.emit("closed");- assert.equal(window.listenerCount("resize"), 0);- assert.equal(setWindowCornerRadius(window, 8), null);+ assert.equal(fixture.borderRadius, 24);+ assert.equal(fixture.lastShape[0].width < 104, true);+ assert.equal(setWindowCornerRadius(fixture.window, 0), 0);+ assert.deepEqual(fixture.lastShape, []);+ assert.equal(fixture.borderRadius, 0);+ assert.equal(setWindowCornerRadius(fixture.window, 4), 4);+ assert.equal(fixture.borderRadius, 4);+ assert.equal(fixture.lastShape[0].width, 118);++ fixture.window.emit("closed");+ assert.equal(fixture.window.listenerCount("resize"), 0);+ assert.equal(fixture.window.listenerCount("move"), 0);+ assert.equal(screen.screen.listenerCount("display-metrics-changed"), 0);+ assert.equal(screen.screen.listenerCount("display-added"), 0);+ assert.equal(screen.screen.listenerCount("display-removed"), 0);+ assert.equal(setWindowCornerRadius(fixture.window, 8), null);});-test("native shape is re-applied after the window is shown or restored", () => {- const window = new EventEmitter();- let bounds = { x: 20, y: 30, width: 100, height: 80 };+test("native region and rounded clip are re-applied after show or restore", () => {+ const fixture = makeWindow();+ const screen = makeScreen();let setShapeCalls = 0;- window.getBounds = () => bounds;- window.isDestroyed = () => false;- window.isMaximized = () => false;- window.isFullScreen = () => false;- window.setShape = () => { setShapeCalls += 1; };+ let setBorderRadiusCalls = 0;+ fixture.window.setShape = () => { setShapeCalls += 1; };+ fixture.contentView.setBorderRadius = () => { setBorderRadiusCalls += 1; };- installWindowShape(window);+ installWindowShape(fixture.window, DEFAULT_WINDOW_CORNER_RADIUS, screen.screen);assert.equal(setShapeCalls, 1);+ assert.equal(setBorderRadiusCalls, 1);- window.emit("show");+ fixture.window.emit("show");assert.equal(setShapeCalls, 2);- window.emit("restore");+ assert.equal(setBorderRadiusCalls, 2);+ fixture.window.emit("restore");assert.equal(setShapeCalls, 3);+ assert.equal(setBorderRadiusCalls, 3);- window.emit("closed");- window.emit("show");- window.emit("restore");+ fixture.window.emit("closed");+ fixture.window.emit("show");+ fixture.window.emit("restore");assert.equal(setShapeCalls, 3);+ assert.equal(setBorderRadiusCalls, 3);});diff --git a/docs/adr/0317-windows-borderless-window-resize.md b/docs/adr/0317-windows-borderless-window-resize.mdindex 01e22c45b..3f559b3e3 100644--- a/docs/adr/0317-windows-borderless-window-resize.md+++ b/docs/adr/0317-windows-borderless-window-resize.md@@ -43,6 +43,15 @@ alongside its background colours. The selected theme supplies it through theexisting window-appearance IPC; removing the theme restores 12 DIP. Main validatesthe value and the calling renderer before changing the native shape.+### Proposed rendering amendment++ADR 0325 proposes moving visible Windows corner painting to the shared native+`contentView.setBorderRadius()` clip while retaining `setShape()` for the+native hit region. The proposal keeps this ADR's resize and minimum-size+contracts. It remains an implementation candidate until the Windows pixel,+click-through, DPI, and resize checks in E2E-167 pass; the accepted baseline+above is not qualified by source-level or mocked tests alone.+## Alternatives- Keep the thick frame: leaves the visible rim.@@ -68,7 +77,8 @@ the value and the calling renderer before changing the native shape.window geometry and lifecycle; this decision does not add a shadow setting.- `setShape` is an experimental Electron API and its pixel-row curve is notanti-aliased by Windows. Native corner hit testing is qualified on the target- Electron version rather than assumed from CSS.+ Electron version rather than assumed from CSS. ADR 0325 proposes a separate+ smooth draw clip, pending the Windows qualification described above.- The Plugin SDK gains one optional, permission-gated appearance property. Oldmanifests remain valid. No host RPC, database schema, or persisted formatchanges.diff --git a/docs/adr/0325-windows-window-corner-compositing.md b/docs/adr/0325-windows-window-corner-compositing.mdnew file mode 100644index 000000000..bfe76518e--- /dev/null+++ b/docs/adr/0325-windows-window-corner-compositing.md@@ -0,0 +1,80 @@+# ADR 0325: Smooth Windows main-window corner compositing++- Status: Proposed; implementation candidate awaits Windows native qualification+- Date: 2026-10-10+- Deciders: PI-Desktop maintainers+- Related: D635, D637, E2E-167, ADR 0248, ADR 0317++## Context++The Windows main window currently uses an opaque `BrowserWindow` background+and a row-based `setShape()` region. The native region controls drawing and+pointer hit testing together, so its integer rectangles produce a hard edge.+The opaque window background can also remain visible behind rounded content+and expose a second color at the lower corners. Renderer CSS alone cannot clip+native `WebContentsView` children such as the browser and plugin panel.++Electron 43.6.0 exposes `View.setBorderRadius()` on the shared `contentView`.+It clips the view tree with a smooth path, but its cutout still captures clicks.+The existing native region therefore remains necessary for click-through and+must be broad enough not to cut off antialiased pixels.++## Decision++Propose the following implementation for the Windows main window, subject to+the qualification gate below:++For the Windows main window only:++1. Create the `BrowserWindow` with a transparent outer surface.+2. Apply the built-in or validated plugin theme background to the shared+ `contentView`, then apply the selected radius with+ `contentView.setBorderRadius()`. Child `WebContentsView` content remains+ inside that common clip.+3. Keep `BrowserWindow.setShape()` as the native hit region. Generate it from+ the actual content-view dimensions and refresh it after resize, monitor/DPI,+ maximize, fullscreen, show, and restore transitions. The hit region includes+ antialias edge coverage without becoming the visible curve.+4. Preserve the 12 DIP default, integer 0–24 DIP authorized theme range,+ existing IPC validation and response, and square corners while maximized or+ fullscreen. A return to a normal window restores the selected radius.+5. Convert plugin `#RRGGBB` / `#RRGGBBAA` values to explicit `rgba(...)` before+ passing them to Electron. Keep Linux's native window background behavior+ and macOS vibrancy/background behavior unchanged.++No renderer CSS radius, resize IPC, database change, plugin API change, shadow+setting, outer margin, or companion window is introduced.++## Qualification gate++This decision remains proposed until a dedicated Windows desktop proves all+of the following with Electron 43.6.0:++- Composited screenshots show a smooth curve at all four corners and only+ expected blending between content and the known desktop background.+- Transparent corners and pixels outside the rounded silhouette pass hit+ testing through to the background window.+- Browser/plugin child views stay clipped by the common parent.+- Native edge and corner resizing, the work-area-capped 800×560 minimum,+ window-state restoration, and settled bounds persistence still work.+- The result holds at 100%, 125%, 150%, 175%, and 200% scaling. Different-DPI+ monitor movement is also checked when a suitable desktop is available.++`test:e2e:window-controls` samples native hit ownership. The isolated+`test:e2e:window-surface` fixture samples the composed screen pixels over+controlled light and dark backgrounds at radii 0, 12, and 24 DIP. If those+checks show that transparent click-through and smooth rendering cannot coexist,+do not accept the implementation; revise the approach and record the measured+failure first.++## Consequences++- The theme background is painted inside the same rounded native view that+ clips the renderer and its child views, removing a separate opaque corner+ plate.+- `setShape()` remains part of native interaction, but no longer defines the+ visible curve.+- Windows transparency and resize behavior require the native qualification+ above. This candidate is not release-qualified until that evidence exists.+- macOS/Linux windows, plugin standalone windows, floating widgets, persisted+ geometry, and the public window IPC remain unchanged.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 641b41dae..c61dcbc89 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -366,4 +366,5 @@ Each ADR includes:| 0322 | [Plugin providers appear in Add Service](0322-plugin-providers-in-add-service.md) | Accepted for implementation (D650; amends ADR 0259) || 0323 | [Make Session Title Generation a Standalone Plugin](0323-plugin-owned-session-titles.md) | Accepted (D652, amended by D654; supersedes ADR 0186) || 0324 | [Make Composer Prompt Enhancement an Optional Plugin](0324-plugin-owned-composer-prompt-enhancement.md) | Accepted (D653; supersedes ADR 0121) |+| 0325 | [Smooth Windows main-window corner compositing](0325-windows-window-corner-compositing.md) | Proposed (implementation candidate; Windows E2E pending) || plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) |diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex b5b90f435..ef336ee95 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1978,8 +1978,13 @@ the window-control state and fullscreen event use the tracked value.`window/setBackgroundColor` remains Electron-local and main-renderer-only. Itsoptional `cornerRadius` is an integer from 0 to 24 DIP; omission restores theWindows main-window default of 12 DIP, matching the global `--radius-md` token.-Main applies the native shape on theme selection and resize, and clears the-corner cutouts during maximize/fullscreen.+Main applies the selected radius on theme selection and resize, and makes the+surface rectangular during maximize/fullscreen. In the proposed ADR 0325+implementation, Windows keeps the outer native window transparent and applies+the theme color to the shared rounded content view; Linux keeps the native+window background, and macOS keeps its existing vibrancy behavior. This+internal rendering change does not alter the IPC request or response and+remains pending Windows native qualification.Malformed values fail with `INVALID_ARGUMENT` before changing the background.Plugin panel chrome uses a separate Electron-local`pi-plugin-panel-window-control` channel with the same four semantic actions,diff --git a/docs/spec/04-ux/07-ui-design-system.md b/docs/spec/04-ux/07-ui-design-system.mdindex 979a85354..43c5d92c7 100644--- a/docs/spec/04-ux/07-ui-design-system.md+++ b/docs/spec/04-ux/07-ui-design-system.md@@ -1123,13 +1123,17 @@ header-height background behind the excluded lane without covering its controls.disables the frameless `WS_THICKFRAME` rim while Electron 43.6's framelesshit test continues to own edge and corner resizing; no border is painted onthe left, right, or bottom. The Windows main window uses the global- `--radius-md` token (12 DIP) as its default rounded hit/draw shape: pixels- outside its corners have no fill or mouse target. A selected+ `--radius-md` token (12 DIP) as its default visible corner radius. The+ proposed ADR 0325 implementation draws that curve on the shared native+ content view and keeps the native shape for outside-corner click-through.+ This rendering change remains pending Windows native qualification; the+ accepted D637 implementation uses the native shape for both drawing and hit+ testing. A selectedplugin theme with `ui.window.appearance` may set `cornerRadius` to an integerfrom 0 through 24 DIP; removing that theme restores the 12 DIP global- default. The shape becomes- rectangular while maximized or fullscreen and follows every resize. Native- window background colors remain theme-owned inside the shape. Electron's borderless+ default. Corners become rectangular while maximized or fullscreen and follow+ every resize. Native window background colors remain theme-owned inside the+ clipped surface. Electron's borderlessfullscreen fallback fills the display without reporting `isFullScreen()`;Main tracks its state so toggling back restores the previous bounds andfullscreen geometry is never persisted. Frameless titlebar dragdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 7cd8d844f..7718f5da8 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -12159,12 +12159,12 @@ This test plan spec is accepted when:return. Release the pointer outside the original window bounds, thenmaximize and enter fullscreen; native hit regions must not blockwindow controls or content in those states.- 6. On Windows, inspect the default 12 DIP corner cutouts, matching the global- `--radius-md` token, before and after- resizing. Apply an authorized theme with `cornerRadius: 0`, then return to- a built-in theme. Reject an out-of-range radius without changing the shape.+ 6. On Windows, inspect the default 12 DIP rounded corners, matching the+ global `--radius-md` token, before and after resizing. Apply authorized+ theme radii of 0 and 24 DIP, then return to a built-in theme. Reject an+ out-of-range radius without changing the surface.7. On Windows, minimize and restore the window, then confirm all four native- corner cutouts still match the selected radius.+ corners still match the selected radius.- **Expected**: Native edge and corner hit regions remain available in framelesschrome, the minimum size remains 800×560 (capped to the displaywork area), and the recovery watchdog does not@@ -12174,19 +12174,25 @@ This test plan spec is accepted when:Electron's frameless native hit regions without the thick-frame rim; no left, bottom,or right native rim is visible. No temporarywork-panel reservation width is persisted or restored.- The four normal-window corners have no painted or interactive pixels outside- the active radius; the default is the global 12 DIP `--radius-md` radius, an- authorized theme may choose 0..24- DIP, and maximized/fullscreen windows are rectangular.+ The four normal-window corners follow the active radius; the default is the+ global 12 DIP `--radius-md` radius, an authorized theme may choose 0..24 DIP,+ and maximized/fullscreen windows are rectangular. In the proposed ADR 0325+ implementation, composited pixels blend only between the corner content and+ the known desktop background, the common content view clips browser/plugin+ children, and points beyond the antialiased pixel fringe pass hit testing+ through.- **Specs linked**: `03-runtime/01-ipc-protocol.md`,`04-ux/01-ui-ia.md`, `04-ux/07-ui-design-system.md`,`04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`,- ADR 0029 / ADR 0151 / ADR 0317+ ADR 0029 / ADR 0151 / ADR 0317 / ADR 0325- **Acceptance**: A (app shell), F (persistence), Quality- **Milestone**: M6+-- **Status**: `test:e2e:window-controls` covers corner cutouts before and after- minimize/restore, theme radius changes, fullscreen, maximize, and controls- in an isolated profile.+- **Status**: `test:e2e:window-controls` covers corner hit regions before and+ after minimize/restore, theme radius changes, fullscreen, maximize, and+ controls in an isolated profile. The isolated `test:e2e:window-surface`+ candidate samples controlled light/dark desktop backgrounds and the shared+ parent clip at radii 0, 12, and 24 DIP. Both Windows suites still require a+ dedicated Windows desktop; source tests do not qualify native compositing.`test:e2e:window-resize-native` adds physical Windows left/right/bottom/cornerdrags and the 800×560 minimum; run it on a dedicated interactive desktop,since another app can take foreground or pointer input during the gesture.diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 36815fbeb..58ee7bcde 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -31,7 +31,7 @@ This log freezes previously open questions into concrete decisions.| D634 | Remove bundled macOS first-launch guidance | **Amend D457 / ADR 0296 and the macOS distribution provisions of ADR 0232 / ADR 0204: neither macOS DMG nor ZIP ships `PI-Desktop-macOS-open.command`, `PI-Desktop-macOS-opening-help.txt`, or another bundled quarantine-clearing helper or opening note. The ZIP contains `PI-Desktop.app` at its root; the DMG remains a two-icon install. This applies to signed releases and local or opt-in unsigned debug builds. See ADR 0309 and E2E-196b.** | The signed release lane has eliminated the user need for an unsigned first-launch workaround; shipping it beside debug builds risks suggesting a Gatekeeper bypass. || D635 | Work-area-capped 800×560 window minimum | **Supersede the 1040×700 window minimum in D156 / D447 (and the matching clauses of ADR 0029 / ADR 0238) and the `1040..10000` `window/setWorkPanelChatWidth` range (ADR 0146): Electron enforces an 800×560 minimum, capped per dimension to the current display work area by `clampMinimumSizeToWorkArea`. The chat-width IPC and renderer accept `800..10000`. On narrow windows the existing `workPanelLayout` budget caps the docked panel so MainChat keeps its 450px floor, collapsing the sidebar first. See US-UI-19 and E2E-167.** | At 150% Windows scaling the work area is about 1280×672 DIP, so a fixed minimum could exceed the screen and leave the window unfittable. || D636 | Local permission approvals have no automatic deadline | **Amend D005 / ADR 0011 and supersede the local tool-permission timeout clauses in the runtime and UX specs: a permission-gated `tools.execute` request remains pending in host-core, the renderer, and the transport until the user chooses Allow once, Allow for session, or Deny, or the request is cancelled / the process shuts down. Remove the 120-second countdown and timeout fields from the local permission contract. Tool-specific execution budgets and the separate RACP/Plan approval lifetimes remain unchanged. See ADR 0310, issue #1214, and E2E-017.** | A visible permission request could be missed while the user worked elsewhere; automatic denial after 120 seconds silently prevented the requested action. Keeping cancellation and execution budgets preserves control and resource safety without turning inattention into a decision. |-| D637 | Remove the Windows frameless resize rim | **Disable the Windows main window's thick frame while retaining Electron 43.6 native frameless edge and corner resizing. Use the global `--radius-md` token (12 DIP) for the default native rounded shape; authorized plugin themes may choose an integer radius from 0 to 24 DIP. Keep the D635 minimum-size contract and existing work-panel resize ownership. See ADR 0317 and E2E-167.** | The thick frame paints an unwanted left, bottom, and right rim that themes cannot remove. Native hit testing and shape keep resizing and transparent outer corners without renderer resize IPC. The former 4 DIP cutout was nearly square and did not match the global radius scale. |+| D637 | Remove the Windows frameless resize rim | **Disable the Windows main window's thick frame while retaining Electron 43.6 native frameless edge and corner resizing. Use the global `--radius-md` token (12 DIP) for the default corner radius; authorized plugin themes may choose an integer radius from 0 to 24 DIP. Keep the D635 minimum-size contract and existing work-panel resize ownership. ADR 0325 proposes moving visible curve drawing to the shared content view while retaining `setShape()` for hit testing; that rendering change awaits Windows native qualification. See ADR 0317, ADR 0325, and E2E-167.** | The thick frame paints an unwanted left, bottom, and right rim that themes cannot remove. The former 4 DIP cutout was nearly square and did not match the global radius scale. The proposed shared content clip aims to smooth the visible curve and avoid a second opaque corner color while preserving native resizing and click-through; only Windows pixel and interaction evidence can qualify it. || D638 | Publish native Linux arm64 artifacts | **Amend D126 / D285 / D603 / ADR 0022: tag releases publish native Linux arm64 AppImage, deb, and rpm packages, built on GitHub's native `ubuntu-22.04-arm` runner and carrying an arm64 `pi-desktop-host-core`. The static Linux targets drop their pinned `arch` and take the workflow's `--x64` / `--arm64` flag; `linux.artifactName` becomes `PI-Desktop-<version>-linux-<arch>.AppImage`; each Linux lane verifies its architecture-named updater feed (`latest-linux.yml` on x64, `latest-linux-arm64.yml` on arm64); the ASAR export reads `linux-unpacked` or `linux-arm64-unpacked` and publishes `PI-Desktop-<version>-linux-<arch>.asar`. `pi-host-bundle` builds both Linux architectures and `PUBLISHED_TARGETS` gains `linux-arm64`. Updater ownership, signing, and delivery modes are unchanged. See ADR 0318, issue #1281, and E2E-192a.** | arm64 Linux devices could not install or run the published x64 artifact, and a cross-built or emulated lane would ship a mismatched Rust sidecar. || D639 | models.dev owns published chat-model metadata | **Supersede D136 / D266 and ADR `pi-ai-core-0991-authority` for chat metadata: the bundled and explicitly refreshed models.dev catalog supplies published chat-model limits, modalities, reasoning metadata, names, and prices. Prefer the selected official publisher; when it has no record, accept another publisher only for a safe, unambiguous match, otherwise keep generic metadata. The checked-in preset identities are the priority set; do not assert an unsupported fixed count of 39. Live endpoint/OAuth discovery still owns selectable IDs. Pi remains responsible for OAuth, wire identity, transport and typed non-chat operations, but never supplies sibling chat limits, reasoning or prices. Explicit user binding overrides remain authoritative. No credentials are sent to models.dev; no host schema/protocol or persistence change. See ADR `models-dev-catalog-authority` and E2E-162 / E2E-MODEL-catalog-window-correction-reaches-saved-bindings.** | A Pi sibling default assigned a 272,000-token window to GPT models whose selected models.dev records publish 1,050,000 tokens, changing the Settings display and runtime context budget. || D640 | User MCP tools keep the normal approval path | **`mcp_<serverId>_<tool>` calls are `medium` risk in host-core: under `ask` and `accept-edits` each call shows the approval card ("MCP server tool requires approval"), allow-once and allow-session keep their usual scope (one call / that exact tool name in that session), `auto` runs without a card, and Plan/Goal still deny. Annotations or risk values the MCP server declares about its own tools are ignored and never lower the path. Dispatch, read-only-mode handling and the `mcp_` namespace are unchanged; no host protocol or persistence change. See ADR `mcp-tool-approval-risk` and E2E-MCP-tool-requires-approval.** | MCP tools were auto-allowed as `low` risk, so a configured server could write files, call networks or run commands without any prompt under `ask`. Configuring a server is consent to launch it, not to every action its opaque tools take. |diff --git a/package.json b/package.jsonindex 0b84b9f66..01c7e0ff4 100644--- a/package.json+++ b/package.json@@ -57,6 +57,7 @@"test:e2e:layout": "node scripts/e2e-three-column-layout.mjs","test:e2e:window-controls": "node scripts/e2e-window-controls.mjs","test:e2e:window-resize-native": "node scripts/e2e-window-controls.mjs --native-edge-drag",+ "test:e2e:window-surface": "node scripts/e2e-window-surface.mjs","test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs","test:e2e:supervision": "node scripts/e2e-supervision.mjs","test:e2e:subagents": "node scripts/e2e-subagents.mjs",diff --git a/scripts/e2e-window-controls.mjs b/scripts/e2e-window-controls.mjsindex af3999aac..943b25b43 100644--- a/scripts/e2e-window-controls.mjs+++ b/scripts/e2e-window-controls.mjs@@ -108,7 +108,11 @@ async function checkControls(label) {assert.ok(ok, label);}-async function checkWindowsRoundedCorners(label, rounded = true, radius = defaultWindowCornerRadius) {+async function checkWindowsRoundedCorners(+ label,+ rounded = true,+ radius = rounded ? defaultWindowCornerRadius : 0,+) {if (process.platform !== "win32") return;let corners;let probeError;@@ -126,7 +130,8 @@ async function checkWindowsRoundedCorners(label, rounded = true, radius = defaulprobeError = undefined;return corners.topLeftCutout === rounded && corners.topRightCutout === rounded &&corners.bottomLeftCutout === rounded && corners.bottomRightCutout === rounded &&- corners.innerCornerOwned === true;+ corners.innerCornerOwned === true && corners.gridMismatches === 0 &&+ corners.insideSamples > 0 && (!rounded || corners.outsideSamples > 0);} catch (error) {probeError = String(error);return false;@@ -135,14 +140,17 @@ async function checkWindowsRoundedCorners(label, rounded = true, radius = defaul} catch (error) {throw new Error(`${label}: ${JSON.stringify(corners)}; ${probeError ?? String(error)}`);}- assert.deepEqual(corners, {- topLeftCutout: rounded,- topRightCutout: rounded,- bottomLeftCutout: rounded,- bottomRightCutout: rounded,- innerCornerOwned: true,- thickFrameStyle: false,- }, label);+ assert.deepEqual([+ corners.topLeftCutout,+ corners.topRightCutout,+ corners.bottomLeftCutout,+ corners.bottomRightCutout,+ ], [rounded, rounded, rounded, rounded], label);+ assert.equal(corners.innerCornerOwned, true, label);+ assert.equal(corners.thickFrameStyle, false, label);+ assert.equal(corners.gridMismatches, 0, `${label}: native corner hit grid`);+ assert.ok(corners.insideSamples > 0, `${label}: inside hit samples`);+ if (rounded) assert.ok(corners.outsideSamples > 0, `${label}: outside click-through samples`);console.log(`PASS ${label}: ${JSON.stringify(corners)}`);}@@ -325,6 +333,10 @@ try {await checkWindowsRoundedCorners("invalid radius leaves the current shape", false);assert.equal((await setRadius(defaultWindowCornerRadius)).ok, true);await checkWindowsRoundedCorners("theme switch restores the global radius token");+ assert.equal((await setRadius(24)).ok, true);+ await checkWindowsRoundedCorners("authorized theme can request 24 DIP corners", true, 24);+ assert.equal((await setRadius(defaultWindowCornerRadius)).ok, true);+ await checkWindowsRoundedCorners("returning to the default radius restores 12 DIP corners");const loaded = await evaluate(`window.piDesktop.invoke('pi-desktop/plugin/loadDevConfirm',{ path: ${JSON.stringify(radiusPluginPath)}, grantedPermissions: ['ui.theme', 'ui.window.appearance'] }diff --git a/scripts/e2e-window-surface.mjs b/scripts/e2e-window-surface.mjsnew file mode 100644index 000000000..d45ec6683--- /dev/null+++ b/scripts/e2e-window-surface.mjs@@ -0,0 +1,132 @@+#!/usr/bin/env node+/** Sample the composed Windows surface of production window helpers in isolation. */+import assert from "node:assert/strict";+import { spawn, execFile } from "node:child_process";+import { promisify } from "node:util";+import { once } from "node:events";+import { mkdir, mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { setTimeout as delay } from "node:timers/promises";+import { assertDesktopBuild, repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";++if (process.platform !== "win32") {+ console.log("SKIP window surface probe: requires a dedicated interactive Windows desktop");+ process.exit(0);+}++const root = repositoryRoot();+const { appDir } = assertDesktopBuild(root);+const { electronBinary } = resolveElectronBinary(root);+const fixtureDir = join(root, "scripts", "e2e", "fixtures", "window-surface");+const execFileAsync = promisify(execFile);+const temp = await mkdtemp(join(tmpdir(), "pi-window-surface-"));+const userArtifactDir = process.env.PI_DESKTOP_WINDOW_SURFACE_ARTIFACT_DIR;+const artifactDir = userArtifactDir+ ? resolve(userArtifactDir)+ : await mkdtemp(join(tmpdir(), "pi-window-surface-artifacts-"));+await mkdir(artifactDir, { recursive: true });++function waitForFixtureReady(child) {+ let output = "";+ let lineBuffer = "";+ let ready = false;+ let rejectReady;+ const result = new Promise((resolveReady, reject) => {+ rejectReady = reject;+ child.stdout.on("data", (chunk) => {+ const text = String(chunk);+ output = (output + text).slice(-8000);+ lineBuffer += text;+ const lines = lineBuffer.split(/\r?\n/);+ lineBuffer = lines.pop() ?? "";+ for (const line of lines) {+ try {+ const value = JSON.parse(line);+ if (value.type === "ready") {+ ready = true;+ resolveReady(value);+ return;+ }+ } catch {+ // Keep non-JSON Electron output for a useful timeout diagnostic.+ }+ }+ });+ child.stderr.on("data", (chunk) => { output = (output + String(chunk)).slice(-8000); });+ child.once("error", reject);+ child.once("exit", (code, signal) => {+ if (!ready) reject(new Error(`Surface fixture exited before ready (${code ?? signal}): ${output}`));+ });+ });+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(`Surface fixture did not become ready: ${output}`)), 45_000);+ });+ return Promise.race([result, timeout]).finally(() => clearTimeout(timer));+}++async function stopFixture(child) {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const exited = once(child, "exit");+ child.kill();+ await Promise.race([exited, delay(5000)]);+}++async function runSurfaceCase(radius, backdropColor, backdropName) {+ const profile = join(temp, `profile-${radius}-${backdropName}`);+ const env = { ...process.env,+ PI_DESKTOP_ELECTRON_PACKAGE: join(appDir, "node_modules", "electron"),+ PI_DESKTOP_WINDOW_SHAPE: join(appDir, "electron", "main", "window-shape.ts"),+ PI_DESKTOP_WINDOW_BACKGROUND: join(appDir, "electron", "main", "window-background.ts"),+ PI_DESKTOP_SURFACE_RADIUS: String(radius),+ PI_DESKTOP_SURFACE_BACKDROP: backdropColor,+ };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(electronBinary, [fixtureDir, `--user-data-dir=${profile}`], {+ cwd: root,+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ try {+ const fixture = await waitForFixtureReady(child);+ const screenshotPath = join(artifactDir, `${backdropName}-radius-${radius}.png`);+ const { stdout } = await execFileAsync("pwsh.exe", [+ "-NoLogo", "-NoProfile", "-File",+ join(root, "scripts", "e2e", "probe-window-surface.ps1"),+ String(child.pid),+ fixture.title,+ String(radius),+ backdropColor,+ screenshotPath,+ ], { timeout: 30_000, maxBuffer: 2_000_000 });+ const result = JSON.parse(stdout.trim());+ assert.equal(result.totalMismatches, 0, `${backdropName}, radius ${radius}: ${JSON.stringify(result.mismatches)}`);+ assert.ok(result.insideSamples > 0, `${backdropName}, radius ${radius}: interior samples`);+ if (radius > 0) {+ assert.ok(result.outsideSamples > 0, `${backdropName}, radius ${radius}: exterior samples`);+ for (const [corner, values] of Object.entries(result.cornerResults)) {+ assert.ok(values.edgeBlendPixels > 0, `${backdropName}, radius ${radius}: ${corner} has an antialiased edge`);+ }+ }+ console.log(`PASS surface ${backdropName}, ${radius} DIP: dpi=${result.dpi}, ` ++ `scale=${result.scaleFactor}, physical=${result.physicalBounds.width}x${result.physicalBounds.height}, ` ++ `edge blends=${result.edgeBlendPixels}, screenshot=${screenshotPath}`);+ } finally {+ await stopFixture(child);+ }+}++try {+ for (const [backdropName, backdropColor] of [+ ["light", "#eaf0f6"],+ ["dark", "#172b3f"],+ ]) {+ for (const radius of [0, 12, 24]) {+ await runSurfaceCase(radius, backdropColor, backdropName);+ }+ }+} finally {+ await rm(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ console.log(`Window surface screenshots: ${artifactDir}`);+}diff --git a/scripts/e2e/fixtures/window-surface/main.mjs b/scripts/e2e/fixtures/window-surface/main.mjsnew file mode 100644index 000000000..79a9e51d4--- /dev/null+++ b/scripts/e2e/fixtures/window-surface/main.mjs@@ -0,0 +1,113 @@+import { createRequire } from "node:module";+import { pathToFileURL } from "node:url";++const require = createRequire(import.meta.url);+const electron = require(process.env.PI_DESKTOP_ELECTRON_PACKAGE);+const { app, BrowserWindow, WebContentsView, screen } = electron;+const { installWindowShape } = await import(+ pathToFileURL(process.env.PI_DESKTOP_WINDOW_SHAPE).href+);+const { applyMainWindowBackground, mainWindowBackgroundOptions } = await import(+ pathToFileURL(process.env.PI_DESKTOP_WINDOW_BACKGROUND).href+);++const radius = Number(process.env.PI_DESKTOP_SURFACE_RADIUS);+const backdropColor = process.env.PI_DESKTOP_SURFACE_BACKDROP;+const title = "PI Desktop Surface Candidate";+let backdropWindow;+let mainWindow;++function dataUrl(markup) {+ return `data:text/html;charset=utf-8,${encodeURIComponent(markup)}`;+}++function mainPage() {+ return dataUrl(`<!doctype html>+ <html><head><meta charset="utf-8"><style>+ * { box-sizing: border-box; }+ html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }+ body { display: flex; background: #f6f6f6; }+ .half { width: 50%; height: 100%; }+ .light { background: #f6f6f6; }+ .dark { background: #181818; }+ </style></head><body><div class="half light"></div><div class="half dark"></div></body></html>`);+}++function childPage() {+ return dataUrl(`<!doctype html>+ <html><head><meta charset="utf-8"><style>+ html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: #d61f69; }+ </style></head><body></body></html>`);+}++app.whenReady().then(async () => {+ if (process.platform !== "win32") throw new Error("surface fixture requires Windows");+ if (!Number.isInteger(radius) || radius < 0 || radius > 24) {+ throw new Error(`invalid fixture radius: ${process.env.PI_DESKTOP_SURFACE_RADIUS}`);+ }++ const display = screen.getPrimaryDisplay();+ const { workArea } = display;+ const width = Math.min(840, workArea.width - 40);+ const height = Math.min(600, workArea.height - 40);+ if (width < 320 || height < 240) throw new Error("primary display is too small for the fixture");++ backdropWindow = new BrowserWindow({+ x: workArea.x,+ y: workArea.y,+ width: workArea.width,+ height: workArea.height,+ frame: false,+ focusable: false,+ skipTaskbar: true,+ resizable: false,+ backgroundColor: backdropColor,+ });+ backdropWindow.showInactive();++ mainWindow = new BrowserWindow({+ x: workArea.x + Math.floor((workArea.width - width) / 2),+ y: workArea.y + Math.floor((workArea.height - height) / 2),+ width,+ height,+ minWidth: Math.min(800, workArea.width),+ minHeight: Math.min(560, workArea.height),+ title,+ frame: false,+ thickFrame: false,+ resizable: true,+ show: false,+ ...mainWindowBackgroundOptions(process.platform, "#fafafa"),+ });+ mainWindow.webContents.on("page-title-updated", (event) => event.preventDefault());+ installWindowShape(mainWindow, radius, screen);+ applyMainWindowBackground(mainWindow, process.platform, "#fafafa");++ const childView = new WebContentsView({+ webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },+ });+ mainWindow.contentView.addChildView(childView);+ // Let the child view extend beyond the parent bounds at the lower-right so+ // the pixel probe verifies the common content-view clip on native children.+ childView.setBounds({ x: width - 48, y: height - 48, width: 96, height: 96 });++ await Promise.all([+ mainWindow.loadURL(mainPage()),+ childView.webContents.loadURL(childPage()),+ ]);+ mainWindow.show();+ mainWindow.focus();++ process.stdout.write(`${JSON.stringify({+ type: "ready",+ processId: process.pid,+ title,+ width,+ height,+ radius,+ backdropColor,+ scaleFactor: display.scaleFactor,+ })}\n`);+});++app.on("window-all-closed", () => app.quit());diff --git a/scripts/e2e/fixtures/window-surface/package.json b/scripts/e2e/fixtures/window-surface/package.jsonnew file mode 100644index 000000000..11dc9e364--- /dev/null+++ b/scripts/e2e/fixtures/window-surface/package.json@@ -0,0 +1,6 @@+{+ "name": "pi-desktop-window-surface-fixture",+ "private": true,+ "type": "module",+ "main": "main.mjs"+}diff --git a/scripts/e2e/probe-window-corners.ps1 b/scripts/e2e/probe-window-corners.ps1index b1a251a8c..403838282 100644--- a/scripts/e2e/probe-window-corners.ps1+++ b/scripts/e2e/probe-window-corners.ps1@@ -16,9 +16,12 @@ public static class CornerProbe {[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr window, uint flags);[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();+ [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);+ [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);}'@+[void][CornerProbe]::SetThreadDpiAwarenessContext([IntPtr](-4))$appWindow = [System.Diagnostics.Process]::GetProcessById($targetProcessId).MainWindowHandleif ($appWindow -eq [IntPtr]::Zero) { throw 'E2E main window is unavailable' }[void][CornerProbe]::SetForegroundWindow($appWindow)@@ -28,6 +31,10 @@ if ([CornerProbe]::GetForegroundWindow() -ne $appWindow) {}$rect = [CornerRect]::new()if (-not [CornerProbe]::GetWindowRect($appWindow, [ref]$rect)) { throw 'Cannot read E2E window bounds' }+$dpi = [CornerProbe]::GetDpiForWindow($appWindow)+if ($dpi -eq 0) { throw 'Cannot read E2E window DPI' }+$scaleFactor = $dpi / 96.0+$radiusPixels = $cornerRadius * $scaleFactorfunction Test-AppAt([int]$pointX, [int]$pointY) {$point = [CornerPoint]::new()@@ -36,11 +43,84 @@ function Test-AppAt([int]$pointX, [int]$pointY) {return [CornerProbe]::GetAncestor([CornerProbe]::WindowFromPoint($point), 2) -eq $appWindow}+function Test-CornerGrid([string]$corner) {+ $mismatches = 0+ $insideSamples = 0+ $outsideSamples = 0+ $extent = [int][Math]::Ceiling($radiusPixels + 3)+ # The conservative integer-DIP hit region includes the rasterized AA edge;+ # scale the ignored fringe to physical pixels for high-DPI displays.+ $boundaryTolerance = 1.5 * $scaleFactor+ for ($localY = 0; $localY -le $extent; $localY += 1) {+ for ($localX = 0; $localX -le $extent; $localX += 1) {+ $pixelX = $localX + 0.5+ $pixelY = $localY + 0.5++ if ($cornerRadius -eq 0 -or $pixelX -ge $radiusPixels -or $pixelY -ge $radiusPixels) {+ $expectedInside = $true+ $boundaryDistance = [double]::PositiveInfinity+ } else {+ $dx = $radiusPixels - $pixelX+ $dy = $radiusPixels - $pixelY+ $distance = [Math]::Sqrt($dx * $dx + $dy * $dy)+ $boundaryDistance = [Math]::Abs($distance - $radiusPixels)+ $expectedInside = $distance -lt $radiusPixels+ }++ # Ignore the one-pixel AA fringe, but prove that the inner corner is+ # reachable and that points fully outside the curve fall through.+ if ($boundaryDistance -le $boundaryTolerance) { continue }+ $screenX = $rect.Left + [int][Math]::Floor($pixelX)+ $screenY = $rect.Top + [int][Math]::Floor($pixelY)+ if ($corner -eq 'topRight' -or $corner -eq 'bottomRight') {+ $screenX = $rect.Right - 1 - $localX+ }+ if ($corner -eq 'bottomLeft' -or $corner -eq 'bottomRight') {+ $screenY = $rect.Bottom - 1 - $localY+ }+ $actualInside = Test-AppAt $screenX $screenY+ if ($expectedInside) { $insideSamples += 1 } else { $outsideSamples += 1 }+ if ($actualInside -ne $expectedInside) { $mismatches += 1 }+ }+ }+ return @{+ mismatches = $mismatches+ insideSamples = $insideSamples+ outsideSamples = $outsideSamples+ }+}++$topLeftCutout = -not (Test-AppAt $rect.Left $rect.Top)+$topRightCutout = -not (Test-AppAt ($rect.Right - 1) $rect.Top)+$bottomLeftCutout = -not (Test-AppAt $rect.Left ($rect.Bottom - 1))+$bottomRightCutout = -not (Test-AppAt ($rect.Right - 1) ($rect.Bottom - 1))+$innerOffset = [int][Math]::Ceiling($radiusPixels) + 2+$innerCornerOwned = Test-AppAt ($rect.Left + $innerOffset) ($rect.Top + $innerOffset)+$grid = @{}+$gridMismatches = 0+$insideSamples = 0+$outsideSamples = 0+foreach ($corner in @('topLeft', 'topRight', 'bottomLeft', 'bottomRight')) {+ $result = Test-CornerGrid $corner+ $grid[$corner] = $result+ $gridMismatches += $result.mismatches+ $insideSamples += $result.insideSamples+ $outsideSamples += $result.outsideSamples+}+@{- topLeftCutout = -not (Test-AppAt $rect.Left $rect.Top)- topRightCutout = -not (Test-AppAt ($rect.Right - 1) $rect.Top)- bottomLeftCutout = -not (Test-AppAt $rect.Left ($rect.Bottom - 1))- bottomRightCutout = -not (Test-AppAt ($rect.Right - 1) ($rect.Bottom - 1))- innerCornerOwned = Test-AppAt ($rect.Left + $cornerRadius + 1) ($rect.Top + $cornerRadius + 1)+ topLeftCutout = $topLeftCutout+ topRightCutout = $topRightCutout+ bottomLeftCutout = $bottomLeftCutout+ bottomRightCutout = $bottomRightCutout+ innerCornerOwned = $innerCornerOwnedthickFrameStyle = ([CornerProbe]::GetWindowLong($appWindow, -16) -band 0x00040000) -ne 0-} | ConvertTo-Json -Compress+ dpi = $dpi+ scaleFactor = $scaleFactor+ radiusDip = $cornerRadius+ physicalBounds = @{ width = $rect.Right - $rect.Left; height = $rect.Bottom - $rect.Top }+ gridMismatches = $gridMismatches+ insideSamples = $insideSamples+ outsideSamples = $outsideSamples+ corners = $grid+} | ConvertTo-Json -Compress -Depth 5diff --git a/scripts/e2e/probe-window-surface.ps1 b/scripts/e2e/probe-window-surface.ps1new file mode 100644index 000000000..22c964573--- /dev/null+++ b/scripts/e2e/probe-window-surface.ps1@@ -0,0 +1,176 @@+param(+ [Parameter(Mandatory = $true)][int]$targetProcessId,+ [Parameter(Mandatory = $true)][string]$windowTitle,+ [Parameter(Mandatory = $true)][int]$cornerRadius,+ [Parameter(Mandatory = $true)][string]$backdropColor,+ [Parameter(Mandatory = $true)][string]$screenshotPath+)++$ErrorActionPreference = 'Stop'+Add-Type -AssemblyName System.Drawing+Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;+public struct SurfaceRect { public int Left; public int Top; public int Right; public int Bottom; }+public static class SurfaceProbe {+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string className, string windowName);+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId);+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out SurfaceRect rect);+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();+ [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);+ [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);+ [DllImport("dwmapi.dll")] public static extern int DwmFlush();+}+'@++[void][SurfaceProbe]::SetThreadDpiAwarenessContext([IntPtr](-4))+$window = [SurfaceProbe]::FindWindow($null, $windowTitle)+if ($window -eq [IntPtr]::Zero) { throw "Cannot find surface fixture window: $windowTitle" }+$ownerProcessId = [uint32]0+[void][SurfaceProbe]::GetWindowThreadProcessId($window, [ref]$ownerProcessId)+if ($ownerProcessId -ne $targetProcessId) { throw 'Surface fixture window belongs to another process' }+[void][SurfaceProbe]::SetForegroundWindow($window)+if ([SurfaceProbe]::GetForegroundWindow() -ne $window) {+ throw 'Surface fixture window is not foreground'+}+[void][SurfaceProbe]::DwmFlush()++$rect = [SurfaceRect]::new()+if (-not [SurfaceProbe]::GetWindowRect($window, [ref]$rect)) { throw 'Cannot read surface fixture bounds' }+$dpi = [SurfaceProbe]::GetDpiForWindow($window)+if ($dpi -eq 0) { throw 'Cannot read surface fixture DPI' }+$scaleFactor = $dpi / 96.0+$radiusPixels = $cornerRadius * $scaleFactor+$windowWidth = $rect.Right - $rect.Left+$windowHeight = $rect.Bottom - $rect.Top++function Convert-HexColor([string]$value) {+ if ($value -notmatch '^#?([0-9a-fA-F]{6})$') { throw "Invalid probe color: $value" }+ $hex = $Matches[1]+ return [System.Drawing.Color]::FromArgb(+ [Convert]::ToInt32($hex.Substring(0, 2), 16),+ [Convert]::ToInt32($hex.Substring(2, 2), 16),+ [Convert]::ToInt32($hex.Substring(4, 2), 16)+ )+}++function Test-ColorNear($actual, $expected, [int]$tolerance) {+ return [Math]::Abs($actual.R - $expected.R) -le $tolerance -and+ [Math]::Abs($actual.G - $expected.G) -le $tolerance -and+ [Math]::Abs($actual.B - $expected.B) -le $tolerance+}++function Test-ColorBlend($actual, $foreground, $background, [int]$tolerance) {+ foreach ($channel in @('R', 'G', 'B')) {+ $minimum = [Math]::Min($foreground.$channel, $background.$channel) - $tolerance+ $maximum = [Math]::Max($foreground.$channel, $background.$channel) + $tolerance+ if ($actual.$channel -lt $minimum -or $actual.$channel -gt $maximum) { return $false }+ }+ return $true+}++$backdrop = Convert-HexColor $backdropColor+$lightContent = Convert-HexColor '#f6f6f6'+$darkContent = Convert-HexColor '#181818'+$childContent = Convert-HexColor '#d61f69'+$childInset = [int][Math]::Round(48 * $scaleFactor)+$extent = [int][Math]::Ceiling($radiusPixels + 3)+$boundaryTolerance = [Math]::Max(1.25, $scaleFactor * 0.75)+$colorTolerance = 3+$results = @{}+$mismatches = [System.Collections.Generic.List[object]]::new()+$totalMismatches = 0+$edgeBlendPixels = 0+$insideSamples = 0+$outsideSamples = 0+$bitmap = [System.Drawing.Bitmap]::new($windowWidth, $windowHeight)+$graphics = [System.Drawing.Graphics]::FromImage($bitmap)+try {+ $graphics.CopyFromScreen($rect.Left, $rect.Top, 0, 0, $bitmap.Size, [System.Drawing.CopyPixelOperation]::SourceCopy)+ $bitmap.Save($screenshotPath, [System.Drawing.Imaging.ImageFormat]::Png)++ foreach ($corner in @('topLeft', 'topRight', 'bottomLeft', 'bottomRight')) {+ $cornerMismatches = 0+ $cornerBlends = 0+ for ($localY = 0; $localY -le $extent; $localY += 1) {+ for ($localX = 0; $localX -le $extent; $localX += 1) {+ $fromLeft = $localX+ $fromTop = $localY+ if ($corner -eq 'topRight' -or $corner -eq 'bottomRight') { $fromLeft = $windowWidth - 1 - $localX }+ if ($corner -eq 'bottomLeft' -or $corner -eq 'bottomRight') { $fromTop = $windowHeight - 1 - $localY }++ $pixelX = $localX + 0.5+ $pixelY = $localY + 0.5+ if ($cornerRadius -eq 0 -or $pixelX -ge $radiusPixels -or $pixelY -ge $radiusPixels) {+ $insideCurve = $true+ $boundaryDistance = [double]::PositiveInfinity+ } else {+ $dx = $radiusPixels - $pixelX+ $dy = $radiusPixels - $pixelY+ $distance = [Math]::Sqrt($dx * $dx + $dy * $dy)+ $insideCurve = $distance -lt $radiusPixels+ $boundaryDistance = [Math]::Abs($distance - $radiusPixels)+ }++ $actual = $bitmap.GetPixel($fromLeft, $fromTop)+ if (-not $insideCurve) {+ $outsideSamples += 1+ $valid = Test-ColorNear $actual $backdrop $colorTolerance+ } else {+ $insideSamples += 1+ if ($fromLeft -ge ($windowWidth - $childInset) -and $fromTop -ge ($windowHeight - $childInset)) {+ $foreground = $childContent+ } elseif ($fromLeft -lt ($windowWidth / 2)) {+ $foreground = $lightContent+ } else {+ $foreground = $darkContent+ }+ if ($boundaryDistance -le $boundaryTolerance) {+ $valid = Test-ColorBlend $actual $foreground $backdrop $colorTolerance+ if ($valid -and -not (Test-ColorNear $actual $foreground $colorTolerance) -and+ -not (Test-ColorNear $actual $backdrop $colorTolerance)) {+ $cornerBlends += 1+ $edgeBlendPixels += 1+ }+ } else {+ $valid = Test-ColorNear $actual $foreground $colorTolerance+ }+ }++ if (-not $valid) {+ $cornerMismatches += 1+ if ($mismatches.Count -lt 32) {+ $mismatches.Add(@{+ corner = $corner+ x = $fromLeft+ y = $fromTop+ expectedSurface = if ($insideCurve) { 'content' } else { 'backdrop' }+ actual = "#$($actual.R.ToString('X2'))$($actual.G.ToString('X2'))$($actual.B.ToString('X2'))"+ })+ }+ }+ }+ }+ $results[$corner] = @{ mismatches = $cornerMismatches; edgeBlendPixels = $cornerBlends }+ $totalMismatches += $cornerMismatches+ }+} finally {+ $graphics.Dispose()+ $bitmap.Dispose()+}++@{+ dpi = $dpi+ scaleFactor = $scaleFactor+ radiusDip = $cornerRadius+ physicalBounds = @{ width = $windowWidth; height = $windowHeight }+ backdropColor = $backdropColor+ totalMismatches = $totalMismatches+ cornerResults = $results+ insideSamples = $insideSamples+ outsideSamples = $outsideSamples+ edgeBlendPixels = $edgeBlendPixels+ mismatches = @($mismatches)+ screenshotPath = $screenshotPath+} | ConvertTo-Json -Compress -Depth 6