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

View File

@@ -18,6 +18,7 @@
| `scripts/build.ps1` | 开发构建(cargo test + build --release + 校验) | | `scripts/build.ps1` | 开发构建(cargo test + build --release + 校验) |
| `scripts/publish.ps1` | 用户手动发布到 Nutstore(Medium) | | `scripts/publish.ps1` | 用户手动发布到 Nutstore(Medium) |
| `tests/smoke.ps1` | cargo test + 关联检查 + 可选隔离启动 | | `tests/smoke.ps1` | cargo test + 关联检查 + 可选隔离启动 |
| `tests/ui-smoke.ps1` + `ui-smoke.mjs` | 发布前 UI 冒烟:CDP 断言页面渲染、截图、JSON 报告(需普通桌面 PowerShell + Node 21+) |
| `tests/fixtures/` | 手工/冒烟用 Markdown 样例 | | `tests/fixtures/` | 手工/冒烟用 Markdown 样例 |
| `reports/` | 验证记录(文本;截图放 `agent/tmp/`,不入库) | | `reports/` | 验证记录(文本;截图放 `agent/tmp/`,不入库) |
| `notes/` | 草稿 | | `notes/` | 草稿 |

View File

@@ -215,6 +215,7 @@ cargo test
- 架构拆分阶段 1(功能不变,`1115052`):`assets/page/{page.html,page.css,page.js}` 存页面;新增 `src/markdown.rs`(md→html 管线)、`src/page.rs`(页面组装,只填 `__MDP_*__` 占位符)、`src/escape.rs`(JS/HTML 转义)。`main.rs` 5535 → 3709 行;页面输出用 home/doc/startup 三组快照做 sha256 对比,逐字节一致。 - 架构拆分阶段 1(功能不变,`1115052`):`assets/page/{page.html,page.css,page.js}` 存页面;新增 `src/markdown.rs`(md→html 管线)、`src/page.rs`(页面组装,只填 `__MDP_*__` 占位符)、`src/escape.rs`(JS/HTML 转义)。`main.rs` 5535 → 3709 行;页面输出用 home/doc/startup 三组快照做 sha256 对比,逐字节一致。
- 架构拆分阶段 2(功能不变,2026-11-03 晚):新增 `src/config.rs`(路径/zoom/窗口几何/对话框);删除 macOS/Linux/Finder 扩展代码、非 Windows 分支和 `objc2` 依赖(仓库现在只能在 Windows 编译);测试模块移到文件末尾;`main.rs` 3709 → 2822 行。59 tests(删除死代码时移除 3 个平台专用测试)。 - 架构拆分阶段 2(功能不变,2026-11-03 晚):新增 `src/config.rs`(路径/zoom/窗口几何/对话框);删除 macOS/Linux/Finder 扩展代码、非 Windows 分支和 `objc2` 依赖(仓库现在只能在 Windows 编译);测试模块移到文件末尾;`main.rs` 3709 → 2822 行。59 tests(删除死代码时移除 3 个平台专用测试)。
- 已决定、未实施:移除应用启动时的 HKCU 关联写入;`publish.ps1` 维持现状(继续写关联)。 - 已决定、未实施:移除应用启动时的 HKCU 关联写入;`publish.ps1` 维持现状(继续写关联)。
- 发布前 UI 冒烟:`agent/tests/ui-smoke.ps1`(普通桌面 PowerShell;启动 CDP、断言页面渲染、截图、写 `target/ui-test/ui-smoke.json`)。DSH 沙箱禁止命名管道,WebView2/Chromium 在沙箱内无法启动(窗口白屏、`msedgewebview2.exe` 立即退出),所以这一项只能由用户手动跑。`ui-smoke.mjs` 已用 mock CDP 服务验证通过。
- 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。 - 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。
- 下一步(讨论中,未动手):编辑区样式化——加粗、标题加粗加大、行内代码换字体。 - 下一步(讨论中,未动手):编辑区样式化——加粗、标题加粗加大、行内代码换字体。
- 技术前提:`<textarea>` 不支持字符级样式;改字号会改变软换行与光标位置,透明叠加层只适合“同字号”样式。 - 技术前提:`<textarea>` 不支持字符级样式;改字号会改变软换行与光标位置,透明叠加层只适合“同字号”样式。

View File

