Files
image-workbench-desktop/tests/iwb-memory-history.spec.js

278 lines
17 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.
// v3.87.7 内存修复(OOM)验收:撤销历史不再钉住图片本体
// ① 画布上有大图(本地 base64)时,撤销快照里必须**只有引用**({__cache}/{__idb}),不能有 base64
// ② 快照深度 ≤ 20(原 60)
// ③ 撤销仍然可用:恢复到上一状态,且图片(引用)能被 hydrate 回来 —— 内存修复不能牺牲功能
// 运行:npm run build && IWB_BASE_URL=http://127.0.0.1:8787 npx playwright test tests/iwb-memory-history.spec.js
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 CFG = {
providers: [{ id: 'p-a', name: '服务商 A', baseUrl: 'https://a.example/v1', keys: [{ id: 'a-1', name: 'K1', value: 'sk-fake' }], models: [{ name: 'gpt-image-2', visible: true }] }],
canvas: { snap: true },
}
// 先种一个"小"画布(符合 localStorage 配额),再把 MB 级原图注入内存中的 ref 节点:
// 这既绕开配额限制,也正好复现 OOM 现场(大图只在内存里)。
async function seedWithBigImage(page) {
const small = { id: 'r1', type: 'ref', x: 60, y: 80, data: { data: '', name: 'big.png', url: '' } }
const gen = { id: 'g1', type: 'gen', x: 520, y: 80, w: 420, data: { model: 'gpt-image-2', provider: 'p-a', keyGroup: 'a-1', size: '1024x1024', ratio: '1:1', res: '1K', variants: 1, taskVariants: {} } }
const board = { id: 'w1', name: 'W', nodes: [small, gen], edges: [], groups: [] }
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
localStorage.setItem('iwb_web_workspaces', JSON.stringify({ workspaces: [d.board], activeId: 'w1', rev: 1 }))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(d.board))
window.__IWB_E2E__ = true
}, { cfg: CFG, board })
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForTimeout(700)
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)
// 注入 MB 级原图(逐像素噪声 → PNG 压不动)
const bigLen = await page.evaluate(() => {
const cv = document.createElement('canvas')
cv.width = 1200; cv.height = 1200
const ctx = cv.getContext('2d')
const id = ctx.createImageData(1200, 1200)
for (let i = 0; i < id.data.length; i += 4) {
id.data[i] = (Math.random() * 256) | 0
id.data[i + 1] = (Math.random() * 256) | 0
id.data[i + 2] = (Math.random() * 256) | 0
id.data[i + 3] = 255
}
ctx.putImageData(id, 0, 0)
const big = cv.toDataURL('image/png')
window.__BIG_LEN__ = big.length
const hasSet = typeof window.__IWB_E2E_SETREF__
const ok = (hasSet === 'function') && window.__IWB_E2E_SETREF__('r1', big)
const nodes = (typeof window.__IWB_E2E_CANVAS__ === 'function') ? window.__IWB_E2E_CANVAS__() : []
return { len: big.length, ok: !!ok, hasSet, hasCanvas: typeof window.__IWB_E2E_CANVAS__, e2e: window.__IWB_E2E__, count: nodes.length, ids: nodes.map((n) => n.id), dataLen: nodes.map((n) => String(((n.data || {}).data) || '').length) }
})
console.log('DIAG_INJECT=' + JSON.stringify(bigLen))
expect(bigLen.ok, '应能把 MB 级原图注入内存中的节点').toBe(true)
expect(bigLen.len).toBeGreaterThan(1000000)
await page.waitForTimeout(300)
}
// 只把"小数字"取回主进程,避免传输几 MB 字符串
const liveMaxImageLen = (page) => page.evaluate(() => {
const nodes = (typeof window.__IWB_E2E_CANVAS__ === 'function') ? window.__IWB_E2E_CANVAS__() : []
let max = 0
for (const n of nodes) {
const d = (n && n.data) || {}
for (const f of ['data', 'url']) if (typeof d[f] === 'string') max = Math.max(max, d[f].length)
}
return max
})
// v3.87.5x(丙方案 C3):hydrate 起不再把图片字节读回 base64 —— 「画布上还持有图片」的判据从
// 「存在 MB 级 base64 字符串」扩展为「图片字段是 base64 或可解析引用(__cache/__blob)」,并额外要求
// 画布上的 <img> 真能解码(省内存不得牺牲功能)。
const liveImageState = (page) => page.evaluate(() => {
const nodes = (typeof window.__IWB_E2E_CANVAS__ === 'function') ? window.__IWB_E2E_CANVAS__() : []
let maxStr = 0
let refs = 0
for (const n of nodes) {
const d = (n && n.data) || {}
for (const f of ['data', 'url']) {
if (typeof d[f] === 'string') maxStr = Math.max(maxStr, d[f].length)
else if (d[f] && typeof d[f] === 'object') refs++
}
}
const img = document.querySelector('[data-node-id="r1"] .iwb-ref-single')
return { maxStr, refs, hasPayload: maxStr > 0 || refs > 0, nw: img ? img.naturalWidth : -1, src: img ? String(img.currentSrc || img.src).slice(0, 24) : '' }
})
const historyStats = (page) => page.evaluate(() => {
const h = (typeof window.__IWB_E2E_HISTORY__ === 'function') ? window.__IWB_E2E_HISTORY__() : null
const stack = (h && h.stack) || []
let maxBig = 0
let nodeCount = 0
for (const snap of stack) {
for (const n of ((snap && snap.nodes) || [])) {
nodeCount++
const d = (n && n.data) || {}
const scan = (v) => {
if (typeof v === 'string') { maxBig = Math.max(maxBig, v.length); return }
if (Array.isArray(v)) { for (const x of v) scan(x); return }
if (v && typeof v === 'object') { scan(v.data); scan(v.url); scan(v.thumb) }
}
scan(d.data); scan(d.url); scan(d.result)
}
}
return { depth: stack.length, idx: h ? h.idx : -1, maxBig, nodeCount, bigLen: window.__BIG_LEN__ || 0 }
})
test('撤销快照只存引用(不含 base64)且深度 ≤20,撤销后图片仍能恢复', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await seedWithBigImage(page)
const dbg = await page.evaluate(() => {
const nodes = (typeof window.__IWB_E2E_CANVAS__ === 'function') ? window.__IWB_E2E_CANVAS__() : null
const domNodes = document.querySelectorAll('.iwb-node').length
return { hook: typeof window.__IWB_E2E_CANVAS__, bigLen: window.__BIG_LEN__ || 0, count: nodes ? nodes.length : -1, domNodes, types: nodes ? nodes.map((n) => n.type) : [], lens: nodes ? nodes.map((n) => { const d = (n.data || {}); return [String(d.data || '').length, String(d.url || '').length, String(d.result || '').length] }) : [] }
})
console.log('DIAG_MEM=' + JSON.stringify(dbg))
const before = await historyStats(page)
expect(before.bigLen, '测试自身要有一张足够大的图(≈真实原图量级)').toBeGreaterThan(1000000)
expect(await liveMaxImageLen(page), '画布上仍然持有原图 base64(这是被修复的"被钉住"对象)').toBeGreaterThan(1000000)
// 触发一次可撤销操作:图像设置里把分辨率改成 2K(patch 含 size → 进入撤销历史)
await page.locator('[data-node-id="g1"] .iwb-gen-summary').click()
const panel = page.locator('.iwb-image-settings')
await expect(panel).toBeVisible()
await panel.locator('.iwb-setgroup').nth(2).locator('.iwb-chip', { hasText: '2K' }).first().click()
await page.keyboard.press('Escape')
await page.waitForTimeout(1600) // 800ms 防抖 + 异步引用化
const after = await historyStats(page)
expect(after.depth, '快照应已入栈').toBeGreaterThanOrEqual(1)
expect(after.depth, '深度上限 20(原 60)').toBeLessThanOrEqual(20)
expect(after.maxBig, '快照里不得出现 base64 图片(>3000 视为未引用化)').toBeLessThan(3000)
// 画布本体不受影响:原图还在(撤销/放大/导出都还需要它)
expect(await liveMaxImageLen(page)).toBeGreaterThan(1000000)
// 撤销仍可用:分辨率回退到 1K,且恢复路径不丢图
await page.locator('.iwb-canvas').click({ position: { x: 1200, y: 900 } })
await page.keyboard.press('Control+z')
await page.waitForTimeout(1800) // 撤销是同步提交 + 异步补 hydrate 图片
const gen = await page.evaluate(() => {
const n = (window.__IWB_E2E_CANVAS__() || []).find((x) => x && x.id === 'g1')
return n ? { res: n.data.res, size: n.data.size } : null
})
expect(gen, '撤销后应能读到生图节点').toBeTruthy()
expect(gen.res, '撤销应把分辨率回退为 1K').toBe('1K')
// C3 契约更新(原:「撤销恢复后画布上仍有 >1MB 的 base64」):hydrate 起引用形态**不再展开成 base64**,
// 所以判据改为「图片载荷仍在画布上(引用形态)+ 画布上的图真能解码显示」——原意是「内存修复不能牺牲功能」。
const liveAfterUndo = await liveImageState(page)
expect(liveAfterUndo.hasPayload, '撤销恢复路径不丢图(画布上仍持有该图的载荷/引用)').toBe(true)
expect(liveAfterUndo.nw, '撤销恢复后画布上的图必须真能解码显示').toBeGreaterThan(0)
expect(errors).toEqual([])
})
// ── 丙方案 C3 契约:hydrate 不再产出 base64(字节留在 Cache Storage / Blob 仓库,画布只留引用)──
test('C3:从存储装载的大图不再把 base64 读回 JS 堆,但画布仍能显示原图', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await page.addInitScript(() => {
const c = document.createElement('canvas')
c.width = 1200; c.height = 900
const x = c.getContext('2d')
for (let i = 0; i < 1200; i++) {
const h = ((i * 2654435761) >>> 0) % 0xffffff
x.fillStyle = '#' + h.toString(16).padStart(6, '0')
x.fillRect((i * 37) % 1160, (i * 91) % 870, 40, 30)
}
const dataUrl = c.toDataURL('image/png')
window.__C3_IMG_LEN__ = dataUrl.length
const board = { id: 'w1', name: 'C3', nodes: [{ id: 'r1', type: 'ref', x: 60, y: 80, data: { data: dataUrl, name: 'big.png', url: '' } }], edges: [], groups: [] }
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: { snap: true } }))
localStorage.setItem('iwb_web_workspaces', JSON.stringify({ workspaces: [board], activeId: 'w1', rev: 1 }))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(board))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
window.__IWB_E2E__ = true
})
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForTimeout(700)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
// 画布必须真能显示(引用 → Cache Storage → objectURL,不依赖 Service Worker 是否已接管)
await expect.poll(() => page.evaluate(() => { const i = document.querySelector('[data-node-id="r1"] .iwb-ref-single'); return i ? i.naturalWidth : 0 }), { timeout: 20000 }).toBeGreaterThan(0)
const bigLen = await page.evaluate(() => window.__C3_IMG_LEN__ || 0)
// 与既有 in-localStorage 用例同口径:>3000 的 dataURL 才会走「引用化」分支(MB 级堆快照由 parity-③/内存指标覆盖)
expect(bigLen, '测试图必须超过引用化阈值(>3000 字符)').toBeGreaterThan(3000)
const st = await page.evaluate(() => {
const n = (window.__IWB_E2E_CANVAS__() || []).find((x) => x.id === 'r1') || {}
const d = (n.data || {}).data
return { kind: typeof d === 'string' ? 'string' : (d && Object.keys(d)[0]) || 'none', len: typeof d === 'string' ? d.length : 0 }
})
console.log('[c3-1] node data =', JSON.stringify(st), 'raw =', bigLen)
expect(st.len, 'C3:hydrate 不得把 MB 级 base64 读回画布数据').toBeLessThan(3000)
expect(['__cache', '__blob'].indexOf(st.kind) >= 0, 'C3:画布上的图应保留为可解析引用,实际 ' + st.kind).toBe(true)
expect((await page.evaluate(() => localStorage.getItem('iwb_ws_w1') || '')).indexOf('data:image/') < 0, 'localStorage 不得残留图片 base64').toBe(true)
expect(errors).toEqual([])
})
test('C3:历史 {__idb} 引用装载时迁移为 {__blob}(imgblob_,IDB Blob),不再读回 base64', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await page.addInitScript(() => {
const board = { id: 'w1', name: 'C3B', nodes: [{ id: 'r1', type: 'ref', x: 60, y: 80, data: { data: '', name: 'big.png', url: '' } }], edges: [], groups: [] }
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: { snap: true } }))
localStorage.setItem('iwb_web_workspaces', JSON.stringify({ workspaces: [board], activeId: 'w1', rev: 1 }))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(board))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
window.__IWB_E2E__ = true
})
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForTimeout(700)
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(300)
// 造一张大图 → 写进「历史 ref_ 形态」的 IDB 键 → 以 {__idb} 注入节点 → 保存 → 切走再切回触发 hydrate 迁移
const info = await page.evaluate(async () => {
const c = document.createElement('canvas')
c.width = 900; c.height = 700
const x = c.getContext('2d')
for (let i = 0; i < 900; i++) {
const h = ((i * 2654435761) >>> 0) % 0xffffff
x.fillStyle = '#' + h.toString(16).padStart(6, '0')
x.fillRect((i * 37) % 860, (i * 91) % 670, 40, 30)
}
const dataUrl = c.toDataURL('image/png')
const db = await new Promise((res, rej) => {
const r = indexedDB.open('iwb_web', 3)
r.onsuccess = () => res(r.result)
r.onerror = () => rej(new Error('idb-open'))
r.onupgradeneeded = () => { const d = r.result; for (const s of ['images', 'logs', 'kv']) if (!d.objectStoreNames.contains(s)) d.createObjectStore(s) }
})
await new Promise((res, rej) => { const t = db.transaction('images', 'readwrite'); t.objectStore('images').put(dataUrl, 'ref_c3_test'); t.oncomplete = () => res(); t.onerror = () => rej(new Error('idb-put')) })
const ok = window.__IWB_E2E_SETREF__('r1', { __idb: 'ref_c3_test' })
return { len: dataUrl.length, ok: !!ok }
})
expect(info.ok, '应能注入 {__idb} 引用').toBe(true)
expect(info.len).toBeGreaterThan(3000)
// 等自动保存把 {__idb} 引用落进 localStorage。用轮询替代固定等待:并发(多 worker)下防抖/落盘时序会漂移,固定 2500ms 偶发不够(引用未落盘 → 切走再回来不会触发迁移)
await expect.poll(() => page.evaluate(() => String(localStorage.getItem('iwb_ws_w1') || '').includes('__idb')), { timeout: 15000 }).toBe(true)
// 切回画布库再进画布 → 走 hydrate(迁移 __idb → __blob)
await W.goHome(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
const diag = await page.evaluate(async () => {
const n = (window.__IWB_E2E_CANVAS__() || []).find((x) => x.id === 'r1') || {}
const d = (n.data || {}).data
const img = document.querySelector('[data-node-id="r1"] .iwb-ref-single')
return { data: typeof d === 'string' ? ('str' + d.length) : JSON.stringify(d), nw: img ? img.naturalWidth : -1, src: img ? String(img.currentSrc || img.src).slice(0, 30) : 'no-img', ls: String(localStorage.getItem('iwb_ws_w1') || '').slice(0, 220) }
})
console.log('[c3-2-diag]', JSON.stringify(diag))
await expect.poll(() => page.evaluate(() => { const i = document.querySelector('[data-node-id="r1"] .iwb-ref-single'); return i ? i.naturalWidth : 0 }), { timeout: 20000 }).toBeGreaterThan(0)
const after = await page.evaluate(async () => {
const n = (window.__IWB_E2E_CANVAS__() || []).find((x) => x.id === 'r1') || {}
const d = (n.data || {}).data
const key = (d && typeof d === 'object' && d.__blob) || ''
let idbKind = 'n/a'
if (key) {
const db = await new Promise((res) => { const r = indexedDB.open('iwb_web', 3); r.onsuccess = () => res(r.result); r.onerror = () => res(null) })
if (db) idbKind = await new Promise((res) => { const t = db.transaction('images', 'readonly'); const g = t.objectStore('images').get(key); g.onsuccess = () => res(g.result ? (g.result instanceof Blob ? 'Blob' : typeof g.result) : 'MISS'); g.onerror = () => res('ERR') })
}
return { kind: typeof d === 'string' ? ('string' + d.length) : (d && Object.keys(d)[0]) || 'none', key, idbKind, nw: (document.querySelector('[data-node-id="r1"] .iwb-ref-single') || {}).naturalWidth || 0, ls: String(localStorage.getItem('iwb_ws_w1') || '') }
})
console.log('[c3-2]', JSON.stringify({ kind: after.kind, key: after.key, idbKind: after.idbKind, nw: after.nw }))
expect(after.kind, 'C3:__idb 应迁移为 __blob 引用').toBe('__blob')
expect(after.key.indexOf('imgblob_'), 'Blob 键应带 imgblob_ 前缀(GC 依赖该前缀)').toBe(0)
expect(after.idbKind, 'IDB 里该键必须是 Blob(不是 base64 字符串)').toBe('Blob')
await expect.poll(() => page.evaluate(() => { const i = document.querySelector('[data-node-id="r1"] .iwb-ref-single'); return i ? i.naturalWidth : 0 }), { timeout: 20000 }).toBeGreaterThan(0)
expect(after.ls.indexOf('data:image/'), 'localStorage 不得残留图片 base64').toBe(-1)
expect(errors).toEqual([])
})