test: add a CDP-based pre-release UI smoke harness

The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside
it (window renders white, msedgewebview2 exits immediately; Edge headless
fails with a Mojo platform-channel access-denied fatal). UI verification
therefore moves to a script the user runs from a normal desktop shell.

- agent/tests/ui-smoke.ps1: launches the built exe with an isolated config
  and --remote-debugging-port, waits for the port, runs the driver, closes.
- agent/tests/ui-smoke.mjs: connects over CDP, snapshots the page (preview
  content, headings, fold toggles, highlighted code, window.ipc bridge),
  saves a screenshot and a JSON report for the agent to read.
- The driver was validated against a mock CDP server; the real end-to-end run
  needs a desktop shell (sandbox cannot host WebView2).
This commit is contained in:
2026-11-04 15:15:24 +08:00
parent fadba614a8
commit 0b97bcb6dc
5 changed files with 360 additions and 1 deletions

206
agent/tests/ui-smoke.mjs Normal file
View File

@@ -0,0 +1,206 @@
#!/usr/bin/env node
// Pre-release UI check for MD Preview.
//
// The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside
// it. Run this from a normal desktop shell via ui-smoke.ps1: it talks to the
// already-running app over the DevTools protocol and writes a JSON report plus
// a screenshot under --out.
//
// Usage: node ui-smoke.mjs --port 9333 --out target/ui-test [--expect home|doc]
import { mkdirSync, writeFileSync } from "node:fs";
import { argv, exit } from "node:process";
import { pathToFileURL } from "node:url";
function parseArgs(list) {
const args = {};
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (!item.startsWith("--")) continue;
const key = item.slice(2);
const next = list[i + 1];
if (next === undefined || next.startsWith("--")) args[key] = true;
else { args[key] = next; i++; }
}
return args;
}
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
async function findPageTarget(port, timeoutMs) {
const deadline = Date.now() + timeoutMs;
let lastError = "no targets";
while (Date.now() < deadline) {
try {
const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(2000) });
const targets = await response.json();
const page = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
if (page) return page;
lastError = `${targets.length} target(s), none is a page`;
} catch (error) {
lastError = String(error && error.message ? error.message : error);
}
await sleep(250);
}
throw new Error(`no page target on port ${port}: ${lastError}`);
}
class Cdp {
constructor(url) {
this.url = url;
this.nextId = 1;
this.pending = new Map();
this.socket = null;
}
async connect(timeoutMs) {
const socket = new WebSocket(this.url);
this.socket = socket;
socket.addEventListener("message", (event) => {
let message;
try { message = JSON.parse(String(event.data)); } catch { return; }
if (message.id && this.pending.has(message.id)) {
const { resolve, reject } = this.pending.get(message.id);
this.pending.delete(message.id);
if (message.error) reject(new Error(`${message.error.code}: ${message.error.message}`));
else resolve(message.result);
}
});
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("CDP connect timed out")), timeoutMs);
socket.addEventListener("open", () => { clearTimeout(timer); resolve(); });
socket.addEventListener("error", () => { clearTimeout(timer); reject(new Error("CDP socket error")); });
});
}
send(method, params = {}, timeoutMs = 10000) {
const id = this.nextId++;
const payload = JSON.stringify({ id, method, params });
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`CDP timeout: ${method}`));
}, timeoutMs);
this.pending.set(id, {
resolve: (value) => { clearTimeout(timer); resolve(value); },
reject: (error) => { clearTimeout(timer); reject(error); },
});
this.socket.send(payload);
});
}
async evaluate(expression, timeoutMs = 10000) {
const result = await this.send("Runtime.evaluate", {
expression,
returnByValue: true,
awaitPromise: true,
userGesture: true,
}, timeoutMs);
if (result.exceptionDetails) {
throw new Error(`page exception: ${result.exceptionDetails.text || "unknown"}`);
}
return result.result ? result.result.value : undefined;
}
close() {
try { this.socket.close(); } catch { /* ignore */ }
}
}
const SNAPSHOT = `(() => {
const preview = document.getElementById('preview');
const style = getComputedStyle(document.documentElement);
return {
readyState: document.readyState,
bodyClass: document.body.className,
previewChildren: preview ? preview.children.length : -1,
previewTextLength: preview ? preview.innerText.length : -1,
firstHeading: (document.querySelector('#preview h1, #preview h2, #preview h3') || {}).textContent || '',
headings: document.querySelectorAll('#preview h1, #preview h2, #preview h3, #preview h4, #preview h5, #preview h6').length,
foldToggles: document.querySelectorAll('.mdp-fold-toggle').length,
codeBlocks: document.querySelectorAll('#preview pre code').length,
highlighted: document.querySelectorAll('#preview pre code.hljs').length,
hasIpc: !!(window.ipc && typeof window.ipc.postMessage === 'function'),
hasApi: ['__setContent', '__setTabs', '__setPreview', '__setEmptyPreview', '__markSaved']
.every((name) => typeof window[name] === 'function'),
zoom: style.getPropertyValue('--content-scale').trim(),
tabs: document.querySelectorAll('#tabs .tab').length,
tabBarVisible: document.body.classList.contains('has-tabs'),
findApi: typeof window.__mdPreviewShowFind === 'function',
};
})()`;
export async function run(options) {
const { port, outDir, expect } = options;
const report = {
startedAt: new Date().toISOString(),
port,
expect,
checks: [],
errors: [],
screenshot: null,
snapshot: null,
};
const check = (name, pass, detail) => report.checks.push({ name, pass: !!pass, detail });
mkdirSync(outDir, { recursive: true });
let cdp;
try {
const target = await findPageTarget(port, options.waitMs ?? 15000);
report.targetUrl = target.url;
cdp = new Cdp(target.webSocketDebuggerUrl);
await cdp.connect(5000);
await cdp.send("Runtime.enable");
await cdp.send("Page.enable");
// Let hljs / katex / mermaid / folding settle after the first paint.
await sleep(900);
const snapshot = await cdp.evaluate(SNAPSHOT);
report.snapshot = snapshot;
check("page loaded", snapshot && snapshot.readyState === "complete", snapshot && snapshot.readyState);
check("preview has content", snapshot && snapshot.previewChildren > 0, snapshot && `${snapshot.previewChildren} child nodes`);
check("webview IPC bridge", snapshot && snapshot.hasIpc, "window.ipc.postMessage");
check("page API installed", snapshot && snapshot.hasApi, "setContent/setTabs/setPreview");
if (expect === "doc") {
check("headings rendered", snapshot && snapshot.headings > 0, snapshot && `${snapshot.headings} headings`);
check("heading fold toggles", snapshot && snapshot.foldToggles > 0, snapshot && `${snapshot.foldToggles} toggles`);
check("code blocks highlighted", snapshot && snapshot.codeBlocks > 0 && snapshot.highlighted > 0, snapshot && `${snapshot.highlighted}/${snapshot.codeBlocks} highlighted`);
check("preview text is not empty", snapshot && snapshot.previewTextLength > 20, snapshot && `${snapshot.previewTextLength} chars`);
} else {
check("home page body", snapshot && snapshot.bodyClass.includes("home"), snapshot && snapshot.bodyClass);
}
const shot = await cdp.send("Page.captureScreenshot", { format: "png" }, 15000);
if (shot && shot.data) {
const file = `${outDir}/ui-smoke.png`;
writeFileSync(file, Buffer.from(shot.data, "base64"));
report.screenshot = file;
} else {
report.errors.push("captureScreenshot returned no data");
}
} catch (error) {
report.errors.push(String(error && error.message ? error.message : error));
} finally {
if (cdp) cdp.close();
}
const failed = report.checks.filter((item) => !item.pass);
const ok = failed.length === 0 && report.errors.length === 0;
const reportPath = `${outDir}/ui-smoke.json`;
writeFileSync(reportPath, JSON.stringify({ ...report, ok }, null, 2));
console.log(JSON.stringify({ ok, failed: failed.length, errors: report.errors, report: reportPath, screenshot: report.screenshot }, null, 2));
return { ok, report, reportPath };
}
if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
const args = parseArgs(argv.slice(2));
const port = Number(args.port ?? 9333);
const outDir = args.out ?? "target/ui-test";
const expect = args.expect ?? "doc";
run({ port, outDir, expect })
.then(({ ok }) => exit(ok ? 0 : 1))
.catch((error) => { console.error(error); exit(2); });
}