Files
image-workbench-desktop/tests/iwb-gallery-insert.spec.js
qiqi f6040581eb test(e2e): 收缩资源中心面板用例,改测停靠栏插件面板(宿主轻量化)
背景:v3.25.82 起「资源中心」全屏浮窗被停靠栏插件面板取代,图库/提示词库改为独立插件。
一批 spec 仍在测已下线的浮窗 UI,长期红且掩盖真回归。按「宿主只守集成契约、面板 UI 归插件仓」收缩:

退役(原因写入 tests/fixtures/e2e-known-red.json 的 retired 段):
- iwb-lib-panel-ux(6 条):浮窗内搜索/快捷键/分类胶囊/插入图标
- iwb-full-window-resize(1 条):浮窗隐形缩放手柄 + 标题栏尺寸数字
- 门禁 spec 数 54 → 52

改写为停靠栏语义:
- iwb-gallery-insert:条目「插入」按钮 → 先选中条目再点工具条「插入」(4 条全绿)
- iwb-canvas-ux 3/4:资源中心 → 图库面板;条目 title 在容器上(4 条中 2 条转绿)
- iwb-stability:图库面板开/关、N 键切换右栏、开面板不移动画布
- iwb-canvas-ops ⑪:图库面板开着时仍能框选
- iwb-plugin-panel-tab-leak:改为「面板切走即卸载、切回只挂一份」(按面板 body 断言)
- _plugin-host-probe 的动态插件面板用例标 fixme:停靠栏面板清单固定为 5 个已知面板,
  动态注册的 panels 能力暂时没有 UI 落点(等宿主补入口再启用)

验证:上述 6 个 spec 由 25 红降到 7 红(剩余为断言类,待逐条判定);gallery-insert / plugin-panel-tab-leak / canvas-ux 复制 / canvas-ops ⑪ 全绿。
2026-11-27 00:05:48 +08:00

