Files
image-workbench-desktop/tests/iwb-plugin-node-coldstart.spec.js

121 lines
5.5 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-11-14 契约:**存档里的插件节点,冷启动必须由插件自己的节点体渲染**
//
// 背景(真机事故):插件脚本是异步下载的,画布会先把存档里的节点画一遍 —— 那一刻
// `NODE_TYPES.get(type).render` 还是 null,于是走通用兜底体(hint + 一个 textarea),
// 用户看到的是「样式节点只剩一段文本」;等插件注册上 render 时 React 不会自己重画,就停在兜底体上。
// 另有一条更狠的旧路径:`canvas-normalize` 见 `hasType(type)` 为 false ⇒ 把 `plugin:<id>:<变体>` 归成 `plugin`,
// 变体身份被抹掉并随存档写回(插件后到也认不回来)。
//
// 本用例用**假插件**(route 拦截 /plugins/*)把两件事一起钉住:
// ① 插件晚到 1.2s,画布先画 → 插件注册完**不用点任何东西**,节点体自动换成插件渲染;
// ② 节点类型保持 `plugin:fake-style:style`(没被降级成 `plugin`)。
const { test, expect } = require('./_pw-coverage')
const crypto = require('node:crypto')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
const PLUGIN_ID = 'fake-style'
const PLUGIN_FILE = 'plugin-fake-style.deadbeef0001.js'
// 假插件:声明 nodeTypes、注册一个「只出不入」的变体,节点体画一行可断言的文字
const PLUGIN_SRC = [
';(function () {',
" var host = window.IWBPluginHost",
" if (!host || typeof host.register !== 'function') return",
' host.register({',
" id: '" + PLUGIN_ID + "',",
" name: '假样式插件',",
" version: '1.0.0',",
' apiVersion: 1,',
" capabilities: ['nodeTypes']",
' }, function (ctx) {',
" if (ctx.nodes && typeof ctx.nodes.register === 'function') {",
' ctx.nodes.register({',
" id: 'style',",
" title: '样式节点',",
' defaults: {},',
' ports: { in: false, out: true },',
' height: 320,',
' render: function (node, props, el) {',
' el.innerHTML = \'\'',
" var d = document.createElement('div')",
" d.className = 'fx-body'",
" d.textContent = '插件渲染 OK:' + ((node.data && node.data.name) || '')",
' el.appendChild(d)',
' }',
' })',
' }',
' return {}',
' })',
'})()',
].join('\n')
const INTEGRITY = 'sha256-' + crypto.createHash('sha256').update(Buffer.from(PLUGIN_SRC, 'utf8')).digest('base64')
const NODE = {
id: 'n1',
type: 'plugin:' + PLUGIN_ID + ':style',
x: 260, y: 200, w: 300, h: 320,
data: { variant: 'style', name: '冷启动用例', outKind: 'prompt', text: '样式提示词原文' },
}
const WS = {
schemaVersion: 1, rev: 1, activeId: 'w1',
workspaces: [{ id: 'w1', name: '冷启动', nodes: [NODE], edges: [], groups: [] }],
}
test('插件节点在冷启动后自动切换到插件节点体(不点任何东西),且类型不被降级', async ({ page }) => {
const pluginHits = []
// 插件晚 1.2s 到达:保证画布先按存档画一遍(此时 render 还没注册)
await page.route('**/plugins/' + PLUGIN_FILE, async (route) => {
pluginHits.push(Date.now())
await new Promise((r) => setTimeout(r, 1200))
await route.fulfill({ status: 200, contentType: 'application/javascript', body: PLUGIN_SRC })
})
await page.route('**/plugins/index.json', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: PLUGIN_ID, version: '1.0.0', file: PLUGIN_FILE, integrity: INTEGRITY }]),
})
})
await page.addInitScript(({ ws, id }) => {
localStorage.clear()
const st = {}
st[id] = { enabled: true, settings: {}, data: {} }
localStorage.setItem('iwb_plugins', JSON.stringify(st))
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
}, { ws: WS, id: PLUGIN_ID })
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForTimeout(600)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
// 插件到达前:兜底体(这里只要求「不是插件体」,允许是 hint + textarea)
await expect(page.locator('[data-node-id="n1"] .iwb-plugin-node-body')).toHaveCount(0)
// 插件到达后:**不点任何东西**,节点体必须自动换成插件渲染
await expect(page.locator('[data-node-id="n1"] .fx-body')).toHaveCount(1, { timeout: 8000 })
await expect(page.locator('[data-node-id="n1"] .fx-body')).toContainText('插件渲染 OK:冷启动用例')
expect(pluginHits.length, '插件脚本应被请求一次').toBeGreaterThanOrEqual(1)
// 类型没有被降级成 `plugin`(旧逻辑会把变体身份抹掉并写回存档 ⇒ 插件后到也认不回来)。
// 存档写入是异步的,这里直接读节点卡上的活数据(React fiber 里的 node.type)。
const liveType = await page.evaluate(() => {
const el = document.querySelector('[data-node-id="n1"]')
if (!el) return null
const k = Object.keys(el).find((x) => x.indexOf('__reactFiber$') === 0)
let f = k ? el[k] : null
for (let i = 0; f && i < 40; i++, f = f.return) {
const p = f.memoizedProps
if (p && p.node && p.node.type) return p.node.type
}
return null
})
expect(liveType, '冷启动后节点类型仍是插件变体类型').toBe('plugin:' + PLUGIN_ID + ':style')
})