@@ -65,9 +65,31 @@ cargo fmt -- --check
手动冒烟(无自动化):多标签切换、编辑/阅读、Ctrl+F、Ctrl+P、折叠、拖拽打开、外部修改提示、只读保存失败。 手动冒烟(无自动化):多标签切换、编辑/阅读、Ctrl+F、Ctrl+P、折叠、拖拽打开、外部修改提示、只读保存失败。
## 5.1 发布前 UI 冒烟(必须由用户在普通 PowerShell 跑)
**为什么不能由 Agent 跑**:DSH 的 Windows 沙箱禁止命名管道,Chromium/WebView2 的 Mojo IPC 起不来。
实测:md-preview 能启动、窗口出现,但 `msedgewebview2.exe` 立刻退出(数据目录只建了一半),页面白屏;Edge headless 报
`FATAL:mojo\public\cpp\platform\platform_channel.cc Check failed: 拒绝访问 (0x5)`。
这是沙箱限制,不是应用 bug;同时开发 exe 是 Low 完整性,从这里 `icacls /setintegritylevel Medium` 会被拒绝(无 write-up)。
**用法**(普通 PowerShell,Node 21+;本机 `C:\Program Files\nodejs\node.exe` 是 24.x):
~~~powershell
cd D:\Scripts\md-preview\AgentLowWorking
.\agent\tests\ui-smoke.ps1 # 开发构建 + code-samples.md
.\agent\tests\ui-smoke.ps1 -Expect home # 启动页
.\agent\tests\ui-smoke.ps1 -KeepOpen # 失败时留着窗口人工看
~~~
- 脚本用独立配置目录(`target\ui-test\config`)启动 exe,设置 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`,等端口起来后调用 `agent/tests/ui-smoke.mjs`。
- mjs 通过 CDP 读取页面快照、断言(页面加载、`#preview` 有内容、`window.ipc` 桥、页面 API、标题/折叠按钮/代码高亮),再截图,写 `target/ui-test/ui-smoke.json` 与 `ui-smoke.png`。
- Agent 可以直接读这两个文件定位问题;失败时把 report 里的 checks 贴出来即可。
- 已知边界:只验证“页面真的渲染了 + 基础 API 在”,不覆盖标签切换、保存、外部修改等 Rust 侧流程(那些靠单元测试和人工点)。
- 注意:如果用 `-Exe` 指向 Nutstore 的发布版(Medium),启动会写 HKCU 关联(应用原有行为,指向它自己);默认的开发构建是 Low,写不了注册表。
## 6. 注意 ## 6. 注意
- 本仓库现在**只能在 Windows 上编译**;`cargo test` 里仍有 `cfg(target_os = "windows")` 的 Windows 专用测试。 - 本仓库现在**只能在 Windows 上编译**;`cargo test` 里仍有 `cfg(target_os = "windows")` 的 Windows 专用测试。
- `main.rs` 顶部的 `windows_subsystem` 只对 release 生效;debug 构建带控制台,属正常。 - `main.rs` 顶部的 `windows_subsystem` 只对 release 生效;debug 构建带控制台,属正常。
- 页面 JS 改动后建议做一次语法检查(临时测试把页面写到文件,再 `node --check`)。 - 页面 JS 改动后建议做一次语法检查(临时测试把页面写到文件,再 `node --check`)。
- 构建/测试临时文件放 `target\tmp`;不要写 `%TEMP%`。 - 构建/测试临时文件放 `target\tmp`;不要写 `%TEMP%`。

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); });
}

129
agent/tests/ui-smoke.ps1 Normal file
View File