276 lines
14 KiB
JavaScript
Raw Permalink 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.
// 图库图片「插入画布」链路(2026-10-20,审计 N1,v3.24.0)
//
// 用户报告的三个症状,本用例逐条守住:
// ① **刷新后图片状态会变** —— 此前插入时把**完整 base64** 写进 node.data.url,
// 刷新时被 wSanitizeWs 换成 {__blob} 引用(状态变化);且刷新时还要把 base64
// 再转回 Blob ⇒ **内存数倍占用、过一会儿才回落**。
// ② **刷新后双击打不开** —— node.data.url 变成引用对象后,ImagePreview 的
// placeholderOf() 对对象只认 .thumb/.url ⇒ 拿到 '' ⇒ <img src=""> 打不开。
// ③ 目标:**不要建立画布的性能** ⇒ 画布里只留引用,不留整图字节。
//
// 本用例**行为断言**(不查源码文本):
// A1 插入后 node.data.url 是**引用**({__blob}/{__cache}),不是 base64
// A2 插入后节点能显示(不图裂)
// A3 插入后双击能打开预览
// A4 **刷新后**双击**仍能打开**预览(核心验收)
// A5 刷新后 node.data.url 仍是引用(不再有「状态变化」)
// A6 刷新后内存占用明显低于「插入整图 base64」的对照组
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
const WS = {
workspaces: [{ id: 'ws_gal', name: '图库测试板', nodes: [], edges: [], groups: [] }],
activeId: 'ws_gal', rev: 1, schemaVersion: 1,
}
// 在页面里造一张真实 PNG(带像素内容 ⇒ 可解码),写入 IndexedDB 缩略图键,
// 并把图库索引写进 localStorage(iwb_web_outputs + 每条的 idb 键)。
//
// ⚠️ 两个必须与线上一致的细节(照抄 app.js 的 storeOutputThumb):
// ① 缩略图字节存 **IDB.put**(不是 kvPut!)—— 键 = 'out_' + name(IDB_OUT_PREFIX)
// ② 索引条目要带 `idb` 字段,否则 galleryHydrator 不会 hydrate 它(src/gallery-hydration.js:14)
// ③ 索引必须在**应用启动前**写入(addInitScript)—— refreshOutputs 只在启动时拉一次
async function seedGallery(page) {
// 用 addInitScript 在应用启动前播种 localStorage(索引 + 工作台)
// ⚠️ 只在**缺失时**播种:刷新后应用会自己保存工作台与 outputs 索引,
// 若每次启动都重写,就会把刚插入的节点冲掉(测的就不是真实行为了)。
// ⚠️ 索引条目形态照抄线上(app.js storeOutputThumb / wAddOutputs):
// · `idb` = 'out_' + name(缩略图字节在 IDB 的键)
// · `url` = 图床远程 URL(**不是**字节)—— 线上就是靠它显示缩略图
await page.addInitScript((ws) => {
if (!localStorage.getItem('iwb_web_workspaces')) localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
if (!localStorage.getItem('iwb_web_outputs')) {
localStorage.setItem('iwb_web_outputs', JSON.stringify([
// ⚠️ 带 origIdb(原图备份)是**线上默认**(cfg.canvas.backupOriginals 默认 true):
// wResolveOutputSrc 的第一优先级就是 origIdb ⇒ 返回**完整原图 base64**
// ⇒ 这正是「插入时把整张图塞进画布」的触发条件(审计 N1 的根因)。
{ name: 'n1.png', url: 'https://example.invalid/n1.png', size: 400, mtime: Date.now(), w: 64, h: 64, idb: 'out_n1.png', origIdb: 'out_orig_n1.png' },
]))
}
}, WS)
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForSelector('.iwb-home-card', { timeout: 25000 })
await page.locator('.iwb-home-card', { hasText: '图库测试板' }).first().dblclick()
await page.waitForSelector('.iwb-canvas-topbar', { timeout: 25000 })
// 缩略图字节:IDB.put('out_n1.png', dataUrl)(与 storeOutputThumb 同键位)
const len = await page.evaluate(async () => {
const c = document.createElement('canvas')
c.width = 64; c.height = 64
const g = c.getContext('2d')
g.fillStyle = '#2b7'; g.fillRect(0, 0, 64, 64)
g.fillStyle = '#f00'; g.fillRect(0, 0, 32, 32)
const dataUrl = c.toDataURL('image/png')
const store = window.IWBStorageIndexedDB.create({})
const ok = await store.put('out_n1.png', dataUrl) // 缩略图
await store.put('out_orig_n1.png', dataUrl) // 原图(origIdb ⇒ 插入时拿的是它)
return { len: dataUrl.length, ok }
})
return len
}
// 2026-11-26:资源中心浮窗已被停靠栏「图库」插件面板取代,统一走 helper
// 2026-11-27:图库已改为停靠栏插件面板 —— 条目不再自带「插入」按钮:
// 先点条目(选中)→ 再点工具条「插入」。
async function insertFromGallery(page) {
await page.locator('.iwb-history-item img').first().click()
const ins = page.locator('.iwb-gal-actions button').filter({ hasText: '插入' }).first()
await expect(ins, '图库工具条应有「插入」按钮').toHaveCount(1)
await ins.click()
}
async function openGallery(page) {
await W.openGallery(page, { waitItems: 15000 })
}
const readNode = (page) => page.evaluate(() => {
// ⚠️ 每个画布独立存一个 key(iwb_ws_<id>),索引(iwb_web_workspaces)只存轻量索引
// (app.js:2562 `LocalStore.set(wsKey(w.id), rec)`;全量快照不再落盘,见 app.js:2566 注释)
const raw = localStorage.getItem('iwb_ws_ws_gal')
const w = raw ? JSON.parse(raw) : null
const n = w && (w.nodes || [])[0]
if (!n) return null
const d = n.data || {}
const url = d.url
return {
type: n.type,
isRef: !!(url && typeof url === 'object'),
refKind: url && typeof url === 'object' ? (url.__blob ? '__blob' : (url.__cache ? '__cache' : 'other')) : '',
len: typeof url === 'string' ? url.length : 0,
isDataUrl: typeof url === 'string' && url.indexOf('data:') === 0,
}
})
// 回到画布:应用可能直接进画布(记住上次工作台),也可能先到首页 ⇒ 两种都兼容
async function waitCanvas(page) {
await page.waitForSelector('.iwb-canvas-topbar, .iwb-home-card', { timeout: 25000 })
const onHome = await page.locator('.iwb-home-card').count()
if (onHome) {
await page.locator('.iwb-home-card', { hasText: '图库测试板' }).first().dblclick()
}
await page.waitForSelector('.iwb-canvas-topbar', { timeout: 25000 })
}
// 画布保存是**防抖**的 ⇒ 插入后要等它落盘(localStorage)再断言
async function waitNodeSaved(page) {
// ⚠️ 不用 page.waitForFunction(fn):线上 CSP 是 `script-src 'self'`(无 unsafe-eval),
// Playwright 注入的求值会被 CSP 拒绝 ⇒ 改为自己轮询。
for (let i = 0; i < 60; i++) {
const n = await page.evaluate(() => {
const raw = localStorage.getItem('iwb_ws_ws_gal')
if (!raw) return 0
try { const w = JSON.parse(raw); return (w.nodes || []).length } catch (e) { return 0 }
})
if (n > 0) return
await page.waitForTimeout(400)
}
throw new Error('等待画布落盘超时(localStorage 里始终没有节点)')
}
test('图库插入:画布里只留引用(不塞整图 base64)', async ({ page }) => {
await seedGallery(page)
await openGallery(page)
await insertFromGallery(page)
await waitNodeSaved(page)
const n = await readNode(page)
expect(n, '画布里应有一个 ref 节点').not.toBeNull()
expect(n.type).toBe('ref')
// A1:必须是引用,不是 base64
expect(n.isRef, 'node.data.url 应是引用对象({__blob}/{__cache}),不是整图 base64').toBe(true)
expect(n.refKind).toBe('__blob')
expect(n.isDataUrl, 'node.data.url 不得是 dataURL(那是整图 base64)').toBe(false)
// A2:节点能显示(不图裂)
await expect(page.locator('.iwb-ref-body img').first()).toBeVisible({ timeout: 15000 })
})
test('图库插入:刷新后双击仍能打开预览(核心回归)', async ({ page }) => {
await seedGallery(page)
await openGallery(page)
await insertFromGallery(page)
await waitNodeSaved(page)
// 刷新(应用会记住上次的工作台 ⇒ 可能**直接回到画布**,不一定经过首页)
await page.reload({ waitUntil: 'domcontentloaded' })
await waitCanvas(page)
// A5:刷新后仍是引用(不再有「状态变化」—— 之前 base64→{__blob})
const n = await readNode(page)
expect(n, '刷新后画布里应仍有 ref 节点').not.toBeNull()
expect(n.isRef, '刷新后 node.data.url 应仍是引用').toBe(true)
expect(n.isDataUrl, '刷新后 node.data.url 不应是 dataURL').toBe(false)
// A4:双击能打开预览(这是用户报告的「双击就不能打开了」)
const body = page.locator('.iwb-ref-body img').first()
await expect(body, '刷新后 ref 节点应能显示图片').toBeVisible({ timeout: 15000 })
await body.dblclick()
await page.waitForTimeout(1500)
// 预览容器是 .iwb-imgpreview(app.js:12712),不是 .iwb-modal-mask
const previewOpen = await page.locator('.iwb-imgpreview').count()
expect(previewOpen, '双击应打开预览弹窗').toBeGreaterThan(0)
const previewImg = await page.locator('.iwb-imgpreview img').first().getAttribute('src').catch(() => null)
expect(previewImg, '预览里的图片应有 src').toBeTruthy()
expect(String(previewImg).length, '预览 src 不应为空串').toBeGreaterThan(0)
})
test('图库插入:刷新后内存占用显著低于「插入整图 base64」', async ({ page }) => {
await seedGallery(page)
await openGallery(page)
const memBefore = await page.evaluate(() => performance.memory ? performance.memory.usedJSHeapSize : 0)
await insertFromGallery(page)
await waitNodeSaved(page)
// 刷新
await page.reload({ waitUntil: 'domcontentloaded' })
await waitCanvas(page)
const memAfter = await page.evaluate(() => performance.memory ? performance.memory.usedJSHeapSize : 0)
// 画布里应**没有**整图 base64 ⇒ 刷新后的堆增量应远小于图片字节数
const galleryBytes = await page.evaluate(() => {
const list = JSON.parse(localStorage.getItem('iwb_web_outputs') || '[]')
return (list[0] && list[0].size) || 0
})
const delta = memAfter - memBefore
// 宽松阈值:增量不应超过图片字节数的 3 倍(旧实现会把整图 base64 拖进堆)
expect(galleryBytes, '测试数据应带图片字节数').toBeGreaterThan(0)
expect(delta, `刷新后堆增量 ${Math.round(delta / 1024)}KB 应显著小于图片字节 ${Math.round(galleryBytes / 1024)}KB 的 3 倍`)
.toBeLessThan(galleryBytes * 3)
})
test('图库插入的图片:生成请求里必须是 base64(不是 blob: 临时地址)', async ({ page }) => {
// 2026-10-30 用户实测:图库插入的图片接进「配置」后,生成报
// 「[其他] 参考图格式不支持;仅允许公网 URL 或本地图片 Base64」。
// 根因:图库插入把图片引用化为 {__blob:'imgblob_…'} 放在 data.url;
// 若 refArgsOf 把它解析成 blob: 临时地址,上游不认;正确做法是**原样透传**,
// 由发请求前的 wResolveRefArgs() 用 wImgRefDataUrl() 转成 base64。
// 链路:图库插入(app 自己写 blob)→ 拖到「配置」节点 → 点生成 → 检查请求体。
const CFG = { providers: [{ id: 'p-a', name: 'A', baseUrl: 'https://a.example/v1', keys: [{ id: 'a-1', name: 'k', value: 'sk-test' }], models: [{ name: 'gpt-image-2', visible: true }] }], canvas: {} }
await page.addInitScript((cfg) => { if (!localStorage.getItem('iwb_web_cfg')) localStorage.setItem('iwb_web_cfg', JSON.stringify(cfg)) }, CFG)
let body = null
await page.route('**/images/generations', async (route) => {
try { body = JSON.parse(route.request().postData() || '{}') } catch (e) { body = {} }
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: [{ url: 'https://example.test/out.png' }] }) })
})
// 画布预置:提示词 + 已配置好的「配置」节点(生图任务需要文本来源;只连图片不会出任务卡)
await page.addInitScript(() => {
if (localStorage.getItem('iwb_web_workspaces')) return
const ws = {
workspaces: [{
id: 'ws_gal', name: '图库测试板', groups: [],
nodes: [
{ id: 'p1', type: 'prompt', x: 120, y: 560, data: { text: '用这张图做参考' } },
{ id: 'g1', type: 'gen', x: 760, y: 180, w: 480, data: { model: 'gpt-image-2', provider: 'p-a', keyGroup: 'a-1', size: '1024x1024', ratio: '1:1', res: '1K' } },
],
edges: [{ id: 'e0', from: 'p1', to: 'g1' }],
}],
activeId: 'ws_gal', rev: 1, schemaVersion: 1,
}
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_ws_gal', JSON.stringify(ws.workspaces[0]))
})
await seedGallery(page)
await openGallery(page)
await insertFromGallery(page)
await waitNodeSaved(page)
await page.keyboard.press('Escape')
await page.waitForTimeout(400)
// 把插入的图片节点连到「配置」节点(拖到节点体上即连)
const refNode = page.locator('.iwb-node').filter({ has: page.locator('.iwb-ref-body') }).first()
const ob = await refNode.locator('.iwb-port-out').first().boundingBox()
const genBox = await page.locator('[data-node-id="g1"]').boundingBox()
await page.mouse.move(ob.x + ob.width / 2, ob.y + ob.height / 2)
await page.mouse.down()
await page.mouse.move(genBox.x + genBox.width / 2, genBox.y + 40, { steps: 14 })
await page.mouse.up()
await page.waitForTimeout(600)
// 落在节点体附近可能弹「引用该节点生成」菜单 ⇒ 关掉它,避免挡住生成按钮
if (await page.locator('.iwb-connect-menu').count()) {
await page.keyboard.press('Escape')
await page.waitForTimeout(300)
}
// 点生成,检查请求体里的参考图是 base64
const genNode = page.locator('[data-node-id="g1"]')
await expect(genNode.locator('.iwb-task').first(), '应生成任务卡').toBeVisible({ timeout: 15000 })
await genNode.locator('.iwb-task button:has-text("生成")').first().click()
await expect.poll(() => body, { timeout: 20000, message: '应捕获到生成请求' }).not.toBeNull()
const flat = JSON.stringify(body)
expect(flat.indexOf('blob:'), '请求体里不得出现 blob: 临时地址').toBeLessThan(0)
expect(flat.indexOf('[object Object]'), '请求体里不得出现 [object Object]').toBeLessThan(0)
expect(/data:image\/[^"]*;base64,/.test(flat), '参考图必须以 base64 dataURL 形式发送').toBe(true)
})