diff --git a/album/src/index.js b/album/src/index.js index 28d8c92..6cd1cff 100644 --- a/album/src/index.js +++ b/album/src/index.js @@ -251,7 +251,7 @@ const hasFileRef = items.some((it) => fileRefOf(it && it.src)) st.btnSettle.style.display = hasFileRef ? '' : 'none' // 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `canReference() || true` 恒真, - // 于是在网页版点它永远没反应。网页版仍可用「+ 添加图片」走文件选择器。 + // 于是在不支持路径引用的宿主里点它永远没反应(这类宿主仍可用「+ 添加图片」走文件选择器)。 const canRef = !!(ctx.images && typeof ctx.images.canReference === 'function' && ctx.images.canReference()) st.btnDir.style.display = canRef ? '' : 'none' st.btnClear.style.display = items.length ? '' : 'none' @@ -676,7 +676,7 @@ } catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) } return } - // 网页版:没有路径 ⇒ 退回文件选择 + 复制进画布存储 + // 不支持路径引用的宿主:退回文件选择 + 复制进画布存储 const input = document.createElement('input') input.type = 'file'; input.accept = 'image/*'; input.multiple = true input.style.display = 'none' diff --git a/album/tools/harness.mjs b/album/tools/harness.mjs index f40d070..b5ddf16 100644 --- a/album/tools/harness.mjs +++ b/album/tools/harness.mjs @@ -184,7 +184,7 @@ ok('跨页拖拽用「每页容量」换算,不用「本页格子数」', ok('删除不再硬编码跳回第 1 页', !/\{ items, page: 0 \}/.test(src) && /page: Math\.min\(pageNow, pagesNow - 1\)/.test(src)) ok('空节点不再显示「全部 0 张一页展示」(压着空态提示的废话)', /const showOne = !showPager && items\.length > 0/.test(src)) -ok('「文件夹」按钮不再 canReference() || true(网页版点了没反应)', +ok('「文件夹」按钮不再 canReference() || true(不支持路径引用时点了没反应)', !/\|\| true \? '' : 'none'/.test(src)) ok('addPaths 里没有 keep 死变量', !/const keep = \(st\.node\.data/.test(src)) ok('缩略图请求并发去重(st.pending,否则导入 30 张要解 60 次原图)', diff --git a/batch-export/README.md b/batch-export/README.md index 02f4f08..a75b382 100644 --- a/batch-export/README.md +++ b/batch-export/README.md @@ -95,15 +95,9 @@ mock 宿主 + 真实 Chromium,覆盖:manifest / 面板注册与挂载 / 列 需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。 -**发布后必须再跑一次真机**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载): - -```bash -node batch-export/tools/e2e-site.mjs -``` - -覆盖:市场安装加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 + -**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** + -队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。 +harness 用真实 Chromium 注入宿主 CSS 变量与 CSP 约束,覆盖面板挂载、勾选框与文字同行 +(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)、队列跑通、 +下载 ZIP + python3 校验条目 / CRC / PNG·JPEG magic / UTF-8 名。发布后在客户端市场里确认版本与加载状态即可。 ## 发布 diff --git a/batch-export/tools/e2e-site.mjs b/batch-export/tools/e2e-site.mjs deleted file mode 100644 index c72fced..0000000 --- a/batch-export/tools/e2e-site.mjs +++ /dev/null @@ -1,282 +0,0 @@ -// 真实站点端到端(开发用,不进 CI)—— batch-export「批量出图」。 -// -// 为什么需要它:harness.mjs 用的是 mock 宿主,面板样式与真实宿主 CSS 变量、真实 CSP、真实 -// 画布桥都不会被执行到。发布后跑一遍这个脚本,能抓到 mock 里永远绿的问题 —— -// 例如 `.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行、把标签挤到面板最右(1.0.0 首次发布即中招)。 -// -// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)+ 真实资源中心面板挂载。 -// -// 运行(需要 Playwright + python3): -// node batch-export/tools/e2e-site.mjs # 默认测试站 -// IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站 -// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。 -import { createRequire } from 'node:module' -import { execFileSync } from 'node:child_process' -import { readFileSync, existsSync, statSync } from 'node:fs' -import path from 'node:path' -import os from 'node:os' -import { fileURLToPath } from 'node:url' - -const HERE = path.dirname(fileURLToPath(import.meta.url)) // /batch-export/tools -const REPO = path.resolve(HERE, '../..') // -const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop' - -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:') - console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/e2e-site.mjs') - process.exit(2) -} - -const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev' -const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'batch-export/package.json'), 'utf8')).version -const ZIP_OUT = path.join(os.tmpdir(), 'iwb-batch-e2e.zip') - -let failed = 0 -const check = (name, ok, detail) => { - if (!ok) failed++ - console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : '')) -} - -console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')') -const browser = await chromium.launch() -const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true }) -const consoleErrors = [] -page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) }) -page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message)) - -// 造两张 200×120 的参考图(非正方形,等比缩放/居中被真正练到) -await page.goto('about:blank') -const PNG = await page.evaluate(() => { - const c = document.createElement('canvas') - c.width = 200; c.height = 120 - const x = c.getContext('2d') - x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 200, 120) - return c.toDataURL('image/png') -}) - -// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled -await page.addInitScript((d) => { - localStorage.clear() - localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} })) - const ws = { - workspaces: [{ - id: 'w1', name: 'W', - nodes: [ - { id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: '菜单A.png', localName: null } }, - { id: 'r2', type: 'ref', x: 460, y: 140, data: { url: '', data: d.png, name: '菜单B.png', localName: null } }, - ], - edges: [], groups: [], - }], - activeId: 'w1', rev: 1, - } - localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws)) - localStorage.setItem('iwb_ws_active', ws.activeId) - localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0])) - localStorage.setItem('iwb_web_outputs', JSON.stringify([])) - localStorage.setItem('iwb_plugins', JSON.stringify({ 'batch-export': { enabled: true, settings: {}, data: {} } })) -}, { png: PNG }) - -// ---------- 1) 站点可达 ---------- -const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' }) -check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status())) - -// ---------- 2) 真实 KV 加载 + 启用 ---------- -await page.waitForFunction(() => window.IWBPluginHost && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 }) -await page.waitForFunction(() => window.IWBPluginHost.list().some((x) => x.id === 'batch-export'), null, { timeout: 20000 }) -const info = await page.evaluate(() => { - const p = window.IWBPluginHost.list().find((x) => x.id === 'batch-export') - return p ? { version: p.version, enabled: p.enabled, active: p.active, capabilities: p.capabilities, error: p.error } : null -}) -check('从真实 KV 加载并启用(active)', Boolean(info && info.active && info.enabled && !info.error), JSON.stringify(info)) -check('线上版本 = batch-export/package.json(' + WANT_VERSION + ')', Boolean(info && info.version === WANT_VERSION), info && info.version) - -// ---------- 3) 面板 tab ---------- -await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick() -await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 }) -check('画布打开、2 个 ref 节点', (await page.locator('.iwb-node[data-node-id^="r"]').count()) === 2) -await page.locator('button[title^="资源中心"]').first().click() -const tab = page.locator('.iwb-res-tab', { hasText: '批量出图' }) -check('资源中心出现「批量出图」tab', (await tab.count()) >= 1) -await tab.first().click() -await page.waitForTimeout(1200) -const mounted = await page.locator('.iwb-full-panel-plugin').count() -check('面板已挂载(真实宿主容器)', mounted >= 1) -// 宿主 .iwb-full-main 是 flex 行容器,只给图库/节点组容器 width:100%;插件容器不撑满就会按内容收缩 -const widthInfo = await page.evaluate(() => { - const main = document.querySelector('.iwb-full-main') - const box = document.querySelector('.iwb-bx') - return { - main: main ? Math.round(main.clientWidth) : 0, - box: box ? Math.round(box.clientWidth) : 0, - } -}) -check('面板撑满内容区宽度(不按内容收缩)', - widthInfo.main > 0 && widthInfo.box >= widthInfo.main - 2, JSON.stringify(widthInfo)) -const rows = await page.locator('.iwb-bx-item').count() -check('面板列出 2 个 ref 节点', rows === 2, 'rows=' + rows) - -// 1.0.0 首发的真实 bug:checkbox 被 .iwb-bx-f input{width:100%} 撑满整行,标签被挤到最右 -const chk = await page.evaluate(() => { - const lab = document.querySelector('.iwb-bx-rowchk') - if (!lab) return null - const input = lab.querySelector('input[type=checkbox]') - const span = lab.querySelector('span') - if (!input || !span) return null - const a = input.getBoundingClientRect() - const b = span.getBoundingClientRect() - return { gap: Math.round(b.left - a.right), sameLine: Math.abs(a.top - b.top) < 12, inputW: Math.round(a.width) } -}) -check('「走本地鲜艺抠图」勾选框与文字同行且紧邻', Boolean(chk && chk.sameLine && chk.gap >= 0 && chk.gap <= 12 && chk.inputW <= 24), JSON.stringify(chk)) -const cutLabel = await page.evaluate(() => { - const s = document.querySelector('.iwb-bx-rowchk span') - return s ? s.textContent.trim() : '' -}) -check('抠图开关文案写明「本地鲜艺抠图」+ 端口', /鲜艺/.test(cutLabel) && /30092/.test(cutLabel), cutLabel) - -// 1.1.0:配置区与列表之间要有明显的隔断(灰底小节头),操作按钮归到列表区 -const sec = await page.evaluate(() => { - const s = document.querySelector('.iwb-bx-sec') - if (!s) return null - const bar = document.querySelector('.iwb-bx-bar') - const a = s.getBoundingClientRect() - const b = bar.getBoundingClientRect() - return { - text: (s.textContent || '').trim().slice(0, 24), - btns: Array.from(s.querySelectorAll('button')).map((x) => x.textContent.trim()), - bg: getComputedStyle(s).backgroundColor, - belowConfig: a.top >= b.bottom - 1, - } -}) -check('隔断:「待处理节点」小节头在配置区正下方,带灰底 + 全选/清空/刷新', - Boolean(sec && sec.belowConfig && sec.text.indexOf('待处理节点') === 0 && - JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']) && sec.bg !== 'rgba(0, 0, 0, 0)'), - JSON.stringify(sec)) - -// 1.1.0:缩略图必须**跑之前**就在(30px 显示 / 64px 源图) -if (rows) { -const preThumb = await page.evaluate(() => { - const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb')) - return { n: imgs.length, w: imgs[0] ? imgs[0].naturalWidth : 0, cssW: imgs[0] ? Math.round(imgs[0].getBoundingClientRect().width) : 0 } -}) -check('列表行首常驻源图缩略图(2 张、64px 位图 / 30px 显示)', - preThumb.n === 2 && preThumb.w === 64 && preThumb.cssW === 30, JSON.stringify(preThumb)) - -// 1.1.0 的 bug:「清空」后勾选框视觉上仍勾着(el() 用 setAttribute('checked','false')) -await page.getByRole('button', { name: '清空', exact: true }).click() -const cleared = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked)) -check('「清空」真的取消勾选', cleared.length === 2 && cleared.every((v) => v === false), JSON.stringify(cleared)) -await page.getByRole('button', { name: '全选', exact: true }).click() -} - -// ---------- 4) 跑队列 ---------- -if (!rows) { - console.log('\n' + (await page.locator('.iwb-full-panel-plugin').first().innerText())) -} else { - await page.getByRole('button', { name: '全选', exact: true }).click() - await page.getByRole('button', { name: '开始出图', exact: true }).click() - await page.waitForFunction(() => { - const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP') - return b && !b.disabled - }, null, { timeout: 120000 }) - const fails = await page.locator('.iwb-bx-item', { hasText: '失败' }).count() - check('队列跑完、无失败项', fails === 0, 'fail=' + fails) - - // 跑完必须「看得见图」:行内缩略图 + 一条说明产物在哪的提示条(1.0.1 之前只有一行文字,用户以为没产出) - const thumbs = await page.locator('.iwb-bx-thumb').count() - check('行内显示产物缩略图(2 张)', thumbs === 2, 'thumbs=' + thumbs) - const thumbOk = thumbs ? await page.evaluate(() => { - const im = document.querySelector('.iwb-bx-thumb') - return { src: String(im.getAttribute('src') || '').slice(0, 5), w: im.naturalWidth, h: im.naturalHeight } - }) : null - check('缩略图是真解码出来的位图(800×800)', Boolean(thumbOk && thumbOk.src === 'blob:' && thumbOk.w === 800 && thumbOk.h === 800), JSON.stringify(thumbOk)) - - // ---------- 4.5) 行内单张下载(1.2.0):不依赖 ZIP,产物在内存里直接落盘 ---------- - const dlState = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({ - text: b.textContent, disabled: b.disabled, title: b.title, - }))) - check('行内下载:每行 JPG / PNG 各一个(2 行 = 4 个)', - dlState.length === 4 && dlState[0].text === 'JPG' && dlState[1].text === 'PNG', - JSON.stringify(dlState.map((b) => b.text))) - check('行内下载:双版本跑完后全部可点', dlState.every((b) => b.disabled === false), JSON.stringify(dlState.map((b) => b.disabled))) - const [jpgDl] = await Promise.all([ - page.waitForEvent('download', { timeout: 30000 }), - page.locator('.iwb-bx-item').first().locator('.iwb-bx-dl').first().click(), - ]) - check('行内下载:点 JPG 直接下载单张(不必先导出 ZIP)', - /\.jpg$/.test(jpgDl.suggestedFilename()), jpgDl.suggestedFilename()) - const doneText = await page.locator('.iwb-bx-done').first().innerText() - check('完成提示条说明「已生成 → 点导出 ZIP」(不写入画布)', /已生成 4 个文件/.test(doneText) && /导出 ZIP/.test(doneText) && /不写入画布/.test(doneText), doneText) - // 1.0.2 的坑:.iwb-bx-btn-hot 与 .iwb-bx-btn 同特异性且定义在前,背景被覆盖 → 高亮没生效 - const zipBg = await page.evaluate(() => { - const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP') - return b ? getComputedStyle(b).backgroundColor : '' - }) - check('导出按钮转为高亮(rgb(29,158,117))', zipBg === 'rgb(29, 158, 117)', zipBg) - - // ---------- 5) 导出 ZIP 并用 python3 校验(系统 unzip 对 UTF-8 名会乱码,见 README) ---------- - const [download] = await Promise.all([ - page.waitForEvent('download', { timeout: 60000 }), - page.getByRole('button', { name: '导出 ZIP', exact: true }).click(), - ]) - await download.saveAs(ZIP_OUT) - check('ZIP 已下载', existsSync(ZIP_OUT), existsSync(ZIP_OUT) ? statSync(ZIP_OUT).size + ' bytes' : '缺失') - const doneAfter = await page.locator('.iwb-bx-done').first().innerText() - check('导出后提示条显示已下载的文件名', /已下载 batch_.*\.zip/.test(doneAfter), doneAfter) - try { - const report = execFileSync('python3', ['-c', ` -import zipfile, sys -z = zipfile.ZipFile(sys.argv[1]) -assert z.testzip() is None, 'CRC 损坏' -for i in z.infolist(): - b = z.read(i.filename) - ext = i.filename.rsplit('.', 1)[-1] - ok = b[:4] == b'\\x89PNG' if ext == 'png' else b[:3] == b'\\xff\\xd8\\xff' - print('%-28s %7dB %s %s' % (i.filename, i.file_size, '格式OK' if ok else '格式BAD', 'utf8' if i.flag_bits & 0x800 else 'nomb')) -`, ZIP_OUT], { encoding: 'utf8' }) - console.log(report.trim()) - const lines = report.trim().split('\n').filter(Boolean) - check('ZIP 4 个条目(2 张 × 双版本)', lines.length === 4, 'entries=' + lines.length) - check('ZIP 条目格式与 UTF-8 文件名标记正确', lines.every((l) => /格式OK/.test(l) && /utf8/.test(l))) - check('双版本命名 <原名>_800x800.png/.jpg', lines.some((l) => /菜单A_800x800\.png/.test(l)) && lines.some((l) => /菜单A_800x800\.jpg/.test(l))) - } catch (e) { - check('ZIP 结构校验(python3)', false, String((e && e.stdout) || (e && e.message)).slice(0, 200)) - } -} - -// ---------- 6) 切到「图库 / 节点组」时不得串页(1.1.0) ---------- -// 真机现象:切到「图库」后批量面板还压在图片上方 —— 宿主两端都渲染成 div 且无 key, -// React 复用同一 DOM 节点,只清理自己管理的子节点,插件 mount 进去的根节点留在原地。 -const clickedGallery = await page.evaluate(() => { - const t = Array.from(document.querySelectorAll('.iwb-res-tab')).find((x) => /图库/.test(x.textContent)) - if (t) t.click() - return Boolean(t) -}) -await page.waitForTimeout(1200) -const gallery = await page.evaluate(() => ({ - historyMounted: document.querySelectorAll('.iwb-history-embedded').length, - panelsInDom: document.querySelectorAll('.iwb-bx').length, - panelInsideHistory: Boolean(document.querySelector('.iwb-history-embedded .iwb-bx')), -})) -check('切到「图库」:批量面板自动摘除,图库内不再混入插件 DOM', - clickedGallery && gallery.historyMounted >= 1 && gallery.panelsInDom === 0 && gallery.panelInsideHistory === false, - JSON.stringify(gallery)) - -await page.locator('.iwb-res-tab', { hasText: '批量出图' }).first().click() -await page.waitForTimeout(1500) -const backRows = await page.locator('.iwb-bx-item').count() -const backThumbs = await page.locator('.iwb-bx-item img.iwb-bx-thumb').count() -check('切回「批量出图」:面板自动重新挂载、列表与缩略图仍在', - backRows === 2 && backThumbs === 2, 'rows=' + backRows + ' thumbs=' + backThumbs) - -// ---------- 7) 无 CSP / SRI 拦截、无页面错误 ---------- -const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t)) -check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | ')) -check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | ')) - -await browser.close() -console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')) -process.exit(failed ? 1 : 0) diff --git a/browser/src/index.js b/browser/src/index.js index d62e4f2..803dec8 100644 --- a/browser/src/index.js +++ b/browser/src/index.js @@ -163,7 +163,7 @@ // 把网址放到画布上:新建一个「网页」节点并带上地址(宿主 canvasWrite 能力)。 // 宿主 createNode 认变体 id('web')—— 不在内置 NODE_TYPES 里时会自动走 addPluginNode。 - // 返回 false 表示这个宿主没提供该能力(旧客户端 / 网页版),调用方自己选退路。 + // 返回 false 表示这个宿主没提供该能力(旧客户端),调用方自己选退路。 function toCanvasNode(ctx, raw) { var url = normalizeUrl(raw) if (!url) return false @@ -647,9 +647,9 @@ setZoom(st, clampZoom(pz0 / 100), false) st.empty.textContent = '在上方地址栏输入网址,网页会显示在这里' // 面板内浏览同样要靠宿主的原生 webview 引擎(src/canvas-webview.js): - // 没有它(网页版 / 旧客户端)就是一块白板,必须说清原因而不是干等。 + // 没有它(旧客户端 / 合成测试宿主)就是一块白板,必须说清原因而不是干等。 var hasEngine = !!(global.IWBCanvasWebview || (global.window && global.window.IWBCanvasWebview)) - if (!invoke()) st.empty.textContent = '面板内浏览需要桌面客户端;网页版请用系统浏览器打开。' + if (!invoke()) st.empty.textContent = '面板内浏览需要桌面客户端;请用系统浏览器打开。' else if (!hasEngine) st.empty.textContent = '当前客户端还没有面板内浏览能力(需要 v3.25.30 及以上)。\n请先更新客户端。' // 面板关掉就没了,「✕ 关闭这个网页」在面板里没有意义 st.close.style.display = 'none' @@ -930,7 +930,7 @@ st.empty.textContent = '在地址栏输入网址,网页会显示在这个节点里' } else if (!supported) { st.empty.style.display = '' - st.empty.textContent = '画布内网页需要桌面客户端;网页版请用左侧「浏览器」面板。' + st.empty.textContent = '画布内网页需要桌面客户端;请用左侧「浏览器」面板。' } else if (!engine) { st.empty.style.display = '' st.empty.textContent = '当前客户端还没有画布内网页能力(需要 v3.25.29 及以上)。\n请先更新客户端;升级前可以点上方 ↗ 用「浏览器」面板打开。' diff --git a/browser/tools/harness.mjs b/browser/tools/harness.mjs index 411f6fb..a7cd1b2 100644 --- a/browser/tools/harness.mjs +++ b/browser/tools/harness.mjs @@ -504,7 +504,7 @@ const okInvoke = () => (name) => { nt.render({ id: 'n2', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host) const stage = host.children.find((c) => c.className === 'iwb-cwv-stage') const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty') - check('网页版节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text) + check('旧客户端节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text) } // ---------- 旧客户端(有 Tauri、但没有画布 webview 引擎)必须提示升级 ---------- diff --git a/image-annotate/README.md b/image-annotate/README.md index 84f6b89..727cabe 100644 --- a/image-annotate/README.md +++ b/image-annotate/README.md @@ -19,7 +19,7 @@ 持有几十 MB 的 base64 字符串)。合成宿主的 CSP 常把 `connect-src` 限为 `'self' https:`、**不含 `data:`** ⇒ `fetch(data:)` 被拦 (桌面客户端的 CSP 含 `data:`,但测试用的合成宿主按更严策略跑,故仍按最严口径处理)。 现改为**纯本地解码**(`atob` → `Uint8Array` → `Blob` → blob URL),与上游行为一致(同样拿到 blob URL),且不依赖 CSP/网络。 -> 这类问题**只有带 CSP 的真机/合成宿主能测出来**(无 CSP 的 mock 页永远绿)。用例见 `image-annotate/tools/e2e-site.mjs`。 +> 这类问题**只有带 CSP 的真机/合成宿主能测出来**(无 CSP 的 mock 页永远绿)。用例见 `image-annotate/tools/harness.mjs` 的 CSP 段。 ### v1.1:选区、便利版 UI、单张输出 @@ -66,8 +66,7 @@ - **侧栏去重**:移除硬度/透明两条滑杆(与就地选项栏画笔/橡皮态完全重复); 侧栏保留调色板全量 + 笔刷大小(滑杆/数字/快捷点)+ 缩放行。 -- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,79 项); - `node image-annotate/tools/e2e-site.mjs`(桌面客户端 CSP/SRI,发布后)。 +- 测试:`node image-annotate/tools/harness.mjs`(合成宿主 + 真实 Chromium,覆盖 CSP / 图层排序 / 输出几何,发布前必跑)。 ## v1.2.2 @@ -1216,11 +1215,12 @@ node scripts/gen-market.js # 生成 market/index.json 发布后回读市场索引确认版本与哈希已更新,再在客户端市场安装验证——不能只看命令退出码。 ## 验证(可选,开发用) -`tools/e2e-site.mjs`:**桌面客户端**端到端(市场安装 + SRI + 漂浮菜单 → 编辑器 → 覆盖/新建), -另含 v1.0.5 的图层顺序回归:画图形 + 粘贴截图 → 唯一高亮、点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底。 +`tools/harness.mjs`:合成宿主 + 真实 Chromium,覆盖 CSP 适配、图层顺序回归(画图形 + 粘贴截图 → 唯一高亮、 +点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底)、输出几何与编辑器命令。 需要 Playwright(可从桌面仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。 ```bash -node image-annotate/tools/e2e-site.mjs +node image-annotate/tools/harness.mjs ``` -> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真机能抓出来。 +> 为什么必须是真 Chromium:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在纯 mock 下永远绿, +> harness 里的合成宿主带 CSP 闸门才能抓出来。 diff --git a/image-annotate/tools/e2e-site.mjs b/image-annotate/tools/e2e-site.mjs deleted file mode 100644 index 7fc6a13..0000000 --- a/image-annotate/tools/e2e-site.mjs +++ /dev/null @@ -1,437 +0,0 @@ -// 真实站点端到端(开发用,不进 CI)。 -// -// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被 -// `connect-src 'self' https: …` 拦掉)在 mock 下永远绿,只有带 CSP 的真站能抓出来。 -// 它不 mock /plugins/*:走真实 KV + 浏览器 SRI 校验 + 真实画布桥。 -// -// 运行: -// node image-annotate/tools/e2e-site.mjs -// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-annotate/tools/e2e-site.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)) // /image-annotate/tools -const REPO = path.resolve(HERE, '../..') // -const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop' - -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:') - console.error(' npm i -D playwright # 本仓或宿主仓皆可') - console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node image-annotate/tools/e2e-site.mjs') - process.exit(2) -} - -const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev' -const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-annotate/package.json'), 'utf8')).version -const CFG = { providers: [], canvas: {} } -const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 } - -let failed = 0 -const check = (name, ok, detail) => { - if (!ok) failed++ - console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : '')) -} -const poll = async (fn, timeout = 25000, step = 250) => { - const end = Date.now() + timeout - for (;;) { - let v - try { v = await fn() } catch { v = false } - if (v) return v - if (Date.now() > end) return false - await new Promise((r) => setTimeout(r, step)) - } -} - -console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')') -const browser = await chromium.launch() -const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }) -const consoleErrors = [] -page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) }) -page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message + ' @ ' + String(e.stack || '').split('\n').slice(1, 4).join(' | '))) -page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) }) - -// 造一张真实的 96x64 PNG 作为节点图片 -await page.goto('about:blank') -const PNG = await page.evaluate(() => { - const c = document.createElement('canvas') - c.width = 96; c.height = 64 - const x = c.getContext('2d') - x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64) - x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40) - return c.toDataURL('image/png') -}) - -await page.addInitScript((d) => { - localStorage.clear() - localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg)) - const ws = JSON.parse(JSON.stringify(d.ws)) - ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }] - localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws)) - localStorage.setItem('iwb_ws_active', ws.activeId) - localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0])) - localStorage.setItem('iwb_web_outputs', JSON.stringify([])) - localStorage.setItem('iwb_plugins', JSON.stringify({ 'image-annotate': { enabled: true, settings: {}, data: {} } })) -}, { cfg: CFG, ws: WS, png: PNG }) - -const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' }) -check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status())) -await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 }) - -// ---------- 1) 真实 KV 加载 + SRI + 启用 ---------- -const active = await poll(async () => page.evaluate(() => { - const p = window.IWBPluginHost.list().find((x) => x.id === 'image-annotate') - return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false -})) -check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active)) -check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version) - -const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' }))) -// 文件名两种都合法:plugins-publish.mjs 产内容寻址名(..js,可 immutable 缓存), -// plugins-publish.sh(带主干守卫的合规通道)产固定名(plugin-image-annotate.js,走 no-cache+ETag)。 -// 断言的关键是「必须带 integrity」,与命名策略无关。 -check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /^\/plugins\/plugin-image-annotate(\.[a-f0-9]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts)) - -// ---------- 2) 打开工作区 + 节点存在 ---------- -await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick() -await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 }) -check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1) - -// ---------- 3) 入口:节点漂浮菜单(回落右键插件命令)---------- -const openEditor = async () => { - await page.locator('.iwb-node[data-node-id="r1"]').click() - const btn = page.locator('.iwb-node-floatbar button[title="标注 / 修图"]') - if (await btn.count()) { await btn.click(); return '漂浮菜单' } - await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } }) - await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '标注 / 修图:选中节点' }).click() - return '右键命令' -} -const entry = await openEditor() -check('节点入口可触发(漂浮菜单或右键命令)', true, entry) - -// ---------- 4) 编辑器打开(真实 CSP 下注入样式)---------- -await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 }) -const opened = await page.evaluate(() => { - const el = document.querySelector('#iwb-editor-overlay') - const style = document.getElementById('iwb-annotate-style') - return { - display: getComputedStyle(el).display, - position: getComputedStyle(el).position, - zIndex: getComputedStyle(el).zIndex, - bg: getComputedStyle(el).backgroundColor, - styleInjected: Boolean(style && style.textContent.includes('.iwb-editor-')), - } -}) -check('编辑器浮层可见', opened.display === 'flex' && opened.position === 'fixed') -check('样式注入生效(CSP unsafe-inline)', opened.styleInjected) -check('浮层压住宿主 UI', Number(opened.zIndex) >= 999998, 'z=' + opened.zIndex + ' bg=' + opened.bg) - -// ---------- 4.5) 剪贴板粘贴:⌘V 把剪贴板图片贴为新图层 ---------- -// 合成 ClipboardEvent(带 image/png File),粘贴应进入「图片放置」模式;回车确认后图层面板 +1 项。 -// SKIP_PASTE=1 可跳过(隔离「粘贴」与「覆盖写回」两条链路的排查用)。 -const SKIP_PASTE = process.env.SKIP_PASTE === '1' -if (!SKIP_PASTE) { - // 先画一个矢量矩形,制造「截图 + 图形」共存场景 —— 这是 z 撞车 / 排序按钮失效的复现前提 - const imgBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox() - await page.locator('.iwb-editor-tool[data-tool="rect"]').click() - await page.mouse.move(imgBox.x + imgBox.width * 0.25, imgBox.y + imgBox.height * 0.25) - await page.mouse.down() - await page.mouse.move(imgBox.x + imgBox.width * 0.75, imgBox.y + imgBox.height * 0.75, { steps: 8 }) - await page.mouse.up() - await page.waitForTimeout(200) - const layersBefore = await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length) - await page.evaluate((png) => { - const bin = atob(png.split(',')[1]) - const bytes = new Uint8Array(bin.length) - for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) - const dt = new DataTransfer() - dt.items.add(new File([bytes], 'paste.png', { type: 'image/png' })) - document.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })) - }, PNG) - await page.waitForTimeout(800) // FileReader → loadImage → 进入放置模式 - await page.keyboard.press('Enter') // 确认放置 → 落层 - const pasted = await poll(async () => page.evaluate((n) => document.querySelectorAll('.iwb-editor-layer-list > *').length > n, layersBefore)) - check('⌘V 粘贴剪贴板图片 → 确认后图层面板 +1', Boolean(pasted), '图层项 ' + layersBefore + ' → ' + await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length)) - - // ---------- 4.6) 图层顺序回归(2026-11-04 修):z 唯一 / 选中唯一 / 四个排序按钮 ---------- - const panelSeq = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item')) - .map((n) => n.querySelector('.iwb-layer-name')?.textContent).join(' > ')) - const activeCount = () => page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item.active').length) - check('图层面板只有一个选中项(画笔目标改用 ✎ 标记)', (await activeCount()) === 1, - 'active=' + await activeCount() + ' / ' + await panelSeq()) - - await page.locator('.iwb-editor-tool[data-tool="select"]').click() - await page.mouse.click(imgBox.x + imgBox.width * 0.5, imgBox.y + imgBox.height * 0.5) - await page.waitForTimeout(150) - const activeItem = await page.evaluate(() => { - const n = document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active') - return n && { type: n.dataset.layerType, name: n.querySelector('.iwb-layer-name')?.textContent } - }) - check('点击「截图+图形」重叠区选中最上层截图(不被下方图形抢走)', - Boolean(activeItem && activeItem.type === 'bitmap' && /图层/.test(activeItem.name)), JSON.stringify(activeItem)) - - // v1.13 起顶栏四个层级按钮已删除(改为图层拖动 + Ctrl+]/[ 快捷键), - // 这里改为断言「按钮确实没了」+ 用快捷键验证排序仍然可用。 - check('顶栏不再有层级排序按钮(改用图层拖动 + Ctrl+]/[)', - (await page.locator('.iwb-editor-layer-btn').count()) === 0 && - (await page.locator('.iwb-editor-header .iwb-editor-commands').count()) === 0, - 'layerBtn=' + await page.locator('.iwb-editor-layer-btn').count()) - - // v1.18(用户 2026-11-10):撤销 / 重做 / 还原 从顶栏搬到工具条最右, - // 「适应窗口 / 收起侧栏」退到它前面两位。这里断言「末尾是撤销组、视图按钮在其前」 - // —— 光看版本号挡不住产物没重建。 - const toolsOrder = await page.evaluate(() => { - const kids = Array.from(document.querySelectorAll('.iwb-editor-tools > *')) - const acts = kids.filter((n) => n.dataset && n.dataset.action).map((n) => n.dataset.action) - const hist = kids[kids.length - 1] - return { - tail: acts.slice(-2), - lastIsHistory: Boolean(hist && hist.classList.contains('iwb-editor-history')), - histActs: [...(hist ? hist.querySelectorAll('[data-action]') : [])].map((b) => b.dataset.action), - headerHasHistory: Boolean(document.querySelector('.iwb-editor-header .iwb-editor-history')), - } - }) - check('工具栏最右是「撤销/重做/还原」组(视图按钮在其前)', - JSON.stringify(toolsOrder.tail) === JSON.stringify(['zoomFit', 'togglePanels']) && - toolsOrder.lastIsHistory && toolsOrder.histActs.join(',') === 'undo,redo,reset' && - !toolsOrder.headerHasHistory, JSON.stringify(toolsOrder)) - - const before = await panelSeq() - const activeName = await page.evaluate(() => document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active .iwb-layer-name')?.textContent) - await page.keyboard.press('Control+[') // 下移一层 - const afterDown = await panelSeq() - check('Ctrl+[ 下移一层改变图层顺序', before !== afterDown, before + ' → ' + afterDown) - await page.keyboard.press('Control+]') // 上移一层 - check('Ctrl+] 上移一层恢复原顺序', (await panelSeq()) === before, await panelSeq()) - - await page.keyboard.press('Control+Shift+[') // 置底 - const afterBottom = await panelSeq() - check('Ctrl+Shift+[ 置底生效(元素不会消失)', - afterBottom !== before && afterBottom.endsWith(String(activeName)), afterBottom) - check('置底后原图不再被钉在最底 —— 图层可以压到原图下面(v1.13 解封)', - !afterBottom.endsWith('原图'), afterBottom) - await page.keyboard.press('Control+Shift+]') // 置顶 - check('Ctrl+Shift+] 置顶生效', (await panelSeq()) !== afterBottom, await panelSeq()) - check('排序后仍只有一个选中项', (await activeCount()) === 1, 'active=' + await activeCount()) - - // v1.15 图片调节:真站确认面板存在、11 项按参数表生成(DOM 由 adjust.js 生成, - // 构建时漏带就会是 0 行 —— 这类「打包产物缺模块」只有真站能发现) - const adjRowCount = await page.locator('.iwb-editor-adj-row').count() - const adjNames = await page.locator('.iwb-editor-adj-name').allTextContents() - check('右侧栏「图片调节」11 项齐全', - adjRowCount === 11 && adjNames.join('/') === '曝光/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度', - 'rows=' + adjRowCount + ' ' + adjNames.join('/')) - check('调节面板认到了作用层(不是「无图层」)', - (await page.locator('.iwb-editor-adj-target').textContent()) !== '无图层', - await page.locator('.iwb-editor-adj-target').textContent()) - - // v1.19:右栏常驻调色面板已删(用户 2026-11-10),颜色只剩工具栏弹层一处。 - // 真站里 DOM 与 CSS 分别打包,这里同时验「右栏干净」和「弹层头部一行 / 16 色 8 列」—— - // 样式漏打包时,头部会退回竖排或色块掉成 6 列,这条会直接露出来。 - const sideColor = await page.evaluate(() => ({ - hasSide: Boolean(document.querySelector('.iwb-editor-left [data-color-surface]')), - firstSection: (document.querySelector('.iwb-editor-left > section') || {}).className || '', - })) - check('右栏调色模块已删(第一个模块是图片调节)', - sideColor.hasSide === false && /iwb-editor-adj/.test(sideColor.firstSection), - JSON.stringify(sideColor)) - - await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click() - await page.waitForTimeout(240) - const popShape = await page.evaluate(() => { - const pop = document.querySelector('.iwb-editor-color-pop') - if (!pop) return null - const r = (el) => el.getBoundingClientRect() - const head = r(pop.querySelector('.iwb-color-pop-head')) - const items = [pop.querySelector('[data-action="palettePick"]'), - pop.querySelector('.iwb-editor-color-hex-input'), - pop.querySelector('[data-action="pinColorPop"]')].map((el) => { - const b = r(el) - return { c: b.top + b.height / 2, l: b.left, r: b.right } - }) - const sw = [...pop.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')] - const grid = pop.querySelector('.iwb-editor-color-swatches') - return { - w: Math.round(r(pop).width), - sameRow: items.every((it) => - Math.abs(it.c - (head.top + head.height / 2)) < 3 && it.l >= head.left - 1 && it.r <= head.right + 1), - common: sw.length, - cols: new Set(sw.map((b) => Math.round(r(b).left))).size, - swatch: sw.length ? Math.round(r(sw[0]).width) : 0, - // v1.20:去色占常用色第一格(20px 同尺寸、第一排最左) - noneFirst: grid.children[0] === pop.querySelector('[data-color-none]'), - cells: grid.children.length, - } - }) - check('色板弹层:头部一行(吸管 / 色值 / 图钉同排)+ 去色占常用色第一格 + 15 色 8 列', - Boolean(popShape) && popShape.sameRow && popShape.noneFirst && popShape.cells === 16 && - popShape.common === 15 && popShape.cols === 8 && popShape.swatch === 20 && popShape.w === 440, - JSON.stringify(popShape)) - await page.keyboard.press('Escape') - await page.waitForTimeout(140) - - const sideBefore = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width)) - const sideGrip = await page.locator('.iwb-editor-side-resizer').boundingBox() - if (sideGrip) { - await page.mouse.move(sideGrip.x + 3, sideGrip.y + 120) - await page.mouse.down() - await page.mouse.move(sideGrip.x + 3 - 70, sideGrip.y + 120, { steps: 6 }) - await page.mouse.up() - await page.waitForTimeout(180) - } - const sideAfter = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width)) - check('右栏可以拖宽(不再固定 220)', sideAfter >= sideBefore + 60, sideBefore + ' → ' + sideAfter) - await page.locator('.iwb-editor-side-resizer').dblclick() - await page.waitForTimeout(150) - - // v1.17:描边可以是「无色」。真站要验的是按钮真的出现在描边槽、点完对象上真的关了, - // 而不只是 CSS 里多了个类 —— 形状消失与否只有跑起来才知道。 - await page.locator('.iwb-editor-tool[data-tool="rect"]').click() - await page.mouse.move(imgBox.x + imgBox.width * 0.12, imgBox.y + imgBox.height * 0.12) - await page.mouse.down() - await page.mouse.move(imgBox.x + imgBox.width * 0.30, imgBox.y + imgBox.height * 0.30, { steps: 6 }) - await page.mouse.up() - await page.waitForTimeout(250) - await page.locator('.iwb-editor-tool[data-tool="select"]').click() - await page.mouse.click(imgBox.x + imgBox.width * 0.21, imgBox.y + imgBox.height * 0.21) - await page.waitForTimeout(200) - await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click() - await page.waitForTimeout(250) - const noneOnStroke = await page.evaluate(() => { - const n = document.querySelector('.iwb-editor-color-pop [data-color-none]') - // v1.20:去色不再 hidden,改用 disabled 表达「这个上下文不能去色」 - return Boolean(n) && Boolean(n.offsetParent) && !n.disabled - }) - await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click()) - await page.waitForTimeout(300) - const noStrokeState = await page.evaluate(() => { - const d = window.__iwbEditor.__debug() - const s = d.shapes.find((x) => x.id === d.selectedShapeId) - return s ? { strokeOn: s.strokeOn, fill: s.fill } : null - }) - check('真站:描边能置「无」(去掉描边顺手切实心,对象不会消失)', - noneOnStroke && Boolean(noStrokeState) && noStrokeState.strokeOn === false && noStrokeState.fill === true, - JSON.stringify({ noneOnStroke, noStrokeState })) - await page.keyboard.press('Escape') - await page.waitForTimeout(120) - - // v1.14 字体选择:真站是带 CSP 的环境,这里确认下拉可用、字体切换真的落到了对象上。 - // 系统字体不受 CSP 约束(CSP 管的是网络字体),所以只要 canvas 能画就没问题。 - const famDbg = () => page.evaluate(() => window.__iwbEditor.__debug()) - const FAM_SEL = '.iwb-editor-optionbar-body select[data-opt-text="fontFamily"]' - await page.locator('.iwb-editor-tool[data-tool="text"]').click() - const famBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox() - await page.mouse.click(famBox.x + 60, famBox.y + 60) - await page.waitForTimeout(300) - await page.evaluate(() => { - const el = document.querySelector('.iwb-editor-text-input') - if (!el) return - el.focus() - el.value = '字体测试' - el.dispatchEvent(new Event('input', { bubbles: true })) - }) - await page.keyboard.press('Enter') - await page.waitForTimeout(400) - - const famOpts = await page.locator(FAM_SEL + ' option').allTextContents() - check('真站选项栏出现字体下拉,四档:黑体 / 宋体 / 楷体 / 圆体', - famOpts.length === 4, JSON.stringify(famOpts)) - - const wSans = ((await famDbg()).texts.find((t) => t.text === '字体测试') || {}).box - await page.selectOption(FAM_SEL, 'serif') - await page.waitForTimeout(320) - const tSerif = (await famDbg()).texts.find((t) => t.text === '字体测试') - check('真站切换宋体生效,且中文宽度不变(全角等宽,版面不跳动)', - Boolean(tSerif && tSerif.fontFamily === 'serif' && wSans && Math.abs(tSerif.box.w - wSans.w) <= 1), - (wSans ? wSans.w : '?') + ' → ' + (tSerif ? tSerif.box.w : '?')) - await page.keyboard.press('Delete') - await page.waitForTimeout(200) - - // 复原成画笔工具,避免影响后面「覆盖」链路的画笔取样 - await page.locator('.iwb-editor-tool[data-tool="brush"]').click() -} - -// ---------- 4.7) v1.1:选区 / 单层 Delete / 还原原图 / ≤500KB 预设 ---------- -const dbg = () => page.evaluate(() => window.__iwbEditor.__debug()) -const v11Box = await page.locator('.iwb-editor-layer-canvas').first().boundingBox() -await page.locator('.iwb-editor-tool[data-tool="marquee"]').click() -await page.mouse.move(v11Box.x + v11Box.width * 0.25, v11Box.y + v11Box.height * 0.25) -await page.mouse.down() -await page.mouse.move(v11Box.x + v11Box.width * 0.7, v11Box.y + v11Box.height * 0.7, { steps: 8 }) -await page.mouse.up() -await page.waitForTimeout(150) -const v11sel = (await dbg()).selection -check('v1.1 框选 + 浮动操作条出现', Boolean(v11sel && v11sel.w > 5 && v11sel.h > 5) && - await page.locator('.iwb-editor-sel-bar').isVisible(), JSON.stringify(v11sel)) -const v11px = (x, y) => page.evaluate(({ px, py }) => { - const d = window.__iwbEditor.__debug() - // 1.2.1 起默认没有 id='draw' 的预建层:填充落进「当前活动层」, - // 所以这里读活动层像素而不是写死 'draw' - return { base: d.pixel('base', px, py), draw: d.pixel(d.activeLayerId, px, py), activeId: d.activeLayerId } -}, { px: x, py: y }) -const vcX = Math.round(v11sel.x + v11sel.w / 2) -const vcY = Math.round(v11sel.y + v11sel.h / 2) -const v11before = await v11px(vcX, vcY) -await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.fill"]').click() -await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]').click() -const v11after = await v11px(vcX, vcY) -check('v1.1 Delete 只清当前层(base 像素原样)', - v11after.draw[3] === 0 && JSON.stringify(v11after.base) === JSON.stringify(v11before.base), - 'draw=' + JSON.stringify(v11after.draw) + ' base=' + JSON.stringify(v11after.base)) -await page.keyboard.press('Control+z') -const v11layersBeforeReset = (await dbg()).layers.length -await page.locator('[data-action="reset"]').click() -check('v1.1 还原原图=只剩原图单层(1.2.1 起不预建画笔层)', (await dbg()).layers.length === 1, JSON.stringify((await dbg()).layers)) -await page.keyboard.press('Control+z') -check('v1.1 还原原图可 Ctrl+Z 撤销', (await dbg()).layers.length === v11layersBeforeReset, - '层数 ' + v11layersBeforeReset + ' → 2 → ' + (await dbg()).layers.length) -await page.locator('[data-action="toggleExportSettings"]').click() -await page.locator('[data-export-key="preset"][data-export-value="ecom800"]').click() -check('v1.1 ≤500KB 输出预设可切换', (await dbg()).exportOptions.maxKB === 500, - JSON.stringify((await dbg()).exportOptions)) -await page.locator('[data-export-key="preset"][data-export-value="original"]').click() -await page.locator('.iwb-editor-tool[data-tool="brush"]').click() - -// ---------- 5) 覆盖:回写真机画布 ---------- -await page.mouse.move(400, 300) -await page.mouse.down() -await page.mouse.move(760, 520, { steps: 8 }) -await page.mouse.up() -await page.locator('[data-action="replace"]').click() - -const replaced = await poll(async () => page.evaluate((orig) => { - const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}') - const n = (ws.nodes || []).find((x) => x.id === 'r1') - if (!n) return false - const v = n.data && (typeof n.data.data === 'string' ? n.data.data : (n.data.data && (n.data.data.__blob || JSON.stringify(n.data.data)))) - return (ws.nodes.length === 1 && v && v !== orig) ? { nodes: ws.nodes.length, changed: true } : false -}, PNG)) -check('「覆盖」写回原节点(节点数不变、内容已变)', Boolean(replaced), JSON.stringify(replaced)) -check('编辑器导出后关闭', (await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false) - -// ---------- 6) 新建:真机画布新增节点 ---------- -await openEditor() -await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 }) -await page.locator('[data-action="newNode"]').click() -const created = await poll(async () => page.evaluate(() => { - const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}') - return (ws.nodes || []).length === 2 ? { nodes: 2 } : false -})) -check('「新建」在真机画布新增节点', Boolean(created), JSON.stringify(created)) -await page.locator('.iwb-canvas').waitFor({ state: 'visible' }) -check('画布渲染出 2 个节点', (await page.locator('.iwb-node').count()) === 2) - -// ---------- 7) 无 CSP / 运行时错误 ---------- -const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t)) -check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | ')) -check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | ')) - -await browser.close() -console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')) -process.exit(failed ? 1 : 0) diff --git a/image-vectorize/README.md b/image-vectorize/README.md index 62f8491..55b9d98 100644 --- a/image-vectorize/README.md +++ b/image-vectorize/README.md @@ -136,8 +136,7 @@ potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE` ```bash npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE) npm run validate # 契约校验 -node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项) -node image-vectorize/tools/e2e-site.mjs # 桌面客户端端到端(市场安装 / SRI / CSP / 真实画布桥) +node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项,含 CSP / 画布桥) # 拿真实素材调参数(不进 CI,最快看到效果): node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3 diff --git a/image-vectorize/tools/e2e-site.mjs b/image-vectorize/tools/e2e-site.mjs deleted file mode 100644 index d9ec5c7..0000000 --- a/image-vectorize/tools/e2e-site.mjs +++ /dev/null @@ -1,276 +0,0 @@ -// 真实站点端到端(开发用,不进 CI)。 -// -// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 —— -// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。 -// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能 -// 悄悄把 'wasm-unsafe-eval' 加回去。 -// -// 运行: -// node image-vectorize/tools/e2e-site.mjs -// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-vectorize/tools/e2e-site.mjs -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-desktop' - -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) -} - -const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev' -const PLUGIN_ID = 'image-vectorize' -const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-vectorize/package.json'), 'utf8')).version -const CFG = { providers: [], canvas: {} } -const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 } - -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)) -const poll = async (fn, timeout = 25000, step = 250) => { - const end = Date.now() + timeout - for (;;) { - let v - try { v = await fn() } catch { v = false } - if (v) return v - if (Date.now() > end) return false - await sleep(step) - } -} - -console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')') -const browser = await chromium.launch() -// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条) -const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }) -try { - await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin }) -} catch (error) { - console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')') -} -const page = await context.newPage() -const consoleErrors = [] -page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) }) -page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message)) -page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) }) - -await page.goto('about:blank') -const PNG = await page.evaluate(() => { - const c = document.createElement('canvas') - c.width = 320; c.height = 320 - const g = c.getContext('2d') - g.fillStyle = '#ffffff'; g.fillRect(0, 0, 320, 320) - g.fillStyle = '#e8422f'; g.beginPath(); g.arc(96, 96, 58, 0, Math.PI * 2); g.fill() - g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(170, 130, 120, 84, 12); g.fill() - g.fillStyle = '#111111'; g.font = 'bold 38px "PingFang SC", sans-serif'; g.fillText('菜单', 96, 250) - return c.toDataURL('image/png') -}) - -await page.addInitScript((d) => { - localStorage.clear() - localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg)) - const ws = JSON.parse(JSON.stringify(d.ws)) - ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }] - localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws)) - localStorage.setItem('iwb_ws_active', ws.activeId) - localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0])) - localStorage.setItem('iwb_web_outputs', JSON.stringify([])) - localStorage.setItem('iwb_plugins', JSON.stringify({ [d.id]: { enabled: true, settings: {}, data: {} } })) -}, { cfg: CFG, ws: WS, png: PNG, id: PLUGIN_ID }) - -const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' }) -check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status())) - -// ---------- 1) 真实 KV 加载 + SRI ---------- -await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 }) -const active = await poll(async () => page.evaluate((id) => { - const p = window.IWBPluginHost.list().find((x) => x.id === id) - return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false -}, PLUGIN_ID)) -check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active)) -check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version) - -const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' }))) -check('插件脚本用 SRI(sha256) 加载', - scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)), - JSON.stringify(scripts.map((s) => s.src))) - -// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ---------- -const cspProbe = await page.evaluate(async () => { - try { - const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0)) - await WebAssembly.instantiate(b) - return 'ok' - } catch (e) { return 'blocked: ' + e.message } -}) -check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120)) - -// ---------- 3) 打开工作区 ---------- -await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick() -await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 }) -check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1) - -// ---------- 4) 入口 → 模态 ---------- -await page.locator('.iwb-node[data-node-id="r1"]').click() -const floatBtn = page.locator('.iwb-node-floatbar button[title="位图转矢量"]') -let entry = '' -if (await floatBtn.count()) { - await floatBtn.click() - entry = '漂浮菜单' -} else { - await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } }) - await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '位图转矢量' }).first().click() - entry = '右键命令' -} -await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 30000 }) -check('节点入口可触发(' + entry + ')', true) -check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => { - const s = document.getElementById('iwb-vectorize-style') - return Boolean(s && s.textContent.indexOf('.vz-') >= 0) -})) - -// 用户 2026-11-09:取消与保存为节点互换,四颗按钮同一套描边配色(绿色主按钮已去掉)。 -// 这条同时是「线上真的是新版」的活体证据 —— 光看版本号挡不住产物没重建。 -check('顶栏顺序 保存为节点→复制→下载→取消,四颗同色', await page.evaluate(() => { - const btns = [...document.querySelectorAll('.vz-header .vz-btn')] - if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false - const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color)) - return colors.size === 1 -})) - -// ---------- 5) 真站 CSP 下引擎能跑 ---------- -const paths = await poll(async () => { - // 统计项是「元素」,合并模式下会带后缀「(N 孤岛合并)」,只取前面的数字 - const t = await page.locator('[data-stat="elements"]').textContent() - const m = /^\s*(\d+)/.exec(t || '') - return m && Number(m[1]) > 0 ? m[1] : false -}, 30000) -check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), '元素=' + paths) -check('默认按孤岛拆分(元素数 > 层数)', Number(paths) > 3, '元素=' + paths) -check('预览为 blob: SVG', await page.evaluate(() => { - const v = document.querySelector('[data-stage="vector"]') - return Boolean(v && /^blob:/.test(v.src) && !v.hidden) -})) - -const stats = await page.evaluate(() => ({ - levels: Number(document.querySelector('[data-stat="levels"]').textContent), - bytes: document.querySelector('[data-stat="bytes"]').textContent, - ms: document.querySelector('[data-stat="ms"]').textContent, -})) -check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats)) - -// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ---------- -check('高级参数默认展开', await page.evaluate(() => { - const box = document.querySelector('[data-adv]') - return Boolean(box && !box.hidden) -})) -check('精度默认「精细」', await page.evaluate(() => { - const a = document.querySelector('[data-seg-group="precision"] button.active') - return Boolean(a && a.dataset.value === 'fine') -})) -// v0.3.1:预览白底 + 填充/背景并排(真站 CSP 下 CSS 得真生效,不能只信本地) -check('预览区白底、无棋盘格', await page.evaluate(() => { - const cs = getComputedStyle(document.querySelector('.vz-preview')) - const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(cs.backgroundColor) - return Boolean(m) && Number(m[1]) > 240 && cs.backgroundImage === 'none' -})) -check('「填充 / 背景」两个色块并排在同一行', await page.evaluate(() => { - const a = document.querySelector('[data-color="color"]') - const b = document.querySelector('[data-color="bg"]') - if (!a || !b) return false - const ra = a.getBoundingClientRect() - const rb = b.getBoundingClientRect() - return Math.abs(ra.top - rb.top) < 2 && rb.left > ra.right - 1 -})) - -// v0.4.0:预览缩放 / 平移(真站上鼠标手势得真能走通,不能只信本地合成宿主) -const pvBox = await page.locator('.vz-preview').boundingBox() -await page.mouse.move(pvBox.x + pvBox.width / 2 + 40, pvBox.y + pvBox.height / 2 - 20) -await page.mouse.wheel(0, -300) -await sleep(220) -// 断言「换算比例」而不是「比容器大」:正方形图 fit 进宽屏预览后本来就比容器窄, -// 拿 rect.width > clientWidth 会比较,放大了也可能不成立(实测真站 549 vs 1011) -check('滚轮放大预览、倍率胶囊出现', await page.evaluate(() => { - const p = document.querySelector('.vz-preview') - const v = document.querySelector('[data-stage="vector"]') - const z = Number(p.style.getPropertyValue('--vz-zoom') || 1) - const chip = document.querySelector('[data-zoom-chip]') - const ratio = v.getBoundingClientRect().width / v.clientWidth - return z > 1.1 && Boolean(chip) && !chip.hidden && Math.abs(ratio - z) < 0.02 -})) -await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2) -await sleep(220) -check('双击复位回 100%', await page.evaluate(() => { - const p = document.querySelector('.vz-preview') - return Number(p.style.getPropertyValue('--vz-zoom') || 1) === 1 -})) - -// 回归:平滑滚轮(小数 deltaY)在真站也必须缩放。旧逻辑靠整数步长识别鼠标,会把这类滚轮当平移。 -await page.evaluate(() => { - const p = document.querySelector('.vz-preview') - const r = p.getBoundingClientRect() - p.dispatchEvent(new WheelEvent('wheel', { - deltaY: -12.5, deltaMode: 0, bubbles: true, cancelable: true, - clientX: r.left + r.width / 2, clientY: r.top + r.height / 2, - })) -}) -await sleep(160) -check('真站:小数步长滚轮照样放大', await page.evaluate(() => { - const p = document.querySelector('.vz-preview') - return Number(p.style.getPropertyValue('--vz-zoom') || 1) > 1.001 -})) -await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2) -await sleep(160) - -// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ---------- -await page.locator('[data-act="copy"]').click() -await sleep(400) -const clip = await page.evaluate(async () => { - try { - const items = await navigator.clipboard.read() - const types = items[0] ? items[0].types : [] - let svg = '' - if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text() - return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' } - } catch (e) { return { error: String(e && e.message) } } -}) -if (clip.error) { - check('复制 SVG 写入剪贴板', false, clip.error) -} else { - check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)', - clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf(' 0, - clip.types.join(',') + ' / ' + clip.svg.length + 'B') - check('复制后给了反馈', /已复制/.test(clip.status), clip.status) - // 拆分是这个版本的核心诉求:粘到 Figma 必须是多个可单独选中的图层,而不是一个整体 - const pathCount = (clip.svg.match(/= 5 && !/ (await page.locator('.iwb-node').count()) >= 2, 25000) -check('保存为节点:画布新增一个图片节点', Boolean(saved), 'nodes=' + await page.locator('.iwb-node').count()) -check('模态已关闭', (await page.locator('.vz-root').count()) === 0) - -const fatal = consoleErrors.filter((e) => /Content Security Policy|Refused to|SRI|integrity/i.test(e)) -check('无 CSP / SRI 报错', fatal.length === 0, fatal.slice(0, 2).join(' | ')) -if (consoleErrors.length) { - console.log('') - console.log('控制台错误(' + consoleErrors.length + ' 条,前 5 条):') - for (const e of consoleErrors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180)) -} - -console.log('') -console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过') -await browser.close() -process.exit(failed ? 1 : 0) diff --git a/style-source/README.md b/style-source/README.md index 3c77a85..98fdcb2 100644 --- a/style-source/README.md +++ b/style-source/README.md @@ -53,7 +53,7 @@ `ensureStyle()` 原本只在 `mount()`(面板)里调用 ⇒ **没打开过「风格库」面板**时,节点体是无样式的裸 DOM, `` 按原图尺寸铺满整个节点(真机表现:图片"跑出来了")。 现在 setup 注册变体前注入一次,`renderStyleNode()` 里再兜一次(幂等)。 -回归用例:`tools/e2e-test-site.mjs` 第 9 段(不开面板直接进存档画布,断言缩略图宽高 ≈56px)。 +回归用例:`tools/harness.mjs` 的「样式表在脚本执行时就已注入(不开面板、不跑 setup 也在)」闸门,以及缩略图 56px 方块的断言。 ### v1.3.2(2026-11-14)注入点再提前到脚本执行 + 缩略图内联兜底 @@ -182,15 +182,14 @@ 数据与图片都是公网 `https://`,桌面宿主 `tauri.conf.json` 的 `img-src … https:` / `connect-src … https:` 已经放行。 对比 `ai-chat`(连本机 `http://127.0.0.1:3425`)必须单独加端口。 -## 测试(三层,从快到慢) +## 测试(两层,从快到慢) | 层 | 命令 | 覆盖什么 | 依赖 | |---|---|---|---| -| 合成宿主 | `node tools/harness.mjs`(88 项) | 面板交互、详情页按钮顺序与同色、节点体结构、变量写入/防抖/不失焦、收起变量、截图 | 无(自带 mock 宿主) | +| 合成宿主 | `node tools/harness.mjs`(88 项) | 面板交互、详情页按钮顺序与同色、节点体结构、变量写入/防抖/不失焦、收起变量、CSS 注入闸门、截图 | 无(自带 mock 宿主 + 真 Chromium) | | 线上数据真网 | `node tools/e2e-real.mjs`(10 项) | styles.json 真拉得到、卡片渲染、样式节点入口 | 网络 | -| 桌面客户端端到端 | `node tools/e2e-test-site.mjs`(15 项) | **宿主新接口到底接上没有**:进画布 → 开资源库 → 点「样式节点」→ 节点体由插件渲染、示例图默认勾选、变量输入不失焦、多变量不裁切、收起生效 | 桌面客户端已装本插件(`SITE=` 换地址,`HEADED=1` 看着跑) | -前两支只验插件自己;**第三支才验宿主**,发布宿主改动后必跑。 +两支都验插件自己;发布宿主改动后,在桌面客户端市场里确认版本与加载状态,并用真实存档画布核对样式节点体(harness 的 CSS 闸门已覆盖「不开面板直接进画布」这一关键场景)。 ## 发布 diff --git a/style-source/tools/e2e-test-site.mjs b/style-source/tools/e2e-test-site.mjs deleted file mode 100644 index 9891324..0000000 --- a/style-source/tools/e2e-test-site.mjs +++ /dev/null @@ -1,283 +0,0 @@ -// 真机验收:**测试站上「宿主新接口 + 本插件」端到端**跑通(harness / e2e-real 都覆盖不到的那一层)。 -// -// 为什么单独一支: -// - `tools/harness.mjs` 跑在合成宿主里,验不了「宿主的 PluginDomBody / 声明式参考图」是否真的接上; -// - `tools/e2e-real.mjs` 验的是「线上真网 + 插件面板」,不去点画布、不落节点。 -// 这支脚本在**真的 test 站**里:双击进工作台 → 开资源库 → 点风格 → 点「样式节点」→ 检查节点体与输入体验。 -// -// 用法: -// node tools/e2e-test-site.mjs # 默认 https://test.image-workbench-web.pages.dev/ -// SITE=https://xxx.pages.dev/ node tools/e2e-test-site.mjs -// HEADED=1 node tools/e2e-test-site.mjs # 看着它跑 -// -// 前置:宿主已部署含「插件节点体 + 声明式参考图」的版本,且 style-source 已在 KV 清单里。 -// 全程只读:不动线上数据,浏览器用一次性 profile(跑完即弃)。 - -import { createRequire } from 'node:module' -import path from 'node:path' -import fs from 'node:fs' - -const HERE = path.dirname(new URL(import.meta.url).pathname) -let chromium = null -for (const base of [path.resolve(HERE, '../..'), path.resolve(HERE, '../../../image-workbench-desktop'), process.cwd()]) { - const pkg = path.join(base, 'package.json') - if (!fs.existsSync(pkg)) continue - try { chromium = createRequire(pkg)('playwright').chromium; break } catch { /* 换下一个 */ } -} -if (!chromium) { - console.error('找不到 playwright:请在插件仓根目录或宿主仓(image-workbench-desktop)里跑') - process.exit(2) -} - -const SITE = process.env.SITE || 'https://test.image-workbench-web.pages.dev/' -let failed = 0 -const check = (name, ok, detail) => { - if (!ok) failed++ - console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : '')) -} -const shot = (name) => page.screenshot({ path: path.join(HERE, 'shot-testsite-' + name + '.png') }).catch(() => {}) - -const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy -const browser = await chromium.launch({ - headless: process.env.HEADED !== '1', - ...(proxy ? { proxy: { server: proxy } } : {}), -}) -const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }) -const errors = [] -page.on('pageerror', (e) => errors.push(String(e))) - -await page.goto(SITE, { waitUntil: 'domcontentloaded' }) -await page.waitForTimeout(1200) -// 启停状态只落 localStorage['iwb_plugins'](真机同款键) -await page.evaluate(() => { - localStorage.setItem('iwb_plugins', JSON.stringify({ 'style-source': { enabled: true, settings: {}, data: {} } })) -}) -await page.reload({ waitUntil: 'domcontentloaded' }) -await page.waitForTimeout(4000) - -// ── 1. 宿主版本:三处新接口的特征串(压缩后函数名会变,只能查字符串) ────────── -const host = await page.evaluate(async () => { - const src = await (await fetch('/app.js', { cache: 'no-store' })).text() - const ver = await (await fetch('/version.json', { cache: 'no-store' })).json().catch(() => ({})) - return { - pluginBody: src.includes('iwb-plugin-node-body'), - selfRef: src.includes('style-ref.png'), - combineTag: src.includes('iwb-combine-src-tag'), - version: ver.version || '', - len: src.length, - } -}) -check('测试站 app.js 含插件节点体 + 声明式参考图 + 组合来源标签', host.pluginBody && host.selfRef && host.combineTag, - JSON.stringify({ version: host.version, len: host.len })) - -// ── 2. 插件已启用并激活 ─────────────────────────────────────────────────── -const list = await page.evaluate(() => { - const h = window.IWBPluginHost - if (!h) return { noHost: true } - const l = typeof h.list === 'function' ? h.list() : [] - return { list: l.map((p) => ({ id: p.id, version: p.version, enabled: p.enabled, active: p.active, error: p.error })) } -}) -const me = (list.list || []).find((p) => p.id === 'style-source') -check('style-source 已启用并激活', Boolean(me && me.active), JSON.stringify(me)) - -// ── 3. 进工作台(首页卡片是「双击打开」,单击只是选中) ────────────────────── -await page.locator('.iwb-home-card').first().dblclick({ timeout: 8000 }) -await page.waitForTimeout(3000) -const entered = await page.evaluate(() => ({ cards: document.querySelectorAll('.iwb-home-card').length })) -check('双击首页卡片进入画布', entered.cards === 0, JSON.stringify(entered)) - -// ── 4. 资源库 → 风格库 tab(N 是宿主「开关资源库」的快捷键) ────────────────── -await page.evaluate(() => { const a = document.activeElement; if (a && a.blur) a.blur() }) -await page.keyboard.press('n') -await page.waitForTimeout(1200) -const tabs = await page.evaluate(() => [...document.querySelectorAll('.iwb-res-tab')].map((b) => (b.textContent || '').trim())) -await page.evaluate(() => { - const hit = [...document.querySelectorAll('.iwb-res-tab')].find((b) => /风格库/.test(b.textContent || '')) - if (hit) hit.click() -}) -check('资源库里有「风格库」tab', tabs.includes('风格库'), JSON.stringify(tabs)) - -// 风格数据是直连 GitHub Pages 拉的,首次没缓存时快时慢 ⇒ 轮询,别写死等待 -await page.waitForFunction(() => document.querySelectorAll('.iwb-ss-card').length > 0, null, { timeout: 30000 }).catch(() => {}) -await page.waitForTimeout(300) -const cards = await page.locator('.iwb-ss-card').count() -check('风格库渲染出卡片', cards > 0, String(cards)) - -// ── 5. 详情页底部三颗按钮:同行、均分、「样式节点」在最左(不是替换掉原来两颗) ── -await page.locator('.iwb-ss-card').first().click() -await page.waitForTimeout(900) -const footInfo = await page.evaluate(() => { - const btns = [...document.querySelectorAll('.iwb-ss-dfoot .iwb-ss-btn')] - return { labels: btns.map((b) => (b.textContent || '').trim()), tops: btns.map((b) => Math.round(b.getBoundingClientRect().top)) } -}) -check('详情页底部三颗按钮同行,「样式节点」在最左', - footInfo.labels.length === 3 && footInfo.labels[0] === '样式节点' && new Set(footInfo.tops).size <= 1, - JSON.stringify(footInfo)) - -// ── 6. 点「样式节点」→ 节点落地,节点体由插件渲染 ───────────────────────────── -await page.locator('.iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '样式节点' }).first().click() -await page.waitForTimeout(1600) -await page.keyboard.press('Escape') -await page.waitForTimeout(400) -await page.keyboard.press('f') -await page.waitForTimeout(700) -await shot('node') - -const node1 = await page.evaluate(() => { - const b = document.querySelector('.iwb-plugin-node-body') - if (!b) return { bodies: 0 } - const rows = [...b.querySelectorAll('.iwb-ssn-row')] - return { - bodies: document.querySelectorAll('.iwb-plugin-node-body').length, - hasRoot: Boolean(b.querySelector('.iwb-ssn')), - name: (b.querySelector('.iwb-ssn-name') || {}).textContent || '', - code: (b.querySelector('.iwb-ssn-code') || {}).textContent || '', - rows: rows.length, - refChecked: b.querySelector('.iwb-ssn-ref input') ? b.querySelector('.iwb-ssn-ref input').checked : null, - hasRunBtn: [...b.querySelectorAll('button')].some((x) => /运行|生成/.test(x.textContent)), - foot: (b.querySelector('.iwb-ssn-foot') || {}).textContent || '', - } -}) -check('样式节点落地且节点体由插件渲染(.iwb-ssn 存在)', node1.hasRoot === true, JSON.stringify(node1).slice(0, 300)) -check('节点体有名称/编号/变量行,示例图默认勾选,且没有生成按钮', - Boolean(node1.name) && Boolean(node1.code) && node1.refChecked === true && node1.hasRunBtn === false, - JSON.stringify(node1).slice(0, 300)) - -// ── 7. 变量输入不失焦、值不被重渲染覆盖(PluginDomBody 固定容器生效) ───────── -const typing = await page.evaluate(async () => { - const b = document.querySelector('.iwb-plugin-node-body .iwb-ssn') - const input = b && b.querySelector('.iwb-ssn-row input') - if (!input) return { noBody: true } - input.focus() - input.value = '真机测试值' - input.dispatchEvent(new Event('input', { bubbles: true })) - await new Promise((r) => setTimeout(r, 700)) - const b2 = document.querySelector('.iwb-plugin-node-body .iwb-ssn') - const input2 = b2.querySelector('.iwb-ssn-row input') - return { sameInput: input === input2, kept: input2.value, focusKept: document.activeElement === input2 } -}) -check('变量输入不失焦、值不被重渲染覆盖', - typing.sameInput === true && typing.kept === '真机测试值' && typing.focusKept === true, JSON.stringify(typing)) - -// ── 8. 变量多的样式:全部露出、不裁切、单行 28px、收起/展开生效 ────────────── -// 上一步把焦点留在了变量输入框里;宿主的快捷键在 INPUT 上直接 return ⇒ 先 blur,否则按 n 只会打出一个字母 -await page.evaluate(() => { const a = document.activeElement; if (a && a.blur) a.blur() }) -await page.keyboard.press('n') -await page.waitForTimeout(1200) -await page.evaluate(() => { - const hit = [...document.querySelectorAll('.iwb-res-tab')].find((b) => /风格库/.test(b.textContent || '')) - if (hit) hit.click() -}) -await page.waitForFunction(() => document.querySelectorAll('.iwb-ss-card').length > 0, null, { timeout: 30000 }).catch(() => {}) - -let picked = null -const total = await page.locator('.iwb-ss-card').count() -for (let i = 0; i < Math.min(total, 30); i++) { - await page.locator('.iwb-ss-card').nth(i).click() - await page.waitForTimeout(380) - const info = await page.evaluate(() => ({ - n: document.querySelectorAll('.iwb-ss-dbody .iwb-ss-var').length, - title: (document.querySelector('.iwb-ss-dtitle') || {}).textContent || '', - })) - if (info.n >= 3) { picked = { idx: i, ...info }; break } -} -check('能找到一个变量 ≥3 的样式(用于压力验证)', Boolean(picked), JSON.stringify(picked)) - -if (picked) { - await page.locator('.iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '样式节点' }).first().click() - await page.waitForTimeout(1600) - await page.keyboard.press('Escape') - await page.waitForTimeout(400) - await page.keyboard.press('f') - await page.waitForTimeout(700) - await shot('multivar') - - const multi = await page.evaluate(() => { - const all = [...document.querySelectorAll('.iwb-plugin-node-body')] - const b = all[all.length - 1] - if (!b) return { noBody: true } - const rows = [...b.querySelectorAll('.iwb-ssn-row')] - return { - bodies: all.length, - rows: rows.length, - labels: rows.map((x) => ((x.querySelector('label') || {}).textContent || '')).filter(Boolean), - rowH: rows.length ? Math.round(rows[0].getBoundingClientRect().height) : 0, - hiddenRows: rows.filter((x) => x.getBoundingClientRect().height < 8).length, - scrollH: b.scrollHeight, - clientH: b.clientHeight, - } - }) - check('变量多的样式:所有变量行都露出、无零高行', multi.rows >= 3 && multi.hiddenRows === 0, JSON.stringify(multi).slice(0, 320)) - check('节点体没有裁切(scrollHeight ≈ clientHeight)', Math.abs(multi.scrollH - multi.clientH) <= 2, - JSON.stringify({ s: multi.scrollH, c: multi.clientH })) - check('变量单行高度 28px 量级', multi.rowH >= 24 && multi.rowH <= 32, String(multi.rowH)) - - const collapsed = await page.evaluate(async () => { - const all = [...document.querySelectorAll('.iwb-plugin-node-body')] - const b = all[all.length - 1] - const btn = b && b.querySelector('.iwb-ssn-toggle') - if (!btn) return { noBtn: true } - const before = Math.round(b.querySelector('.iwb-ssn-vars').getBoundingClientRect().height) - btn.click() - await new Promise((r) => setTimeout(r, 500)) - const box = b.querySelector('.iwb-ssn-vars') - return { before, after: Math.round(box.getBoundingClientRect().height), hidden: box.classList.contains('is-hidden'), tip: btn.title } - }) - check('「收起变量」生效(变量区收起,按钮变成「展开变量」)', - collapsed.hidden === true && collapsed.after === 0 && collapsed.tip === '展开变量', JSON.stringify(collapsed)) - await shot('collapsed') -} - -// ── 9. 冷启动:**一次都没打开过「风格库」面板**,节点体也必须是有样式的 ────────────── -// v1.3.1 修的事故:CSS 原先进在 mount() 里,从存档打开画布时面板不 mount ⇒ `` -// 拿不到 56px 约束,按原图尺寸铺满整个节点(用户原话「图片都跑出来了」)。 -{ - const COLD_NODE = { - id: 'cold1', type: 'plugin:style-source:style', x: 260, y: 200, w: 300, h: 380, - data: { - variant: 'style', styleId: 'cold-style', name: '冷启动样式', code: 'ST9999', outKind: 'prompt', - promptTpl: '一张{主体}的图', varMeta: [{ key: '主体', label: '主体' }], vars: { 主体: '手表' }, - text: '一张手表的图', preview: 'https://example.invalid/cold.png', refName: 'ST9999.png', - refOn: true, refUrl: 'https://example.invalid/cold.png', collapsed: false, - }, - } - const ws = { workspaces: [{ id: 'w1', name: '冷启动', nodes: [COLD_NODE], edges: [], groups: [] }], activeId: 'w1', rev: 1 } - const ctx2 = await browser.newContext({ viewport: { width: 1400, height: 900 } }) - const p2 = await ctx2.newPage() - await p2.addInitScript(({ ws, board }) => { - localStorage.clear() - localStorage.setItem('iwb_plugins', JSON.stringify({ 'style-source': { enabled: true, settings: {}, data: {} } })) - localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws)) - localStorage.setItem('iwb_ws_active', 'w1') - localStorage.setItem('iwb_ws_w1', JSON.stringify(board)) - }, { ws, board: ws.workspaces[0] }) - await p2.goto(SITE, { waitUntil: 'domcontentloaded' }) - await p2.waitForTimeout(1500) - await p2.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick().catch(() => {}) - await p2.waitForFunction(() => Boolean(document.querySelector('.iwb-plugin-node-body')), null, { timeout: 20000 }).catch(() => {}) - const cold = await p2.evaluate(() => { - const th = document.querySelector('.iwb-ssn-thumb') - const body = document.querySelector('.iwb-plugin-node-body') - const node = document.querySelector('.iwb-node') - return { - hasBody: Boolean(body), - hasStyle: Boolean(document.getElementById('iwb-ss-style')), - thumbW: th ? Math.round(th.getBoundingClientRect().width) : 0, - thumbH: th ? Math.round(th.getBoundingClientRect().height) : 0, - nodeW: node ? Math.round(node.getBoundingClientRect().width) : 0, - } - }) - check('冷启动(没开过风格库):节点体成立 + 样式已注入', cold.hasBody && cold.hasStyle, JSON.stringify(cold)) - check('冷启动:缩略图被 CSS 约束在 56px(不是按原图铺满节点)', - cold.thumbW >= 40 && cold.thumbW <= 62 && cold.thumbH >= 40 && cold.thumbH <= 62, - JSON.stringify({ w: cold.thumbW, h: cold.thumbH, nodeW: cold.nodeW })) - await p2.screenshot({ path: path.join(HERE, 'shot-testsite-coldstart.png') }).catch(() => {}) - await ctx2.close() -} - -check('全程无页面 JS 异常', errors.length === 0, errors.slice(0, 3).join(' | ')) - -await browser.close() -console.log('') -console.log(failed === 0 ? '全部通过' : failed + ' 项失败') -process.exit(failed === 0 ? 0 : 1) diff --git a/white-bg-800/README.md b/white-bg-800/README.md index b8e84b5..a1d1d6d 100644 --- a/white-bg-800/README.md +++ b/white-bg-800/README.md @@ -103,7 +103,7 @@ npm run validate ```bash node white-bg-800/tools/harness.mjs ``` -- `tools/e2e-site.mjs`:真实桌面客户端的端到端(市场安装 + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。 +- 发布后回读市场索引 + 客户端市场里确认版本与加载状态;透明底等设置类用例由 harness 覆盖。 > harness 里的 mock `ctx.log` 必须是**函数**(真实宿主如此),早先写成对象导致凡是走 `ctx.log` 的分支全炸。 > 另外几何断言在有损格式下要留 ±4px 容差(jpeg 边缘振铃),精确几何用 `format=png` 的用例测。 diff --git a/white-bg-800/tools/e2e-site.mjs b/white-bg-800/tools/e2e-site.mjs deleted file mode 100644 index 3b8ef0d..0000000 --- a/white-bg-800/tools/e2e-site.mjs +++ /dev/null @@ -1,228 +0,0 @@ -// 真实站点端到端(开发用,不进 CI)—— white-bg-800「白底图」。 -// -// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被 -// `connect-src 'self' https: …` 拦掉,因为宿主 CSP 的 `connect-src` 不含 `data:`) -// 在 mock 下永远绿,只有带真实 KV + 浏览器 SRI + 真实 CSP 的真站能抓出来。 -// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)校验 + 真实画布桥。 -// -// 运行(需要 Playwright): -// node white-bg-800/tools/e2e-site.mjs # 默认测试站 -// IWB_BASE_URL=https://iwb.maqiart.eu.org node white-bg-800/tools/e2e-site.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)) // /white-bg-800/tools -const REPO = path.resolve(HERE, '../..') // -const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop' - -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:') - console.error(' npm i -D playwright # 本仓或宿主仓皆可') - console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node white-bg-800/tools/e2e-site.mjs') - process.exit(2) -} - -const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev' -const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'white-bg-800/package.json'), 'utf8')).version -const CFG = { providers: [], canvas: {} } -const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 } - -let failed = 0 -const check = (name, ok, detail) => { - if (!ok) failed++ - console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : '')) -} -const poll = async (fn, timeout = 25000, step = 250) => { - const end = Date.now() + timeout - for (;;) { - let v - try { v = await fn() } catch { v = false } - if (v) return v - if (Date.now() > end) return false - await new Promise((r) => setTimeout(r, step)) - } -} - -console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')') -const browser = await chromium.launch() -const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }) -const consoleErrors = [] -page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) }) -page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message)) - -// 造一张真实的 96x64 PNG 作为节点图片(故意非正方形,让 800 方画布的等比缩放/居中被真正练到) -await page.goto('about:blank') -const PNG = await page.evaluate(() => { - const c = document.createElement('canvas') - c.width = 96; c.height = 64 - const x = c.getContext('2d') - x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64) - x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40) - return c.toDataURL('image/png') -}) - -// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled -await page.addInitScript((d) => { - localStorage.clear() - localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg)) - const ws = JSON.parse(JSON.stringify(d.ws)) - ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }] - localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws)) - localStorage.setItem('iwb_ws_active', ws.activeId) - localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0])) - localStorage.setItem('iwb_web_outputs', JSON.stringify([])) - localStorage.setItem('iwb_plugins', JSON.stringify({ 'white-bg-800': { enabled: true, settings: {}, data: {} } })) -}, { cfg: CFG, ws: WS, png: PNG }) - -// ---------- 1) 站点可达 ---------- -const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' }) -check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status())) - -// ---------- 2) 宿主就绪 + 真实 KV 加载并启用 ---------- -const hostReady = await poll(async () => page.evaluate(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true), 30000) -check('window.IWBPluginHost 就绪(initialized)', Boolean(hostReady)) -const active = await poll(async () => page.evaluate(() => { - const p = window.IWBPluginHost.list().find((x) => x.id === 'white-bg-800') - return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false -})) -check('从真实 KV 加载并启用(active)', Boolean(active), JSON.stringify(active)) - -// ---------- 3) 版本 ---------- -check('线上版本 = white-bg-800/package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version) - -// ---------- 4) SRI ---------- -const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' }))) -check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /plugin-white-bg-800(\.[0-9a-f]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts)) - -// ---------- 5) 打开工作区 + 种子节点 ---------- -await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick() -await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 }) -check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1) - -// ---------- 6) 入口:节点漂浮菜单(title 是静态字面量「白底图」;回落右键插件命令)---------- -const triggerWhiteBg = async () => { - await page.locator('.iwb-node[data-node-id="r1"]').click() - const btn = page.locator('.iwb-node-floatbar button[title="白底图"]') - if (await btn.count()) { await btn.click(); return '漂浮菜单' } - await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } }) - await page.locator('.iwb-ctx-item').filter({ hasText: '白底图:选中节点' }).click() - return '右键命令' -} -const entry = await triggerWhiteBg() -check('节点入口可触发(漂浮菜单或右键命令)', true, entry) - -// ---------- 7) 默认「新建」:恰好 2 个节点、新节点为 src_800x800.png ---------- -const created = await poll(async () => page.evaluate(() => { - const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}') - const nodes = ws.nodes || [] - if (nodes.length !== 2) return false - const n = nodes.find((x) => x.id !== 'r1') || nodes[1] - return { nodes: nodes.length, name: n.data && n.data.name } -})) -const wsNodes = created ? created.nodes : await page.evaluate(() => (JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}').nodes || []).length) -check('默认「新建」:iwb_ws_w1 恰好 2 个节点', wsNodes === 2, 'nodes=' + wsNodes) -check('新节点 data.name = src_800x800.jpg(默认 format=jpeg)', Boolean(created && /^src_800x800\.jpg$/.test(created.name || '')), created && String(created.name)) - -// ---------- 8) 页内解引用 + 解码新建 JPEG:800x800、左上像素为白色 ---------- -// 宿主「C3」引用模型:localStorage 里只存引用,字节在别处 —— 假设 localStorage 里有 base64 是 -// 不可能的(by design)。两种引用形态都要认: -// a) { __blob: 'imgblob__' } → IndexedDB(src/image-blob-store.js) -// b) { __cache: '<同源 URL>' } → 宿主把大 dataURL 外置成 /__iwb_cache__/xxx(当前线上形态) -// 故在页内经 IWBImageBlobStore 解引用或同源 fetch __cache(CSP connect-src 'self' 放行)。 -const resolved = await poll(async () => page.evaluate(async () => { - // 读节点图(按优先级解引用):a) data: 字符串直用 b) {__blob} 引用解引用 c) 其余形态给诊断失败 - const resolveNodeDataUrl = async (d) => { - if (typeof d === 'string' && /^data:/.test(d)) return { dataUrl: d, via: 'data:' } // a) - if (d && typeof d === 'object' && typeof d.__cache === 'string' && d.__cache) { // b2) 宿主把大 dataURL 外置成同源缓存引用 - const toDataUrl = (blob) => new Promise((res) => { - const fr = new FileReader() - fr.onload = () => res(String(fr.result || '')) - fr.onerror = () => res('') - fr.readAsDataURL(blob) - }) - try { - // /__iwb_cache__/ 由 SW 直出;冷启动 SW 未接管时该路径会落到 Pages 404(返回 HTML)。 - // 故优先直接读 Cache Storage,读不到再走 fetch(此时 SW 已接管)。 - const abs = new URL(d.__cache, location.origin).href - if (typeof caches !== 'undefined') { - const hit = (await caches.match(abs)) || (await caches.match(d.__cache)) - if (hit) { - const blob = await hit.blob() - const u = await toDataUrl(blob) - return u ? { dataUrl: u, via: '__cache(CS ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' } - } - } - const resp = await fetch(abs) - const blob = await resp.blob() - const u = await toDataUrl(blob) - return u ? { dataUrl: u, via: '__cache(fetch ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' } - } catch (e) { - return { error: '__cache 抓取抛错: ' + ((e && e.message) || String(e)) } - } - } - if (d && typeof d === 'object' && typeof d.__blob === 'string' && d.__blob) { // b) - const Lib = window.IWBImageBlobStore - if (!Lib) return { error: 'window.IWBImageBlobStore 缺失' } - try { - let u = '' - if (typeof Lib.resolveDataUrl === 'function') { - u = await Lib.resolveDataUrl(d.__blob) - } else if (typeof Lib.create === 'function') { - // 与 app.js:730 同一构造:idb 用宿主同一存储运行时(get 直出 Blob) - const idb = (window.IWBStorageRuntime && window.IWBStorageRuntime.indexedDb) || - (window.IWBStorageFallbackIndexeddb && window.IWBStorageContract && window.IWBStorageFallbackIndexeddb.create({ contract: window.IWBStorageContract.indexedDb })) - if (!idb || typeof idb.get !== 'function') return { error: '取不到宿主 idb(IWBStorageRuntime.indexedDb)' } - u = await Lib.create({ idb }).resolveDataUrl(d.__blob) - } else { - return { error: 'IWBImageBlobStore 无 resolveDataUrl / create' } - } - return (typeof u === 'string' && u) ? { dataUrl: u, via: '__blob' } : { error: '解引用未返回字节(' + d.__blob + ')' } - } catch (e) { - return { error: '解引用抛错: ' + ((e && e.message) || String(e)) } - } - } - return { error: '未知 data 形态: ' + (d == null ? String(d) : typeof d) + ' keys=' + (d && typeof d === 'object' ? Object.keys(d).join(',') : '-') + ' sample=' + JSON.stringify(d).slice(0, 220) } // c) - } - const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}') - const nodes = ws.nodes || [] - const n = nodes.length === 2 ? (nodes.find((x) => x.id !== 'r1') || nodes[1]) : null - if (!n) return false // 新节点未就绪 → 重试 - const r = await resolveNodeDataUrl(n.data && n.data.data) - if (r.error) return { error: r.error } - if (!/^data:image\/jpeg;base64,/.test(r.dataUrl)) return { error: '解引用结果不是 JPEG dataURL(via=' + r.via + '): ' + String(r.dataUrl).slice(0, 40) } - const img = new Image() - const ok = await new Promise((res) => { img.onload = () => res(true); img.onerror = () => res(false); img.src = r.dataUrl }) - if (!ok) return { dataOk: true, via: r.via, decodeError: 'Image 解码失败' } - const c = document.createElement('canvas') - c.width = img.naturalWidth; c.height = img.naturalHeight - const x = c.getContext('2d') - x.drawImage(img, 0, 0) - const px = x.getImageData(0, 0, 1, 1).data - return { dataOk: true, via: r.via, w: img.naturalWidth, h: img.naturalHeight, px: [px[0], px[1], px[2], px[3]] } -})) -const d = resolved || {} -const dDiag = d.error || d.decodeError || (resolved ? '' : '轮询超时:新节点未出现') -check('新节点 data 为 JPEG 字节(引用已解析)', Boolean(d.dataOk), d.dataOk ? d.via : dDiag) -check('新建 JPEG 解码尺寸 = 800x800', Boolean(d.dataOk && d.w === 800 && d.h === 800), d.dataOk ? d.w + 'x' + d.h : dDiag) -// jpeg 有损:纯白角落允许 ±5 的压缩抖动,但 alpha 必须不透明 -check('新建 JPEG 左上像素 ≈ 白色且不透明', Boolean(d.dataOk && d.px && d.px[0] >= 250 && d.px[1] >= 250 && d.px[2] >= 250 && d.px[3] === 255), JSON.stringify(d.px) || dDiag) - -// 透明模式(transparent)不在此二次跑(需改设置再整轮重放,易碎)——由 white-bg-800/tools/harness.mjs 覆盖。 - -// ---------- 9) 无 CSP / SRI 拦截 ---------- -const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t)) -check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | ')) - -// ---------- 10) 无页面级运行时错误 ---------- -check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | ')) - -await browser.close() -console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')) -process.exit(failed ? 1 : 0)