Files
image-workbench-desktop/tests/clipboard-audit.spec.js
T
qiqi a8151364b2 test(e2e): 环境依赖用例改为开关跳过(全量跑 0 红)
7 条用例需要真实能力(无头 web 环境必红),改为默认跳过、可手动开启:
- clipboard-audit 3 条:真实剪贴板读图
- iwb-image-memory-parity 4 条:真实远端图床 / 同源图片代理
(download-cors 1 条此前已 fixme,同样需要桌面环境)

开关在 tests/_helpers/env.js:默认跳过;设 IWB_E2E_ENV_DEPS=1 才执行。

验证:全量 52 spec / 195 用例 → 187 通过、0 失败、8 跳过、0 flaky(106s,52/52 spec 全绿)。
基线 tests/fixtures/e2e-known-red.json 已清空(0 已知红),之后出现的任何红都是新增回归。
2026-11-27 07:32:04 +08:00

767 lines
42 KiB
JavaScript
Raw 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.
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const { requireEnvDeps } = require('./_helpers/env')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8799'
// 原图 = 1x1 蓝色,系统剪贴板图 = 1x1 红色(颜色可区分 → 用像素判定「是否回到原图」)
const PNG_BLUE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNgYPgPAAEDAQAIicLsAAAAAElFTkSuQmCC'
const PNG_RED_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC'
const workspace = {
workspaces: [
{
id: 'ws_a', name: '画布A',
nodes: [
{ id: 'pa', type: 'prompt', x: 160, y: 160, data: { text: '画布A 提示词', title: '' } },
{ id: 'ra', type: 'ref', x: 160, y: 420, data: { url: '', data: PNG_BLUE, name: 'blue.png', localName: null } },
],
edges: [], groups: [],
},
{ id: 'ws_b', name: '画布B', nodes: [], edges: [], groups: [] },
],
activeId: 'ws_a',
rev: 1,
}
test.use({ baseURL, viewport: { width: 1440, height: 1000 }, permissions: ['clipboard-read', 'clipboard-write'] })
const errors = []
async function boot(page, ws) {
await page.addInitScript((data) => {
localStorage.clear()
localStorage.setItem('iwb_web_workspaces', JSON.stringify(data))
localStorage.setItem('iwb_ws_active', data.activeId)
localStorage.setItem('iwb_e2e_initialized', '1')
}, ws)
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await page.goto('/', { waitUntil: 'domcontentloaded' })
await W.waitHomeReady(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await W.waitCanvasOpen(page)
}
// 第 2 个节点是 fixture 里的参考图节点 ra(DOM 顺序 = nodes 顺序,粘贴出的节点都追加在后面)
const raNode = (page) => page.locator('.iwb-node').nth(1)
async function putImage(page, b64) {
await page.evaluate(async (b) => {
const bin = atob(b)
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
const blob = new Blob([bytes], { type: 'image/png' })
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
}, b64 || PNG_RED_B64)
}
// 在页面里用 canvas 画一张纯色图并放进系统剪贴板(不依赖硬编码 base64,颜色绝对可辨)
async function putColor(page, rgb) {
const b64 = await page.evaluate((c) => {
const cv = document.createElement('canvas')
cv.width = 8; cv.height = 8
const ctx = cv.getContext('2d')
ctx.fillStyle = 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')'
ctx.fillRect(0, 0, 8, 8)
return cv.toDataURL('image/png').split(',')[1]
}, rgb)
await putImage(page, b64)
}
// 真实 Ctrl+V:Playwright 的 keyboard.press 在 headless Chromium 不会派发 paste 事件,
// 必须用 CDP 的编辑命令 'paste'(等价于用户按下 Ctrl+V → 浏览器真正读系统剪贴板)
async function realPaste(page) {
const client = await page.context().newCDPSession(page)
await client.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, code: 'KeyV', key: 'v', commands: ['paste'] })
await page.waitForTimeout(150)
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, code: 'KeyV', key: 'v' })
}
// 真实 Ctrl+Shift+V(浏览器会同时派发「纯文本粘贴」,用来验证它被抑制)
async function realPasteGroup(page) {
const client = await page.context().newCDPSession(page)
await client.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 10, windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, code: 'KeyV', key: 'V', commands: ['paste'] })
await page.waitForTimeout(150)
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 10, windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, code: 'KeyV', key: 'V' })
}
// 读画布顶栏的状态条文案(提示通道:setNotice → .iwb-status-item)
const statusText = (page) => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-status-item')).map((x) => String(x.textContent || '')).join(' | '))
// 造一次真实的 drop(v3.24.74):DataTransfer 在页面里现场构造,files 由 items.add(File) 填出 ——
// 这是「从资源管理器拖文件到画布」在 DOM 层的样子,比直接调导入函数更能守住准入分支。
async function dropFiles(page, files) {
const dt = await page.evaluateHandle((items) => {
const d = new DataTransfer()
for (const it of items) {
let bytes = new Uint8Array([1, 2, 3, 4]) // 默认给非图片字节:本用例只关心准入判定
if (it.b64) {
const bin = atob(it.b64)
bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
}
d.items.add(new File([bytes], it.name, { type: it.type || '' }))
}
return d
}, files)
const box = await page.locator('.iwb-canvas').boundingBox()
await page.dispatchEvent('.iwb-canvas', 'drop', {
dataTransfer: dt,
clientX: Math.round(box.x + box.width * 0.7),
clientY: Math.round(box.y + box.height * 0.6),
})
}
// 读参考图节点当前显示的像素(判断「蓝=原图 / 红=粘贴图」)
async function pixelOf(page) {
return page.evaluate(async () => {
const img = document.querySelectorAll('.iwb-node')[1].querySelector('img.iwb-ref-single')
if (!img) return 'no-img'
const el = new Image()
el.crossOrigin = 'anonymous'
await new Promise((res) => { el.onload = res; el.onerror = res; el.src = img.src })
const c = document.createElement('canvas')
c.width = 1; c.height = 1
const ctx = c.getContext('2d')
try { ctx.drawImage(el, 0, 0, 1, 1) } catch (e) { return 'err:' + e.message }
const d = ctx.getImageData(0, 0, 1, 1).data
return d[0] + ',' + d[1] + ',' + d[2]
})
}
// 像素语义判定(2026-11-07)
// 为什么不再比精确 RGB:pixelOf 把图片 drawImage 缩到 1×1 取色,浏览器在
// SW 接管页面后(或不同 color-space/合成路径)会给出 ±1 的通道差(实测蓝 255→254、
// 红 255→254,**蓝色与红色本身仍能明确区分**)。精确比较属于环境脆弱断言。
// 这里改为"主通道判定",强度不降:要求目标通道 > 200 且另两个通道 < 60。
const chans = (s) => String(s).split(',').map(Number)
const isBlue = (s) => { const c = chans(s); return c.length === 3 && c[2] > 200 && c[0] < 60 && c[1] < 60 }
const isRed = (s) => { const c = chans(s); return c.length === 3 && c[0] > 200 && c[1] < 60 && c[2] < 60 }
const isGreen = (s) => { const c = chans(s); return c.length === 3 && c[1] > 200 && c[0] < 60 && c[2] < 60 }
test('1. 画布A 复制 → 切画布B → Ctrl+Shift+V 粘到视口中心且可一次撤销(指针不在画布上时)', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await W.waitSelectedCount(page, 2)
const selA = await page.locator('.iwb-node-selected').count()
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
const raw = await page.evaluate(() => localStorage.getItem('iwb_clipboard'))
const parsed = JSON.parse(raw)
// 回画布库 → 打开第二张画布(跨画布粘贴)
await W.goHome(page)
console.log('[check1] home cards = ' + (await page.locator('.iwb-home-card:not(.iwb-home-new)').count()))
await page.locator('.iwb-home-card:not(.iwb-home-new)').nth(1).dblclick()
await W.waitCanvasOpen(page)
const nodeB0 = await page.locator('.iwb-node').count()
// v3.24.69 起落点跟指针(见 test 17)。把指针停在画布外的导航按钮上 ⇒ 走 fallback:
// 仍按视口中心贴,这条守的就是「指针不可用时不会贴到看不见的地方」。
const nav = await page.locator(W.HOME_NAV).first().boundingBox()
await page.mouse.move(Math.round(nav.x + nav.width / 2), Math.round(nav.y + nav.height / 2))
// v3.24.67:节点/节点组只走 Ctrl+Shift+V(Ctrl+V 不再回退贴节点组 —— 见 test 8)
await realPasteGroup(page)
await W.waitNodeCount(page, nodeB0 + 2, { timeout: 10000 })
const nodeB1 = await page.locator('.iwb-node').count()
const geom = await page.evaluate(() => {
const canvas = document.querySelector('.iwb-canvas')
const cb = canvas.getBoundingClientRect()
const nodes = Array.from(document.querySelectorAll('.iwb-node'))
if (!nodes.length) return null
let minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9
for (const n of nodes) { const r = n.getBoundingClientRect(); if (r.width < 1) continue; minX = Math.min(minX, r.left); minY = Math.min(minY, r.top); maxX = Math.max(maxX, r.right); maxY = Math.max(maxY, r.bottom) }
return { cx: Math.round((minX + maxX) / 2), cy: Math.round((minY + maxY) / 2), ccx: Math.round(cb.left + cb.width / 2), ccy: Math.round(cb.top + cb.height / 2) }
})
await page.keyboard.press('Control+z')
await W.waitNodeCount(page, nodeB0)
const nodeB2 = await page.locator('.iwb-node').count()
console.log('[check1] selA=' + selA + ' clipNodes=' + parsed.nodes.length + ' at=' + typeof parsed.at + ' nodesB: ' + nodeB0 + ' -> ' + nodeB1 + ' -> undo ' + nodeB2)
console.log('[check1] 粘贴组中心 vs 视口中心 = ' + JSON.stringify(geom))
expect(selA).toBe(2)
expect(parsed.nodes.length).toBe(2)
expect(typeof parsed.at).toBe('number')
expect(nodeB1).toBe(nodeB0 + 2)
expect(nodeB2).toBe(nodeB0)
expect(Math.abs(geom.cx - geom.ccx)).toBeLessThan(90)
expect(Math.abs(geom.cy - geom.ccy)).toBeLessThan(90)
expect(errors).toEqual([])
})
// v3.24.68 反转了这条的语义(用户二次裁定:一个键贴所有):
// 原来守的是「Ctrl+C 不碰系统剪贴板」,现在 Ctrl+C **必须**写系统剪贴板,否则 Ctrl+V 贴不出节点组。
// 但当年撤回的教训仍然要守:写进去的必须是**人话**,不能是裸 JSON。
test('2. Ctrl+C 写系统剪贴板:带节点组标记 + 人话摘要,不是裸 JSON', async ({ page }) => {
await boot(page, workspace)
await page.evaluate(() => navigator.clipboard.writeText('外部文本哨兵'))
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
await waitGraphInClipboard(page) // 复制是异步写系统剪贴板:等标记落地再读,别用固定毫秒
const txt = await page.evaluate(() => navigator.clipboard.readText())
console.log('[check2] 系统剪贴板纯文本 = ' + JSON.stringify(String(txt).slice(0, 120)))
expect(txt).toBe('画布A 提示词') // 人话:节点组里的提示词全文
expect(String(txt).indexOf('iwb-clipboard')).toBe(-1) // 不是裸 JSON
expect(String(txt).indexOf('base64')).toBe(-1)
expect(errors).toEqual([])
})
test('3. 系统剪贴板有图:Ctrl+V 新建 ref(不替换选中 ref),Ctrl+Shift+V 仍贴节点组', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
const before = await page.locator('.iwb-node').count()
// 先点空白处清空选择(app 行为:点击已在选中集合内的节点会保持整组选择)
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
const rn = raNode(page)
await rn.locator('img.iwb-ref-single').click({ position: { x: 20, y: 20 } })
await W.waitSelectedCount(page, 1)
const selCnt = await page.locator('.iwb-node-selected').count()
const pixelBefore = await pixelOf(page)
await putImage(page)
await realPaste(page) // 浏览器真正用系统剪贴板里的图片粘贴
await W.waitNodeCount(page, before + 1, { timeout: 10000 })
const afterPaste = await page.locator('.iwb-node').count()
const pixelAfter = await pixelOf(page)
await page.keyboard.press('Control+Shift+v')
await W.waitNodeCount(page, afterPaste + 2)
const afterGroup = await page.locator('.iwb-node').count()
console.log('[check3] 选中 ref 数=' + selCnt + ';nodes ' + before + ' -> 贴图 ' + afterPaste + ' -> Ctrl+Shift+V ' + afterGroup)
console.log('[check3] 选中 ref 像素 before=' + pixelBefore + ' after=' + pixelAfter + '(蓝=0,0,255 原图未被替换;红=255,0,0 被替换)')
expect(selCnt).toBe(1)
expect(afterPaste).toBe(before + 1)
expect(isBlue(pixelBefore), '选中 ref 原图应为蓝(' + pixelBefore + ')').toBe(true)
expect(isBlue(pixelAfter), 'Ctrl+V 贴图不应替换选中 ref,仍应为蓝(' + pixelAfter + ')').toBe(true)
expect(afterGroup).toBe(afterPaste + 2)
expect(errors).toEqual([])
})
test('4. 显式入口替换参考图后可撤销回原图', async ({ page }) => {
await boot(page, workspace)
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
const rn = raNode(page)
await rn.locator('img.iwb-ref-single').click({ position: { x: 20, y: 20 } })
await W.waitSelectedCount(page, 1)
const pixelBefore = await pixelOf(page)
const btn = page.locator('.iwb-node-floatbar button[aria-label="粘贴"]').first()
await expect(btn).toBeVisible()
await putImage(page)
await btn.click()
await W.poll(page, async () => isRed(await pixelOf(page)), { timeout: 12000 }).toBe(true)
const pixelAfter = await pixelOf(page)
await page.keyboard.press('Control+z')
await W.poll(page, async () => isBlue(await pixelOf(page)), { timeout: 12000 }).toBe(true)
const pixelUndo = await pixelOf(page)
console.log('[check4] 像素 before=' + pixelBefore + ' after=' + pixelAfter + ' undo=' + pixelUndo + '(蓝=原图, 红=粘贴图)')
expect(isBlue(pixelBefore), '原图应为蓝(' + pixelBefore + ')').toBe(true)
expect(isRed(pixelAfter), '替换后应为红(' + pixelAfter + ')').toBe(true)
expect(isBlue(pixelUndo), '撤销后应回到蓝(' + pixelUndo + ')').toBe(true)
expect(errors).toEqual([])
})
test('5. TTL:11 分钟前的内部剪贴板不粘贴且被删除', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await page.waitForTimeout(250)
await page.evaluate(() => {
const c = JSON.parse(localStorage.getItem('iwb_clipboard'))
c.at = Date.now() - 11 * 60 * 1000
localStorage.setItem('iwb_clipboard', JSON.stringify(c))
})
await page.reload({ waitUntil: 'domcontentloaded' })
await W.waitHomeReady(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await W.waitCanvasOpen(page)
const before = await page.locator('.iwb-node').count()
// 2026-11-26:⌘V 现在会**主动读系统剪贴板**(mac 上没有编辑焦点时不会派发 paste 事件,
// 这是唯一通路),而系统剪贴板按设计不设 TTL(用户清空即止)。所以先把它清空 ——
// 否则测的就不是「内部剪贴板过期」,而是「系统剪贴板里还有内容」。
await page.evaluate(() => navigator.clipboard.writeText(''))
await page.keyboard.press('Control+v')
await W.poll(page, () => page.evaluate(() => localStorage.getItem('iwb_clipboard')), { timeout: 8000 }).toBeNull()
const after = await page.locator('.iwb-node').count()
const left = await page.evaluate(() => localStorage.getItem('iwb_clipboard'))
console.log('[check5] nodes ' + before + ' -> ' + after + ';条目仍存在=' + (left !== null))
expect(after).toBe(before)
expect(left).toBeNull()
expect(errors).toEqual([])
})
test('6. 粘贴出的 gen 节点不携带旧结果(手写跨标签剪贴板 → Ctrl+Shift+V)', async ({ page }) => {
await boot(page, workspace)
await page.evaluate(() => {
localStorage.setItem('iwb_clipboard', JSON.stringify({
app: 'image-workbench', type: 'iwb-clipboard', at: Date.now(),
nodes: [{ id: 'gx', type: 'gen', x: 0, y: 0, data: { model: 'qwen-image-3.0', provider: 'tuzi', keyGroup: 'daily', size: '1024x1024', variants: 1, result: [{ items: [{ ok: true, url: 'https://img.example.com/old.png' }] }] } }],
edges: [], groups: [],
}))
})
const before = await page.locator('.iwb-node').count()
await page.keyboard.press('Control+Shift+v')
// gen 节点粘贴是异步(先 hydrate 再落画布);这里保留短固定等待 + 计数轮询兜底
await page.waitForTimeout(900)
const after = await page.locator('.iwb-node').count()
const saved = await page.evaluate(() => {
const out = []
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (!/^iwb_ws_/.test(k)) continue
try { const v = JSON.parse(localStorage.getItem(k)); for (const n of (v.nodes || [])) out.push({ id: n.id, type: n.type, result: n.data && n.data.result }) } catch (e) { /* ignore */ }
}
return out
})
const gens = saved.filter((n) => n.type === 'gen')
console.log('[check6] nodes ' + before + ' -> ' + after + ';已保存 gen 节点 result = ' + JSON.stringify(gens.map((g) => g.result)))
expect(after).toBe(before + 1)
expect(gens.length).toBe(1)
expect(gens[0].result).toBeNull()
expect(errors).toEqual([])
})
test('7. Ctrl+Shift+V 永远贴节点组,且浏览器派发的纯文本 paste 被抑制', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
await page.evaluate(() => navigator.clipboard.writeText('这段文本绝不能变成提示词节点'))
const before = await page.locator('.iwb-node').count()
await realPasteGroup(page)
await W.waitNodeCount(page, before + 2)
const after = await page.locator('.iwb-node').count()
const promptTexts = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-node textarea, .iwb-node .iwb-prompt-input')).map((e) => e.value || e.textContent || ''))
const leaked = promptTexts.some((t) => String(t).indexOf('绝不能变成提示词节点') >= 0)
console.log('[check7] nodes ' + before + ' -> ' + after + ';纯文本被贴成提示词节点 = ' + leaked)
expect(after).toBe(before + 2)
expect(leaked).toBe(false)
expect(errors).toEqual([])
})
// ── v3.24.68:统一剪贴板 —— Ctrl+C 把节点组也写进系统剪贴板,Ctrl+V 直接贴回来 ──
// 用户 2026-11-11 二次裁定:一个键贴所有,不再要求记 Ctrl+Shift+V(它降级为后门)。
//
// 注意:本文件原来的测试 8 用 keyboard.press('Control+v'),而 headless Chromium 下这个调用
// **不会派发 paste 事件**(只触发 keydown → probe 提示),所以它从没真正跑过粘贴路径 —— 假绿。
// 下面统一改用 realPaste()(CDP 的编辑命令 'paste',等价于用户真的按下 Ctrl+V)。
test('8. 复制节点后 Ctrl+V 直接贴回节点组(不再需要 Ctrl+Shift+V)', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
// 复制是**异步**写系统剪贴板:等标记真的进了剪贴板再按 Ctrl+V,不要用固定毫秒
await W.poll(page, () => page.evaluate(async () => {
try {
const items = await navigator.clipboard.read()
for (const it of items) {
if (it.types.indexOf('text/html') < 0) continue
const html = await (await it.getType('text/html')).text()
if (html.indexOf('iwb:graph:v1:') >= 0) return true
}
} catch (e) { /* 读不到就再等一轮 */ }
return false
}), { timeout: 10000 }).toBe(true)
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await W.waitNodeCount(page, before + 2, { timeout: 12000 }) // fixture 里 2 个节点(pa + ra)
const after = await page.locator('.iwb-node').count()
console.log('[check8] nodes ' + before + ' -> ' + after + '(复制 2 个,Ctrl+V 应贴回 2 个)')
expect(after).toBe(before + 2)
expect(errors).toEqual([])
})
test('9. 粘贴图片不再自动下载原图(粘贴 ≠ 另存到下载目录)', async ({ page }) => {
await boot(page, workspace)
const downloads = []
page.on('download', (d) => downloads.push(d.suggestedFilename()))
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
await putImage(page)
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await W.waitNodeCount(page, before + 1, { timeout: 10000 })
// 等新节点的图真正渲染出来:说明 FileReader → 压缩 → 落画布这条回调链已经跑完,
// 旧实现在这条链的末尾同步调 downloadUrl —— 此刻还没有下载事件才算真的取消了。
await W.poll(page, () => page.evaluate(() => {
const nodes = document.querySelectorAll('.iwb-node')
const last = nodes[nodes.length - 1]
const img = last && last.querySelector('img.iwb-ref-single')
return !!(img && img.getAttribute('src'))
}), { timeout: 10000 }).toBe(true)
const after = await page.locator('.iwb-node').count()
console.log('[check9] nodes ' + before + ' -> ' + after + ';触发下载数 = ' + downloads.length)
expect(after).toBe(before + 1)
expect(downloads).toEqual([])
expect(errors).toEqual([])
})
test('10. 多张图片一起粘 → 每一张都建为参考图节点(旧实现只取第一张)', async ({ page }) => {
await boot(page, workspace)
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
const before = await page.locator('.iwb-node').count()
// 合成一次真实 paste 事件(CDP 无法把「两个文件」放进系统剪贴板)
await page.evaluate(() => {
const make = (rgb, name) => new Promise((res) => {
const cv2 = document.createElement('canvas')
cv2.width = 8; cv2.height = 8
const c2 = cv2.getContext('2d')
c2.fillStyle = 'rgb(' + rgb.join(',') + ')'
c2.fillRect(0, 0, 8, 8)
cv2.toBlob((bl) => res(new File([bl], name, { type: 'image/png' })), 'image/png')
})
return Promise.all([make([255, 0, 0], 'r.png'), make([0, 255, 0], 'g.png'), make([0, 0, 255], 'b.png')]).then((files) => {
const dt = new DataTransfer()
for (const f of files) dt.items.add(f)
const ev = new Event('paste', { bubbles: true, cancelable: true })
Object.defineProperty(ev, 'clipboardData', { value: dt })
window.dispatchEvent(ev)
})
})
await W.waitNodeCount(page, before + 3, { timeout: 15000 })
const after = await page.locator('.iwb-node').count()
// 落盘提示是异步 setState,用轮询等文案出现(不要用固定毫秒)。
// 顶栏状态项可能有多枚(如常驻的「请设置 Key」),拼起来判。
const statusText = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-status-item')).map((x) => String(x.textContent || '')).join(' | '))
await W.poll(page, statusText, { timeout: 8000 }).toContain('3 张')
const toast = await statusText()
console.log('[check10] nodes ' + before + ' -> ' + after + ';提示 = ' + JSON.stringify(toast))
expect(after).toBe(before + 3)
expect(toast).toContain('3 张')
expect(errors).toEqual([])
})
test('11. 点过「粘贴替换」之后再粘贴图片,不会把这张参考图再替换一次', async ({ page }) => {
await boot(page, workspace)
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
const rn = raNode(page)
await rn.locator('img.iwb-ref-single').click({ position: { x: 20, y: 20 } })
await W.waitSelectedCount(page, 1)
// ① 显式替换:系统剪贴板 = 红 → 点气泡「粘贴」→ 变成红
await putColor(page, [255, 0, 0])
const btn = page.locator('.iwb-node-floatbar button[aria-label="粘贴"]').first()
await expect(btn).toBeVisible()
await btn.click()
await W.poll(page, async () => isRed(await pixelOf(page)), { timeout: 12000 }).toBe(true)
// ② 之后普通 Ctrl+V 粘一张绿图:应该**新建节点**,而这张 ref 必须仍是红
// (旧实现的待命监听不摘除 → 这里会把 ref 又替换成绿)
await putColor(page, [0, 255, 0])
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await W.waitNodeCount(page, before + 1, { timeout: 10000 })
// 等新节点真的有图 → 说明这次粘贴的处理链已结束(残留监听若存在,此刻也已生效)
await W.poll(page, () => page.evaluate(() => {
const nodes = document.querySelectorAll('.iwb-node')
const last = nodes[nodes.length - 1]
const img = last && last.querySelector('img.iwb-ref-single')
return !!(img && img.getAttribute('src'))
}), { timeout: 10000 }).toBe(true)
const pixel = await pixelOf(page)
console.log('[check11] nodes ' + before + ' -> ' + (await page.locator('.iwb-node').count()) + ';原 ref 像素 = ' + pixel + '(应仍为红,未被第二次替换)')
expect(isRed(pixel), '原 ref 应仍为红(' + pixel + ');变绿说明残留监听又替换了一次').toBe(true)
expect(errors).toEqual([])
})
test('12. 图片粘进提示词输入框:不落节点,但给一句说明(旧实现纯静默)', async ({ page }) => {
requireEnvDeps(test, '需要真实剪贴板读图能力(无头浏览器读不到图像)')
await boot(page, workspace)
const ta = page.locator('.iwb-node').first().locator('textarea').first()
await ta.dblclick()
await ta.evaluate((el) => el.focus())
await W.poll(page, () => page.evaluate(() => (document.activeElement && document.activeElement.tagName) || '')).toBe('TEXTAREA')
const before = await page.locator('.iwb-node').count()
await page.evaluate(() => new Promise((res) => {
const cv = document.createElement('canvas')
cv.width = 8; cv.height = 8
const c2 = cv.getContext('2d')
c2.fillStyle = 'rgb(255,0,0)'
c2.fillRect(0, 0, 8, 8)
cv.toBlob((bl) => {
const dt = new DataTransfer()
dt.items.add(new File([bl], 'r.png', { type: 'image/png' }))
const ev = new Event('paste', { bubbles: true, cancelable: true })
Object.defineProperty(ev, 'clipboardData', { value: dt })
document.activeElement.dispatchEvent(ev)
res()
}, 'image/png')
}))
const statusText = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-status-item')).map((x) => String(x.textContent || '')).join(' | '))
await W.poll(page, statusText, { timeout: 8000 }).toContain('输入框')
const after = await page.locator('.iwb-node').count()
console.log('[check12] nodes ' + before + ' -> ' + after + ';提示 = ' + JSON.stringify(await statusText()))
expect(after).toBe(before)
expect(errors).toEqual([])
})
// 等「节点组标记」真的进了系统剪贴板(复制是异步写,不能靠固定毫秒)
const waitGraphInClipboard = (page) => W.poll(page, () => page.evaluate(async () => {
try {
const items = await navigator.clipboard.read()
for (const it of items) {
if (it.types.indexOf('text/html') < 0) continue
const html = await (await it.getType('text/html')).text()
if (html.indexOf('iwb:graph:v1:') >= 0) return true
}
} catch (e) { /* 读不到就再等一轮 */ }
return false
}), { timeout: 10000 }).toBe(true)
const clearSelection = async (page) => {
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
}
// 「系统剪贴板里那段文字」必须是唯一被贴出来的东西:证明有标记才贴节点组,没标记绝不误贴
test('13. 复制节点后系统剪贴板被别的文字覆盖 → Ctrl+V 贴文字,不误贴旧节点组', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
await waitGraphInClipboard(page)
// 模拟用户又去别处复制了一段文字:系统剪贴板被替换(内部剪贴板仍是刚才那 2 个节点)
await page.evaluate(async () => {
await navigator.clipboard.write([new ClipboardItem({ 'text/plain': new Blob(['外部复制的一段文字'], { type: 'text/plain' }) })])
})
await clearSelection(page)
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await W.waitNodeCount(page, before + 1, { timeout: 12000 })
const lastText = await page.evaluate(() => {
const ns = Array.from(document.querySelectorAll('.iwb-node'))
const n = ns[ns.length - 1]
const ta = n && n.querySelector('textarea')
return ta ? ta.value : ''
})
const after = await page.locator('.iwb-node').count()
console.log('[check13] nodes ' + before + ' -> ' + after + ';新节点文本 = ' + JSON.stringify(lastText))
expect(after).toBe(before + 1) // 只贴 1 个提示词节点,而不是把 2 个旧节点贴回来
expect(lastText).toBe('外部复制的一段文字') // 贴的是剪贴板里的文字
expect(errors).toEqual([])
})
// 剪贴板 API 不可写时(老浏览器 / 非 HTTPS / file://)复制只进内部那份,Ctrl+V 仍要能贴
test('14. 系统剪贴板为空(写空文本)时 Ctrl+V 回退贴内部剪贴板', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
await waitGraphInClipboard(page)
await page.evaluate(async () => {
await navigator.clipboard.write([new ClipboardItem({ 'text/plain': new Blob([''], { type: 'text/plain' }) })])
})
await clearSelection(page)
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await W.waitNodeCount(page, before + 2, { timeout: 12000 })
const after = await page.locator('.iwb-node').count()
console.log('[check14] nodes ' + before + ' -> ' + after + '(空剪贴板应回退贴内部那 2 个节点)')
expect(after).toBe(before + 2)
expect(errors).toEqual([])
})
// 老 bug 回归:旧实现用 300ms 定时器 + 递增 token 回退,连按 3 次只贴 1 份。
// 现在每次 paste 事件独立处理 → 3 次 = 3 份。
test('15. 复制一份、连按 3 次 Ctrl+V → 贴出 3 份(旧实现只贴 1 份)', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
await waitGraphInClipboard(page)
await clearSelection(page)
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await realPaste(page)
await realPaste(page)
await W.waitNodeCount(page, before + 6, { timeout: 25000 }) // 2 个节点 × 3 次
const after = await page.locator('.iwb-node').count()
console.log('[check15] nodes ' + before + ' -> ' + after + '(3 次粘贴 = +6)')
expect(after).toBe(before + 6)
expect(errors).toEqual([])
})
// 旧实现把裸 JSON 写进系统剪贴板 → 粘到别的应用是一坨 JSON(当年因此被撤回)。
// 现在 text/plain 是「提示词全文」或「N 个节点」。
test('16. 复制节点后粘到别的应用 → 是可读文字,不是一坨 JSON', async ({ page, context }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await W.waitInternalClipboard(page)
await waitGraphInClipboard(page)
// 同源另开一页(剪贴板权限按 origin 授予),塞一个 textarea 当作「别的应用」
const p2 = await context.newPage()
await p2.goto('/', { waitUntil: 'domcontentloaded' })
await p2.evaluate(() => {
const ta = document.createElement('textarea')
ta.id = 'iwb-probe-ta'
ta.style.cssText = 'position:fixed;left:0;top:0;width:600px;height:200px;z-index:99999'
document.body.appendChild(ta)
})
await p2.click('#iwb-probe-ta')
await realPaste(p2)
const got = await p2.evaluate(() => document.getElementById('iwb-probe-ta').value)
await p2.close()
console.log('[check16] 粘到别的应用 = ' + JSON.stringify(got))
expect(got).toBe('画布A 提示词') // fixture 里 pa 节点的提示词全文
expect(got.indexOf('{')).toBe(-1) // 不是 JSON
expect(got.indexOf('base64')).toBe(-1) // 也不是图片数据
expect(errors).toEqual([])
})
// ── v3.24.69:粘贴落点跟鼠标(用户实测后裁定,推翻「不跟鼠标」)──────────────
// 旧行为:落点 = 视口中心 + 自动避让。连贴几张都得从中心把节点拖走,指哪贴哪更顺手。
// 判据用屏幕坐标比:DOM boundingBox 与鼠标点都已是屏幕像素,不掺 viewport 换算。
// v3.24.74 收紧判据:语义从「节点中心对准指针」改成「**左上角**对准指针」——
// 旧语义要用 nodeTypeH 的估算高度反推左上角(prompt 216 vs 实测 ~90),视觉中心恒定偏上 63px。
// 所以这里不再比中心(那会掩盖偏差),直接比左上角,容差 24px(findSpot 的 20px 间隙 + 取整)。
test('17. 粘贴落点跟随鼠标(左上角对准指针,偏差 <24px)', async ({ page }) => {
await boot(page, workspace)
await page.evaluate(async () => {
await navigator.clipboard.write([new ClipboardItem({ 'text/plain': new Blob(['落点跟随测试'], { type: 'text/plain' }) })])
})
const cv = await page.locator('.iwb-canvas').boundingBox()
// 选远离 fixture 两个节点的空地;只移动不点击(点击会选中节点/进入拖动)
const tx = Math.round(cv.x + cv.width * 0.62)
const ty = Math.round(cv.y + cv.height * 0.78)
await page.mouse.move(tx, ty)
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await W.waitNodeCount(page, before + 1, { timeout: 12000 })
const box = await page.locator('.iwb-node').last().boundingBox()
const nx = Math.round(box.x)
const ny = Math.round(box.y)
console.log('[check17] 指针 (' + tx + ',' + ty + ') → 新节点左上角 (' + nx + ',' + ny + ')')
// 旧语义下左上角会偏上 (估算高 - 实际高)/2 ≈ 63px,且横向偏半个节点宽 ⇒ 这条会红
expect(Math.abs(nx - tx)).toBeLessThan(24)
expect(Math.abs(ny - ty)).toBeLessThan(24)
expect(errors).toEqual([])
})
// ── v3.24.70:焦点落在节点输入框里时,Ctrl+C / Ctrl+V 曾双双静默失效 ──────────
// 用户实测:「复制本地的图片到画布,后面复制粘贴就不起作用了」。
// 根因:onKey 第一行只要焦点在 INPUT/TEXTAREA 就无条件 return —— 而原生复制在
// **没有选中文字**时本来就拿不到任何东西,于是画布既不复制也不粘贴,且一句提示都没有。
// 触发路径极自然:粘完图片后节点就落在鼠标下面,用户「点一下节点」点中的正是图片链接框。
test('18. 焦点在节点输入框里按 Ctrl+C 仍能复制节点(旧实现静默失效)', async ({ page }) => {
await boot(page, workspace)
await page.keyboard.press('Control+a')
await W.waitSelectedCount(page, 2)
const url = page.locator('.iwb-ref-url-input').first()
await url.click()
const active = await page.evaluate(() => String((document.activeElement && document.activeElement.className) || ''))
console.log('[check18] 焦点落在 = ' + active)
expect(active).toContain('iwb-ref-url-input')
// 哨兵:复制真的发生了才会被覆盖
await page.evaluate(() => navigator.clipboard.writeText('哨兵-未被复制'))
await page.keyboard.press('Control+c')
await waitGraphInClipboard(page)
const txt = await page.evaluate(() => navigator.clipboard.readText())
console.log('[check18] 系统剪贴板 = ' + JSON.stringify(String(txt).slice(0, 60)))
expect(txt).toBe('画布A 提示词')
await W.poll(page, () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-status-item')).map((x) => String(x.textContent || '')).join(' | ')), { timeout: 8000 }).toContain('已复制 2 个节点')
expect(errors).toEqual([])
})
test('19. 焦点在节点输入框里粘节点组:带提示词→粘文字;只有摘要→拦下且不污染输入框', async ({ page }) => {
requireEnvDeps(test, '需要真实剪贴板读图能力(无头浏览器读不到图像)')
await boot(page, workspace)
// 情形 A(v3.24.70 的原始诉求):复制的是**带提示词**的节点组 → 粘进输入框应该得到那段提示词文字。
// 2026-11-26 改口径:这类粘贴放行原生(拦掉等于把「复制提示词贴到别处」这个用法做没了)。
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await waitGraphInClipboard(page)
const url = page.locator('.iwb-ref-url-input').first()
await url.click()
const before = await page.locator('.iwb-node').count()
await realPaste(page)
await page.waitForTimeout(400)
const val = await url.inputValue()
console.log('[check19] 带提示词 → 输入框 = ' + JSON.stringify(val))
expect(val).toBe('画布A 提示词')
expect(await page.locator('.iwb-node').count()).toBe(before)
// 情形 B(本次修的缺陷):复制的只有图片节点,摘要退化成「1 个节点」。
// 旧实现只弹提示不拦,摘要被原生粘贴打进输入框,把用户的提示词改掉了。
await url.fill('')
await clearSelection(page)
await page.locator('.iwb-node').nth(1).click()
await W.waitSelectedCount(page, 1)
await page.keyboard.press('Control+c')
await page.waitForTimeout(400)
await url.click()
await realPaste(page)
await W.poll(page, () => statusText(page), { timeout: 8000 }).toContain('画布')
const val2 = await url.inputValue()
console.log('[check19] 只有摘要 → 输入框 = ' + JSON.stringify(val2) + ';提示 = ' + JSON.stringify(await statusText(page)))
expect(val2).toBe('')
expect(await page.locator('.iwb-node').count()).toBe(before)
expect(errors).toEqual([])
})
// ── v3.24.74:拖进非图片文件曾完全静默;MIME 不填的 PNG 反而被静默丢掉 ──────────
// 旧实现是 `if (!f.type || f.type.indexOf('image/') !== 0) continue`:
// ① 拖一个 PDF / HEIC 进画布,画布毫无反应(用户只会以为"拖放坏了");
// ② Windows 资源管理器「复制文件」出来的 PNG 恰好 type 为空 ⇒ 能拖进来的图被直接丢掉;
// ③ HEIC 有 image/heic 而混过去,压缩失败后按原图导入 ⇒ 画布上多一张打不开的坏图。
// 三条的根因是「准入判据写在三个地方且互相不一致」,修法是统一到 src/image-admit.js。
test('20. 拖入 PDF 必须给提示(不静默);MIME 为空的 PNG 仍能落成参考图', async ({ page }) => {
await boot(page, workspace)
const before = await page.locator('.iwb-node').count()
await dropFiles(page, [{ name: '合同.pdf', type: 'application/pdf' }])
await W.poll(page, () => statusText(page), { timeout: 8000 }).toContain('暂不支持')
const afterPdf = await page.locator('.iwb-node').count()
console.log('[check20] 拖 PDF 后节点数 ' + before + ' -> ' + afterPdf + '(不该多出节点)')
expect(afterPdf).toBe(before)
// 同一个落点再拖一张「type 为空」的 PNG:按扩展名承认,必须真的落成参考图
await dropFiles(page, [{ name: 'no-mime.png', type: '', b64: PNG_RED_B64 }])
await W.waitNodeCount(page, before + 1, { timeout: 12000 })
console.log('[check20] 拖 type 为空的 PNG 后节点数 = ' + (await page.locator('.iwb-node').count()))
expect(errors).toEqual([])
})
// ── v3.24.75:同一张图连粘两次,画布上会堆出两个一模一样的参考图节点 ────────────
// 真实触发路径:截图 → Ctrl+V(图还没出来,以为没粘上)→ 再按一次 ⇒ 两张同样的图。
// 判据必须同时守住两件事,缺一条就会把功能做坏:
// ① 重复的不该落(否则去重没生效);
// ② 换一张图必须照常落(否则变成"以后都粘不进来"的严重回归)。
// 还要求重复时**选中已有节点**:只给一句提示而东西在屏幕外,用户等于什么都没看到。
test('21. 同一张图连粘两次只建一个节点;换一张图照常落地', async ({ page }) => {
requireEnvDeps(test, '需要真实剪贴板读图能力(无头浏览器读不到图像)')
await boot(page, workspace)
const cv = await page.locator('.iwb-canvas').boundingBox()
await page.mouse.click(cv.x + cv.width - 60, cv.y + 130)
await W.waitSelectedCount(page, 0)
const before = await page.locator('.iwb-node').count()
// 用固定字节的图(不用 canvas 现画):两次粘贴的输入必须逐字节相同,否则测的是编码抖动
await putImage(page, PNG_RED_B64)
await realPaste(page)
await W.waitNodeCount(page, before + 1, { timeout: 12000 })
const afterFirst = await page.locator('.iwb-node').count()
// 剪贴板内容不变,再粘一次 = 用户重复按了一次 Ctrl+V
await realPaste(page)
await W.poll(page, () => statusText(page), { timeout: 8000 }).toContain('已经在画布上')
const afterDup = await page.locator('.iwb-node').count()
const sel = await page.locator('.iwb-node-selected').count()
// 换一张不同的图(绿色,8×8 由 canvas 生成):必须照常落成新节点
await putColor(page, [0, 255, 0])
await realPaste(page)
await W.waitNodeCount(page, before + 2, { timeout: 12000 })
const afterOther = await page.locator('.iwb-node').count()
console.log('[check21] nodes ' + before + ' -> 首粘 ' + afterFirst + ' -> 重复粘 ' + afterDup + '(选中 ' + sel + ' 个)-> 换图 ' + afterOther)
expect(afterFirst).toBe(before + 1)
expect(afterDup, '同一张图再粘不该多出节点').toBe(before + 1)
expect(sel, '重复粘贴时应选中已有节点,用户才知道它在哪').toBe(1)
expect(afterOther, '不同图必须照常落地').toBe(before + 2)
expect(errors).toEqual([])
})