@@ -0,0 +1,129 @@
<#
MD Preview 发布前 UI 冒烟(需要普通桌面 PowerShell)
- 通过 WebView2 的 CDP 端口检查页面是否真的渲染,并截图
- 默认使用仓库里的开发构建(Low 完整性,启动时写不了 HKCU,安全)
- 不要在 DSH 沙箱里跑:沙箱禁止命名管道,Chromium/WebView2 起不来
#>
#requires -Version 5.1
[CmdletBinding()]
param(
[string]$Exe = '',
[string]$Fixture = '',
[int]$Port = 9333,
[ValidateSet('doc', 'home')]
[string]$Expect = 'doc',
[string]$OutDir = '',
[switch]$KeepOpen
)
$ErrorActionPreference = 'Stop'
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
Set-Location $repoRoot
if (-not $Exe) { $Exe = Join-Path $repoRoot 'target\release\md-preview.exe' }
if (-not $Fixture) { $Fixture = Join-Path $repoRoot 'agent\tests\fixtures\code-samples.md' }
if (-not $OutDir) { $OutDir = Join-Path $repoRoot 'target\ui-test' }
if (-not (Test-Path -LiteralPath $Exe)) { throw ('missing exe: ' + $Exe + '(先运行 agent\scripts\build.ps1)') }
if (-not (Test-Path -LiteralPath $Fixture)) { throw ('missing fixture: ' + $Fixture) }
$node = Get-Command node -ErrorAction SilentlyContinue
if (-not $node) { $node = 'C:\Program Files\nodejs\node.exe' }
if (-not (Test-Path -LiteralPath $node)) { throw 'Node.js 未找到(需要 Node 21+,用其内置 WebSocket)' }
& $node -e "process.exit(('WebSocket' in globalThis) ? 0 : 1)" 2>$null
if ($LASTEXITCODE -ne 0) { throw ('Node 版本太旧:需要 Node 21+ 的内置 WebSocket(当前 ' + (& $node --version) + ')') }
New-Item -ItemType Directory -Force $OutDir | Out-Null
$configDir = Join-Path $OutDir 'config'
$logOut = Join-Path $OutDir 'app.stdout.log'
$logErr = Join-Path $OutDir 'app.stderr.log'
$reportPath = Join-Path $OutDir 'ui-smoke.json'
Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue
Remove-Item -Force $logOut, $logErr, $reportPath, (Join-Path $OutDir 'ui-smoke.png') -ErrorAction SilentlyContinue
# 单实例:如果目标 exe 已经在跑,新的启动会被转发出去,CDP 端口就不会出现。
$exePath = (Resolve-Path -LiteralPath $Exe).Path
$running = @()
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
$path = $null
try { $path = $process.Path } catch { }
if ($path -and ($path -ieq $exePath)) { $running += [string]$process.Id }
}
if ($running.Count -gt 0) {
throw ('目标 exe 已在运行(PID ' + ($running -join ', ') + '),请先关闭它;否则启动会被单实例转发。')
}
# 端口探测:CDP 起来之前不要跑断言。
function Test-Port([int]$port) {
$client = New-Object System.Net.Sockets.TcpClient
try {
$task = $client.ConnectAsync('127.0.0.1', $port)
if (-not $task.Wait(400)) { return $false }
return $client.Connected
} catch {
return $false
} finally {
$client.Dispose()
}
}
$previousConfig = $env:MD_PREVIEW_CONFIG_DIR
$previousArgs = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$proc = $null
$exitCode = 1
try {
$env:MD_PREVIEW_CONFIG_DIR = $configDir
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = '--remote-debugging-port=' + $Port
Write-Host ('==> launching ' + $exePath) -ForegroundColor Cyan
$proc = Start-Process -FilePath $exePath -ArgumentList @('"' + $Fixture + '"') -PassThru -RedirectStandardOutput $logOut -RedirectStandardError $logErr
$deadline = (Get-Date).AddSeconds(25)
$up = $false
while ((Get-Date) -lt $deadline) {
if ($proc.HasExited) { break }
if (Test-Port $Port) { $up = $true; break }
Start-Sleep -Milliseconds 300
}
if (-not $up) {
Write-Host 'ERROR: CDP 端口没有起来。' -ForegroundColor Red
Write-Host ' - 不要在 DSH 沙箱里运行本脚本:沙箱禁止命名管道,Chromium/WebView2 无法启动。'
Write-Host ' - 确认没有其它 MD Preview 实例占用同一个配置目录。'
if (Test-Path -LiteralPath $logErr) {
$err = Get-Content -LiteralPath $logErr -ErrorAction SilentlyContinue | Select-Object -Last 10
if ($err) { Write-Host ' app.stderr:'; $err | ForEach-Object { Write-Host (' ' + $_) } }
}
if ($proc.HasExited) { Write-Host (' app 已退出,exit code ' + $proc.ExitCode) }
throw 'CDP port did not open'
}
Write-Host ('==> node agent\tests\ui-smoke.mjs --port ' + $Port + ' --expect ' + $Expect) -ForegroundColor Cyan
& $node (Join-Path $repoRoot 'agent\tests\ui-smoke.mjs') --port $Port --out $OutDir --expect $Expect
$exitCode = $LASTEXITCODE
if (Test-Path -LiteralPath $reportPath) {
$report = Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json
$failed = @($report.checks | Where-Object { -not $_.pass })
if ($failed.Count -gt 0) {
Write-Host 'FAILED checks:' -ForegroundColor Red
$failed | ForEach-Object { Write-Host (' - ' + $_.name + ': ' + $_.detail) -ForegroundColor Red }
} else {
Write-Host ('OK: ' + @($report.checks).Count + ' checks') -ForegroundColor Green
}
if ($report.screenshot) { Write-Host ('screenshot: ' + $report.screenshot) }
Write-Host ('report : ' + $reportPath)
}
} finally {
if ($proc -and -not $KeepOpen) {
try {
if (-not $proc.HasExited) {
$proc.CloseMainWindow() | Out-Null
if (-not $proc.WaitForExit(5000)) { $proc.Kill() }
}
} catch { }
}
if ($null -eq $previousConfig) { Remove-Item Env:\MD_PREVIEW_CONFIG_DIR -ErrorAction SilentlyContinue } else { $env:MD_PREVIEW_CONFIG_DIR = $previousConfig }
if ($null -eq $previousArgs) { Remove-Item Env:\WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS -ErrorAction SilentlyContinue } else { $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $previousArgs }
}
exit $exitCode