Skip to content

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

test(window): retain native evidence and add independent Windows replay

Linuxdazhaoebf2800f7e8f
diff --git a/.github/workflows/windows-native-snap.yml b/.github/workflows/windows-native-snap.yml
new file mode 100644
index 000000000..2f50721f2
--- /dev/null
+++ b/.github/workflows/windows-native-snap.yml
@@ -0,0 +1,61 @@
+name: Windows native snap acceptance
+
+on:
+ workflow_dispatch:
+ push:
+ paths:
+ - '.github/workflows/windows-native-snap.yml'
+ - 'scripts/e2e-window-snap.mjs'
+ - 'scripts/e2e/run-window-snap.ps1'
+ - 'scripts/e2e/probe-window-snap.cs'
+ - 'scripts/e2e/fixtures/window-snap/**'
+ - 'apps/desktop/electron/main/window-*.ts'
+ - 'crates/host-core/src/rpc/window_*.rs'
+ pull_request:
+ paths:
+ - '.github/workflows/windows-native-snap.yml'
+ - 'scripts/e2e-window-snap.mjs'
+ - 'scripts/e2e/run-window-snap.ps1'
+ - 'scripts/e2e/probe-window-snap.cs'
+ - 'scripts/e2e/fixtures/window-snap/**'
+ - 'apps/desktop/electron/main/window-*.ts'
+ - 'crates/host-core/src/rpc/window_*.rs'
+
+permissions:
+ contents: read
+
+jobs:
+ native-snap:
+ name: Interactive baseline / candidate / frame pixels
+ runs-on: windows-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: pnpm/action-setup@v6
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 24
+ cache: pnpm
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ - name: Install pinned Electron
+ run: pnpm --filter @pi-desktop/desktop exec install-electron
+ - name: Build native Host
+ run: cargo build -p host-core --locked
+ - name: Run interactive native acceptance
+ shell: pwsh
+ run: node scripts/e2e-window-snap.mjs --matrix --artifacts "$env:RUNNER_TEMP/native-snap-evidence"
+ - name: Retain native results, logs, screenshots and replay sources
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: native-snap-${{ github.event.pull_request.head.sha || github.sha }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/native-snap-evidence
+ if-no-files-found: error
+ retention-days: 30
diff --git a/docs/adr/windows-native-snap-without-frame-insets.md b/docs/adr/windows-native-snap-without-frame-insets.md
index 010e9aeb4..7606095fd 100644
--- a/docs/adr/windows-native-snap-without-frame-insets.md
+++ b/docs/adr/windows-native-snap-without-frame-insets.md
@@ -51,6 +51,12 @@ on the available Windows version, not a real Windows 10 installation.
`ok: true`. Native geometry/pixel assertions are identical for both input paths;
the fixture never treats an input acknowledgement alone as success.
+`--matrix --artifacts <new-directory>` runs the expected failing baseline and
+passing candidate as one acceptance job. The portable `run.ps1` and Windows
+workflow retain revision/hash provenance, results, logs and pixel captures on
+failure as well as success. A baseline startup/input failure cannot qualify
+the reproduction. See [independent replay](../project/windows-native-snap-replay.md).
+
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
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/after-fullscreen.png b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/after-fullscreen.png
new file mode 100644
index 000000000..8db0e15fc
Binary files /dev/null and b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/after-fullscreen.png differ
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/baseline.json b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/baseline.json
new file mode 100644
index 000000000..f31808ab2
--- /dev/null
+++ b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/baseline.json
@@ -0,0 +1 @@
+{"pointerInput":"external","baseline":true,"environment":{"processId":18792,"title":"Native Snap Regression","nativeHandle":"2228830","systemVersion":"10.0.26100","electronVersion":"43.6.0","legacySurface":false,"workArea":{"x":0,"y":0,"width":2560,"height":1392},"displayBounds":{"x":0,"y":0,"width":2560,"height":1440},"maximized":false,"fullscreen":false,"scaleFactor":1},"before":{"x":200,"y":140,"width":1200,"height":800,"clientX":200,"clientY":140,"clientWidth":1200,"clientHeight":800,"visibleX":200,"visibleY":140,"visibleWidth":1200,"visibleHeight":800,"style":"0x14030000"},"left":{"x":200,"y":140,"width":1200,"height":800,"clientX":200,"clientY":140,"clientWidth":1200,"clientHeight":800,"visibleX":200,"visibleY":140,"visibleWidth":1200,"visibleHeight":800,"style":"0x14030000"},"ok":false,"error":"System.Exception: Win+Left did not snap to the work-area half\r\n 在 WindowSnapProbe.Wait(Func`1 predicate, String message, Int32 milliseconds)\r\n 在 WindowSnapProbe.Main()","checks":11}
\ No newline at end of file
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/candidate.json b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/candidate.json
new file mode 100644
index 000000000..32b99ae1a
--- /dev/null
+++ b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/candidate.json
@@ -0,0 +1 @@
+{"pointerInput":"external","baseline":false,"environment":{"processId":17884,"title":"Native Snap Regression","nativeHandle":"1114960","systemVersion":"10.0.26100","electronVersion":"43.6.0","legacySurface":false,"workArea":{"x":0,"y":0,"width":2560,"height":1392},"displayBounds":{"x":0,"y":0,"width":2560,"height":1440},"maximized":false,"fullscreen":false,"scaleFactor":1},"before":{"x":200,"y":140,"width":1200,"height":800,"clientX":200,"clientY":140,"clientWidth":1200,"clientHeight":800,"visibleX":200,"visibleY":140,"visibleWidth":1200,"visibleHeight":800,"style":"0x14C70000"},"left":{"x":0,"y":0,"width":1280,"height":1392,"clientX":0,"clientY":0,"clientWidth":1280,"clientHeight":1392,"visibleX":0,"visibleY":0,"visibleWidth":1280,"visibleHeight":1392,"style":"0x14C70000"},"right":{"x":1280,"y":0,"width":1280,"height":1392,"clientX":1280,"clientY":0,"clientWidth":1280,"clientHeight":1392,"visibleX":1280,"visibleY":0,"visibleWidth":1280,"visibleHeight":1392,"style":"0x14C70000"},"dragLeft":{"x":0,"y":0,"width":1280,"height":1392,"clientX":0,"clientY":0,"clientWidth":1280,"clientHeight":1392,"visibleX":0,"visibleY":0,"visibleWidth":1280,"visibleHeight":1392,"style":"0x14C70000"},"resized":{"x":205,"y":140,"width":1295,"height":800,"clientX":205,"clientY":140,"clientWidth":1295,"clientHeight":800,"visibleX":205,"visibleY":140,"visibleWidth":1295,"visibleHeight":800,"style":"0x14C70000"},"minimumWidth":{"x":600,"y":140,"width":800,"height":800,"clientX":600,"clientY":140,"clientWidth":800,"clientHeight":800,"visibleX":600,"visibleY":140,"visibleWidth":800,"visibleHeight":800,"style":"0x14C70000"},"minimumHeight":{"x":200,"y":140,"width":1200,"height":560,"clientX":200,"clientY":140,"clientWidth":1200,"clientHeight":560,"visibleX":200,"visibleY":140,"visibleWidth":1200,"visibleHeight":560,"style":"0x14C70000"},"keyboardMaximized":{"x":-8,"y":-8,"width":2576,"height":1408,"clientX":0,"clientY":0,"clientWidth":2560,"clientHeight":1392,"visibleX":0,"visibleY":0,"visibleWidth":2560,"visibleHeight":1392,"style":"0x15C70000"},"maximized":{"x":-8,"y":-8,"width":2576,"height":1408,"clientX":0,"clientY":0,"clientWidth":2560,"clientHeight":1392,"visibleX":0,"visibleY":0,"visibleWidth":2560,"visibleHeight":1392,"style":"0x15C70000"},"restoredMaximized":{"x":-8,"y":-8,"width":2576,"height":1408,"clientX":0,"clientY":0,"clientWidth":2560,"clientHeight":1392,"visibleX":0,"visibleY":0,"visibleWidth":2560,"visibleHeight":1392,"style":"0x15C70000"},"ok":true,"checks":121}
\ No newline at end of file
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/left.png b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/left.png
new file mode 100644
index 000000000..469dac395
Binary files /dev/null and b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/left.png differ
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/manifest.json b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/manifest.json
new file mode 100644
index 000000000..ffbe0a3c3
--- /dev/null
+++ b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/manifest.json
@@ -0,0 +1,17 @@
+{
+ "schemaVersion": 1,
+ "sourceRevision": "38c5a5bd77ef910849ce3c1bc5f5d8577dad1a71",
+ "recordKind": "preserved-author-run",
+ "provenance": "Recorded after the original run from preserved results and streams. Source revision follows the staging record; this is not an independently attested or replayed CI run.",
+ "hostSha256": "ee2561677531af10f13f47cf3a528dea6c870d56dccca5af2ec4a350b72b0d50",
+ "compiledProbeSourceSha256": "9b6d4d37c35990c7c0c7a894f7cdb72c33201fa6aa00e2ca5c689b77a14016be",
+ "files": {
+ "after-fullscreen.png": "720478217b8b8070be481dfa4dc5b0a5eaa72c6316d32fab34304dc2742447b1",
+ "baseline.json": "85f7fe820ba941fe615e23d06bd305b7b50d87ae8450ce3b8f0f83caa029d81d",
+ "candidate.json": "64ffd806019fcc1a4bbc36abe24b9bc0b8f3ef6ebcf8f30e55e6e1793f730d7d",
+ "left.png": "ba7bd348d928c658c3245f8bc4719cfa78e051683caa2b761707ae29121d25c8",
+ "normal.png": "720478217b8b8070be481dfa4dc5b0a5eaa72c6316d32fab34304dc2742447b1",
+ "stderr.txt": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "stdout.txt": "7eb70257593da06f682a3ddda54a9d260d4fc514f645237f5ca74b08f8da61a6"
+ }
+}
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/normal.png b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/normal.png
new file mode 100644
index 000000000..8db0e15fc
Binary files /dev/null and b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/normal.png differ
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/stderr.txt b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/stderr.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/project/windows-native-snap-evidence/38c5a5bd77ef/stdout.txt b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/stdout.txt
new file mode 100644
index 000000000..8b1378917
--- /dev/null
+++ b/docs/project/windows-native-snap-evidence/38c5a5bd77ef/stdout.txt
@@ -0,0 +1 @@
+
diff --git a/docs/project/windows-native-snap-replay.md b/docs/project/windows-native-snap-replay.md
new file mode 100644
index 000000000..21ef1a400
--- /dev/null
+++ b/docs/project/windows-native-snap-replay.md
@@ -0,0 +1,103 @@
+# Replaying Windows native snap acceptance
+
+The `Windows native snap acceptance` workflow runs baseline and candidate in
+one Windows job and uploads evidence even when acceptance fails. It checks out
+the exact pull request head, builds Host with `Cargo.lock`, and installs the
+pinned Electron. The job uses read-only permissions, no credentials, and no
+deployment. Its artifact is named `native-snap-<head SHA>-<attempt>`.
+
+## Independent interactive Windows run
+
+Use an unlocked Windows desktop with snapping enabled, an available DWM,
+100% scale and at least a 1920×1080 display. Session 0 and locked desktops fail
+explicitly. Keep the desktop free of unrelated windows while input is sent.
+An RDP connection must remain connected. Windows Server runs are recorded as
+that product, not described as Windows 11 client qualification.
+
+Fetch the PR head into a separate worktree:
+
+```powershell
+git fetch https://github.com/vastsa/PI-Desktop.git pull/2333/head
+git worktree add --detach ../native-snap-review FETCH_HEAD
+Set-Location ../native-snap-review
+git rev-parse HEAD
+```
+
+Reuse provisioned Node/pnpm, compatible workspace dependencies, Rust and MSVC
+build tools. Clean CI runners install with `pnpm install --frozen-lockfile`;
+a reviewer with an existing development environment reuses it per AGENTS.md.
+
+```powershell
+cargo build -p host-core --locked
+pnpm --filter @pi-desktop/desktop exec install-electron
+$artifacts = Join-Path $env:TEMP ('native-snap-evidence-' + [Guid]::NewGuid())
+node scripts/e2e-window-snap.mjs --matrix --artifacts $artifacts
+Get-Content "$artifacts/summary.json"
+```
+
+For a Windows build machine without the JavaScript build toolchain, prepare
+the same portable job in a clean source worktree with compatible dependencies:
+
+```sh
+PI_DESKTOP_HOST_BIN='C:\validation\pi-desktop-host-core.exe' \
+PI_DESKTOP_SNAP_ELECTRON='C:\validation\electron\electron.exe' \
+node scripts/e2e-window-snap.mjs --prepare /tmp/native-snap-job
+```
+
+Copy that directory to Windows and run the included job in the interactive
+account, using a Host built from the revision recorded in `source.json`:
+
+```powershell
+powershell.exe -NoProfile -File C:\validation\native-snap-job\run.ps1 `
+ -Matrix -ArtifactDirectory C:\validation\native-snap-evidence
+```
+
+`--prepare` alone is not acceptance. Dirty source is recorded and rejected.
+Use a new output directory for every attempt. The input adapter option remains
+available for remote desktops that cannot use native SendInput:
+`--external-pointer` stages requests in the runtime directory named by
+`active-directory.txt` while the job runs. An adapter acknowledges the same
+`runId`/`id`; the geometry and pixel assertions still determine the result.
+The standard workflow and native path require no private adapter or account.
+
+## Verdict and evidence
+
+Matrix success requires both:
+
+- Baseline: the snap service is omitted, its style lacks the fixed snap mask,
+ Win+Left leaves the original bounds unchanged, and the exact failure is
+ `Win+Left did not snap to the work-area half`. Startup/input/desktop errors
+ are failures of the job, never accepted as reproduction.
+- Candidate: every native assertion passes, including physical titlebar
+ snapping, light/dark client-edge pixels, minimum sizes, Win+Up/Down,
+ maximize/minimize/restore and fullscreen restoration. Maximized client and
+ DWM-visible rectangles must equal the work area. The maximized client pixels
+ are also captured; invisible native resize margins are measured separately.
+
+The artifact contains source revision/tree and file hashes, runtime Host and
+Electron SHA256, actual OS/session/display metadata, baseline/candidate JSON,
+timestamped probe logs, Electron stdout/stderr, fixture errors on failure,
+synthetic-window PNGs, replay sources, the compiled probe and `SHA256SUMS`.
+Profiles, databases, credentials and unrelated desktop captures are excluded.
+Temporary runtime/user paths in diagnostic text are redacted on export.
+
+Download the job artifact from the Actions run. Check `summary.json`'s source
+revision against the PR head, check every hash in `SHA256SUMS`, and compare
+`source.hashes` with that checkout. Retaining a prior artifact does not qualify
+a later executable revision. The native checks exercise production Main
+services and the real Host with synthetic content, not the full renderer or
+an installed application. Windows 10, legacy transparent windows, mixed DPI
+and hover Snap Layouts remain outside this qualification.
+
+## Preserved original-head evidence
+
+[Original-head artifacts](windows-native-snap-evidence/38c5a5bd77ef/manifest.json)
+retain the original `38c5a5bd77ef910849ce3c1bc5f5d8577dad1a71` author run:
+[baseline](windows-native-snap-evidence/38c5a5bd77ef/baseline.json),
+[candidate](windows-native-snap-evidence/38c5a5bd77ef/candidate.json),
+[normal pixels](windows-native-snap-evidence/38c5a5bd77ef/normal.png),
+[snapped pixels](windows-native-snap-evidence/38c5a5bd77ef/left.png),
+[restored pixels](windows-native-snap-evidence/38c5a5bd77ef/after-fullscreen.png),
+and stdout/stderr. The manifest was reconstructed from preserved files and
+the staging record after the run; it is not independent attestation. The
+current replay job records provenance before launching the probe.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 6bf206cfa..78e845d99 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -14136,6 +14136,16 @@ record actual OS/DPI, source revision, Host, Electron version, result and artifa
from the Windows run separately. Native Windows 10 and mixed-monitor DPI checks
remain separate qualification, and hover Snap Layouts is outside this regression.
+For independent review, run `--matrix --artifacts <new-directory>` or the
+`Windows native snap acceptance` workflow. Only the exact unchanged-bounds
+Win+Left baseline failure plus a fully passing candidate qualifies. Locked
+desktops, session 0, input failures and startup errors must fail the job.
+Retain SHA/tree/source hashes, binary hashes, OS/session/display metadata,
+baseline/candidate JSON, timestamped logs, stdout/stderr and normal/snapped/
+maximized/restored client PNGs. Upload artifacts even on failure; exclude
+profiles and redact runtime/user paths. See
+[native replay procedure](../../project/windows-native-snap-replay.md).
+
- **Preconditions**: PI-Desktop is open in a normal, non-maximized window on
macOS, Windows, or Linux. On Windows, the left, bottom, and right rim must
have no visible native border. Run the case with the work panel closed and once
diff --git a/scripts/README.md b/scripts/README.md
index fcc89dbf0..edbb902a9 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -53,7 +53,8 @@ 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-window-snap.mjs` | `pnpm test:e2e:window-snap [--matrix --artifacts <new-directory>] [--baseline] [--external-pointer] [--prepare <directory>]` | Windows shell snapping, native frame pixels, resize/minimums, maximize/restore and fullscreen through production Main/Host services; [independent replay](../docs/project/windows-native-snap-replay.md) |
+| `e2e/run-window-snap.ps1` | Portable fixture `run.ps1 -Matrix -ArtifactDirectory <new-directory>` | Interactive baseline/candidate job with source/binary provenance and retained results, logs and pixel artifacts |
| `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-snap.mjs b/scripts/e2e-window-snap.mjs
index 03993198d..d276ef998 100644
--- a/scripts/e2e-window-snap.mjs
+++ b/scripts/e2e-window-snap.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { createRequire } from "node:module";
import { mkdir, copyFile, readFile, writeFile, mkdtemp } from "node:fs/promises";
@@ -10,6 +11,8 @@ import { promisify } from "node:util";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const prepare = process.argv.includes("--prepare");
+const matrix = process.argv.includes("--matrix");
+const run = promisify(execFile);
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-"));
@@ -33,6 +36,20 @@ await build({
} }],
});
await copyFile(join(root, "scripts/e2e/probe-window-snap.cs"), join(directory, "probe.cs"));
+await copyFile(join(root, "scripts/e2e/run-window-snap.ps1"), join(directory, "run.ps1"));
+const git = async (...args) => (await run("git", args, { cwd: root })).stdout.trim();
+const files = ["scripts/e2e-window-snap.mjs", "scripts/e2e/run-window-snap.ps1", "scripts/e2e/probe-window-snap.cs",
+ "scripts/e2e/fixtures/window-snap/main.cjs", "scripts/e2e/host.mjs", "pnpm-lock.yaml", "Cargo.lock",
+ "apps/desktop/package.json", "apps/desktop/electron/main/window-native-snap.ts",
+ "apps/desktop/electron/main/window-native-corners.ts", "apps/desktop/electron/main/window-native-handle.ts",
+ "apps/desktop/electron/main/window-fullscreen.ts", "apps/desktop/electron/main/window-shape.ts",
+ "crates/host-core/src/rpc/window_snap_rpc.rs", "crates/host-core/src/rpc/window_owner.rs"];
+const hashes = {};
+for (const file of files) hashes[file] = createHash("sha256").update(await readFile(join(root, file))).digest("hex");
+await writeFile(join(directory, "source.json"), JSON.stringify({
+ revision: await git("rev-parse", "HEAD"), tree: await git("rev-parse", "HEAD^{tree}"),
+ clean: (await git("status", "--porcelain", "--untracked-files=no")) === "", hashes,
+}, null, 2));
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")),
@@ -44,13 +61,13 @@ await writeFile(join(directory, "options.json"), JSON.stringify({
}));
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"));
+ const index = process.argv.indexOf("--artifacts");
+ const artifacts = index < 0 ? join(directory, "artifacts") : resolve(process.argv[index + 1]);
+ try {
+ await run("powershell.exe", ["-NoProfile", "-File", join(directory, "run.ps1"),
+ "-ArtifactDirectory", artifacts, ...(matrix ? ["-Matrix"] : [])], { timeout: 660_000 });
+ } finally { console.log(`Native snap artifacts: ${artifacts}`); }
+ const result = JSON.parse(await readFile(join(artifacts, "summary.json"), "utf8"));
assert.equal(result.ok, true, JSON.stringify(result));
- console.log(JSON.stringify({ ...result, artifacts: directory }));
+ console.log(JSON.stringify(result));
}
diff --git a/scripts/e2e/probe-window-snap.cs b/scripts/e2e/probe-window-snap.cs
index 933763257..906df4df7 100644
--- a/scripts/e2e/probe-window-snap.cs
+++ b/scripts/e2e/probe-window-snap.cs
@@ -28,6 +28,8 @@ public static class WindowSnapProbe {
[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("user32.dll",SetLastError=true)] static extern IntPtr OpenInputDesktop(uint flags,bool inherit,uint access);
+ [DllImport("user32.dll")] static extern bool CloseDesktop(IntPtr desktop);
[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();
@@ -35,6 +37,7 @@ public static class WindowSnapProbe {
static readonly Dictionary<string, object> Result = new Dictionary<string, object>();
static int sequence, pointerSequence, checks;
static bool externalPointer;
+ static void Log(string message) { File.AppendAllText(FilePath("probe.log"),DateTime.UtcNow.ToString("o")+" "+message+Environment.NewLine); }
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]); }
@@ -91,6 +94,7 @@ public static class WindowSnapProbe {
File.Move(temporary,destination);
}
static Dictionary<string, object> Command(string action, bool value = false) {
+ Log("window command: "+action+" "+value);
int id=++sequence;
WriteCommand(Json.Serialize(new Dictionary<string,object>{{"id",id},{"action",action},{"value",value}}));
Dictionary<string,object> state=null;
@@ -122,8 +126,14 @@ public static class WindowSnapProbe {
uint absoluteY=(uint)Math.Round((y-GetSystemMetrics(77))*65535.0/(GetSystemMetrics(79)-1));
InjectMouse(0xC001,absoluteX,absoluteY);
}
- static void Pixels(IntPtr window, string label) {
+ static void Pixels(IntPtr window, string label, bool clientOnly = false) {
Focus(window); var r=Rect(window); int width=r.Right-r.Left,height=r.Bottom-r.Top;
+ if(clientOnly) {
+ SnapRect client;var origin=new SnapPoint();
+ Check(GetClientRect(window,out client) && ClientToScreen(window,ref origin),"read maximized pixels");
+ r.Left=origin.X;r.Top=origin.Y;width=client.Right;height=client.Bottom;
+ }
+ Log("checking pixels: "+label);
using(var bitmap=new Bitmap(width,height)) using(var graphics=Graphics.FromImage(bitmap)) {
string mismatch="";
try {
@@ -151,22 +161,31 @@ public static class WindowSnapProbe {
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");
+ Pixels(window,label,true);
}
[STAThread] public static void Main() {
Process child=null; SnapPoint pointer; bool saved=GetCursorPos(out pointer);
+ System.Threading.Tasks.Task<string> stdout=null,stderr=null;
NativeWindow foreign=new NativeWindow();
try {
+ Result["runId"]=RunId;Result["startedAt"]=DateTime.UtcNow.ToString("o");
+ Result["sessionId"]=Process.GetCurrentProcess().SessionId;
+ Log("starting native snap acceptance");
+ Check(Process.GetCurrentProcess().SessionId>0,"an interactive Windows session is required; session 0 is unsupported");
+ var desktop=OpenInputDesktop(0,false,0x101);
+ Check(desktop!=IntPtr.Zero,"the interactive input desktop is unavailable or locked");
+ CloseDesktop(desktop);
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));
+ foreach(var name in new[]{"result.json","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();
+ child=Process.Start(info); stdout=child.StandardOutput.ReadToEndAsync(); 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;
@@ -175,6 +194,7 @@ public static class WindowSnapProbe {
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);
+ Log("checking Win+Left");
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);
@@ -200,20 +220,27 @@ public static class WindowSnapProbe {
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");
+ Result["fullscreen"]=Bounds(window);
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["afterFullscreenSnap"]=Bounds(window);
Result["ok"]=true;
WriteCommand("{\"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();}
+ } catch(Exception error) {Result["ok"]=false;Result["failure"]=error.Message;Result["error"]=error.ToString();Log("failed: "+error.Message);}
finally {
if(child!=null && !child.HasExited){
WriteCommand("{\"action\":\"quit\"}");
- if(!child.WaitForExit(10000)){child.Kill();child.WaitForExit();}
+ if(!child.WaitForExit(10000)){
+ var kill=Process.Start(new ProcessStartInfo("taskkill.exe","/PID "+child.Id+" /T /F"){UseShellExecute=false,CreateNoWindow=true});
+ kill.WaitForExit(10000);child.WaitForExit(5000);
+ }
}
+ if(stdout!=null)File.WriteAllText(FilePath("stdout.txt"),stdout.Wait(5000)?stdout.Result:"stdout collection timed out");
+ if(stderr!=null)File.WriteAllText(FilePath("stderr.txt"),stderr.Wait(5000)?stderr.Result:"stderr collection timed out");
foreign.DestroyHandle();if(saved)SetCursorPos(pointer.X,pointer.Y);
- Result["checks"]=checks;File.WriteAllText(FilePath("result.json"),Json.Serialize(Result));
+ Result["checks"]=checks;Result["finishedAt"]=DateTime.UtcNow.ToString("o");
+ File.WriteAllText(FilePath("result.json"),Json.Serialize(Result));Log("completed: "+Result["ok"]+" checks="+checks);
}
}
}
diff --git a/scripts/e2e/run-window-snap.ps1 b/scripts/e2e/run-window-snap.ps1
new file mode 100644
index 000000000..eb180b2b1
--- /dev/null
+++ b/scripts/e2e/run-window-snap.ps1
@@ -0,0 +1,99 @@
+param(
+ [string]$ArtifactDirectory = (Join-Path $PSScriptRoot 'artifacts'),
+ [switch]$Matrix
+)
+$ErrorActionPreference = 'Stop'
+$root = $PSScriptRoot
+$ArtifactDirectory = [IO.Path]::GetFullPath($ArtifactDirectory)
+if (Test-Path $ArtifactDirectory) { throw 'Use a new artifact directory for every run.' }
+New-Item -ItemType Directory $ArtifactDirectory | Out-Null
+$options = Get-Content (Join-Path $root 'options.json') -Raw | ConvertFrom-Json
+$source = Get-Content (Join-Path $root 'source.json') -Raw | ConvertFrom-Json
+$summary = [ordered]@{ schemaVersion = 1; source = $source; startedAt = [DateTime]::UtcNow.ToString('o'); ok = $false; cases = @() }
+$scratch = Join-Path ([IO.Path]::GetTempPath()) ('native-snap-' + [Guid]::NewGuid().ToString('N'))
+function Resolve-Binary($value) {
+ if ([IO.Path]::IsPathRooted($value)) { return $value }
+ return Join-Path $root $value
+}
+function Write-Json($path, $value) {
+ [IO.File]::WriteAllText($path, ($value | ConvertTo-Json -Depth 30), [Text.UTF8Encoding]::new($false))
+}
+try {
+ if (-not $source.clean) { throw 'Native acceptance requires a clean source checkout.' }
+ $summary.os = Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber
+ $summary.sessionId = [Diagnostics.Process]::GetCurrentProcess().SessionId
+ $summary.interactive = [Environment]::UserInteractive
+ $options.hostBinary = Resolve-Binary $options.hostBinary
+ $options.electronBinary = Resolve-Binary $options.electronBinary
+ $summary.hostSha256 = (Get-FileHash $options.hostBinary -Algorithm SHA256).Hash.ToLowerInvariant()
+ $summary.electronSha256 = (Get-FileHash $options.electronBinary -Algorithm SHA256).Hash.ToLowerInvariant()
+ New-Item -ItemType Directory $scratch | Out-Null
+ Add-Type -Path (Join-Path $root 'probe.cs') -OutputAssembly (Join-Path $scratch 'probe.exe') -OutputType WindowsApplication -ReferencedAssemblies System.dll,System.Drawing.dll,System.Windows.Forms.dll,System.Web.Extensions.dll
+ $cases = @('candidate')
+ if ($options.baseline) { $cases = @('baseline') }
+ if ($Matrix) { $cases = @('baseline', 'candidate') }
+ foreach ($case in $cases) {
+ $runtime = Join-Path $scratch $case
+ $evidence = Join-Path $ArtifactDirectory $case
+ New-Item -ItemType Directory $runtime, $evidence | Out-Null
+ Copy-Item (Join-Path $root 'main.cjs') $runtime
+ Copy-Item (Join-Path $scratch 'probe.exe') $runtime
+ $options.baseline = ($case -eq 'baseline')
+ Write-Json (Join-Path $runtime 'options.json') $options
+ # An external adapter follows this file; no private transport is required by the native path.
+ [IO.File]::WriteAllText((Join-Path $ArtifactDirectory 'active-directory.txt'), $runtime)
+ $process = Start-Process (Join-Path $runtime 'probe.exe') -PassThru
+ $completed = $process.WaitForExit(300000)
+ if (-not $completed) {
+ & taskkill.exe /PID $process.Id /T /F | Out-Null
+ }
+ # Never upload profiles, databases, user paths or unrelated desktop captures.
+ foreach ($name in @('result.json', 'ready.json', 'probe.log', 'stdout.txt', 'stderr.txt', 'fixture-error.txt')) {
+ $file = Join-Path $runtime $name
+ if (Test-Path $file) {
+ $text = [IO.File]::ReadAllText($file)
+ foreach ($privatePath in @($runtime, $root, $env:USERPROFILE)) {
+ if ($privatePath) {
+ $text = $text.Replace($privatePath.Replace('\', '\\'), '<runtime>').Replace($privatePath, '<runtime>')
+ }
+ }
+ [IO.File]::WriteAllText((Join-Path $evidence $name), $text, [Text.UTF8Encoding]::new($false))
+ }
+ }
+ Get-ChildItem $runtime -Filter '*.png' | Copy-Item -Destination $evidence
+ if (-not $completed) { throw "$case native probe timed out; see retained artifacts." }
+ $result = Get-Content (Join-Path $evidence 'result.json') -Raw | ConvertFrom-Json
+ if ($case -eq 'baseline' -and $Matrix) {
+ $unchanged = $true
+ foreach ($field in @('x', 'y', 'width', 'height')) {
+ if ($result.before.$field -ne $result.left.$field) { $unchanged = $false }
+ }
+ $style = [Convert]::ToUInt32($result.before.style.Substring(2), 16)
+ $passed = ($result.ok -eq $false -and $result.baseline -eq $true -and
+ $result.failure -ceq 'Win+Left did not snap to the work-area half' -and
+ $unchanged -and ($style -band 0x00C40000) -eq 0)
+ } else {
+ $passed = ($result.ok -eq $true -and $result.baseline -eq $false)
+ }
+ $summary.cases += [ordered]@{ name = $case; runId = $result.runId; passed = $passed; checks = $result.checks }
+ if (-not $passed) { throw "$case did not satisfy its acceptance contract; see retained artifacts." }
+ }
+ $summary.ok = $true
+} catch {
+ $summary.error = $_.Exception.Message
+ throw
+} finally {
+ $summary.finishedAt = [DateTime]::UtcNow.ToString('o')
+ Write-Json (Join-Path $ArtifactDirectory 'summary.json') $summary
+ foreach ($name in @('main.cjs', 'probe.cs', 'run.ps1', 'source.json')) {
+ Copy-Item (Join-Path $root $name) $ArtifactDirectory
+ }
+ if (Test-Path (Join-Path $scratch 'probe.exe')) { Copy-Item (Join-Path $scratch 'probe.exe') $ArtifactDirectory }
+ $hashes = Get-ChildItem $ArtifactDirectory -Recurse -File | Where-Object Name -ne 'active-directory.txt' | ForEach-Object {
+ $relative = $_.FullName.Substring($ArtifactDirectory.Length + 1).Replace('\', '/')
+ (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() + ' ' + $relative
+ }
+ [IO.File]::WriteAllLines((Join-Path $ArtifactDirectory 'SHA256SUMS'), [string[]]$hashes)
+ Remove-Item (Join-Path $ArtifactDirectory 'active-directory.txt') -ErrorAction SilentlyContinue
+ if (Test-Path $scratch) { Remove-Item $scratch -Recurse -Force }
+}