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

181 lines
10 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.0.4(B)撤销历史不再钉住图片字节 —— 快照**入栈前同步引用化**契约
//
// 用户实测(v3.0.1/v3.0.2,**一次撤销都没做**):
// 刷新后 historyMB 0.1 / depth 11 → 导入 4K 后编辑 historyMB **10.5~11.6MB / depth 19**、base64MB 18.7~51.3
// ⇒ 快照是「每次画布变更自动 push」(与是否按 Ctrl+Z 无关),且快照里保留了 `data:image/...` 大 base64。
// 修法:在唯一生成处 `historyRawSnapshot`(pushHistory / pushHistoryDebounced 都经它)**同步**把
// >3000 的 dataURL 换成 `{__cache}` 引用(复用保存路径同源的 `containsBigDataUrl` + `stripBigValueSync`)。
//
// 本文件 = 两条守护契约(行为级):
// ① 快照序列化后**不含** `data:image/`,且历史栈总字节是 **KB 级**(而不是"每层 MB 级 × 深度")
// ② 撤销 / 重做之后图片**仍能正常显示**(引用 → hydrate → objectURL → <img> 真解码)
const { test, expect } = require('./_pw-coverage')
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 节点:
// 绕开配额限制,同时精确复现现场(大图只在内存里,历史快照会把它钉住)。
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)
// 注入 ≈3MB+ 的真实量级原图(1200×1200 逐像素噪声 → PNG 压不动)
const injected = 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')
const ok = (typeof window.__IWB_E2E_SETREF__ === 'function') && window.__IWB_E2E_SETREF__('r1', big)
return { len: big.length, ok: !!ok }
})
expect(injected.ok, '应能把 MB 级原图注入内存中的节点').toBe(true)
expect(injected.len, '测试图必须是 MB 级(否则契约没有意义)').toBeGreaterThan(1000000)
// 等画布把注入的图真解码出来(撤销后还要再验一次)
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)
await page.waitForTimeout(200)
return injected.len
}
// 只回传数字/短串,避免把几 MB 字符串搬回主进程
const historyBytes = (page) => page.evaluate(() => {
const h = (typeof window.__IWB_E2E_HISTORY__ === 'function') ? window.__IWB_E2E_HISTORY__() : null
const stack = (h && h.stack) || []
let maxSnap = 0
let maxBig = 0
let refFields = 0
let rawFields = 0
for (const snap of stack) {
let bytes = 0
try { bytes = JSON.stringify(snap).length } catch (e) { bytes = -1 }
maxSnap = Math.max(maxSnap, bytes)
for (const n of ((snap && snap.nodes) || [])) {
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') { for (const k in v) scan(v[k]) }
}
scan(d.data); scan(d.url); scan(d.result)
for (const f of ['data', 'url', 'result']) {
if (typeof d[f] === 'string' && d[f].length > 3000) rawFields++
else if (d[f] && typeof d[f] === 'object' && (d[f].__cache || d[f].__blob || d[f].__idb)) refFields++
}
}
}
let total = 0
try { total = JSON.stringify(stack).length } catch (e) { total = -1 }
const r1 = stack.length ? ((stack[stack.length - 1].nodes || []).find((n) => n.id === 'r1') || {}) : {}
const r1d = (r1.data || {}).data
return {
depth: stack.length, idx: h ? h.idx : -1, total, maxSnap, maxBig, refFields, rawFields,
r1Kind: (typeof r1d === 'string') ? ('string:' + r1d.length) : (r1d ? Object.keys(r1d).join('+') : 'none'),
hasDataImage: total > 0 ? (JSON.stringify(stack).indexOf('data:image/') >= 0) : null,
}
})
const liveImg = (page) => page.evaluate(() => {
const n = (typeof window.__IWB_E2E_CANVAS__ === 'function') ? (window.__IWB_E2E_CANVAS__() || []).find((x) => x && x.id === 'r1') : null
const d = (n && n.data) || {}
const v = d.data
const el = document.querySelector('[data-node-id="r1"] .iwb-ref-single')
return {
fieldKind: (typeof v === 'string') ? ('string:' + v.length) : (v ? Object.keys(v).join('+') : 'none'),
fieldIsBig: typeof v === 'string' && v.length > 3000,
nw: el ? el.naturalWidth : -1,
src: el ? String(el.currentSrc || el.src).slice(0, 12) : '',
}
})
test('B-① 快照入栈即引用化:历史栈序列化字节 KB 级、快照内无 data:image/ 大 base64', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
const imgBytes = await seedWithBigImage(page)
// 实时画布此刻**仍**持有原图 base64(撤销/放大/导出都需要它;被治理的是"快照把它钉住")
const liveBefore = await liveImg(page)
expect(liveBefore.fieldIsBig, '实时画布仍应持有原图 base64(本改动只治理快照)').toBe(true)
// 触发**恰好一次** pushHistory
const depthAfterPush = await page.evaluate(() => window.__IWB_E2E_PUSH_HISTORY__())
expect(depthAfterPush, '快照应已入栈').toBeGreaterThanOrEqual(1)
await page.waitForTimeout(600) // 留出 Cache 写入落地的时间(引用可用性由 B-② 验证)
const st = await historyBytes(page)
console.log('[B-①] img = ' + imgBytes + ' 字节 · 历史 ' + JSON.stringify(st))
expect(st.hasDataImage, '快照序列化后**不得**含 data:image/(大图必须已引用化)').toBe(false)
expect(st.maxBig, '快照里不得出现 >3000 的图片字符串(视为未引用化)').toBeLessThan(3000)
expect(st.rawFields, '快照的图片字段不得残留裸 base64').toBe(0)
expect(st.refFields, '快照的图片字段应是可解析引用({__cache}/{__blob})').toBeGreaterThanOrEqual(1)
expect(st.r1Kind, 'r1 的图片字段形态应是引用').toContain('__cache')
// 关键:字节数从"MB 级 × 深度"降到 KB 级(断言与图大小无关的上界)
expect(st.total, '历史栈总字节应远小于图片本身(KB 级)').toBeLessThan(100000)
expect(st.maxSnap, '单份快照字节应远小于图片本身(KB 级)').toBeLessThan(50000)
expect(errors).toEqual([])
})
test('B-② 撤销 / 重做后图片仍能正常显示(引用 → hydrate → objectURL → 真解码)', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await seedWithBigImage(page)
// 用户可见路径触发一次快照:图像设置里把分辨率改成 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 防抖 + Cache 写入落地
const st = await historyBytes(page)
console.log('[B-②] after-edit = ' + JSON.stringify(st))
expect(st.depth, '快照应已入栈').toBeGreaterThanOrEqual(1)
expect(st.hasDataImage, '用户路径产出的快照也不得含 data:image/').toBe(false)
// 撤销:分辨率回 1K,且 r1 的图片仍能显示(引用解析回来)
await page.locator('.iwb-canvas').click({ position: { x: 1200, y: 900 } })
await page.keyboard.press('Control+z')
await page.waitForTimeout(1800)
const gen = await page.evaluate(() => { const n = (window.__IWB_E2E_CANVAS__() || []).find((x) => x && x.id === 'g1'); return n ? { res: n.data.res } : null })
expect(gen && gen.res, '撤销应把分辨率回退为 1K').toBe('1K')
const afterUndo = await liveImg(page)
console.log('[B-②] after-undo = ' + JSON.stringify(afterUndo))
expect(afterUndo.fieldIsBig, '撤销恢复的应是引用形态(不再把 base64 读回画布)').toBe(false)
expect(afterUndo.fieldKind, '撤销恢复的图片字段应是引用').toContain('__cache')
expect(afterUndo.nw, '撤销后画布上的图必须真能解码显示').toBeGreaterThan(0)
// 重做:图片同样不能丢
await page.keyboard.press('Control+Shift+z')
await page.waitForTimeout(1800)
const afterRedo = await liveImg(page)
console.log('[B-②] after-redo = ' + JSON.stringify(afterRedo))
expect(afterRedo.nw, '重做后画布上的图必须真能解码显示').toBeGreaterThan(0)
expect(errors).toEqual([])
})