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(window): use native DWM corners on Windows 11
vastsa3bc5b2dd9913
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex 9b34ce729..968e2d451 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -35,6 +35,10 @@ import { readWindowState, writeWindowState } from "../window-preferences";import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";import { isWindowFullScreen } from "../window-fullscreen";import { DEFAULT_WINDOW_CORNER_RADIUS, installWindowShape } from "../window-shape";+import {+ installWindows11CornerController,+ usesWindows11NativeCorners,+} from "../window-native-corners";import { applyMainWindowBackground, mainWindowBackgroundOptions } from "../window-background";import { recoverRendererAfterGone } from "../renderer-recovery";@@ -167,6 +171,10 @@ export async function createWindow({const initialWindowBackground = builtinWindowBackground(nativeTheme.shouldUseDarkColors ? "dark" : "light",);+ const windows11NativeCorners = usesWindows11NativeCorners(+ process.platform,+ process.getSystemVersion(),+ );windowState.mainWindow = new BrowserWindow({...(restoredBounds ?? { width: 1200, height: 800 }),minWidth: initialMinWidth,@@ -194,7 +202,12 @@ export async function createWindow({: {frame: false,...(process.platform === "win32" ? { thickFrame: false } : {}),- ...mainWindowBackgroundOptions(process.platform, initialWindowBackground),+ ...mainWindowBackgroundOptions(+ process.platform,+ initialWindowBackground,+ windows11NativeCorners,+ initialWindowBackground,+ ),}),...(process.platform === "win32"? {@@ -214,9 +227,25 @@ export async function createWindow({});const window = windowState.mainWindow;if (process.platform === "win32") {- installWindowShape(window, DEFAULT_WINDOW_CORNER_RADIUS, screen);+ if (windows11NativeCorners) {+ await installWindows11CornerController(+ window,+ DEFAULT_WINDOW_CORNER_RADIUS,+ () => windowState.host,+ screen,+ logger,+ );+ } else {+ installWindowShape(window, DEFAULT_WINDOW_CORNER_RADIUS, screen);+ }}- applyMainWindowBackground(window, process.platform, initialWindowBackground);+ applyMainWindowBackground(+ window,+ process.platform,+ initialWindowBackground,+ windows11NativeCorners,+ initialWindowBackground,+ );suppressLinuxFramelessSystemMenu(window);const initialBounds = window.getBounds();windowState.workPanelBaseBounds = restoredBoundsdiff --git a/apps/desktop/electron/main/host-process.ts b/apps/desktop/electron/main/host-process.tsindex 32a91ad1d..7e08042d8 100644--- a/apps/desktop/electron/main/host-process.ts+++ b/apps/desktop/electron/main/host-process.ts@@ -121,7 +121,10 @@ export class HostProcess extends RuntimeHostProcess {// Only Electron knows whether this build runs from `resources/` or a// source checkout, so it resolves the bundled-plugin directory and// host-core simply reconciles its registry against it (ADR 0105).- env: builtinPlugins ? { PI_DESKTOP_BUILTIN_PLUGINS_DIR: builtinPlugins } : {},+ env: {+ PI_DESKTOP_ELECTRON_PID: String(process.pid),+ ...(builtinPlugins ? { PI_DESKTOP_BUILTIN_PLUGINS_DIR: builtinPlugins } : {}),+ },onStderr: onStderr ?? fallbackStderrLogger,diagnoseFailure: diagnoseHostFailure,});diff --git a/apps/desktop/electron/main/ipc/window-ipc.ts b/apps/desktop/electron/main/ipc/window-ipc.tsindex 692b81b7d..a1d61cb1c 100644--- a/apps/desktop/electron/main/ipc/window-ipc.ts+++ b/apps/desktop/electron/main/ipc/window-ipc.ts@@ -20,8 +20,8 @@ import {} from "../work-panel-window";import {DEFAULT_WINDOW_CORNER_RADIUS,- setWindowCornerRadius,} from "../window-shape";+import { applyWindowCornerRadius, usesWindows11NativeCorners } from "../window-native-corners";import { applyMainWindowBackground } from "../window-background";import type { IpcRegistrar } from "./types";@@ -136,13 +136,23 @@ export function registerWindowIpc({const color = isWindowBackgroundColor(requested)? requested: builtinWindowBackground(theme);+ const windows11NativeCorners = usesWindows11NativeCorners(+ process.platform,+ process.getSystemVersion(),+ );+ applyMainWindowBackground(+ mainWindow,+ process.platform,+ color,+ windows11NativeCorners,+ builtinWindowBackground(theme),+ );const cornerRadius = process.platform === "win32"- ? setWindowCornerRadius(+ ? await applyWindowCornerRadius(mainWindow,typeof requestedRadius === "number" ? requestedRadius : DEFAULT_WINDOW_CORNER_RADIUS,): null;- 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.tsindex 1afee82ce..5935756b9 100644--- a/apps/desktop/electron/main/window-background.ts+++ b/apps/desktop/electron/main/window-background.ts@@ -23,8 +23,16 @@ export function toElectronBackgroundColor(color: string): string {export function mainWindowBackgroundOptions(platform: BackgroundPlatform,color: string,+ windows11NativeCorners = false,+ opaqueFallbackColor = color,): Pick<BrowserWindowConstructorOptions, "backgroundColor" | "transparent"> {if (platform === "win32") {+ if (windows11NativeCorners) {+ return {+ transparent: false,+ backgroundColor: toOpaqueElectronBackgroundColor(color, opaqueFallbackColor),+ };+ }return { transparent: true, backgroundColor: "#00000000" };}if (platform === "darwin") return {};@@ -36,14 +44,47 @@ export function applyMainWindowBackground(window: BackgroundWindow,platform: BackgroundPlatform,color: string,+ windows11NativeCorners = false,+ opaqueFallbackColor = color,): boolean {if (platform === "darwin") return false;- const electronColor = toElectronBackgroundColor(color);- if (platform === "win32") {+ const useOpaqueWindowsSurface = platform === "win32" && windows11NativeCorners;+ const electronColor = useOpaqueWindowsSurface+ ? toOpaqueElectronBackgroundColor(color, opaqueFallbackColor)+ : toElectronBackgroundColor(color);+ if (platform === "win32" && !useOpaqueWindowsSurface) {window.contentView.setBackgroundColor(electronColor);} else {window.setBackgroundColor(electronColor);}return true;}++/**+ * Windows 11's DWM corner path requires an opaque top-level surface. Preserve+ * a plugin theme's translucent color by flattening it onto the host palette.+ */+function toOpaqueElectronBackgroundColor(color: string, fallbackColor: string): string {+ if (!isWindowBackgroundColor(color) || !isWindowBackgroundColor(fallbackColor)) {+ throw new TypeError("invalid window background color");+ }++ const foreground = [+ Number.parseInt(color.slice(1, 3), 16),+ Number.parseInt(color.slice(3, 5), 16),+ Number.parseInt(color.slice(5, 7), 16),+ ];+ const background = [+ Number.parseInt(fallbackColor.slice(1, 3), 16),+ Number.parseInt(fallbackColor.slice(3, 5), 16),+ Number.parseInt(fallbackColor.slice(5, 7), 16),+ ];+ const alpha = color.length === 9 ? Number.parseInt(color.slice(7, 9), 16) / 255 : 1;+ const channels = foreground.map((value, index) => {+ const behind = background[index];+ if (behind === undefined) throw new TypeError("invalid window background color");+ return Math.round(value * alpha + behind * (1 - alpha));+ });+ return `#${channels.map((value) => value.toString(16).padStart(2, "0")).join("")}`;+}diff --git a/apps/desktop/electron/main/window-native-corners.ts b/apps/desktop/electron/main/window-native-corners.tsnew file mode 100644index 000000000..4de41d388--- /dev/null+++ b/apps/desktop/electron/main/window-native-corners.ts@@ -0,0 +1,163 @@+import type { BrowserWindow, Screen } from "electron";+import type { HostProcess } from "./host-process";+import type { Logger } from "./logger";+import { isWindowFullScreen } from "./window-fullscreen.ts";+import {+ DEFAULT_WINDOW_CORNER_RADIUS,+ normalizeWindowCornerRadius,+ setWindowCornerRadius,+} from "./window-shape.ts";++const controllers = new WeakMap<BrowserWindow, NativeCornerController>();++export type NativeCornerController = {+ setRadius: (radius: number) => Promise<number>;+ flush: () => Promise<void>;+};++type CornerScreen = Pick<Screen, "on" | "removeListener">;+type HostProvider = () => HostProcess | null;+type WindowLogger = Pick<Logger, "app">;++/** Windows 11 reports NT 10.0 with a build number starting at 22000. */+export function usesWindows11NativeCorners(+ platform: NodeJS.Platform,+ systemVersion: string,+): boolean {+ if (platform !== "win32") return false;+ const parts = systemVersion.split(".");+ const major = Number(parts[0]);+ const minor = Number(parts[1]);+ const build = Number(parts[2]);+ return Number.isInteger(major) && Number.isInteger(minor) && Number.isInteger(build) &&+ (major > 10 || (major === 10 && minor === 0 && build >= 22000));+}++function nativeHandleAsDecimal(window: BrowserWindow): string {+ const bytes = window.getNativeWindowHandle();+ if (bytes.length === 0) throw new Error("native window handle is unavailable");+ let handle = 0n;+ for (let index = bytes.length - 1; index >= 0; index -= 1) {+ const byte = bytes[index];+ if (byte === undefined) throw new Error("native window handle is invalid");+ handle = (handle << 8n) | BigInt(byte);+ }+ if (handle === 0n) throw new Error("native window handle is invalid");+ return handle.toString(10);+}++/**+ * Use the Windows 11 DWM preference for the main window. The native API owns+ * the visible edge and hit testing; Electron's region-based shape remains the+ * fallback for Windows builds before 22000.+ */+export async function installWindows11CornerController(+ window: BrowserWindow,+ initialRadius: number = DEFAULT_WINDOW_CORNER_RADIUS,+ getHost: HostProvider,+ windowScreen: CornerScreen,+ logger: WindowLogger,+): Promise<NativeCornerController> {+ const nativeHandle = nativeHandleAsDecimal(window);+ let radius = normalizeWindowCornerRadius(initialRadius);+ let generation = 0;+ let disposed = false;+ let pending: Promise<void> = Promise.resolve();++ const enqueue = (): Promise<void> => {+ const requestGeneration = ++generation;+ const rounded = radius > 0 && !window.isMaximized() && !isWindowFullScreen(window);+ const operation = pending.catch(() => undefined).then(async () => {+ if (disposed || window.isDestroyed() || requestGeneration !== generation) return;+ const host = getHost();+ if (!host) throw new Error("host-core is unavailable for native window corners");+ await host.call("window.setNativeCornerPreference", {+ nativeHandle,+ ownerPid: process.pid,+ preference: rounded ? "round" : "square",+ }, 5_000);+ });+ pending = operation;+ return operation;+ };++ const reportFailure = (error: unknown) => {+ logger.app("lifecycle", "warn", "native window corner preference failed", {+ data: String(error),+ });+ };+ const reapply = () => {+ void enqueue().catch(reportFailure);+ };+ const controller: NativeCornerController = {+ async setRadius(nextRadius) {+ radius = normalizeWindowCornerRadius(nextRadius);+ try {+ await enqueue();+ // If another state transition queued while this request was pending,+ // wait until the newest preference has reached DWM before replying.+ while (true) {+ const latest = pending;+ await latest;+ if (latest === pending) break;+ }+ return radius;+ } catch (error) {+ reportFailure(error);+ throw error;+ }+ },+ async flush() {+ while (true) {+ const latest = pending;+ await latest;+ if (latest === pending) return;+ }+ },+ };+ controllers.set(window, controller);++ window.on("maximize", reapply);+ window.on("unmaximize", reapply);+ window.on("enter-full-screen", reapply);+ window.on("leave-full-screen", reapply);+ 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 = () => {+ disposed = true;+ window.removeListener("maximize", reapply);+ window.removeListener("unmaximize", reapply);+ window.removeListener("enter-full-screen", reapply);+ window.removeListener("leave-full-screen", reapply);+ window.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);++ try {+ await controller.setRadius(radius);+ } catch {+ // Keep startup available when the backend cannot apply the optional DWM+ // hint. The failure is logged; Windows may still apply its default policy.+ }+ return controller;+}++/** Apply a theme's requested radius through DWM or the legacy Windows path. */+export async function applyWindowCornerRadius(+ window: BrowserWindow,+ radius: number,+): Promise<number | null> {+ const nativeController = controllers.get(window);+ if (nativeController) return nativeController.setRadius(radius);+ return setWindowCornerRadius(window, radius);+}diff --git a/apps/desktop/electron/main/window-shape.ts b/apps/desktop/electron/main/window-shape.tsindex 029180cb1..117c14a29 100644--- a/apps/desktop/electron/main/window-shape.ts+++ b/apps/desktop/electron/main/window-shape.ts@@ -8,6 +8,10 @@ const controllers = new WeakMap<BrowserWindow, { setRadius: (radius: number) =>type WindowShapeScreen = Pick<Screen, "getDisplayMatching" | "on" | "removeListener">;+export function normalizeWindowCornerRadius(radius: number): number {+ return Math.max(0, Math.min(MAX_WINDOW_CORNER_RADIUS, Math.round(radius)));+}+/*** 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@@ -42,7 +46,7 @@ export function installWindowShape(initialRadius = DEFAULT_WINDOW_CORNER_RADIUS,windowScreen?: WindowShapeScreen,) {- let radius = Math.max(0, Math.min(MAX_WINDOW_CORNER_RADIUS, Math.round(initialRadius)));+ let radius = normalizeWindowCornerRadius(initialRadius);let lastShape = "";const apply = (force = false) => {if (window.isDestroyed()) return;@@ -95,7 +99,7 @@ export function installWindowShape(const controller = {setRadius(next: number) {- radius = Math.max(0, Math.min(MAX_WINDOW_CORNER_RADIUS, Math.round(next)));+ radius = normalizeWindowCornerRadius(next);apply();return radius;},diff --git a/apps/desktop/test/window-background-theme.test.mjs b/apps/desktop/test/window-background-theme.test.mjsindex 33a5ef633..6345e475f 100644--- a/apps/desktop/test/window-background-theme.test.mjs+++ b/apps/desktop/test/window-background-theme.test.mjs@@ -25,10 +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]*?applyMainWindowBackground\(mainWindow, process\.platform, color\)/,+ /handleWithEvent\(IPC\.invoke\.windowSetBackgroundColor,[\s\S]*?registrar\.assertMainWindowSender\(event\)[\s\S]*?!isWindowBackgroundColor\(requested\)[\s\S]*?applyMainWindowBackground\([\s\S]*?mainWindow,[\s\S]*?process\.platform,[\s\S]*?color,[\s\S]*?windows11NativeCorners,[\s\S]*?builtinWindowBackground\(theme\)/,);- assert.match(mainSource, /mainWindowBackgroundOptions\(process\.platform, initialWindowBackground\)/);- assert.match(mainSource, /applyMainWindowBackground\(window, process\.platform, initialWindowBackground\)/);+ assert.match(mainSource, /mainWindowBackgroundOptions\([\s\S]*?process\.platform,[\s\S]*?initialWindowBackground,[\s\S]*?windows11NativeCorners/);+ assert.match(mainSource, /applyMainWindowBackground\([\s\S]*?window,[\s\S]*?process\.platform,[\s\S]*?initialWindowBackground,[\s\S]*?windows11NativeCorners/);// 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.mjsindex e13bd83c0..e96953438 100644--- a/apps/desktop/test/window-background.test.mjs+++ b/apps/desktop/test/window-background.test.mjs@@ -38,6 +38,20 @@ test("constructor background options keep only the Windows outer surface transpaassert.deepEqual(mainWindowBackgroundOptions("darwin", "#ffffff"), {});});+test("Windows 11 uses an opaque top-level background", () => {+ assert.deepEqual(mainWindowBackgroundOptions("win32", "#12345680", true, "#ffffff"), {+ transparent: false,+ backgroundColor: "#8899aa",+ });++ const windows11 = makeWindow();+ assert.equal(+ applyMainWindowBackground(windows11, "win32", "#00000080", true, "#ffffff"),+ true,+ );+ assert.deepEqual(windows11.calls, [["window", "#7f7f7f"]]);+});+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);diff --git a/apps/desktop/test/window-native-corners.test.mjs b/apps/desktop/test/window-native-corners.test.mjsnew file mode 100644index 000000000..bf6aaa015--- /dev/null+++ b/apps/desktop/test/window-native-corners.test.mjs@@ -0,0 +1,149 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import test from "node:test";+import {+ applyWindowCornerRadius,+ installWindows11CornerController,+ usesWindows11NativeCorners,+} from "../electron/main/window-native-corners.ts";++function makeWindow() {+ const window = new EventEmitter();+ let maximized = false;+ let fullScreen = false;+ let destroyed = false;+ window.getNativeWindowHandle = () => Buffer.from([0x78, 0x56, 0x34, 0x12]);+ window.isMaximized = () => maximized;+ window.isFullScreen = () => fullScreen;+ window.isDestroyed = () => destroyed;+ return {+ window,+ setMaximized(value) { maximized = value; },+ setFullScreen(value) { fullScreen = value; },+ close() {+ destroyed = true;+ window.emit("closed");+ },+ };+}++function makeHost(onCall = async () => undefined) {+ const calls = [];+ return {+ calls,+ async call(method, params, timeoutMs) {+ const call = { method, params, timeoutMs };+ calls.push(call);+ return onCall(call);+ },+ };+}++function makeScreen() {+ return new EventEmitter();+}++const logger = { app() {} };++test("Windows 11 detection uses the native build threshold", () => {+ assert.equal(usesWindows11NativeCorners("win32", "10.0.21999"), false);+ assert.equal(usesWindows11NativeCorners("win32", "10.0.22000"), true);+ assert.equal(usesWindows11NativeCorners("win32", "10.0.26100"), true);+ assert.equal(usesWindows11NativeCorners("darwin", "10.0.26100"), false);+ assert.equal(usesWindows11NativeCorners("win32", "unknown"), false);+});++test("DWM preference follows theme radius, window state, and display updates", async () => {+ const fixture = makeWindow();+ const host = makeHost();+ const screen = makeScreen();+ const controller = await installWindows11CornerController(+ fixture.window,+ 12,+ () => host,+ screen,+ logger,+ );++ assert.deepEqual(host.calls[0], {+ method: "window.setNativeCornerPreference",+ params: {+ nativeHandle: "305419896",+ ownerPid: process.pid,+ preference: "round",+ },+ timeoutMs: 5_000,+ });++ fixture.setMaximized(true);+ fixture.window.emit("maximize");+ await controller.flush();+ assert.equal(host.calls.at(-1).params.preference, "square");++ fixture.setMaximized(false);+ fixture.window.emit("unmaximize");+ await controller.flush();+ assert.equal(host.calls.at(-1).params.preference, "round");++ fixture.setFullScreen(true);+ fixture.window.emit("enter-full-screen");+ await controller.flush();+ assert.equal(host.calls.at(-1).params.preference, "square");++ fixture.setFullScreen(false);+ fixture.window.emit("leave-full-screen");+ await controller.flush();+ assert.equal(host.calls.at(-1).params.preference, "round");++ assert.equal(await applyWindowCornerRadius(fixture.window, 0), 0);+ assert.equal(host.calls.at(-1).params.preference, "square");+ assert.equal(await applyWindowCornerRadius(fixture.window, 24), 24);+ assert.equal(host.calls.at(-1).params.preference, "round");++ const callCount = host.calls.length;+ screen.emit("display-metrics-changed", {}, { scaleFactor: 1.75 }, ["scaleFactor"]);+ await controller.flush();+ assert.equal(host.calls.length, callCount + 1);+ assert.equal(host.calls.at(-1).params.preference, "round");++ fixture.close();+ assert.equal(fixture.window.listenerCount("maximize"), 0);+ assert.equal(screen.listenerCount("display-metrics-changed"), 0);+ assert.equal(await applyWindowCornerRadius(fixture.window, 8), null);+});++test("overlapping theme requests leave DWM with the newest preference", async () => {+ let beginSlowCall;+ let releaseSlowCall;+ const slowCallStarted = new Promise((resolve) => { beginSlowCall = resolve; });+ const slowCall = new Promise((resolve) => { releaseSlowCall = resolve; });+ let holdNext = false;+ const host = makeHost(async ({ params }) => {+ if (holdNext) {+ holdNext = false;+ beginSlowCall();+ await slowCall;+ }+ return { rounded: params.preference === "round" };+ });+ const fixture = makeWindow();+ const controller = await installWindows11CornerController(+ fixture.window,+ 12,+ () => host,+ makeScreen(),+ logger,+ );++ holdNext = true;+ const first = controller.setRadius(24);+ await slowCallStarted;+ const second = controller.setRadius(0);+ releaseSlowCall();+ assert.deepEqual(await Promise.all([first, second]), [0, 0]);+ assert.deepEqual(+ host.calls.slice(-2).map((call) => call.params.preference),+ ["round", "square"],+ );+ assert.equal(host.calls.at(-1).params.preference, "square");+});diff --git a/crates/host-core/Cargo.toml b/crates/host-core/Cargo.tomlindex 87a4665cc..ad0a6f24b 100644--- a/crates/host-core/Cargo.toml+++ b/crates/host-core/Cargo.toml@@ -37,6 +37,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }[target.'cfg(windows)'.dependencies]windows-sys = { version = "0.61.2", features = ["Win32_Foundation",+ "Win32_Graphics_Dwm","Win32_Globalization","Win32_Storage_FileSystem","Win32_System_JobObjects",diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 1bb4e289a..ba80fb93c 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -2,6 +2,7 @@ mod config_sync_rpc;mod scheduled_rpc;mod scheduled_tools;mod todos;+mod window_corner_rpc;use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};use std::path::{Path, PathBuf};@@ -1823,6 +1824,7 @@ async fn handle_request(}}))}+ "window.setNativeCornerPreference" => window_corner_rpc::handle(params),"keyboard.setGlobalShortcut" => {let binding = params.get("binding")diff --git a/crates/host-core/src/rpc/window_corner_rpc.rs b/crates/host-core/src/rpc/window_corner_rpc.rsnew file mode 100644index 000000000..5d3bd91bb--- /dev/null+++ b/crates/host-core/src/rpc/window_corner_rpc.rs@@ -0,0 +1,161 @@+use serde::Deserialize;+use serde_json::Value;++#[cfg(windows)]+use serde_json::json;++use super::{rpc_err, JsonRpcError};++const ELECTRON_PID_ENV: &str = "PI_DESKTOP_ELECTRON_PID";++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+struct SetNativeCornerPreferenceParams {+ native_handle: String,+ owner_pid: u32,+ preference: String,+}++pub(super) fn handle(params: Value) -> Result<Value, JsonRpcError> {+ let request: SetNativeCornerPreferenceParams = serde_json::from_value(params)+ .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))?;+ let native_handle = request+ .native_handle+ .parse::<usize>()+ .ok()+ .filter(|handle| *handle != 0)+ .ok_or_else(|| rpc_err(1002, "invalid native window handle", "INVALID_PARAMS"))?;+ let rounded = match request.preference.as_str() {+ "round" => true,+ "square" => false,+ _ => {+ return Err(rpc_err(+ 1002,+ "invalid native window corner preference",+ "INVALID_PARAMS",+ ));+ }+ };+ let electron_pid = std::env::var(ELECTRON_PID_ENV)+ .ok()+ .and_then(|value| value.parse::<u32>().ok())+ .filter(|pid| *pid != 0)+ .ok_or_else(|| {+ rpc_err(+ 1001,+ "Electron owner process is unavailable",+ "UNAUTHORIZED",+ )+ })?;+ validate_owner_pid(request.owner_pid, electron_pid)?;++ #[cfg(windows)]+ {+ apply_windows_corner_preference(native_handle, electron_pid, rounded)+ .map_err(|error| rpc_err(1000, error, "INTERNAL"))?;+ Ok(json!({ "rounded": rounded }))+ }+ #[cfg(not(windows))]+ {+ let _ = (native_handle, rounded);+ Err(rpc_err(+ 1004,+ "native Windows corner preferences are unsupported on this platform",+ "UNSUPPORTED",+ ))+ }+}++fn validate_owner_pid(request_pid: u32, electron_pid: u32) -> Result<(), JsonRpcError> {+ if request_pid == electron_pid {+ return Ok(());+ }+ Err(rpc_err(+ 1001,+ "native window owner does not match Electron",+ "UNAUTHORIZED",+ ))+}++#[cfg(windows)]+fn apply_windows_corner_preference(+ native_handle: usize,+ electron_pid: u32,+ rounded: bool,+) -> Result<(), String> {+ use std::ffi::c_void;+ use std::mem::size_of;+ use windows_sys::Win32::Graphics::Dwm::{+ DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND, DWMWCP_ROUND,+ };+ use windows_sys::Win32::UI::WindowsAndMessaging::{GetWindowThreadProcessId, IsWindow};++ let hwnd = native_handle as windows_sys::Win32::Foundation::HWND;+ if unsafe { IsWindow(hwnd) } == 0 {+ return Err("native window handle is not a live window".to_string());+ }++ let mut actual_owner_pid = 0_u32;+ if unsafe { GetWindowThreadProcessId(hwnd, &mut actual_owner_pid) } == 0 {+ return Err("native window owner could not be read".to_string());+ }+ if actual_owner_pid != electron_pid {+ return Err("native window is not owned by the Electron process".to_string());+ }++ let preference = if rounded {+ DWMWCP_ROUND+ } else {+ DWMWCP_DONOTROUND+ };+ let result = unsafe {+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_WINDOW_CORNER_PREFERENCE as u32,+ (&preference as *const i32).cast::<c_void>(),+ size_of::<i32>() as u32,+ )+ };+ if result < 0 {+ return Err(format!(+ "DwmSetWindowAttribute failed with HRESULT 0x{:08X}",+ result as u32,+ ));+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn native_window_owner_must_match_electron() {+ assert!(validate_owner_pid(42, 42).is_ok());+ let error = validate_owner_pid(41, 42).unwrap_err();+ assert_eq!(error.data.unwrap()["errorCode"], "UNAUTHORIZED");+ }++ #[test]+ fn rejects_invalid_handle_and_preference_before_platform_call() {+ let invalid_handle = handle(json!({+ "nativeHandle": "0",+ "ownerPid": 42,+ "preference": "round"+ }))+ .unwrap_err();+ assert_eq!(invalid_handle.data.unwrap()["errorCode"], "INVALID_PARAMS");++ let invalid_preference = handle(json!({+ "nativeHandle": "42",+ "ownerPid": 42,+ "preference": "custom"+ }))+ .unwrap_err();+ assert_eq!(+ invalid_preference.data.unwrap()["errorCode"],+ "INVALID_PARAMS"+ );+ }+}diff --git a/docs/adr/0317-windows-borderless-window-resize.md b/docs/adr/0317-windows-borderless-window-resize.mdindex 3f559b3e3..75008a9a8 100644--- a/docs/adr/0317-windows-borderless-window-resize.md+++ b/docs/adr/0317-windows-borderless-window-resize.md@@ -31,26 +31,26 @@ Electron's `thickFrame: false` fullscreen path changes display bounds withoutsetting the value returned by `isFullScreen()`. Main tracks this fallback sofullscreen toggles, renderer events, and persisted normal bounds remain correct.-Apply the global `--radius-md` shape (12 DIP) to the Windows main window.-The previous 4 DIP cutout was too small to read as a rounded corner and did not-match the shared design scale. Electron's-`setShape` removes both drawing and pointer hit testing outside its rectangles,-so the corner cutouts have no opaque fill while the existing native background-colour remains theme-owned inside the window. Main reapplies the shape on-resize, and makes it rectangular while maximized or fullscreen. A plugin with+On Windows builds before 22000, keep the existing 12 DIP `--radius-md`+`contentView` clip and native `setShape()` hit region. A plugin with`ui.window.appearance` may declare an integer `cornerRadius` from 0 to 24 DIP-alongside its background colours. The selected theme supplies it through the-existing window-appearance IPC; removing the theme restores 12 DIP. Main validates-the value and the calling renderer before changing the native shape.+alongside its background colours; the selected theme supplies it through the+existing window-appearance IPC, and removing the theme restores 12 DIP. Main+validates the value and the calling renderer before changing the shape.++On Windows build 22000 and later, ADR 0325 replaces both the visible `setShape()`+curve and the shared content-view clip with the system DWM corner preference.+Zero remains square and any positive radius requests a system-rounded window;+DWM does not promise distinct 12 or 24 DIP radii. This path requires an opaque+top-level window and leaves native corner hit behavior to Windows.### 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.+ADR 0325 proposes the DWM path for Windows 11 and later while keeping the+existing shape path for older Windows builds. It keeps this ADR's native+resize and minimum-size contracts. The candidate remains unqualified until+Windows pixel, corner-hit, DPI, and resize checks in E2E-167 pass; source-level+or mocked checks alone do not qualify it.## Alternatives@@ -75,10 +75,10 @@ above is not qualified by source-level or mocked tests alone.this thick-frame-free window retains its current bounds. An external CSSshadow would need transparent window margin or a companion surface, changingwindow geometry and lifecycle; this decision does not add a shadow setting.-- `setShape` is an experimental Electron API and its pixel-row curve is not- anti-aliased by Windows. Native corner hit testing is qualified on the target- Electron version rather than assumed from CSS. ADR 0325 proposes a separate- smooth draw clip, pending the Windows qualification described above.+- Windows builds before 22000 retain the non-antialiased pixel-row `setShape()`+ curve and its native hit region. Windows 11 and later use DWM's best-effort+ system curve and native hit behavior; that API does not promise click-through+ in clipped corner pixels. Both paths need the platform checks in E2E-167.- 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.mdindex bfe76518e..2f0052686 100644--- a/docs/adr/0325-windows-window-corner-compositing.md+++ b/docs/adr/0325-windows-window-corner-compositing.md@@ -1,4 +1,4 @@-# ADR 0325: Smooth Windows main-window corner compositing+# ADR 0325: Use native DWM corners for the Windows 11 main window- Status: Proposed; implementation candidate awaits Windows native qualification- Date: 2026-10-10@@ -7,74 +7,83 @@## 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.+The Windows main window currently uses a transparent outer window,+`contentView.setBorderRadius()` for the visible clip, and `setShape()` for the+native hit region. This keeps child views inside one clip, but depends on+Electron transparency and a window region. Windows 11's DWM corner API may+ignore its rounding hint for windows that use per-pixel alpha or a window+region, so that path cannot guarantee the system-rendered curve.-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.+The Windows 11 API provides `DWMWA_WINDOW_CORNER_PREFERENCE`. Its `ROUND`+preference is a system hint, not a promise of a specific radius or that every+window style will be rounded. Windows 11 deliberately keeps maximized and+snapped windows square. See Microsoft's guidance on+[rounded corners](https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-rounded-corners)+and the [`DWM_WINDOW_CORNER_PREFERENCE` values](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference).## 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.+1. On Windows build 22000 and later, create an opaque, frameless window and+ request the native DWM corner preference through the existing Electron Main+ to Host Core process boundary. Do not call `setShape()` or+ `contentView.setBorderRadius()` on this path.+2. Host Core accepts only the HWND whose owning PID matches the Electron PID+ injected by Electron Main when it starts Host Core. No plugin, renderer, or+ standalone-window API is added.+3. Map radius `0` and maximized/fullscreen states to `DWMWCP_DONOTROUND`. Map+ every positive authorized radius to `DWMWCP_ROUND`. Windows 11 owns the+ visible system radius; values 1 through 24 DIP do not select distinct exact+ radii. The public plugin range and default remain unchanged.+4. Keep the existing transparent content clip and native shape path on Windows+ builds before 22000. Keep macOS, Linux, plugin standalone windows, and+ floating components unchanged.+5. On the Windows 11 path, keep the top-level surface opaque. A contributed+ `#rrggbbaa` background is flattened over the resolved built-in theme+ background before it is applied, so alpha does not create per-pixel window+ transparency.+6. Keep the existing `window/setBackgroundColor` request and response,+ validation, theme fallback, geometry persistence, and native frameless edge+ resize behavior. No renderer corner state, resize emulation, database field,+ plugin permission, setting, or public API is added.## Qualification gate-This decision remains proposed until a dedicated Windows desktop proves all-of the following with Electron 43.6.0:+This decision remains proposed until a dedicated Windows desktop running+Electron 43.6.0 proves all of the following:-- 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.+- Windows 11 displays a DWM-rounded opaque main window with radius 0 square and+ positive radii rounded; tests do not assume 12 and 24 DIP produce different+ system radii.+- Theme changes update the opaque native background, including alpha+ flattening and fallback after a theme is disabled or removed.+- Browser and plugin child views remain within the top-level visible outline.+- Maximize, fullscreen, restore, minimize, show, and DPI changes restore the+ correct system preference.+- Native edge/corner resizing, the work-area-capped 800×560 minimum, settled+ bounds persistence, and the existing window placement behavior remain intact.+- The native corner hit behavior is recorded on Windows 11; this path no longer+ promises `setShape()` click-through outside the rounded silhouette.+- Windows builds before 22000 retain the existing rounded shape and native+ resize behavior. macOS and Linux regressions are also checked.-`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.+The `DWM_WINDOW_CORNER_PREFERENCE` API is explicitly best-effort. If the+Windows 11 build used for qualification does not render the requested rounded+window with this Electron style, do not call the candidate complete; record the+observed behavior and revise the approach.## 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.+- Windows 11 uses the system's antialiased corner rendering and native corner+ hit behavior. It no longer uses transparent pixels or an integer `setShape()`+ region for the visible silhouette.+- Positive theme radii keep their range and meaning as “rounded,” but Windows+ 11 chooses the radius. Windows builds before 22000 retain the prior exact DIP+ clip behavior.+- DWM may decline to round a window based on its style or environment, and+ Windows may keep snapped or virtualized windows square. Windows native+ qualification is required before release claims.+- The Windows 11 background stays opaque; alpha colors are composited against+ the built-in palette. Other platforms keep their existing background and+ vibrancy behavior.diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex f5b17e8f7..2b540c8b7 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1983,8 +1983,8 @@ not touch the tray icon: D216 (ADR 0078) creates one at startup on everyplatform, and minimize-to-tray needs it whichever close behavior is stored.Maximize/unmaximize changes also emit-`window/event/maximized`. Unknown actions fail. These Electron-only channels-do not cross into host-core and do not change the host RPC protocol version.+`window/event/maximized`. Unknown actions fail. These window-control channels+remain Electron-only and do not change the host RPC protocol version.The preload exposes no arbitrary BrowserWindow bounds or resize channel.Windows retains Electron's native frameless edge/corner hit testing with`thickFrame: false`; the renderer does not submit window geometry.@@ -1994,13 +1994,17 @@ 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 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.+On Windows build 22000 and later, Main maps radius 0 to the native square+preference and every positive radius to the DWM system-rounded preference;+maximized/fullscreen states request square corners. Windows chooses the actual+positive radius. The top-level surface stays opaque, and an alpha background is+flattened over the built-in background for the resolved theme. Earlier Windows+builds retain the existing `contentView` clip and native shape behavior. Linux+keeps the native window background, and macOS keeps its existing vibrancy+behavior. The internal Main-to-Host Core DWM call checks that the HWND belongs+to the Electron process; it is not exposed through preload, renderer IPC, or the+plugin API. This does not alter the `window/setBackgroundColor` 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 43c5d92c7..750abbcd7 100644--- a/docs/spec/04-ux/07-ui-design-system.md+++ b/docs/spec/04-ux/07-ui-design-system.md@@ -1123,17 +1123,18 @@ 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 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 selected+ `--radius-md` token (12 DIP) as its default corner request. Windows 11 and+ later use the DWM system-rounded preference for any positive radius and a+ square preference for radius 0; DWM chooses the actual radius and may decline+ to round based on window style or environment. Windows builds before 22000+ retain the existing `contentView` clip and native shape. The Windows 11 path+ uses an opaque top-level surface, so contributed alpha colors are composited+ over the resolved built-in theme background. 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. Corners become rectangular while maximized or fullscreen and follow- every resize. Native window background colors remain theme-owned inside the- clipped surface. Electron's borderless+ default. Corners become rectangular while maximized or fullscreen; positive+ values on Windows 11 do not guarantee an exact DIP radius. Native window+ background colors remain theme-owned. 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 2bff3f018..d2a46698c 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -12214,15 +12214,21 @@ This test plan spec is accepted when:maximum, then verify the target follows the live budget (`client width - 360px - expanded sidebar`) instead of a fixed cap.4. Close and relaunch the app after the resize settles.5. On Windows, start an edge gesture, press Escape, and verify original bounds- return. Release the pointer outside the original window bounds, then- maximize and enter fullscreen; native hit regions must not block- window controls or content in those states.- 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- corners still match the selected radius.+ return. Maximize and enter fullscreen; corners must be square in both+ states. Restore the window and confirm the selected corner preference+ returns. Record native corner hit behavior rather than assuming that DWM+ corners pass clicks through.+ 6. On Windows, inspect the default 12 DIP corner request before and after+ resizing. Apply authorized theme radii of 0 and 24 DIP, then return to a+ built-in theme. Radius 0 must be square. On Windows 11, positive values+ request the same system-rounded preference and are not asserted as exact+ DIP radii; on earlier Windows builds, the existing clip retains its exact+ DIP behavior. Reject an out-of-range radius without changing the surface.+ 7. On Windows, minimize and restore the window, then confirm the selected+ corner preference is applied again. Open browser and plugin child views and+ confirm their pixels stay within the top-level silhouette. On Windows 11,+ also verify alpha theme colors are flattened over the built-in theme+ background on an opaque top-level window.- **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@@ -12232,25 +12238,30 @@ 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 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.+ Windows 11 uses DWM's native rounded preference for positive radii and a+ square preference for radius 0, maximize, and fullscreen. The default request+ remains 12 DIP and authorized themes retain the integer 0..24 DIP range, but+ DWM selects the actual positive radius and the test does not require 12 and+ 24 to look different. Its top-level surface is opaque, including when a+ contributed alpha color is flattened over the built-in theme background.+ Earlier Windows builds retain the existing content clip and integer shape+ hit region. Browser/plugin child views stay within the top-level outline;+ Windows 11 corner click behavior is recorded as native system behavior and+ is not treated as `setShape()` click-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 0325- **Acceptance**: A (app shell), F (persistence), Quality- **Milestone**: M6+-- **Status**: `test:e2e:window-controls` covers corner hit regions before and+- **Status**: `test:e2e:window-controls` covers corner preferences before andafter minimize/restore, theme radius changes, fullscreen, maximize, andcontrols 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.+ candidate samples controlled light/dark desktop backgrounds and child-view+ bounds. Windows 11 additionally verifies the opaque DWM path and system+ preference; earlier Windows builds verify the legacy clip and shape path.+ 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/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex c894f138c..6d066366c 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -193,7 +193,7 @@ providers?: PluginProviderContrib[]; // Host-owned provider rows; needs `providesettings?: PluginSettingContrib[];themes?: PluginThemeContrib[];scenicThemes?: PluginScenicThemesContrib;- windowAppearance?: PluginWindowAppearanceContrib; // native window background and Windows corner radius; needs `ui.window.appearance`+ windowAppearance?: PluginWindowAppearanceContrib; // native window background and Windows corner request; needs `ui.window.appearance`composerTransforms?: PluginComposerTransformContrib[]; // explicit Composer text actions; needs `composer.transform`mcpServers?: PluginMcpServerContrib[];services?: PluginServiceContrib[];@@ -294,7 +294,11 @@ type PluginWindowAppearanceContrib = {declared themes is selected. It does not change macOS/Linux native corners.Removing the theme or its `ui.window.appearance` grant restores the Windowsmain-window default of 12 DIP (`--radius-md`). Invalid or fractional values-reject the manifest.+reject the manifest. On Windows build 22000 and later, 0 requests square+corners and every positive value requests the same native DWM rounded+preference; Windows chooses the exact radius. Earlier Windows builds retain the+requested DIP radius. On Windows 11, an 8-digit background is composited over+the resolved built-in theme color so the top-level window remains opaque.type PluginSkillContrib = {id?: string; // defaults to the file name without its extensiondiff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.mdindex ee81e65b8..e7af8456e 100644--- a/docs/spec/07-plugins/04-plugin-security.md+++ b/docs/spec/07-plugins/04-plugin-security.md@@ -119,7 +119,12 @@ before it is ever sent to the UI:the selected one; leaving the theme restores the host background, because theappearance is derived from the live catalog rather than remembered. macOSkeeps `vibrancy` and its native corner behavior; Linux retains native corner- behavior; Windows defaults to the global 12 DIP `--radius-md` token+ behavior. Windows defaults to a 12 DIP corner request. On Windows 11 (build+ 22000+), radius 0 requests square corners and positive values use the same+ system-rounded preference, while the OS chooses the actual radius; alpha+ backgrounds are composited over the resolved built-in theme color to keep the+ top-level window opaque. Earlier Windows builds retain the requested DIP+ radius- The CSS is read from disk at load time and delivered whole over IPC; therenderer injects it into a single dedicated `<style>` element appended afterthe app's own stylesheets, so it can override tokens but never inject markup.diff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.mdindex 81626a97c..7b59d066a 100644--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md@@ -12,7 +12,7 @@ Provide a permission–capability–risk–default-policy reference table for re| `ui.view` | low | `contributes.views` are listed in the work panel and may be opened | Granted at install | Same isolation as a panel window: sandboxed page, per-plugin partition, `net.domains` egress. Filtered by activation scope || `ui.theme` | low | `contributes.themes` CSS is loaded and offered in Settings; runtime `pi.themes.upsert` / `remove` / `list` and `pi.app.setTheme` (ADR 0260) | Granted at install | CSS is sanitized by the host; it cannot script. Declared `assets` are served over the host's read-only `plugin-asset:` scheme. `setTheme` may only select a built-in preference or a currently registered plugin theme. There is no per-plugin theme count cap || `ui.settings` | low | `contributes.settingsDestinations` adds a sandboxed Settings entry in Extensions | Granted at install | Rendered only in host Extensions group; isolated view host with same sandbox as panel views (ADR 0261) |-| `ui.window.appearance` | low | `contributes.windowAppearance` sets the native window background and Windows main-window corner radius while one of the plugin's themes is selected | Granted at install | `#rrggbb` / `#rrggbbaa` background and integer `cornerRadius` 0..24 DIP; restores host background and the global 12 DIP `--radius-md` radius when the theme is gone. macOS keeps vibrancy and native corners |+| `ui.window.appearance` | low | `contributes.windowAppearance` sets the native window background and Windows main-window corner request while one of the plugin's themes is selected | Granted at install | `#rrggbb` / `#rrggbbaa` background and integer `cornerRadius` 0..24 DIP; restores host background and the 12 DIP default request when the theme is gone. Windows 11 maps 0 to square and positive values to the system-rounded preference (not exact DIP radii); alpha is composited over the built-in theme color on its opaque window. Earlier Windows builds retain the requested DIP radius. macOS keeps vibrancy and native corners || `clipboard.read` | medium | `clipboard.readText`, `clipboard.getHistory` | Confirm on first use | May read sensitive information and retained clipboard history || `clipboard.write` | medium | `clipboard.writeText` | Confirm on first use | Prevents clipboard pollution || `notify` | low | `ui.notify`, `ui.getNotificationPermission`, `ui.requestNotificationPermission`, `ui.showNativeNotification` | Can be granted by default | Native delivery is OS-controlled; avoid notification-spam abuse |diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 58ee7bcde..e850fba3a 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 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. |+| 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. Keep the D635 minimum-size contract and existing work-panel resize ownership. On Windows build 22000 and later, use an opaque top-level window and the DWM corner preference: radius 0 requests square corners, and any positive radius requests the system-rounded corner. The default remains 12 DIP and authorized plugin themes retain integer 0..24 DIP, but Windows 11 selects the actual positive radius. Flatten alpha backgrounds over the built-in theme color on this path. Windows builds before 22000 retain the existing 12 DIP content clip and native `setShape()` hit region; macOS/Linux are unchanged. See ADR 0317, ADR 0325, and E2E-167.** | The thick frame paints an unwanted left, bottom, and right rim. The transparent shared clip can conflict with Windows 11's native corner policy, while an integer `setShape()` cannot produce the system's antialiased curve. DWM owns the Windows 11 curve and hit behavior, so the native radius is not exact and Windows 11 no longer promises shape-region click-through. Native Windows evidence is required to qualify the change. || 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/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex d1d6bba23..809d5e130 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -630,9 +630,9 @@ export type PluginProviderContrib = {* `ui.window.appearance` grant.*/export type PluginWindowAppearanceContrib = {- /** `#rrggbb` or `#rrggbbaa`, applied per resolved palette. */+ /** `#rrggbb` or `#rrggbbaa`, applied per resolved palette; Windows 11 flattens alpha over the built-in palette. */backgroundColor?: { light?: string; dark?: string };- /** Windows main-window radius in DIP. Applies while a contributed theme is selected. */+ /** Windows main-window radius request in DIP; Windows 11 uses the system radius for positive values. */cornerRadius?: number;};diff --git a/scripts/e2e-window-controls.mjs b/scripts/e2e-window-controls.mjsindex 943b25b43..9237e5207 100644--- a/scripts/e2e-window-controls.mjs+++ b/scripts/e2e-window-controls.mjs@@ -128,6 +128,11 @@ async function checkWindowsRoundedCorners(]);corners = JSON.parse(stdout.trim());probeError = undefined;+ if (corners.windowsBuild >= 22000) {+ return corners.cornerMode === "dwm-native" &&+ corners.innerCornerOwned === true && corners.thickFrameStyle === false &&+ corners.nativeHitSampleCount > 0;+ }return corners.topLeftCutout === rounded && corners.topRightCutout === rounded &&corners.bottomLeftCutout === rounded && corners.bottomRightCutout === rounded &&corners.innerCornerOwned === true && corners.gridMismatches === 0 &&@@ -140,17 +145,26 @@ async function checkWindowsRoundedCorners(} catch (error) {throw new Error(`${label}: ${JSON.stringify(corners)}; ${probeError ?? String(error)}`);}- assert.deepEqual([- corners.topLeftCutout,- corners.topRightCutout,- corners.bottomLeftCutout,- corners.bottomRightCutout,- ], [rounded, rounded, rounded, rounded], label);+ if (corners.windowsBuild < 22000) {+ 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`);+ if (corners.windowsBuild < 22000) {+ 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`);+ if (rounded && corners.windowsBuild < 22000) {+ assert.ok(corners.outsideSamples > 0, `${label}: outside click-through samples`);+ }+ if (corners.windowsBuild >= 22000) {+ console.log(`INFO ${label}: native DWM corner hit behavior recorded: ${JSON.stringify(corners.nativeCornerHitBehavior)}`);+ }console.log(`PASS ${label}: ${JSON.stringify(corners)}`);}@@ -196,7 +210,7 @@ async function checkNativeWindowResizes(edges) {}console.log(`PASS native ${edge} drag: ${stdout.trim()}`);}- await checkWindowsRoundedCorners("resized window corners remain transparent");+ await checkWindowsRoundedCorners("resized window corner behavior remains correct");}try {@@ -258,7 +272,7 @@ try {await waitFor(() => evaluate(`document.querySelector('.app-work-panel-toggle')?.disabled === false`), "active session");await settle();await checkControls("panel closed");- await checkWindowsRoundedCorners("normal window corners are transparent");+ await checkWindowsRoundedCorners("normal window corner behavior");await checkNativeWindowResizes(["left-min", "bottom-min"]);await click(".app-work-panel-toggle");await waitFor(() => evaluate(`!!document.querySelector('.work-panel')`), "panel opened");@@ -334,9 +348,9 @@ try {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);+ await checkWindowsRoundedCorners("authorized theme can request a 24 DIP rounded preference", true, 24);assert.equal((await setRadius(defaultWindowCornerRadius)).ok, true);- await checkWindowsRoundedCorners("returning to the default radius restores 12 DIP corners");+ await checkWindowsRoundedCorners("returning to the default radius restores the 12 DIP request");const loaded = await evaluate(`window.piDesktop.invoke('pi-desktop/plugin/loadDevConfirm',{ path: ${JSON.stringify(radiusPluginPath)}, grantedPermissions: ['ui.theme', 'ui.window.appearance'] }@@ -372,7 +386,7 @@ try {await waitFor(() => evaluate(`document.visibilityState === 'visible'`), "native window shown");await settle();await checkControls("restored after native minimize");- await checkWindowsRoundedCorners("corners remain transparent after native minimize and restore");+ await checkWindowsRoundedCorners("corner behavior after native minimize and restore");// Configure only the disposable profile so close-to-tray can be observed// without leaving a blocking native confirmation dialog on the test runner.await evaluate(`window.piDesktop.invoke('pi-desktop/window/closeBehavior/set', {behavior:'tray'})`);diff --git a/scripts/e2e-window-surface.mjs b/scripts/e2e-window-surface.mjsindex d45ec6683..e0882e71b 100644--- a/scripts/e2e-window-surface.mjs+++ b/scripts/e2e-window-surface.mjs@@ -78,7 +78,10 @@ async function runSurfaceCase(radius, backdropColor, 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_NATIVE_CORNERS: join(appDir, "electron", "main", "window-native-corners.ts"),PI_DESKTOP_WINDOW_BACKGROUND: join(appDir, "electron", "main", "window-background.ts"),+ PI_DESKTOP_E2E_HOST_HELPER: join(root, "scripts", "e2e", "host.mjs"),+ PI_DESKTOP_SURFACE_PROFILE: profile,PI_DESKTOP_SURFACE_RADIUS: String(radius),PI_DESKTOP_SURFACE_BACKDROP: backdropColor,};@@ -101,15 +104,19 @@ async function runSurfaceCase(radius, backdropColor, backdropName) {screenshotPath,], { timeout: 30_000, maxBuffer: 2_000_000 });const result = JSON.parse(stdout.trim());+ assert.equal(result.cornerMode, fixture.cornerMode, "fixture and screen probe agree on the Windows corner path");assert.equal(result.totalMismatches, 0, `${backdropName}, radius ${radius}: ${JSON.stringify(result.mismatches)}`);assert.ok(result.insideSamples > 0, `${backdropName}, radius ${radius}: interior samples`);+ if (result.cornerMode === "dwm-native") {+ assert.equal(result.nativeBackgroundSample, true, `${backdropName}, radius ${radius}: opaque alpha-composited window background`);+ }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}, ` ++ console.log(`PASS surface ${backdropName}, ${radius} DIP request (${result.cornerMode}): dpi=${result.dpi}, ` +`scale=${result.scaleFactor}, physical=${result.physicalBounds.width}x${result.physicalBounds.height}, ` +`edge blends=${result.edgeBlendPixels}, screenshot=${screenshotPath}`);} finally {diff --git a/scripts/e2e/fixtures/window-surface/main.mjs b/scripts/e2e/fixtures/window-surface/main.mjsindex 79a9e51d4..179a46b49 100644--- a/scripts/e2e/fixtures/window-surface/main.mjs+++ b/scripts/e2e/fixtures/window-surface/main.mjs@@ -7,6 +7,9 @@ const { app, BrowserWindow, WebContentsView, screen } = electron;const { installWindowShape } = await import(pathToFileURL(process.env.PI_DESKTOP_WINDOW_SHAPE).href);+const { installWindows11CornerController, usesWindows11NativeCorners } = await import(+ pathToFileURL(process.env.PI_DESKTOP_WINDOW_NATIVE_CORNERS).href+);const { applyMainWindowBackground, mainWindowBackgroundOptions } = await import(pathToFileURL(process.env.PI_DESKTOP_WINDOW_BACKGROUND).href);@@ -16,6 +19,7 @@ const backdropColor = process.env.PI_DESKTOP_SURFACE_BACKDROP;const title = "PI Desktop Surface Candidate";let backdropWindow;let mainWindow;+let host;function dataUrl(markup) {return `data:text/html;charset=utf-8,${encodeURIComponent(markup)}`;@@ -25,12 +29,13 @@ 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>`);+ html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: transparent; }+ body { display: flex; }+ .half { position: absolute; top: 0; width: calc(50% - 24px); height: 100%; }+ .light { left: 0; background: #f6f6f6; }+ .dark { right: 0; background: #181818; }+ .window-background-swatch { position: fixed; z-index: 2; left: calc(50% - 24px); top: calc(50% - 24px); width: 48px; height: 48px; }+ </style></head><body><div class="half light"></div><div class="half dark"></div><div class="window-background-swatch"></div></body></html>`);}function childPage() {@@ -47,6 +52,11 @@ app.whenReady().then(async () => {}const display = screen.getPrimaryDisplay();+ const windows11NativeCorners = usesWindows11NativeCorners(+ process.platform,+ process.getSystemVersion(),+ );+ const fixtureBackground = windows11NativeCorners ? "#00000080" : "#fafafa";const { workArea } = display;const width = Math.min(840, workArea.width - 40);const height = Math.min(600, workArea.height - 40);@@ -77,11 +87,38 @@ app.whenReady().then(async () => {thickFrame: false,resizable: true,show: false,- ...mainWindowBackgroundOptions(process.platform, "#fafafa"),+ ...mainWindowBackgroundOptions(+ process.platform,+ fixtureBackground,+ windows11NativeCorners,+ "#ffffff",+ ),});mainWindow.webContents.on("page-title-updated", (event) => event.preventDefault());- installWindowShape(mainWindow, radius, screen);- applyMainWindowBackground(mainWindow, process.platform, "#fafafa");+ if (windows11NativeCorners) {+ const { Host, resolveHostBinary } = await import(+ pathToFileURL(process.env.PI_DESKTOP_E2E_HOST_HELPER).href+ );+ process.env.PI_DESKTOP_ELECTRON_PID = String(process.pid);+ host = new Host(resolveHostBinary(), process.env.PI_DESKTOP_SURFACE_PROFILE);+ await host.start();+ await installWindows11CornerController(+ mainWindow,+ radius,+ () => host,+ screen,+ { app: (...args) => console.error(...args) },+ );+ } else {+ installWindowShape(mainWindow, radius, screen);+ }+ applyMainWindowBackground(+ mainWindow,+ process.platform,+ fixtureBackground,+ windows11NativeCorners,+ "#ffffff",+ );const childView = new WebContentsView({webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },@@ -107,7 +144,11 @@ app.whenReady().then(async () => {radius,backdropColor,scaleFactor: display.scaleFactor,+ cornerMode: windows11NativeCorners ? "dwm-native" : "legacy-shape",})}\n`);});+app.on("before-quit", () => {+ if (host) void host.stop().catch((error) => console.error("host cleanup failed", error));+});app.on("window-all-closed", () => app.quit());diff --git a/scripts/e2e/probe-window-corners.ps1 b/scripts/e2e/probe-window-corners.ps1index 403838282..1776016cf 100644--- a/scripts/e2e/probe-window-corners.ps1+++ b/scripts/e2e/probe-window-corners.ps1@@ -34,6 +34,8 @@ if (-not [CornerProbe]::GetWindowRect($appWindow, [ref]$rect)) { throw 'Cannot r$dpi = [CornerProbe]::GetDpiForWindow($appWindow)if ($dpi -eq 0) { throw 'Cannot read E2E window DPI' }$scaleFactor = $dpi / 96.0+$windowsBuild = [Environment]::OSVersion.Version.Build+$nativeDwm = $windowsBuild -ge 22000$radiusPixels = $cornerRadius * $scaleFactorfunction Test-AppAt([int]$pointX, [int]$pointY) {@@ -47,6 +49,8 @@ function Test-CornerGrid([string]$corner) {$mismatches = 0$insideSamples = 0$outsideSamples = 0+ $observedWindowSamples = 0+ $observedOutsideSamples = 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.@@ -79,6 +83,7 @@ function Test-CornerGrid([string]$corner) {$screenY = $rect.Bottom - 1 - $localY}$actualInside = Test-AppAt $screenX $screenY+ if ($actualInside) { $observedWindowSamples += 1 } else { $observedOutsideSamples += 1 }if ($expectedInside) { $insideSamples += 1 } else { $outsideSamples += 1 }if ($actualInside -ne $expectedInside) { $mismatches += 1 }}@@ -87,6 +92,8 @@ function Test-CornerGrid([string]$corner) {mismatches = $mismatchesinsideSamples = $insideSamplesoutsideSamples = $outsideSamples+ observedWindowSamples = $observedWindowSamples+ observedOutsideSamples = $observedOutsideSamples}}@@ -115,6 +122,8 @@ foreach ($corner in @('topLeft', 'topRight', 'bottomLeft', 'bottomRight')) {bottomRightCutout = $bottomRightCutoutinnerCornerOwned = $innerCornerOwnedthickFrameStyle = ([CornerProbe]::GetWindowLong($appWindow, -16) -band 0x00040000) -ne 0+ windowsBuild = $windowsBuild+ cornerMode = if ($nativeDwm) { 'dwm-native' } else { 'legacy-shape' }dpi = $dpiscaleFactor = $scaleFactorradiusDip = $cornerRadius@@ -122,5 +131,8 @@ foreach ($corner in @('topLeft', 'topRight', 'bottomLeft', 'bottomRight')) {gridMismatches = $gridMismatchesinsideSamples = $insideSamplesoutsideSamples = $outsideSamples+ nativeHitSampleCount = ($grid.Values | ForEach-Object { $_.observedWindowSamples } | Measure-Object -Sum).Sum+ nativeOutsideSampleCount = ($grid.Values | ForEach-Object { $_.observedOutsideSamples } | Measure-Object -Sum).Sum+ nativeCornerHitBehavior = $gridcorners = $grid} | ConvertTo-Json -Compress -Depth 5diff --git a/scripts/e2e/probe-window-surface.ps1 b/scripts/e2e/probe-window-surface.ps1index 22c964573..49c1c2a9e 100644--- a/scripts/e2e/probe-window-surface.ps1+++ b/scripts/e2e/probe-window-surface.ps1@@ -41,6 +41,9 @@ if (-not [SurfaceProbe]::GetWindowRect($window, [ref]$rect)) { throw 'Cannot rea$dpi = [SurfaceProbe]::GetDpiForWindow($window)if ($dpi -eq 0) { throw 'Cannot read surface fixture DPI' }$scaleFactor = $dpi / 96.0+$windowsBuild = [Environment]::OSVersion.Version.Build+$nativeDwm = $windowsBuild -ge 22000+$cornerMode = if ($nativeDwm) { 'dwm-native' } else { 'legacy-shape' }$radiusPixels = $cornerRadius * $scaleFactor$windowWidth = $rect.Right - $rect.Left$windowHeight = $rect.Bottom - $rect.Top@@ -74,14 +77,25 @@ $backdrop = Convert-HexColor $backdropColor$lightContent = Convert-HexColor '#f6f6f6'$darkContent = Convert-HexColor '#181818'$childContent = Convert-HexColor '#d61f69'+$windowBackground = if ($nativeDwm) {+ Convert-HexColor '#7f7f7f'+} else {+ Convert-HexColor '#fafafa'+}$childInset = [int][Math]::Round(48 * $scaleFactor)-$extent = [int][Math]::Ceiling($radiusPixels + 3)+$backgroundHalfWidth = [int][Math]::Ceiling(24 * $scaleFactor)+$extent = if ($nativeDwm) {+ [int][Math]::Ceiling(24 * $scaleFactor + 3)+} else {+ [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+$nativeBackgroundSample = $null$insideSamples = 0$outsideSamples = 0$bitmap = [System.Drawing.Bitmap]::new($windowWidth, $windowHeight)@@ -89,6 +103,10 @@ $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)+ if ($nativeDwm) {+ $backgroundPixel = $bitmap.GetPixel([int][Math]::Floor($windowWidth / 2), [int][Math]::Floor($windowHeight / 2))+ $nativeBackgroundSample = Test-ColorNear $backgroundPixel ([System.Drawing.Color]::FromArgb(127, 127, 127)) $colorTolerance+ }foreach ($corner in @('topLeft', 'topRight', 'bottomLeft', 'bottomRight')) {$cornerMismatches = 0@@ -102,39 +120,62 @@ try {$pixelX = $localX + 0.5$pixelY = $localY + 0.5- if ($cornerRadius -eq 0 -or $pixelX -ge $radiusPixels -or $pixelY -ge $radiusPixels) {+ $actual = $bitmap.GetPixel($fromLeft, $fromTop)+ if ($fromLeft -ge ($windowWidth - $childInset) -and $fromTop -ge ($windowHeight - $childInset)) {+ $foreground = $childContent+ } elseif ([Math]::Abs(($fromLeft + 0.5) - ($windowWidth / 2)) -lt $backgroundHalfWidth) {+ $foreground = $windowBackground+ } elseif ($fromLeft -lt ($windowWidth / 2)) {+ $foreground = $lightContent+ } else {+ $foreground = $darkContent+ }++ if ($nativeDwm) {+ $nearForeground = Test-ColorNear $actual $foreground $colorTolerance+ $nearBackdrop = Test-ColorNear $actual $backdrop $colorTolerance+ $isBlend = (Test-ColorBlend $actual $foreground $backdrop $colorTolerance) -and+ -not $nearForeground -and -not $nearBackdrop+ if ($nearForeground) {+ $insideSamples += 1+ $valid = $true+ } elseif ($cornerRadius -gt 0 -and $nearBackdrop) {+ $outsideSamples += 1+ $valid = $true+ } elseif ($cornerRadius -gt 0 -and $isBlend) {+ $cornerBlends += 1+ $edgeBlendPixels += 1+ $valid = $true+ } else {+ $valid = $false+ }+ $insideCurve = $nearForeground+ } elseif ($cornerRadius -eq 0 -or $pixelX -ge $radiusPixels -or $pixelY -ge $radiusPixels) {$insideCurve = $true$boundaryDistance = [double]::PositiveInfinity+ $insideSamples += 1+ $valid = Test-ColorNear $actual $foreground $colorTolerance} 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+ if (-not $insideCurve) {+ $outsideSamples += 1+ $valid = Test-ColorNear $actual $backdrop $colorTolerance} 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+ $insideSamples += 1+ 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}- } else {- $valid = Test-ColorNear $actual $foreground $colorTolerance}}@@ -163,6 +204,9 @@ try {@{dpi = $dpiscaleFactor = $scaleFactor+ windowsBuild = $windowsBuild+ cornerMode = $cornerMode+ nativeBackgroundSample = $nativeBackgroundSampleradiusDip = $cornerRadiusphysicalBounds = @{ width = $windowWidth; height = $windowHeight }backdropColor = $backdropColor