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): restore native Windows snapping without frame insets
Linuxdazhao463a025d46af
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex 1db58f43b..d42073a19 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -39,6 +39,7 @@ import {import { readWindowState, writeWindowState } from "../window-preferences";import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";import { isWindowFullScreen } from "../window-fullscreen";+import { installWindowsNativeSnap } from "../window-native-snap";import { DEFAULT_WINDOW_CORNER_RADIUS, installWindowShape } from "../window-shape";import {installWindows11CornerController,@@ -277,6 +278,7 @@ export async function createWindow({});const window = windowState.mainWindow;if (process.platform === "win32") {+ await installWindowsNativeSnap(window, () => windowState.host, logger);if (windows11NativeCorners) {await installWindows11CornerController(window,diff --git a/apps/desktop/electron/main/window-native-corners.ts b/apps/desktop/electron/main/window-native-corners.tsindex 4de41d388..7f4955333 100644--- a/apps/desktop/electron/main/window-native-corners.ts+++ b/apps/desktop/electron/main/window-native-corners.ts@@ -2,6 +2,7 @@ import type { BrowserWindow, Screen } from "electron";import type { HostProcess } from "./host-process";import type { Logger } from "./logger";import { isWindowFullScreen } from "./window-fullscreen.ts";+import { nativeWindowHandle } from "./window-native-handle.ts";import {DEFAULT_WINDOW_CORNER_RADIUS,normalizeWindowCornerRadius,@@ -33,19 +34,6 @@ export function usesWindows11NativeCorners((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@@ -58,7 +46,7 @@ export async function installWindows11CornerController(windowScreen: CornerScreen,logger: WindowLogger,): Promise<NativeCornerController> {- const nativeHandle = nativeHandleAsDecimal(window);+ const nativeHandle = nativeWindowHandle(window);let radius = normalizeWindowCornerRadius(initialRadius);let generation = 0;let disposed = false;diff --git a/apps/desktop/electron/main/window-native-handle.ts b/apps/desktop/electron/main/window-native-handle.tsnew file mode 100644index 000000000..0579698cd--- /dev/null+++ b/apps/desktop/electron/main/window-native-handle.ts@@ -0,0 +1,14 @@+import type { BrowserWindow } from "electron";++export function nativeWindowHandle(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);+}diff --git a/apps/desktop/electron/main/window-native-snap.ts b/apps/desktop/electron/main/window-native-snap.tsnew file mode 100644index 000000000..bcbb100f3--- /dev/null+++ b/apps/desktop/electron/main/window-native-snap.ts@@ -0,0 +1,44 @@+import type { BrowserWindow } from "electron";+import type { HostProcess } from "./host-process";+import type { Logger } from "./logger";+import { isWindowFullScreen } from "./window-fullscreen.ts";+import { nativeWindowHandle } from "./window-native-handle.ts";++/** Restore shell styles without opting back into Electron's native frame insets. */+export async function installWindowsNativeSnap(+ window: BrowserWindow,+ getHost: () => Pick<HostProcess, "call"> | null,+ logger: Pick<Logger, "app">,+): Promise<{ flush: () => Promise<void> }> {+ const nativeHandle = nativeWindowHandle(window);+ let disposed = false;+ let pending: Promise<void> = Promise.resolve();+ const apply = (): Promise<void> => {+ pending = pending.catch(() => undefined).then(async () => {+ if (disposed || window.isDestroyed() || isWindowFullScreen(window)) return;+ const host = getHost();+ if (!host) throw new Error("host-core is unavailable for native window snapping");+ await host.call("window.enableNativeSnap", { nativeHandle, ownerPid: process.pid }, 5_000);+ });+ return pending;+ };+ const reportFailure = (error: unknown) => {+ logger.app("lifecycle", "warn", "native window snapping failed", { data: String(error) });+ };+ const refresh = () => { void apply().catch(reportFailure); };+ window.on("show", refresh);+ window.on("restore", refresh);+ window.on("maximize", refresh);+ window.on("unmaximize", refresh);+ window.on("leave-full-screen", refresh);+ window.once("closed", () => {+ disposed = true;+ window.removeListener("show", refresh);+ window.removeListener("restore", refresh);+ window.removeListener("maximize", refresh);+ window.removeListener("unmaximize", refresh);+ window.removeListener("leave-full-screen", refresh);+ });+ await apply().catch(reportFailure);+ return { flush: () => pending };+}diff --git a/apps/desktop/test/window-native-snap.test.mjs b/apps/desktop/test/window-native-snap.test.mjsnew file mode 100644index 000000000..2ddbe62df--- /dev/null+++ b/apps/desktop/test/window-native-snap.test.mjs@@ -0,0 +1,77 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import test from "node:test";+import { installWindowsNativeSnap } from "../electron/main/window-native-snap.ts";+import { setWindowFullScreen } from "../electron/main/window-fullscreen.ts";++function fixture() {+ const window = new EventEmitter();+ let fullScreen = false;+ window.isDestroyed = () => false;+ window.getNativeWindowHandle = () => Buffer.from([0x78, 0x56, 0x34, 0x12]);+ window.isFullScreen = () => fullScreen;+ window.setFullScreen = (value) => {+ fullScreen = value;+ window.emit(value ? "enter-full-screen" : "leave-full-screen");+ };+ const calls = [];+ const warnings = [];+ const host = { async call(method, params, timeout) { calls.push({ method, params, timeout }); } };+ const logger = { app(...args) { warnings.push(args); } };+ return { window, host, calls, logger, warnings };+}++test("native snap is ready before startup continues and survives window transitions", async () => {+ const f = fixture();+ const controller = await installWindowsNativeSnap(f.window, () => f.host, f.logger);+ assert.deepEqual(f.calls[0], {+ method: "window.enableNativeSnap",+ params: { nativeHandle: "305419896", ownerPid: process.pid },+ timeout: 5_000,+ });+ for (const event of ["show", "maximize", "unmaximize", "restore"]) {+ const count = f.calls.length;+ f.window.emit(event);+ await controller.flush();+ assert.equal(f.calls.length, count + 1, event);+ }+ setWindowFullScreen(f.window, true, true);+ const count = f.calls.length;+ f.window.emit("show");+ await controller.flush();+ assert.equal(f.calls.length, count, "fullscreen does not gain resize/caption styles");+ setWindowFullScreen(f.window, false, true);+ await controller.flush();+ assert.equal(f.calls.length, count + 1, "leaving fullscreen restores native snap");+});++test("a failed optional style update is logged and can recover with a replacement Host", async () => {+ const f = fixture();+ let host = null;+ const controller = await installWindowsNativeSnap(f.window, () => host, f.logger);+ assert.equal(f.warnings.length, 1);+ host = f.host;+ f.window.emit("show");+ await controller.flush();+ assert.equal(f.calls.length, 1);+});++test("closing a window cancels queued native mutations and removes its subscriptions", async () => {+ const f = fixture();+ const controller = await installWindowsNativeSnap(f.window, () => f.host, f.logger);+ const count = f.calls.length;+ f.window.emit("restore");+ f.window.emit("closed");+ await controller.flush();+ assert.equal(f.calls.length, count);+ for (const event of ["show", "maximize", "unmaximize", "restore", "leave-full-screen"]) {+ assert.equal(f.window.listenerCount(event), 0);+ }+});++test("an invalid native handle never reaches Host", async () => {+ const f = fixture();+ f.window.getNativeWindowHandle = () => Buffer.alloc(8);+ await assert.rejects(installWindowsNativeSnap(f.window, () => f.host, f.logger), /invalid/);+ assert.equal(f.calls.length, 0);+});diff --git a/apps/desktop/test/window-resize.test.mjs b/apps/desktop/test/window-resize.test.mjsindex 05a10d282..20b9a768e 100644--- a/apps/desktop/test/window-resize.test.mjs+++ b/apps/desktop/test/window-resize.test.mjs@@ -10,7 +10,7 @@ const reservationHandler = mainSource.slice(mainSource.indexOf("IPC.invoke.windowSetWorkPanelChatWidth"),);-test("the main window keeps native edge resizing without the Windows thick frame", () => {+test("the main window keeps native resizing without Electron frame insets", () => {assert.match(mainSource, /resizable:\s*true/);assert.match(mainSource, /process\.platform === "win32" \? \{ thickFrame: false \}/);// The BrowserWindow props use the clamped `initialMin*` values so a smalldiff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 814f68399..95df2e74f 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -12,6 +12,8 @@ mod scheduled_settings;mod scheduled_tools;mod todos;mod window_corner_rpc;+mod window_owner;+mod window_snap_rpc;mod worktree_rpc;#[cfg(test)]@@ -2063,6 +2065,7 @@ async fn handle_request(}))}"window.setNativeCornerPreference" => window_corner_rpc::handle(params),+ "window.enableNativeSnap" => window_snap_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.rsindex 5d3bd91bb..6a054a043 100644--- a/crates/host-core/src/rpc/window_corner_rpc.rs+++ b/crates/host-core/src/rpc/window_corner_rpc.rs@@ -4,9 +4,7 @@ use serde_json::Value;#[cfg(windows)]use serde_json::json;-use super::{rpc_err, JsonRpcError};--const ELECTRON_PID_ENV: &str = "PI_DESKTOP_ELECTRON_PID";+use super::{rpc_err, window_owner, JsonRpcError};#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase")]@@ -19,12 +17,7 @@ struct SetNativeCornerPreferenceParams {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 native_handle = window_owner::parse_native_handle(&request.native_handle)?;let rounded = match request.preference.as_str() {"round" => true,"square" => false,@@ -36,18 +29,7 @@ pub(super) fn handle(params: Value) -> Result<Value, JsonRpcError> {));}};- 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)?;+ let electron_pid = window_owner::electron_owner_pid(request.owner_pid)?;#[cfg(windows)]{@@ -57,7 +39,7 @@ pub(super) fn handle(params: Value) -> Result<Value, JsonRpcError> {}#[cfg(not(windows))]{- let _ = (native_handle, rounded);+ let _ = (native_handle, rounded, electron_pid);Err(rpc_err(1004,"native Windows corner preferences are unsupported on this platform",@@ -66,17 +48,6 @@ pub(super) fn handle(params: Value) -> Result<Value, JsonRpcError> {}}-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,@@ -88,20 +59,7 @@ fn apply_windows_corner_preference(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 hwnd = window_owner::owned_hwnd(native_handle, electron_pid)?;let preference = if rounded {DWMWCP_ROUND@@ -130,13 +88,6 @@ 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!({diff --git a/crates/host-core/src/rpc/window_owner.rs b/crates/host-core/src/rpc/window_owner.rsnew file mode 100644index 000000000..719daa0d9--- /dev/null+++ b/crates/host-core/src/rpc/window_owner.rs@@ -0,0 +1,79 @@+use super::{rpc_err, JsonRpcError};++pub(super) fn parse_native_handle(value: &str) -> Result<usize, JsonRpcError> {+ value+ .parse::<usize>()+ .ok()+ .filter(|handle| *handle != 0)+ .ok_or_else(|| rpc_err(1002, "invalid native window handle", "INVALID_PARAMS"))+}++pub(super) fn electron_owner_pid(request_pid: u32) -> Result<u32, JsonRpcError> {+ let pid = std::env::var("PI_DESKTOP_ELECTRON_PID")+ .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_pid, pid)?;+ Ok(pid)+}++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)]+pub(super) fn owned_hwnd(+ native_handle: usize,+ electron_pid: u32,+) -> Result<windows_sys::Win32::Foundation::HWND, String> {+ 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;+ 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());+ }+ Ok(hwnd)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[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 native_handles_must_be_nonzero_decimal_integers() {+ assert_eq!(parse_native_handle("42").unwrap(), 42);+ for value in ["0", "-1", "0x42", "not-a-handle", "18446744073709551616"] {+ assert_eq!(+ parse_native_handle(value).unwrap_err().data.unwrap()["errorCode"],+ "INVALID_PARAMS"+ );+ }+ }+}diff --git a/crates/host-core/src/rpc/window_snap_rpc.rs b/crates/host-core/src/rpc/window_snap_rpc.rsnew file mode 100644index 000000000..d546f871b--- /dev/null+++ b/crates/host-core/src/rpc/window_snap_rpc.rs@@ -0,0 +1,114 @@+use serde::Deserialize;+use serde_json::Value;++use super::{rpc_err, window_owner, JsonRpcError};++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct EnableNativeSnapParams {+ native_handle: String,+ owner_pid: u32,+}++pub(super) fn handle(params: Value) -> Result<Value, JsonRpcError> {+ let request: EnableNativeSnapParams = serde_json::from_value(params)+ .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))?;+ let native_handle = window_owner::parse_native_handle(&request.native_handle)?;+ let electron_pid = window_owner::electron_owner_pid(request.owner_pid)?;+ #[cfg(windows)]+ {+ let border_suppressed = enable_native_snap(native_handle, electron_pid)+ .map_err(|error| rpc_err(1000, error, "INTERNAL"))?;+ Ok(serde_json::json!({ "enabled": true, "borderSuppressed": border_suppressed }))+ }+ #[cfg(not(windows))]+ {+ let _ = (native_handle, electron_pid);+ Err(rpc_err(+ 1004,+ "native Windows snapping is unsupported on this platform",+ "UNSUPPORTED",+ ))+ }+}++#[cfg(windows)]+fn enable_native_snap(native_handle: usize, electron_pid: u32) -> Result<bool, String> {+ use windows_sys::Win32::Foundation::{GetLastError, SetLastError, E_INVALIDARG};+ use windows_sys::Win32::Graphics::Dwm::{+ DwmSetWindowAttribute, DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE,+ };+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ GetWindowLongW, SetWindowLongW, SetWindowPos, GWL_STYLE, SWP_FRAMECHANGED, SWP_NOACTIVATE,+ SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WS_CAPTION, WS_THICKFRAME,+ };+ let hwnd = window_owner::owned_hwnd(native_handle, electron_pid)?;+ unsafe { SetLastError(0) };+ let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) } as u32;+ if style == 0 && unsafe { GetLastError() } != 0 {+ return Err(std::io::Error::last_os_error().to_string());+ }+ // Keep Electron's thickFrame:false client layout; restore only the shell's+ // snap/animation styles. WS_CAPTION also prevents a maximized DWM rim.+ let next = style | WS_THICKFRAME | WS_CAPTION;+ if next != style {+ unsafe { SetLastError(0) };+ if unsafe { SetWindowLongW(hwnd, GWL_STYLE, next as i32) } == 0+ && unsafe { GetLastError() } != 0+ {+ return Err(std::io::Error::last_os_error().to_string());+ }+ if unsafe {+ SetWindowPos(+ hwnd,+ std::ptr::null_mut(),+ 0,+ 0,+ 0,+ 0,+ SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER,+ )+ } == 0+ {+ return Err(std::io::Error::last_os_error().to_string());+ }+ }+ // Windows 11 otherwise draws a one-pixel DWM outline over the client edge.+ let color = DWMWA_COLOR_NONE;+ let result = unsafe {+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_BORDER_COLOR as u32,+ (&color as *const u32).cast(),+ std::mem::size_of::<u32>() as u32,+ )+ };+ if result == E_INVALIDARG {+ return Ok(false); // Windows 10 has no configurable DWM border color.+ }+ if result < 0 {+ return Err(format!(+ "native window border suppression failed: 0x{:08X}",+ result as u32+ ));+ }+ Ok(true)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rejects_invalid_native_snap_requests_before_platform_calls() {+ for params in [+ serde_json::json!({}),+ serde_json::json!({"nativeHandle":"0","ownerPid":42}),+ ] {+ assert_eq!(+ handle(params).unwrap_err().data.unwrap()["errorCode"],+ "INVALID_PARAMS"+ );+ }+ }+}diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 2556b891b..28a46e024 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -413,3 +413,4 @@ Each ADR includes:| 0345 | [One settings destination owns one subject](0345-one-settings-destination-one-subject.md) | Accepted (D684; amends D143, D166, D678) || 0346 | [`@agent` mentions route a turn to a named subagent](0346-composer-agent-mentions.md) | Accepted (issue #986; extends 0024 / 0062) || composer-local-file-references | [Pasted local files are live references](composer-local-file-references.md) | Accepted (issue #2314) |+| windows-native-snap-without-frame-insets | [Restore Windows snapping without Electron frame insets](windows-native-snap-without-frame-insets.md) | Accepted (issue #2330; amends ADR 0317) |diff --git a/docs/adr/windows-native-snap-without-frame-insets.md b/docs/adr/windows-native-snap-without-frame-insets.mdnew file mode 100644index 000000000..010e9aeb4--- /dev/null+++ b/docs/adr/windows-native-snap-without-frame-insets.md@@ -0,0 +1,61 @@+# ADR: Restore Windows snapping without Electron frame insets++- Status: Accepted+- Date: 2026-11-13+- Related: issue #2330, ADR 0317, ADR 0325, E2E-167++## Context++Pinned Electron 43.6.0 removes `WS_THICKFRAME` and `WS_CAPTION` when the main+window uses `thickFrame: false`, excluding it from native keyboard and titlebar+drag snapping. Enabling Electron's thick frame restores its left/right/bottom+client-area insets and would regress the borderless surface fixed by ADR 0317.++## Decision++Keep `frame: false` and `thickFrame: false`. Private Main-to-Host RPC+`window.enableNativeSnap` restores only the HWND's `WS_THICKFRAME | WS_CAPTION`+bits, preserving other styles and bounds. Electron keeps its inset-free client+layout. `WS_CAPTION` also prevents the maximized DWM overshoot seen when only+`WS_THICKFRAME` is restored. Set Windows 11's `DWMWA_BORDER_COLOR` to+`DWMWA_COLOR_NONE` so DWM cannot paint an outline over the client edges.+Windows 10's unsupported-attribute `E_INVALIDARG` is handled explicitly; other+native failures remain errors.++The RPC accepts a decimal HWND and owner PID, never an arbitrary style mask.+Host checks the requested PID against Main's injected PID and verifies the live+HWND owner before mutation. Share this validation with the corner RPC. No raw+handle or new channel is exposed to renderer, preload, plugins, or remote clients.++Main awaits initial application before showing the window and reapplies after+show, restore, maximize, unmaximize, and leaving fullscreen. Active fullscreen+is excluded; closing cancels queued work and subscriptions. Errors are logged+without preventing startup, and later transitions can retry with the current+Host. Existing minimum sizes, persistence, resizing, corners, fullscreen+interlocks, and maximize/work-area correction remain unchanged.++## Consequences++`test:e2e:window-snap` exercises the production Main service and compiled Host in+an isolated profile. It checks keyboard snapping, physical titlebar drag,+client-edge pixels, native edge resize/minimums, maximize/minimize/restore, and+fullscreen/restore. Both the client and DWM-visible maximized frame must match+the work area; invisible resize margins in `GetWindowRect` are not overflow.++`--baseline` omits service installation and must fail the keyboard-snap check.+`--prepare <directory>` prepares a fixture for an existing Windows runtime and+is not a passing test. `--legacy-surface` exercises the transparent/shape path+on the available Windows version, not a real Windows 10 installation.+`--external-pointer` lets an existing remote-desktop input adapter acknowledge+`pointer-request.json` through `pointer-response.json` with the same `runId`, `id` and+`ok: true`. Native geometry/pixel assertions are identical for both input paths;+the fixture never treats an input acknowledgement alone as success.++The renderer's custom maximize button still needs separate `HTMAXBUTTON`+integration for hover-triggered Snap Layouts. This keyboard/drag fix introduces+no global key interception or renderer snapping implementation. Requalify native+layout and pixels on Electron upgrades: separating its layout option from the+HWND styles is deliberate.++References: [Electron style handling](https://github.com/electron/electron/blob/v43.6.0/shell/browser/native_window_views.cc#L395-L411),+[DWM border attributes](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute).diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 0a6b093e7..eab075e1e 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1,5 +1,17 @@# 01. IPC Protocol+### Private native window snapping++`window.enableNativeSnap` is Main-to-Host only: `{nativeHandle: string, ownerPid: number}`+returns `{enabled: true, borderSuppressed: boolean}`. The decimal, nonzero HWND+must belong to the Main process injected through `PI_DESKTOP_ELECTRON_PID`.+Host validates both the requested PID and live window owner, restores the fixed+`WS_THICKFRAME | WS_CAPTION` mask, and suppresses the Windows 11 DWM outline.+Windows 10 reports `borderSuppressed: false` for the unsupported attribute.+Invalid parameters, unauthorized owners, and other native failures remain errors.+No renderer/preload/plugin channel, schema migration, or protocol version changes.+See [native snapping ADR](../../adr/windows-native-snap-without-frame-insets.md).+### composer/readClipboardDirectoriesAn additive main-window-only Electron channel accepting no source paths. Duringdiff --git a/docs/spec/04-ux/07-ui-design-system.md b/docs/spec/04-ux/07-ui-design-system.mdindex 5ad12b6d6..51c37de43 100644--- a/docs/spec/04-ux/07-ui-design-system.md+++ b/docs/spec/04-ux/07-ui-design-system.md@@ -1,5 +1,16 @@# 07. UI Design System+## Windows native snapping without a painted frame++The main window retains Electron's `frame: false` / `thickFrame: false` client+layout. Host restores the shell's native snap/caption styles and suppresses+Windows 11's DWM outline. Keyboard and physical titlebar-drag snapping remain+OS-owned; left/right/bottom pixels remain renderer-owned without native insets.+Existing minimum sizes, corner preferences, fullscreen and work-area maximize+correction remain in effect. Hover Snap Layouts on the custom maximize button+is not provided by this style repair. See+[native snapping ADR](../../adr/windows-native-snap-without-frame-insets.md).+## 1. Goals1. Provide a **single source of truth** for visual tokens, component foundations, and layout metrics across PI-Desktopdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex e3a18b9e1..6bf206cfa 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -14121,6 +14121,21 @@ This test plan spec is accepted when:#### E2E-167: Window edge resize stays smooth and persists the settled bounds+Native Windows snapping regression (issue #2330): on an interactive Windows+desktop with a work-area half at least the nominal minimum width, run+`pnpm test:e2e:window-snap` against the candidate Windows Host and pinned Electron.+The isolated fixture uses production Main snapping/corner/fullscreen services,+real Host RPC, HWND-owner rejection checks, physical Win+Left/Right and titlebar+drag input, edge pixels, native resize/minimums, maximize/minimize/restore and+fullscreen/restore. Left/right snapping must equal the work-area halves; normal+and snapped client edges have no native insets or painted rim. Maximized client+and DWM-visible bounds must equal the work area. `--baseline` must fail the+keyboard assertion. `--legacy-surface` covers the older transparent surface on+the available OS only. `--prepare <directory>` stages portable fixture sources;+record actual OS/DPI, source revision, Host, Electron version, result and artifacts+from the Windows run separately. Native Windows 10 and mixed-monitor DPI checks+remain separate qualification, and hover Snap Layouts is outside this regression.+- **Preconditions**: PI-Desktop is open in a normal, non-maximized window onmacOS, Windows, or Linux. On Windows, the left, bottom, and right rim musthave no visible native border. Run the case with the work panel closed and oncediff --git a/package.json b/package.jsonindex 3fb3e1852..dbc889c03 100644--- a/package.json+++ b/package.json@@ -72,6 +72,7 @@"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:window-snap": "node scripts/e2e-window-snap.mjs","test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs","test:e2e:browser-local-files": "node scripts/e2e-browser-local-file-access.mjs","test:e2e:session-metadata-reads": "node scripts/e2e-session-metadata-reads.mjs",diff --git a/scripts/README.md b/scripts/README.mdindex e75326ee0..fcc89dbf0 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -53,6 +53,7 @@ The scenarios are specified in| Script | Alias | Purpose ||---|---|---|| `e2e-tool-admission.mjs` | `node scripts/e2e-tool-admission.mjs` | Isolated real-host tool admission: queued Bash burst leaves capacity for another session's Read/Write and recovers all counters |+| `e2e-window-snap.mjs` | `pnpm test:e2e:window-snap [--baseline] [--external-pointer] [--prepare <directory>]` | Windows shell snapping, native frame pixels, resize/minimums, maximize/restore and fullscreen through production Main/Host services and real desktop input || `e2e-smoke.mjs` | `pnpm test:e2e` | Protocol-level E2E against host-core, plus an optional live model || `e2e-plan.mjs` | `pnpm test:e2e:plan` | Plan state, checkpoint artifact, and approval transitions || `e2e-transcript-cache.mjs` | `pnpm test:e2e:transcript-cache` | Isolated Host RPC regression for large transcript cache creation, append plus middle Task rewrite, legacy cache recovery, paging, message navigation, invalid UTF-8 recovery, and process restart |diff --git a/scripts/e2e-window-controls.mjs b/scripts/e2e-window-controls.mjsindex 9237e5207..d493abcbe 100644--- a/scripts/e2e-window-controls.mjs+++ b/scripts/e2e-window-controls.mjs@@ -130,7 +130,7 @@ async function checkWindowsRoundedCorners(probeError = undefined;if (corners.windowsBuild >= 22000) {return corners.cornerMode === "dwm-native" &&- corners.innerCornerOwned === true && corners.thickFrameStyle === false &&+ corners.innerCornerOwned === true && corners.thickFrameStyle === true &&corners.nativeHitSampleCount > 0;}return corners.topLeftCutout === rounded && corners.topRightCutout === rounded &&@@ -154,7 +154,7 @@ async function checkWindowsRoundedCorners(], [rounded, rounded, rounded, rounded], label);}assert.equal(corners.innerCornerOwned, true, label);- assert.equal(corners.thickFrameStyle, false, label);+ assert.equal(corners.thickFrameStyle, true, label);if (corners.windowsBuild < 22000) {assert.equal(corners.gridMismatches, 0, `${label}: native corner hit grid`);}diff --git a/scripts/e2e-window-snap.mjs b/scripts/e2e-window-snap.mjsnew file mode 100644index 000000000..03993198d--- /dev/null+++ b/scripts/e2e-window-snap.mjs@@ -0,0 +1,56 @@+#!/usr/bin/env node+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { createRequire } from "node:module";+import { mkdir, copyFile, readFile, writeFile, mkdtemp } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const prepare = process.argv.includes("--prepare");+assert.ok(prepare || process.platform === "win32", "run on an interactive Windows desktop, or use --prepare <directory>");+const output = process.argv[process.argv.indexOf("--prepare") + 1];+const directory = prepare ? resolve(output) : await mkdtemp(join(tmpdir(), "window-snap-"));+await mkdir(directory, { recursive: true });+const require = createRequire(join(root, "apps/desktop/package.json"));+const { build } = require("esbuild");+await build({+ entryPoints: [join(root, "scripts/e2e/fixtures/window-snap/main.cjs")],+ outfile: join(directory, "main.cjs"), bundle: true, platform: "node", format: "cjs", external: ["electron"],+ banner: { js: 'const __fixtureModuleUrl = require("node:url").pathToFileURL(__filename).href;' },+ define: { "import.meta.url": "__fixtureModuleUrl" },+ alias: {+ SNAP_HOST_HELPER: join(root, "scripts/e2e/host.mjs"),+ SNAP_WINDOW_MODULE: join(root, "apps/desktop/electron/main/window-native-snap.ts"),+ SNAP_CORNERS_MODULE: join(root, "apps/desktop/electron/main/window-native-corners.ts"),+ SNAP_FULLSCREEN_MODULE: join(root, "apps/desktop/electron/main/window-fullscreen.ts"),+ SNAP_SHAPE_MODULE: join(root, "apps/desktop/electron/main/window-shape.ts"),+ },+ plugins: [{ name: "shared-ndjson-source", setup(builder) {+ builder.onResolve({ filter: /packages\/shared\/dist\/ndjson\.js$/ }, () => ({ path: join(root, "packages/shared/src/ndjson.ts") }));+ } }],+});+await copyFile(join(root, "scripts/e2e/probe-window-snap.cs"), join(directory, "probe.cs"));+await writeFile(join(directory, "options.json"), JSON.stringify({+ hostBinary: process.env.PI_DESKTOP_HOST_BIN || join(root, "target/debug/pi-desktop-host-core.exe"),+ electronBinary: process.env.PI_DESKTOP_SNAP_ELECTRON || (prepare ? "electron/electron.exe" : require("electron")),+ baseline: process.argv.includes("--baseline"),+ externalPointer: process.argv.includes("--external-pointer"),+ legacySurface: process.argv.includes("--legacy-surface"),+ minWidth: Number(process.env.PI_DESKTOP_SNAP_MIN_WIDTH || 800),+ minHeight: Number(process.env.PI_DESKTOP_SNAP_MIN_HEIGHT || 560),+}));+if (prepare) console.log(directory);+else {+ const run = promisify(execFile);+ const quote = (value) => `'${value.replaceAll("'", "''")}'`;+ const compile = `Add-Type -Path ${quote(join(directory, "probe.cs"))} -OutputAssembly ${quote(join(directory, "probe.exe"))} -OutputType WindowsApplication -ReferencedAssemblies System.dll,System.Drawing.dll,System.Windows.Forms.dll,System.Web.Extensions.dll`;+ await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",+ compile]);+ await run(join(directory, "probe.exe"), [], { timeout: 300_000 });+ const result = JSON.parse(await readFile(join(directory, "result.json"), "utf8"));+ assert.equal(result.ok, true, JSON.stringify(result));+ console.log(JSON.stringify({ ...result, artifacts: directory }));+}diff --git a/scripts/e2e/fixtures/window-snap/main.cjs b/scripts/e2e/fixtures/window-snap/main.cjsnew file mode 100644index 000000000..c276aea8e--- /dev/null+++ b/scripts/e2e/fixtures/window-snap/main.cjs@@ -0,0 +1,103 @@+const { app, BrowserWindow, screen } = require("electron");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const { Host } = require("SNAP_HOST_HELPER");+const { installWindowsNativeSnap } = require("SNAP_WINDOW_MODULE");+const { installWindows11CornerController, usesWindows11NativeCorners } = require("SNAP_CORNERS_MODULE");+const { isWindowFullScreen, setWindowFullScreen } = require("SNAP_FULLSCREEN_MODULE");+const { installWindowShape } = require("SNAP_SHAPE_MODULE");++const root = __dirname;+const options = JSON.parse(fs.readFileSync(path.join(root, "options.json"), "utf8"));+const baseline = process.argv.includes("--baseline");+let host;+let window;+let timer;+let snap;+let corners;+let quitting = false;+const logger = { app: (...args) => console.error(...args) };+const resolve = (name) => path.isAbsolute(name) ? name : path.join(root, name);++app.whenReady().then(async () => {+ const legacySurface = options.legacySurface || !usesWindows11NativeCorners(process.platform, process.getSystemVersion());+ host = new Host(resolve(options.hostBinary), path.join(root, baseline ? "host-baseline" : "host-candidate"), {+ env: { PI_DESKTOP_ELECTRON_PID: String(process.pid) }, quiet: true,+ });+ await host.start();+ window = new BrowserWindow({+ x: 200, y: 140, width: 1200, height: 800,+ minWidth: options.minWidth, minHeight: options.minHeight,+ frame: false, thickFrame: false, resizable: true, show: false,+ transparent: legacySurface, backgroundColor: legacySurface ? "#00000000" : "#181818",+ title: "Native Snap Regression", webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false },+ });+ const nativeHandle = window.getNativeWindowHandle().readBigUInt64LE().toString();+ await assert.rejects(host.call("window.enableNativeSnap", { nativeHandle: "0", ownerPid: process.pid }),+ (error) => error.errorCode === "INVALID_PARAMS");+ await assert.rejects(host.call("window.enableNativeSnap", { nativeHandle, ownerPid: process.pid + 1 }),+ (error) => error.errorCode === "UNAUTHORIZED");+ const foreignHandle = process.argv.find((arg) => arg.startsWith("--foreign-handle="))?.split("=")[1];+ assert.ok(foreignHandle);+ await assert.rejects(host.call("window.enableNativeSnap", { nativeHandle: foreignHandle, ownerPid: process.pid }),+ (error) => error.errorCode === "INTERNAL");+ if (!baseline) snap = await installWindowsNativeSnap(window, () => host, logger);+ if (legacySurface) installWindowShape(window, 12, screen);+ else corners = await installWindows11CornerController(window, 12, () => host, screen, logger);+ window.webContents.on("page-title-updated", (event) => event.preventDefault());+ await window.loadURL("data:text/html," + encodeURIComponent(`<style>+ html,body{margin:0;width:100%;height:100%;overflow:hidden;background:linear-gradient(90deg,#f6f6f6 50%,#181818 50%)}+ header{height:46px;-webkit-app-region:drag;background:#7f7f7f}+ </style><header></header>`));+ window.setTitle("Native Snap Regression");+ window.show(); window.focus();+ const snapshot = () => ({ processId: process.pid, title: window.getTitle(), nativeHandle,+ systemVersion: process.getSystemVersion(), electronVersion: process.versions.electron, legacySurface,+ workArea: screen.getDisplayMatching(window.getBounds()).workArea,+ displayBounds: screen.getDisplayMatching(window.getBounds()).bounds,+ maximized: window.isMaximized(), fullscreen: isWindowFullScreen(window),+ scaleFactor: screen.getDisplayMatching(window.getBounds()).scaleFactor });+ const flush = async () => { if (snap) await snap.flush(); if (corners) await corners.flush(); };+ await flush();+ fs.writeFileSync(path.join(root, "ready.json"), JSON.stringify(snapshot()));+ let active = false;+ timer = setInterval(async () => {+ const file = path.join(root, "command.json");+ if (active || !fs.existsSync(file)) return;+ active = true;+ try {+ const command = JSON.parse(fs.readFileSync(file, "utf8")); fs.unlinkSync(file);+ if (command.action === "quit") { app.quit(); return; }+ if (command.action === "reset") {+ if (isWindowFullScreen(window)) setWindowFullScreen(window, false, true);+ if (window.isMaximized()) window.unmaximize();+ window.setBounds({ x: 200, y: 140, width: 1200, height: 800 }); window.focus();+ }+ if (command.action === "maximize") window.maximize();+ if (command.action === "unmaximize") window.unmaximize();+ if (command.action === "minimize") window.minimize();+ if (command.action === "restore") window.restore();+ if (command.action === "fullscreen") setWindowFullScreen(window, command.value, true);+ await new Promise((done) => setTimeout(done, 500));+ await flush();+ fs.writeFileSync(path.join(root, "state.json"), JSON.stringify({ ...snapshot(), id: command.id }));+ } catch (error) {+ fs.writeFileSync(path.join(root, "fixture-error.txt"), String(error.stack || error));+ } finally { active = false; }+ }, 25);+}).catch(async (error) => {+ fs.writeFileSync(path.join(root, "fixture-error.txt"), String(error.stack || error));+ if (host) await host.stop().catch((cleanupError) => console.error("fixture Host cleanup failed", cleanupError));+ app.exit(1);+});++app.on("before-quit", (event) => {+ if (quitting) return;+ event.preventDefault(); quitting = true; clearInterval(timer);+ void (async () => {+ try { if (host) await host.stop(); app.exit(0); }+ catch (error) { console.error("fixture Host cleanup failed", error); app.exit(1); }+ })();+});+app.on("window-all-closed", () => app.quit());diff --git a/scripts/e2e/probe-window-snap.cs b/scripts/e2e/probe-window-snap.csnew file mode 100644index 000000000..72dd57fc4--- /dev/null+++ b/scripts/e2e/probe-window-snap.cs@@ -0,0 +1,208 @@+using System;+using System.IO;+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Threading;+using System.Drawing;+using System.Windows.Forms;+using System.Collections.Generic;+using System.Web.Script.Serialization;++public struct SnapRect { public int Left, Top, Right, Bottom; }+public struct SnapPoint { public int X, Y; }+public struct SnapMouseInput { public int x,y; public uint data,flags,time; public UIntPtr extra; }+public struct SnapInput { public uint type; public SnapMouseInput mouse; }+public static class WindowSnapProbe {+ [DllImport("user32.dll")] static extern int GetWindowLong(IntPtr h, int index);+ [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out SnapRect r);+ [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out SnapRect r);+ [DllImport("user32.dll")] static extern bool ClientToScreen(IntPtr h, ref SnapPoint p);+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();+ [DllImport("user32.dll")] static extern bool IsIconic(IntPtr window);+ [DllImport("user32.dll")] static extern short GetAsyncKeyState(int key);+ [DllImport("user32.dll")] static extern int GetSystemMetrics(int index);+ [DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr h, uint message, IntPtr wParam, IntPtr lParam);+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint processId);+ [DllImport("user32.dll")] static extern bool GetCursorPos(out SnapPoint p);+ [DllImport("user32.dll")] static extern bool SetCursorPos(int x, int y);+ [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);+ [DllImport("user32.dll",SetLastError=true)] static extern uint SendInput(uint count, SnapInput[] input, int size);+ [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);+ [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attribute, out SnapRect r, int size);+ static readonly string Root = AppDomain.CurrentDomain.BaseDirectory;+ static readonly JavaScriptSerializer Json = new JavaScriptSerializer();+ static readonly string RunId = Guid.NewGuid().ToString("N");+ static readonly Dictionary<string, object> Result = new Dictionary<string, object>();+ static int sequence, pointerSequence, checks;+ static bool externalPointer;+ static void Check(bool condition, string message) { if (!condition) throw new Exception(message); checks++; }+ static string FilePath(string name) { return Path.Combine(Root, name); }+ static int Number(Dictionary<string, object> value, string key) { return Convert.ToInt32(value[key]); }+ static Dictionary<string, object> Read(string name) {+ if (!File.Exists(FilePath(name))) return null;+ try { return Json.Deserialize<Dictionary<string, object>>(File.ReadAllText(FilePath(name))); }+ catch (ArgumentException) { return null; }+ }+ static void Wait(Func<bool> predicate, string message, int milliseconds = 5000) {+ var clock = Stopwatch.StartNew();+ Application.DoEvents();+ while (!predicate()) {+ if (File.Exists(FilePath("fixture-error.txt"))) throw new Exception(File.ReadAllText(FilePath("fixture-error.txt")));+ if (clock.ElapsedMilliseconds > milliseconds) throw new Exception(message);+ Application.DoEvents(); Thread.Sleep(25);+ }+ }+ static SnapRect Rect(IntPtr window) { SnapRect rect; Check(GetWindowRect(window, out rect), "read window bounds"); return rect; }+ static Dictionary<string, object> Bounds(IntPtr window) {+ var r = Rect(window); SnapRect client, visible; var origin = new SnapPoint();+ Check(GetClientRect(window, out client) && ClientToScreen(window, ref origin), "read client bounds");+ Check(DwmGetWindowAttribute(window, 9, out visible, 16) >= 0, "read DWM visible frame");+ return new Dictionary<string, object> {+ {"x",r.Left},{"y",r.Top},{"width",r.Right-r.Left},{"height",r.Bottom-r.Top},+ {"clientX",origin.X},{"clientY",origin.Y},{"clientWidth",client.Right},{"clientHeight",client.Bottom},+ {"visibleX",visible.Left},{"visibleY",visible.Top},{"visibleWidth",visible.Right-visible.Left},{"visibleHeight",visible.Bottom-visible.Top},+ {"style","0x"+GetWindowLong(window,-16).ToString("X8")}+ };+ }+ static bool IsRect(IntPtr window, int x, int y, int width, int height) {+ SnapRect r; return GetWindowRect(window,out r) && r.Left==x && r.Top==y && r.Right-r.Left==width && r.Bottom-r.Top==height;+ }+ static void Focus(IntPtr window) {+ var r = Rect(window);+ if(externalPointer) Pointer("click",r.Left+250,r.Top+100,0,0);+ else {SetCursorPos(r.Left+250,r.Top+100);InjectMouse(2);InjectMouse(4);}+ Wait(() => GetForegroundWindow()==window,"fixture did not receive real foreground input");+ Application.DoEvents(); Thread.Sleep(80);+ }+ static void Key(IntPtr window, byte key) {+ Focus(window);+ try { keybd_event(0x5b,0,0,UIntPtr.Zero); keybd_event(key,0,0,UIntPtr.Zero); Thread.Sleep(60); }+ finally { keybd_event(key,0,2,UIntPtr.Zero); keybd_event(0x5b,0,2,UIntPtr.Zero); }+ }+ static Dictionary<string, object> Command(string action, bool value = false) {+ int id=++sequence;+ File.WriteAllText(FilePath("command.json"),Json.Serialize(new Dictionary<string,object>{{"id",id},{"action",action},{"value",value}}));+ Dictionary<string,object> state=null;+ Wait(() => { state=Read("state.json"); return state!=null && Number(state,"id")==id; },"fixture command timed out: "+action,15000);+ return state;+ }+ static void Drag(int x, int y, int endX, int endY) {+ if(externalPointer) {Pointer("drag",x,y,endX,endY);return;}+ MovePointer(x,y); Application.DoEvents(); Thread.Sleep(80); InjectMouse(2); Application.DoEvents(); Thread.Sleep(50);+ try {+ Check((GetAsyncKeyState(1)&0x8000)!=0,"physical mouse down was not registered");+ for(int step=1;step<=12;step++){MovePointer(x+(endX-x)*step/12,y+(endY-y)*step/12);Application.DoEvents();Thread.Sleep(50);}+ }+ finally { InjectMouse(4); }+ }+ static void Pointer(string action, int x, int y, int endX, int endY) {+ int id=++pointerSequence;+ File.WriteAllText(FilePath("pointer-request.json"),Json.Serialize(new Dictionary<string,object>{{"runId",RunId},{"id",id},{"action",action},{"x",x},{"y",y},{"endX",endX},{"endY",endY}}));+ Dictionary<string,object> response=null;+ Wait(() => {response=Read("pointer-response.json");return response!=null && Number(response,"id")==id && (string)response["runId"]==RunId;},"external pointer adapter did not acknowledge input",30000);+ Check(response.ContainsKey("ok") && (bool)response["ok"],"external pointer input failed");+ }+ static void InjectMouse(uint flags, uint x=0, uint y=0) {+ var input=new SnapInput();input.mouse.x=(int)x;input.mouse.y=(int)y;input.mouse.flags=flags;+ Check(SendInput(1,new[]{input},Marshal.SizeOf(typeof(SnapInput)))==1,"native mouse input was rejected");+ }+ static void MovePointer(int x, int y) {+ uint absoluteX=(uint)Math.Round((x-GetSystemMetrics(76))*65535.0/(GetSystemMetrics(78)-1));+ uint absoluteY=(uint)Math.Round((y-GetSystemMetrics(77))*65535.0/(GetSystemMetrics(79)-1));+ InjectMouse(0xC001,absoluteX,absoluteY);+ }+ static void Pixels(IntPtr window, string label) {+ Focus(window); var r=Rect(window); int width=r.Right-r.Left,height=r.Bottom-r.Top;+ using(var bitmap=new Bitmap(width,height)) using(var graphics=Graphics.FromImage(bitmap)) {+ string mismatch="";+ try {+ // DWM reports target bounds before its snap animation finishes.+ Wait(() => {+ graphics.CopyFromScreen(r.Left,r.Top,0,0,bitmap.Size);+ foreach(var point in new[]{new Point(0,height/2),new Point(1,height/2),new Point(width-1,height/2),new Point(width-2,height/2),new Point(width/4,height-1),new Point(width*3/4,height-1)}) {+ var actual=bitmap.GetPixel(point.X,point.Y); int expected=point.X<width/2?246:24;+ if(Math.Abs(actual.R-expected)>3 || Math.Abs(actual.G-expected)>3 || Math.Abs(actual.B-expected)>3) {+ mismatch=point+": "+actual; return false;+ }+ }+ return true;+ },label+" client edge never reached its renderer colors");+ Check(true,label+" has no painted native rim");+ } catch(Exception error) {throw new Exception(label+" painted edge: "+mismatch,error);}+ finally {bitmap.Save(FilePath(label+".png"));}+ }+ }+ static void ClientEqualsWindow(IntPtr window) {+ var b=Bounds(window);+ Check(Number(b,"x")==Number(b,"clientX") && Number(b,"y")==Number(b,"clientY") && Number(b,"width")==Number(b,"clientWidth") && Number(b,"height")==Number(b,"clientHeight"),"native frame insets returned");+ }+ static void Maximized(IntPtr window, Dictionary<string,object> area, string label) {+ var b=Bounds(window); Result[label]=b;+ Check(Number(b,"clientX")==Number(area,"x") && Number(b,"clientY")==Number(area,"y") && Number(b,"clientWidth")==Number(area,"width") && Number(b,"clientHeight")==Number(area,"height"),label+" client extends beyond the work area");+ Check(Number(b,"visibleX")==Number(area,"x") && Number(b,"visibleY")==Number(area,"y") && Number(b,"visibleWidth")==Number(area,"width") && Number(b,"visibleHeight")==Number(area,"height"),label+" visible frame extends beyond the work area");+ }+ [STAThread] public static void Main() {+ Process child=null; SnapPoint pointer; bool saved=GetCursorPos(out pointer);+ NativeWindow foreign=new NativeWindow();+ try {+ SetThreadDpiAwarenessContext(new IntPtr(-4));+ var options=Read("options.json"); bool baseline=(bool)options["baseline"];+ externalPointer=options.ContainsKey("externalPointer") && (bool)options["externalPointer"];+ Result["pointerInput"]=externalPointer?"external":"native";+ var parameters=new CreateParams(); parameters.Style=unchecked((int)0x80000000); parameters.Width=1; parameters.Height=1;+ foreign.CreateHandle(parameters); int originalStyle=GetWindowLong(foreign.Handle,-16);+ foreach(var name in new[]{"ready.json","state.json","command.json","fixture-error.txt","pointer-request.json","pointer-response.json"}) File.Delete(FilePath(name));+ string electron=(string)options["electronBinary"]; if(!Path.IsPathRooted(electron))electron=FilePath(electron);+ var info=new ProcessStartInfo(electron,"\""+FilePath("main.cjs")+"\" "+(baseline?"--baseline ":"")+"--foreign-handle="+foreign.Handle.ToInt64()+" --user-data-dir=\""+FilePath("electron-profile")+"\"");+ info.UseShellExecute=false;info.CreateNoWindow=true;info.RedirectStandardOutput=true;info.RedirectStandardError=true;+ child=Process.Start(info); var stdout=child.StandardOutput.ReadToEndAsync(); var stderr=child.StandardError.ReadToEndAsync();+ Dictionary<string,object> ready=null;+ Wait(() => {ready=Read("ready.json");return ready!=null;},"fixture startup timed out",45000);+ var window=new IntPtr(long.Parse((string)ready["nativeHandle"])); uint owner;+ GetWindowThreadProcessId(window,out owner); Check(owner==(uint)Number(ready,"processId") && owner==child.Id,"fixture handle owner mismatch");+ Check(GetWindowLong(foreign.Handle,-16)==originalStyle,"foreign window style was modified");+ var area=(Dictionary<string,object>)ready["workArea"]; int x=Number(area,"x"),y=Number(area,"y"),half=Number(area,"width")/2,height=Number(area,"height");+ Check(half>=Number(options,"minWidth"),"work-area half is smaller than the nominal minimum width");+ Result["baseline"]=baseline;Result["environment"]=ready;Result["before"]=Bounds(window);+ Key(window,0x25); Thread.Sleep(300); Result["left"]=Bounds(window);+ Wait(() => IsRect(window,x,y,half,height),"Win+Left did not snap to the work-area half"); ClientEqualsWindow(window);Pixels(window,"left");+ Command("reset"); Key(window,0x27);+ Wait(() => IsRect(window,x+half,y,Number(area,"width")-half,height),"Win+Right did not snap to the work-area half");Result["right"]=Bounds(window);ClientEqualsWindow(window);Pixels(window,"right");+ Command("reset");Focus(window); var normal=Rect(window);+ Check(SendMessage(window,0x84,IntPtr.Zero,new IntPtr(((normal.Top+22)<<16)|((normal.Left+250)&0xffff))).ToInt64()==2,"titlebar does not expose native HTCAPTION");+ Drag(normal.Left+250,normal.Top+22,x,y+height/2);+ Result["dragLeft"]=Bounds(window);+ Wait(() => IsRect(window,x,y,half,height),"titlebar drag did not snap to the work-area half");Result["dragLeft"]=Bounds(window);ClientEqualsWindow(window);+ Command("reset");Pixels(window,"normal");normal=Rect(window);+ Drag(normal.Right-1,normal.Top+height/3,normal.Right+99,normal.Top+height/3);+ Wait(() => Rect(window).Right-Rect(window).Left>=1290,"native right edge did not resize");Result["resized"]=Bounds(window);ClientEqualsWindow(window);Pixels(window,"resized");+ Command("reset");normal=Rect(window);Drag(normal.Left+1,normal.Top+300,normal.Right-10,normal.Top+300);+ Wait(() => Rect(window).Right-Rect(window).Left==Number(options,"minWidth"),"native minimum width was not enforced");Result["minimumWidth"]=Bounds(window);+ Command("reset");normal=Rect(window);Drag(normal.Left+300,normal.Bottom-1,normal.Left+300,normal.Top+10);+ Wait(() => Rect(window).Bottom-Rect(window).Top==Number(options,"minHeight"),"native minimum height was not enforced");Result["minimumHeight"]=Bounds(window);+ Command("reset");Key(window,0x26);Command("snapshot");Maximized(window,area,"keyboardMaximized");+ Key(window,0x28);Wait(() => IsRect(window,200,140,1200,800),"Win+Down did not restore the normal window");+ Key(window,0x28);Wait(() => IsIconic(window),"Win+Down did not minimize the normal window");Command("restore");+ Command("reset");Command("maximize");Maximized(window,area,"maximized");+ Command("minimize");Command("restore");Maximized(window,area,"restoredMaximized");+ Command("unmaximize");ClientEqualsWindow(window);Pixels(window,"restored");+ var state=Command("fullscreen",true);Check((bool)state["fullscreen"],"fullscreen state was lost");+ var display=(Dictionary<string,object>)ready["displayBounds"];+ Wait(() => IsRect(window,Number(display,"x"),Number(display,"y"),Number(display,"width"),Number(display,"height")),"fullscreen does not fill the display");+ Command("fullscreen",false);ClientEqualsWindow(window);Pixels(window,"after-fullscreen");+ Key(window,0x25);Wait(() => IsRect(window,x,y,half,height),"snapping was lost after fullscreen");+ Result["ok"]=true;+ File.WriteAllText(FilePath("command.json"),"{\"action\":\"quit\"}");+ Check(child.WaitForExit(10000),"fixture did not retire its Host");+ File.WriteAllText(FilePath("stdout.txt"),stdout.Result);File.WriteAllText(FilePath("stderr.txt"),stderr.Result);+ } catch(Exception error) {Result["ok"]=false;Result["error"]=error.ToString();}+ finally {+ if(child!=null && !child.HasExited){+ File.WriteAllText(FilePath("command.json"),"{\"action\":\"quit\"}");+ if(!child.WaitForExit(10000)){child.Kill();child.WaitForExit();}+ }+ foreign.DestroyHandle();if(saved)SetCursorPos(pointer.X,pointer.Y);+ Result["checks"]=checks;File.WriteAllText(FilePath("result.json"),Json.Serialize(Result));+ }+ }+}