// v3.87.46/47 契约(丙方案 C1 + E):画布图片内存对齐 —— 远端 4K 只解码小预览、失败负缓存、复制不深拷贝、原图只在预览出现
// 背景:画布此前把 2160×3840 原图直接塞进
,跨域图缩略图失败后不缓存失败 ⇒ 每次渲染重复解码整张 4K;
// 复制/实例化/快照用 JSON.parse(JSON.stringify(...)) 深拷贝图片字节 ⇒ 复制 11 节点 +1030MB。
// 运行:npm run build && IWB_BASE_URL=http://127.0.0.1:8787 npx playwright test tests/iwb-image-memory-parity.spec.js
// 或: IWB_E2E_SPECS=tests/iwb-image-memory-parity.spec.js node scripts/serve-test.js
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const zlib = require('zlib')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
// serviceWorkers: 'block' 是**测试确定性**需要,不是产品行为改变:
// sw.js 会拦截所有跨域
(destination==='image')并自己 fetch,而 Playwright 的 page.route 不拦截
// Service Worker 发起的请求 ⇒ 预览原图的 4K 请求会绕过 mock 直接打到真实 DNS 而 ERR_FAILED。
// 屏蔽 SW 后,跨域
才回到 page.route 可见的网络层(代理 /api/img 是同源请求,两种模式都在)。
test.use({ baseURL, viewport: { width: 1500, height: 1000 }, serviceWorkers: 'block' })
// ── 造一张「真 4K 尺寸、字节很小」的 PNG:尺寸决定解码成本(2160×3840 ≈ 830 万像素),
// 低熵渐变让 deflate 后只有几百 KB,route.fulfill 与本地传输都很快。
const BIG_W = 2160
const BIG_H = 3840
function makePng(w, h) {
const stride = w * 3 + 1
const raw = Buffer.allocUnsafe(stride * h)
for (let y = 0; y < h; y++) {
const off = y * stride
raw[off] = 0 // filter: none
for (let x = 0; x < w; x++) {
const p = off + 1 + x * 3
raw[p] = x & 0xff
raw[p + 1] = y & 0xff
raw[p + 2] = (x + y) & 0xff
}
}
const chunk = (type, data) => {
const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0)
const body = Buffer.concat([Buffer.from(type, 'latin1'), data])
const crc = Buffer.alloc(4); crc.writeUInt32BE(zlib.crc32(body) >>> 0, 0)
return Buffer.concat([len, body, crc])
}
const ihdr = Buffer.alloc(13)
ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4)
ihdr[8] = 8; ihdr[9] = 2; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', zlib.deflateSync(raw, { level: 9 })),
chunk('IEND', Buffer.alloc(0)),
])
}
const BIG_PNG = makePng(BIG_W, BIG_H)
// 真实图床 URL 通常是长签名串(wDisplayThumbKey 只对长度 >64 的串建缓存;短 URL 直接原样返回)
const REMOTE = 'https://mock-cdn.example.com/big-4k-image.png?sign=abcdefghijklmnopqrstuvwxyz0123456789&expires=1893456000&x-iwb-test=1'
function cfgWithProviders() {
return { providers: [{ id: 'p-a', name: 'A', baseUrl: 'https://a.example/v1', keys: [{ id: 'a-1', name: 'K', value: 'sk' }], models: [{ name: 'gpt-image-2.5', visible: true }] }], canvas: { snap: true } }
}
// 小缩略图(320×568):模拟「生成结果已落库缩略图」的形态(idb + data),画布显示它、不碰原图
const SMALL_W = 320
const SMALL_H = 568
const SMALL_DATA_URL = 'data:image/png;base64,' + makePng(SMALL_W, SMALL_H).toString('base64')
// 一个「生图节点(带远端 4K 结果) → 输出节点」的画布:输出节点的 .iwb-out-cell-img 走的正是 wDisplayThumbOf
function boardWithRemote4k(opts) {
const o = opts || {}
const item = { ok: true, url: REMOTE, width: BIG_W, height: BIG_H }
// 带落库缩略图的结果:thumbOf(r) 会选 data(本地小图),画布不会去请求远端原图
if (o.thumb) { item.idb = 'out_seed_thumb'; item.data = o.thumb }
const ws = {
schemaVersion: 1, rev: 1, activeId: 'w1',
workspaces: [{
id: 'w1', name: 'MEM', nodes: [
{ id: 'g1', type: 'gen', x: 620, y: 120, w: 320, data: { model: 'gpt-image-2.5', provider: 'p-a', keyGroup: 'a-1', ratio: '9:16', res: '4K', quality: 'auto', result: [{ promptId: 'p1', label: '结果', items: [item] }] } },
{ id: 'o1', type: 'out', x: 120, y: 120, w: 420, data: {} },
],
edges: [{ id: 'e1', from: 'g1', to: 'o1' }], groups: [],
}],
}
return ws
}
async function seedAndOpen(page, ws, cfg) {
await page.addInitScript((d) => {
window.__IWB_E2E__ = true
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
localStorage.setItem('iwb_web_workspaces', JSON.stringify(d.ws))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(d.ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
}, { ws, cfg: cfg || cfgWithProviders() })
await page.goto('/', { waitUntil: 'domcontentloaded' })
await W.waitHomeReady(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.waitForTimeout(400)
}
const MOCK_HEADERS = { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' }
function mockRemote(page, counters) {
const c = counters || {}
c.remote = 0; c.proxy = 0
page.route(/mock-cdn\.example\.com/, async (route) => {
c.remote++
await route.fulfill({ status: 200, contentType: 'image/png', headers: MOCK_HEADERS, body: BIG_PNG })
})
page.route('**/api/img?**', async (route) => {
c.proxy++
await route.fulfill({ status: 200, contentType: 'image/png', headers: MOCK_HEADERS, body: BIG_PNG })
})
return c
}
// 等「首帧原图 → 显示缩略图」收敛:naturalWidth 必须是 >0 且 ≤max(0 表示还没解码,不算通过)
async function waitThumb(img, max, label) {
await expect.poll(async () => {
const w = await img.evaluate((el) => el.naturalWidth)
return w > 0 && w <= max
}, { timeout: 20000, message: (label || '显示缩略图') + ' 应在若干秒内收敛到 >0 且 ≤' + max }).toBe(true)
return img.evaluate((el) => el.naturalWidth)
}
// 节点体是 React.memo 的(app.js areNodeEqual):显示缩略图生成后,还要有一次节点级重渲染才会换 src。
// 真实用户滚动/点选必然带来重渲染;这里用「点一下该节点」确定性地触发,避免测试靠运气等自发的重渲染。
async function nudgeNodeRender(page, nodeId) {
await page.locator('[data-node-id="' + nodeId + '"] .iwb-node-head').click()
await page.waitForTimeout(200)
}
test('① 跨域远端 4K:输出节点会经代理生成小预览(naturalWidth ≤ 768)', async ({ page }) => {
const counters = mockRemote(page)
await seedAndOpen(page, boardWithRemote4k())
const img = page.locator('.iwb-out-cell-img').first()
await expect(img).toBeVisible()
// 先等缩略图真的被生成(跨域 → 同源代理 /api/img),再触发一次重渲染让它挂到 DOM 上
await expect.poll(() => counters.proxy, { timeout: 20000, message: '跨域图必须走同源代理 /api/img 出缩略图' }).toBeGreaterThanOrEqual(1)
await nudgeNodeRender(page, 'o1')
const w = await waitThumb(img, 768, '跨域远端 4K')
const src = await img.evaluate((el) => String(el.currentSrc || el.src).slice(0, 32))
console.log('[parity-1] settled naturalWidth =', w, 'src =', src, 'remote =', counters.remote, 'proxy =', counters.proxy)
expect(w, '小预览必须有真实尺寸').toBeGreaterThan(0)
expect(src, '画布最终应挂小预览(data:/blob:),而不是远端原图').toMatch(/^(data:|blob:)/)
})
test('② 负缓存:连续 3 次重渲染不会重复请求远端图(代理命中 ≤2 且不增长)', async ({ page }) => {
const counters = mockRemote(page)
await seedAndOpen(page, boardWithRemote4k())
const img = page.locator('.iwb-out-cell-img').first()
await expect.poll(() => counters.proxy, { timeout: 20000 }).toBeGreaterThanOrEqual(1)
await nudgeNodeRender(page, 'o1')
await waitThumb(img, 768, '跨域远端 4K')
await page.waitForTimeout(500)
const proxyAfterThumb = counters.proxy
const remoteAfterThumb = counters.remote
const box = await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').first().boundingBox()
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
for (let i = 0; i < 3; i++) { await page.mouse.wheel(0, i % 2 ? 120 : -120); await page.waitForTimeout(150) }
await page.waitForTimeout(600)
console.log('[parity-2] proxy', proxyAfterThumb, '->', counters.proxy, ' remote', remoteAfterThumb, '->', counters.remote)
expect(counters.proxy, '整段链路代理命中应 ≤2(首帧 + 缩略图各一次)').toBeLessThanOrEqual(2)
expect(counters.proxy - proxyAfterThumb, '重渲染期间代理商不应再请求(负/正缓存生效)').toBeLessThanOrEqual(0)
expect(counters.remote - remoteAfterThumb, '重渲染期间不应再请求远端原图').toBeLessThanOrEqual(0)
})
test('③ 复制含大图节点:复制的是引用而不是图片字节(堆增量 <200MB / 画布 base64 总量不增加)', async ({ page }) => {
await page.addInitScript(() => {
window.__IWB_E2E__ = true
// 页面内造一张大图(随机色块 → JPEG 体积足够大),放进 ref 节点
const c = document.createElement('canvas')
c.width = 1400; c.height = 2100
const g = c.getContext('2d')
for (let i = 0; i < 1400; i++) {
const h = ((i * 2654435761) >>> 0) % 0xffffff
g.fillStyle = '#' + h.toString(16).padStart(6, '0')
g.fillRect((i * 37) % 1360, (i * 91) % 2070, 40, 34)
}
window.__IWB_BIG__ = c.toDataURL('image/jpeg', 0.95)
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} }))
const ws = { schemaVersion: 1, rev: 1, activeId: 'w1', workspaces: [{ id: 'w1', name: 'CP', nodes: [{ id: 'r1', type: 'ref', x: 140, y: 140, w: 420, data: { url: '', data: '', name: 'big.jpg', localName: null } }], edges: [], groups: [] }] }
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
})
await page.goto('/', { waitUntil: 'domcontentloaded' })
await W.waitHomeReady(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.waitForTimeout(400)
const big = await page.evaluate(() => window.__IWB_BIG__)
console.log('[parity-3] big base64 chars =', big.length, 'MB≈', (big.length / 1048576).toFixed(1))
await page.evaluate((d) => window.__IWB_E2E_SETREF__('r1', d), big)
await page.waitForTimeout(400)
// performance.memory 在本机 headless Chromium 是**常量桩**(申请 100MB 也纹丝不动,实测恒为 10000000)。
// 先做一次 8MB 分配探针判断它是否真的可用;不可用则按任务允许的方式降级到「画布 base64 总量」。
const heapLive = await page.evaluate(() => {
const m = performance.memory
const a = m && m.usedJSHeapSize
window.__IWB_HEAP_PROBE__ = 'x'.repeat(8 * 1024 * 1024)
const b = m && m.usedJSHeapSize
return !!(a && b && b - a > 4 * 1024 * 1024)
})
console.log('[parity-3] performance.memory 可用 =', heapLive)
const snap = () => page.evaluate(() => {
const nodes = window.__IWB_E2E_CANVAS__() || []
return {
heap: (performance.memory && performance.memory.usedJSHeapSize) || -1,
chars: nodes.reduce((s, n) => s + ((n.data && typeof n.data.data === 'string') ? n.data.data.length : 0), 0),
bigNodes: nodes.filter((n) => n.data && typeof n.data.data === 'string' && n.data.data.length > 3000).length,
nodes: nodes.length,
clipLen: (localStorage.getItem('iwb_clipboard') || '').length,
clipHasBase64: /data:image\//.test(localStorage.getItem('iwb_clipboard') || ''),
}
})
const before = await snap()
await page.locator('[data-node-id="r1"] .iwb-node-head').click()
await page.keyboard.press('Control+c')
await page.waitForTimeout(400)
// v3.24.67:节点组只走 Ctrl+Shift+V(Ctrl+V 不再回退贴节点组)
await page.keyboard.press('Control+Shift+v')
await page.waitForTimeout(1500)
const after = await snap()
console.log('[parity-3] before', JSON.stringify(before), 'after', JSON.stringify(after))
expect(after.nodes, '粘贴应新增节点').toBeGreaterThanOrEqual(before.nodes + 1)
// ── 可观测契约:粘贴出的节点持有的是引用(__cache/__idb),不是又一份图片字节 ──
expect(after.chars, '复制/粘贴不应在画布内再复制一份图片 base64').toBeLessThanOrEqual(before.chars)
expect(after.bigNodes, '大图字节节点数不应因复制而增加').toBe(before.bigNodes)
expect(after.clipLen, '复制应写入内部剪贴板').toBeGreaterThan(0)
expect(after.clipHasBase64, '内部剪贴板只应存引用,不应驻留 base64').toBe(false)
// ── 用户要求的内存增量上界(仅在 performance.memory 真的可用时才是有效证据)──
if (heapLive) {
const dMB = (after.heap - before.heap) / 1048576
console.log('[parity-3] heap delta MB =', dMB.toFixed(1))
expect(dMB, '复制大图节点不应产生 200MB 级堆增量').toBeLessThan(200)
} else {
console.log('[parity-3] 降级:本机 performance.memory 为常量桩,已改用「画布 base64 总量不增加 + 剪贴板为引用」作为断言')
}
})
test('④ 画布只加载预览小图;点开 .iwb-imgpreview 才出现原图尺寸', async ({ page }) => {
const counters = mockRemote(page)
await seedAndOpen(page, boardWithRemote4k({ thumb: SMALL_DATA_URL }))
// 2026-11-03:画布保存改为「结果精简落盘」——`items[].data`(缩略图 base64)会被剥掉,只留 `idb` 引用,
// 装载时由 warmThumbs 从 IDB 读回。所以先把缩略图**真的写进 IDB**(真实生成流程就是 `IDB.put(out_*, thumb)`),
// 否则这里构造的是「idb 键指向不存在字节」的假形态,任何实现都还原不出缩略图。
await page.evaluate((thumb) => new Promise((res) => {
const req = indexedDB.open('iwb_web', 3)
req.onsuccess = () => {
try {
const t = req.result.transaction('images', 'readwrite')
t.objectStore('images').put(thumb, 'out_seed_thumb')
t.oncomplete = () => res(1); t.onerror = () => res(0)
} catch (e) { res(0) }
}
req.onerror = () => res(0)
}), SMALL_DATA_URL)
await page.waitForTimeout(700) // 等一次保存把精简后的结果落盘,再 reload(保证走的是「从 idb 回读」这条路)
await page.reload({ waitUntil: 'domcontentloaded' })
await page.waitForTimeout(700)
const card = page.locator('.iwb-home-card:not(.iwb-home-new)').first()
if (await card.count()) await card.dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.waitForTimeout(400)
const cell = page.locator('.iwb-out-cell-img').first()
await expect(cell).toBeVisible()
await expect.poll(() => cell.evaluate((el) => el.naturalWidth), { timeout: 15000 }).toBe(SMALL_W)
const canvasW = await cell.evaluate((el) => el.naturalWidth)
const canvasSrc = await cell.evaluate((el) => String(el.currentSrc || el.src).slice(0, 24))
expect(canvasW, '未点开预览时画布图必须是 ≤1024 的小图').toBeLessThanOrEqual(1024)
expect(canvasSrc, '画布上的图应是本地小图(data:/blob:),不是远端原图').toMatch(/^(data:|blob:)/)
expect(await page.locator('.iwb-imgpreview').count(), '未点开时不应存在预览层').toBe(0)
console.log('[parity-4] canvas naturalWidth =', canvasW, 'remote =', counters.remote)
await cell.click()
const prev = page.locator('.iwb-imgpreview img').first()
await expect(prev).toBeVisible()
await expect.poll(() => prev.evaluate((el) => el.naturalWidth), { timeout: 20000 }).toBeGreaterThan(1024)
const prevW = await prev.evaluate((el) => el.naturalWidth)
const prevSrc = await prev.evaluate((el) => String(el.currentSrc || el.src))
console.log('[parity-4] preview naturalWidth =', prevW, 'src =', prevSrc.slice(0, 48), 'remote =', counters.remote, 'proxy =', counters.proxy)
expect(prevSrc, '预览拿到的应是原图源(远端图床 URL)').toMatch(/mock-cdn\.example\.com/)
expect(prevW, '预览应拿到原图尺寸(>1024)').toBeGreaterThan(1024)
})
// S14 多标签:打开标签保留 hydrate/objectURL——切走再切回不重新请求缩略图(切回即用、不闪黑图)
test('⑤ 多标签:切走再切回不重新请求(打开标签保留 objectURL,S14)', async ({ page }) => {
const counters = mockRemote(page)
const two = {
schemaVersion: 1, rev: 1, activeId: 'w1',
workspaces: [
{ ...boardWithRemote4k().workspaces[0], name: 'Alpha' },
{ id: 'w2', name: 'Beta', nodes: [{ id: 'p1', type: 'prompt', x: 100, y: 100, w: 280, data: { text: 'hi' } }], edges: [], groups: [] },
],
}
await page.addInitScript((d) => {
window.__IWB_E2E__ = true
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
localStorage.setItem('iwb_web_workspaces', JSON.stringify(d.ws))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(d.ws.workspaces[0]))
localStorage.setItem('iwb_ws_w2', JSON.stringify(d.ws.workspaces[1]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
}, { ws: two, cfg: cfgWithProviders() })
await page.goto('/', { waitUntil: 'domcontentloaded' })
await W.waitHomeReady(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').filter({ hasText: 'Alpha' }).dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
const img = page.locator('.iwb-out-cell-img').first()
await expect(img).toBeVisible()
await expect.poll(() => counters.proxy, { timeout: 20000 }).toBeGreaterThanOrEqual(1)
await nudgeNodeRender(page, 'o1')
await waitThumb(img, 768, '跨域远端 4K')
const src0 = await img.evaluate((el) => String(el.currentSrc || el.src))
const proxyAfter = counters.proxy
// 打开第二个画布(Beta)成为第二个标签
await page.locator('.iwb-tab-home').click()
await W.waitHomeReady(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').filter({ hasText: 'Beta' }).dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.waitForTimeout(300)
// 切回 Alpha 标签(S14:打开标签保留 objectURL,切回即用)
await page.locator('.iwb-tab').filter({ hasText: 'Alpha' }).click()
await page.waitForTimeout(600)
const img2 = page.locator('.iwb-out-cell-img').first()
await expect(img2).toBeVisible()
const src1 = await img2.evaluate((el) => String(el.currentSrc || el.src))
const nw = await img2.evaluate((el) => el.naturalWidth)
console.log('[parity-5] proxy', proxyAfter, '->', counters.proxy, ' remote', counters.remote, ' naturalWidth =', nw)
expect(counters.proxy - proxyAfter, '切回打开标签不应重新请求缩略图(objectURL 保留)').toBeLessThanOrEqual(0)
expect(src1, '切回后仍应是同一小预览(objectURL 不变)').toBe(src0)
expect(nw, '切回后图片应已显示(>0,不闪黑图)').toBeGreaterThan(0)
})