Files
iwb-plugins-desktop/image-vectorize/tools/harness.mjs
T
qiqi 6f3a4676bb chore(image-vectorize): 存档未发布插件(描摹质量不达标,已下线)
用户实测描摹效果达不到可交付线(中文笔画断裂 / 抗锯齿边缘毛刺 / 浅色块碎层),
裁定不做这个插件。线上已清理:KV 清单移除、字节 GC 删除、宿主 `wasm-unsafe-eval` 收回。

代码本身是好的(VTracer wasm 跑通、5 预设 + 全参数面板 + 空格对比预览 + SVG/PNG 双输出、
本地 harness 27 项 + 真站 e2e 13 项全绿),问题在算法定位:VTracer 适合 logo / 线稿 /
纯平色块,不适合照片与带抗锯齿的合成图。留档备查,README 顶部已标注「已下线,未发布」。
2026-11-05 01:04:35 +08:00

251 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 位图转矢量:本地端到端(开发用,不进 CI)。
//
// 直接把构建产物注入合成宿主,在真实 Chromium 里验证:
// 注册 / 模态 / wasm 引擎真跑出矢量 / 预设与参数联动 / 黑白模式禁用颜色项 /
// 颜色精度区间保护 / 边缘净化 / SVG 下载 / 保存为 PNG 节点 / 空格对比 / Esc 关闭 / 参数记忆。
//
// 页面刻意带上宿主同款 CSP(script-src 无 unsafe-inline,但有 wasm-unsafe-eval),
// 这样「wasm 能不能编译」这条约束是被真实测到的,而不是绕过去的。
//
// 运行:node image-vectorize/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
const WANT_VERSION = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8')).version
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT')
process.exit(2)
}
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
// 描摹是异步的(wasm 一次几十毫秒 + 150ms 防抖),等统计数字出现即可
const waitStats = async (page, timeout = 8000) => {
const end = Date.now() + timeout
for (;;) {
const t = await page.locator('[data-stat="paths"]').textContent().catch(() => null)
if (t && t !== '–') return t
if (Date.now() > end) return false
await sleep(120)
}
}
const pathsNow = (page) => page.locator('[data-stat="paths"]').textContent()
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const errors = []
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { errors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
const CSP = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https: http:"
await page.setContent('<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="' + CSP + '"><style>body{margin:0}</style></head><body><div id="host"></div></body></html>')
// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态)
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 400; c.height = 400
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 400, 400)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(120, 120, 74, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(214, 164, 150, 104, 14); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 46px "PingFang SC", sans-serif'; g.fillText('菜单', 124, 310)
g.strokeStyle = '#2e9e6b'; g.lineWidth = 4
g.beginPath(); g.moveTo(60, 356); g.bezierCurveTo(150, 330, 260, 390, 350, 350); g.stroke()
return c.toDataURL('image/png')
})
await page.evaluate(() => {
window.IWBPluginHost = { register(manifest, factory) { window.__manifest = manifest; window.__factory = factory } }
window.__actions = {}
window.__commands = {}
window.__settings = {}
window.__writes = []
})
// 产物用 CDP 直接执行注入:本页带 CSP(script-src 无 unsafe-inline),addScriptTag 会被拦。
// 这只影响「把代码装进页面」,插件运行时编译 wasm 仍受页面 CSP 约束 —— 那才是要测的点。
await page.evaluate(readFileSync(PLUGIN_ENTRY, 'utf8'))
const boot = await page.evaluate((png) => {
const ctx = {
id: 'image-vectorize', manifest: window.__manifest, apiVersion: 1,
log() {},
settings: {
get(k) { return window.__settings[k] },
set(k, v) { window.__settings[k] = v },
all() { return { ...window.__settings } },
},
storage: { get() {}, set() {}, remove() {}, keys() { return [] } },
events: { on() { return () => {} }, emit() { return true } },
canvas: {
getNodeImage() { return { dataUrl: png } },
getSelectedNode() { return { id: 'r1', type: 'ref', name: 'src.png' } },
setNodeImage() { window.__writes.push({ kind: 'replace' }); return true },
createImageNode(o) { window.__writes.push({ kind: 'newNode', name: o.name, head: String(o.dataUrl).slice(0, 22), len: String(o.dataUrl).length }); return { id: 'r2' } },
},
nodeActions: { register(r) { window.__actions[r.id] = r } },
commands: { register(r) { window.__commands[r.id] = r } },
}
window.__plugin = window.__factory(ctx)
return {
version: window.__manifest.version,
capabilities: window.__manifest.capabilities,
actions: Object.keys(window.__actions),
commands: Object.keys(window.__commands),
settings: Object.keys(window.__manifest.settings || {}),
icons: Object.keys(window.__actions).map((id) => String(window.__actions[id].icon || ''))
.concat(Object.keys(window.__commands).map((id) => String(window.__commands[id].icon || ''))),
}
}, PNG)
check('产物可执行(IIFE 打包 + 注册成功)', boot.version === WANT_VERSION, 'version=' + boot.version)
check('注册了节点动作与命令', boot.actions.includes('vectorize-node') && boot.commands.includes('vectorize-selected'), boot.actions.join(','))
// 图标不能与别的插件撞车:'vector-square' 是 white-bg-800 的,两个插件同屏时认不出谁是谁(用户实测反馈过)
check('节点动作图标是钢笔笔头(不与 white-bg-800 的 vector-square 重复)', boot.icons.indexOf('pen-tool') >= 0 && boot.icons.indexOf('vector-square') < 0, boot.icons.join(','))
check('manifest 声明了参数记忆项', ['preset', 'colorPrecision', 'denoise', 'outScale'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
check('capabilities 含 canvasWrite(要写回节点)', boot.capabilities.includes('canvasWrite'), boot.capabilities.join(','))
await page.evaluate(() => { window.__commands['vectorize-selected'].run().catch(() => {}) })
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
check('模态打开:预览区 + 参数面板 + 三个动作按钮齐全', await page.evaluate(() => {
const q = (s) => Boolean(document.querySelector(s))
return q('.vz-preview') && q('.vz-panel') && q('[data-act="cancel"]') && q('[data-act="svg"]') && q('[data-act="save"]')
}))
const first = await waitStats(page)
check('wasm 引擎首次描摹成功(CSP 下 wasm 可编译)', Boolean(first) && Number(first) > 0, 'paths=' + first)
check('预览是矢量(blob: SVG 且不是原图)', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
const o = document.querySelector('[data-stage="original"]')
return Boolean(v && v.src.startsWith('blob:') && !v.hidden && o.hidden)
}))
// 透明区必须是中性灰棋盘:电商素材大量是黑字/深色 logo,深色棋盘会把内容直接吞掉,
// 看起来像「描摹失败」(这个坑实测踩过一次)
check('预览透明底用浅色棋盘(深色内容不会被吞)', await page.evaluate(() => {
const bg = getComputedStyle(document.querySelector('.vz-preview')).backgroundColor
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(bg)
if (!m) return false
const lum = (Number(m[1]) + Number(m[2]) + Number(m[3])) / 3
return lum > 150
}))
const stats = await page.evaluate(() => ({
paths: Number(document.querySelector('[data-stat="paths"]').textContent),
colors: Number(document.querySelector('[data-stat="colors"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('色层覆盖够用(红/蓝/黑/绿/白至少分 4 层)', stats.colors >= 4, JSON.stringify(stats))
check('描摹耗时 < 3s(400×400 参考图)', Number(String(stats.ms).replace('ms', '')) < 3000, stats.ms)
check('默认预设为「标志 / 图标」且高亮', await page.evaluate(() => {
const a = document.querySelector('.vz-preset.active')
return Boolean(a && a.dataset.preset === 'logo')
}))
await page.locator('.vz-preset[data-preset="photo"]').click()
await sleep(900)
check('切「照片」预设:颜色精度→4 且重新描摹', await page.evaluate(() =>
document.querySelector('[data-param="colorPrecision"]').value === '4' &&
document.querySelector('.vz-preset[data-preset="photo"]').classList.contains('active')),
'paths=' + await pathsNow(page))
// 手动拖滑杆即脱离预设(预设只是参数组合的快捷方式)
await page.evaluate(() => {
const i = document.querySelector('[data-param="filterSpeckle"]')
i.value = '20'
i.dispatchEvent(new Event('input', { bubbles: true }))
})
await sleep(700)
check('手动改参数后脱离预设高亮', await page.evaluate(() => !document.querySelector('.vz-preset.active')))
await page.locator('[data-seg-group="binary"] button[data-value="binary"]').click()
await sleep(700)
check('黑白模式禁用颜色精度/色层差异(不假装可调)', await page.evaluate(() =>
document.querySelector('[data-param="colorPrecision"]').disabled &&
document.querySelector('[data-param="layerDifference"]').disabled))
check('黑白模式仍产出路径', await waitStats(page))
await page.locator('[data-seg-group="binary"] button[data-value="color"]').click()
await sleep(700)
check('切回彩色后颜色参数恢复可调', await page.evaluate(() => !document.querySelector('[data-param="colorPrecision"]').disabled))
// 实测:colorPrecision ≥6 会把整张图塌成一个色块,=8 直接 wasm abort,故滑杆必须夹在 1–5
check('颜色精度被夹在 1–5(引擎安全区间)', await page.evaluate(() => {
const i = document.querySelector('[data-param="colorPrecision"]')
return i.min === '1' && i.max === '5'
}))
await page.locator('[data-seg-group="denoise"] button[data-value="3"]').click()
await sleep(1100)
check('边缘净化 1/3:重新描摹并保持可用', Boolean(await waitStats(page)) &&
await page.evaluate(() => document.querySelector('[data-seg-group="denoise"] button.active')?.dataset.value === '3'),
'paths=' + await pathsNow(page))
const dlPromise = page.waitForEvent('download', { timeout: 12000 }).catch(() => null)
await page.locator('[data-act="svg"]').click()
const download = await dlPromise
check('「下载 SVG」触发文件下载', Boolean(download) && /\.svg$/.test(download.suggestedFilename() || ''), download ? download.suggestedFilename() : 'no download')
await page.locator('[data-act="save"]').click()
await sleep(1400)
const wrote = await page.evaluate(() => window.__writes[0])
check('「保存为节点」写出 PNG 图片节点', Boolean(wrote) && wrote.kind === 'newNode' && wrote.head.startsWith('data:image/png'),
wrote ? JSON.stringify({ kind: wrote.kind, head: wrote.head, kb: Math.round(wrote.len / 1024) + 'KB' }) : 'no write')
check('保存后模态自动关闭', (await page.locator('.vz-root').count()) === 0)
check('参数记忆写回宿主 settings', await page.evaluate(() => {
const s = window.__settings
return Number(s.outScale) === 2 && Number(s.denoise) === 3 && s.binary === false && Number(s.filterSpeckle) === 20
}), await page.evaluate(() => JSON.stringify(window.__settings)))
// 重新打开应沿用上次参数
await page.evaluate(() => { window.__commands['vectorize-selected'].run().catch(() => {}) })
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
await waitStats(page)
check('重新打开沿用上次参数(filterSpeckle=20、denoise=1/3)', await page.evaluate(() =>
document.querySelector('[data-param="filterSpeckle"]').value === '20' &&
document.querySelector('[data-seg-group="denoise"] button.active')?.dataset.value === '3'))
// 空格对比原图
await page.keyboard.down('Space')
await sleep(220)
const spaceOn = await page.evaluate(() => !document.querySelector('[data-stage="original"]').hidden && document.querySelector('[data-badge]').textContent === '原图')
await page.keyboard.up('Space')
await sleep(220)
const spaceOff = await page.evaluate(() => document.querySelector('[data-stage="original"]').hidden)
check('按住空格对比原图、松开回到矢量', spaceOn && spaceOff)
await page.keyboard.press('Escape')
await sleep(400)
check('Esc 关闭模态', (await page.locator('.vz-root').count()) === 0)
if (errors.length) {
console.log('')
console.log('页面错误:')
for (const e of errors.slice(0, 6)) console.log(' ' + e)
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
process.exit(failed ? 1 : 0)