/* HEL-669 导出尾帧 browser validation against the isolated stack: * vite dev (5173) → backend (8247) → fake ComfyUI (18188), seeded by seed.py. * * node e2e/lastframe.mjs [dir-with-real-generated-mp4s] * * Every clip reaches the UI through the normal generate → worker download * path (fake ComfyUI serves it via the `video_file` mode). Real clips come * from the optional directory; portrait / square / black-tail / all-black / * WebM clips are synthesised in the browser with MediaRecorder. * Prints PASS/FAIL per check; exported PNGs + screenshots go to * e2e/shots/lastframe/. */ import { chromium } from 'playwright'; import { spawn } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const ROOT = path.dirname(fileURLToPath(import.meta.url)); const OUT = path.join(ROOT, 'shots', 'lastframe'); const SAMPLES = path.join(OUT, 'samples'); fs.mkdirSync(SAMPLES, { recursive: true }); const API = 'http://127.0.0.1:8247'; const WEB = 'http://127.0.0.1:5173'; const MODE_FILE = path.join(ROOT, 'fake_mode.json'); const REAL_DIR = process.argv[2] ? path.resolve(process.argv[2]) : null; let failures = 0; function ok(name, cond, extra = '') { console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ' — ' + extra : ''}`); if (!cond) failures++; } const api = async (p, init) => { const r = await fetch(API + p, { headers: { 'Content-Type': 'application/json' }, ...init }); return r.json(); }; const fileUrl = (p) => `/api/file?path=${encodeURIComponent(p)}`; const sha = (p) => crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex'); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** Generate a studio video job whose output is `file`; returns the saved asset path. */ async function generateWith(file, prompt) { fs.writeFileSync(MODE_FILE, JSON.stringify({ mode: 'ok', delay_sec: 0, videos: true, video_file: file })); const r = await api('/api/playground/generate', { method: 'POST', body: JSON.stringify({ workflow_id: 2, input_values: { 1: prompt, 2: 6 }, source: 'studio-video' }), }); const id = r.job.id; for (let i = 0; i < 150; i++) { const j = (await api('/api/playground/jobs')).find((x) => x.id === id); if (j?.status === 'done') return j.output_paths[0]; if (j?.status === 'failed') throw new Error(`job ${id} failed: ${j.error}`); await sleep(200); } throw new Error(`job ${id} timed out`); } /** PNG width/height from the IHDR chunk. */ function pngSize(buf) { const sig = buf.subarray(0, 8).toString('hex') === '89504e470d0a1a0a'; return sig ? { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) } : null; } /** Browser-side: synthesise a clip; returns base64 bytes. */ async function synth(page, spec) { return page.evaluate(async ({ w, h, seconds, fps, mime, mode }) => { const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); const total = Math.round(seconds * fps); const paint = (i) => { const left = (total - i) / fps; if (mode === 'allblack' || (mode === 'fadeblack' && left <= 0.4)) ctx.fillStyle = '#000'; else if (mode === 'marker' && left <= 0.5) ctx.fillStyle = '#d0208c'; else ctx.fillStyle = mode === 'fadeblack' ? '#e08a1e' : '#00b4c8'; ctx.fillRect(0, 0, w, h); if (mode !== 'allblack' && !(mode === 'fadeblack' && left <= 0.4)) { ctx.fillStyle = '#fff'; ctx.fillRect(((i * 7) % w) | 0, (h / 3) | 0, (w / 10) | 0, (h / 10) | 0); ctx.font = `${(h / 12) | 0}px sans-serif`; ctx.fillText(`#${i}`, 12, h - 24); } }; paint(0); const stream = canvas.captureStream(fps); const rec = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 4e6 }); const chunks = []; rec.ondataavailable = (e) => e.data.size && chunks.push(e.data); const stopped = new Promise((r) => (rec.onstop = r)); rec.start(100); for (let i = 0; i < total; i++) { paint(i); await new Promise((r) => setTimeout(r, 1000 / fps)); } await new Promise((r) => setTimeout(r, 150)); rec.stop(); await stopped; const buf = new Uint8Array(await new Blob(chunks).arrayBuffer()); let s = ''; for (let i = 0; i < buf.length; i += 0x8000) s += String.fromCharCode(...buf.subarray(i, i + 0x8000)); return btoa(s); }, spec); } /** Browser-side: stats of a PNG + the frame an independent player shows at `at`. */ async function inspectPng(page, b64, src, at) { return page.evaluate( async ({ b64, src, at }) => { const S = 64; const grab = (el) => { const c = document.createElement('canvas'); c.width = S; c.height = S; const x = c.getContext('2d'); x.drawImage(el, 0, 0, S, S); return x.getImageData(0, 0, S, S).data; }; const img = new Image(); img.src = `data:image/png;base64,${b64}`; await img.decode(); const a = grab(img); let sum = 0; for (let i = 0; i < a.length; i += 4) sum += 0.2126 * a[i] + 0.7152 * a[i + 1] + 0.0722 * a[i + 2]; const c = (S / 2) * S * 4 + (S / 2) * 4; const center = [a[c], a[c + 1], a[c + 2]]; const diffAt = async (t) => { const v = document.createElement('video'); v.muted = true; v.src = src; await new Promise((r, j) => ((v.onloadeddata = r), (v.onerror = j))); let d = v.duration; if (!Number.isFinite(d)) { v.currentTime = 1e101; await new Promise((r) => (v.onseeked = r)); d = v.duration; } v.currentTime = t < 0 ? Math.max(0, d + t) : t; await new Promise((r) => (v.onseeked = r)); await new Promise((r) => setTimeout(r, 120)); const b = grab(v); let diff = 0; for (let i = 0; i < a.length; i += 4) diff += Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]); return { diff: diff / (S * S * 3), duration: d, w: v.videoWidth, h: v.videoHeight }; }; const tail = await diffAt(at); const start = await diffAt(0); return { mean: sum / (S * S), center, tail, start }; }, { b64, src, at }, ); } /** Verify one downloaded PNG against its source clip. */ async function verifyDownload(page, label, download, assetPath, expect = {}) { const name = download.suggestedFilename(); const dest = path.join(OUT, name); await download.saveAs(dest); const buf = fs.readFileSync(dest); const size = pngSize(buf); const base = path.basename(assetPath).replace(/\.[^.]+$/, ''); const m = name.match(/_尾帧_(\d+\.\d{3})s\.png$/); ok(`${label}: 文件名对应原视频与尾帧时间`, name.startsWith(base + '_尾帧_') && !!m, name); ok(`${label}: 是 PNG`, !!size); const st = await inspectPng(page, buf.toString('base64'), fileUrl(assetPath), -0.05); ok( `${label}: 尺寸等于视频原生尺寸`, size && size.w === st.tail.w && size.h === st.tail.h, `${size?.w}×${size?.h} vs 视频 ${st.tail.w}×${st.tail.h}`, ); const t = m ? Number(m[1]) : NaN; const back = st.tail.duration - t; if (expect.fellBack) { ok(`${label}: 片尾黑屏时回退到非黑帧`, back > 0.3 && back <= 1.05, `t=${t}s, 片长 ${st.tail.duration.toFixed(3)}s`); } else { ok(`${label}: 取的是片尾(距结尾 ≤0.06s)`, back >= 0 && back <= 0.06, `t=${t}s, 片长 ${st.tail.duration.toFixed(3)}s`); ok(`${label}: 与独立播放器片尾画面一致`, st.tail.diff < 6, `平均差 ${st.tail.diff.toFixed(2)},与首帧差 ${st.start.diff.toFixed(2)}`); } ok(`${label}: 非黑帧/空白帧`, st.mean > 20, `平均亮度 ${st.mean.toFixed(1)}`); if (expect.center) { const [r, g, b] = st.center; ok(`${label}: 画面为片尾标记色`, expect.center([r, g, b]), `中心像素 rgb(${r},${g},${b})`); } return { name, dest, size }; } /** Lightweight side servers: no-CORS, CORS, and a never-answering one. */ function sideServers() { const code = ` import http.server, socketserver, sys, threading, time, os os.chdir(sys.argv[1]) class NoCors(http.server.SimpleHTTPRequestHandler): def log_message(self, *a): pass class Cors(NoCors): def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') super().end_headers() class Hang(http.server.BaseHTTPRequestHandler): def do_GET(self): time.sleep(60) def log_message(self, *a): pass for port, h in ((18190, NoCors), (18192, Cors), (18191, Hang)): s = socketserver.ThreadingTCPServer(('127.0.0.1', port), h) s.daemon_threads = True threading.Thread(target=s.serve_forever, daemon=True).start() print('up', flush=True) time.sleep(3600) `; const proc = spawn('python3', ['-c', code, SAMPLES], { stdio: ['ignore', 'pipe', 'inherit'] }); return new Promise((resolve) => proc.stdout.once('data', () => resolve(proc))); } const isMagenta = ([r, g, b]) => r > 150 && g < 90 && b > 90; const lastToast = (page) => page.locator('.toast-host .toast .msg').last(); const run = async () => { const settings = await api('/api/settings'); const ASSETS = settings.assets_dir; const browser = await chromium.launch(); const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, acceptDownloads: true }); const page = await ctx.newPage(); page.on('pageerror', (e) => console.log('PAGEERROR:', e.message)); await page.goto(`${WEB}/video`); await page.waitForSelector('#desk-prompt', { timeout: 20000 }); // ---------- 样本:真实生成视频 + 合成横/竖/方/黑尾 ---------- const clips = []; if (REAL_DIR) { for (const f of fs.readdirSync(REAL_DIR).filter((x) => x.endsWith('.mp4')).sort()) { clips.push({ label: `真实·${f}`, file: path.join(REAL_DIR, f), prompt: `尾帧验证 ${f}`, real: true }); } } const specs = [ { key: 'portrait', w: 720, h: 1280, mime: 'video/mp4;codecs=avc1', mode: 'marker', ext: 'mp4' }, { key: 'square', w: 768, h: 768, mime: 'video/mp4;codecs=avc1', mode: 'marker', ext: 'mp4' }, { key: 'landscape-webm', w: 1280, h: 720, mime: 'video/webm;codecs=vp9', mode: 'marker', ext: 'webm' }, { key: 'fadeblack', w: 960, h: 540, mime: 'video/mp4;codecs=avc1', mode: 'fadeblack', ext: 'mp4' }, { key: 'allblack', w: 640, h: 360, mime: 'video/mp4;codecs=avc1', mode: 'allblack', ext: 'mp4' }, ]; const synthFiles = {}; for (const s of specs) { const b64 = await synth(page, { ...s, seconds: 2.4, fps: 24 }); const f = path.join(SAMPLES, `synth-${s.key}.${s.ext}`); fs.writeFileSync(f, Buffer.from(b64, 'base64')); synthFiles[s.key] = f; } ok('合成竖屏/方形/WebM/黑尾样本', Object.values(synthFiles).every((f) => fs.statSync(f).size > 1000)); clips.push({ label: '竖屏 720×1280', file: synthFiles.portrait, prompt: '尾帧验证 竖屏', center: isMagenta }); clips.push({ label: '方形 768×768', file: synthFiles.square, prompt: '尾帧验证 方形', center: isMagenta }); clips.push({ label: '黑尾 960×540', file: synthFiles.fadeblack, prompt: '尾帧验证 黑尾', fellBack: true }); for (const c of clips) c.asset = await generateWith(c.file, c.prompt); ok('样本均经平台生成流程落盘', clips.every((c) => c.asset && fs.existsSync(c.asset)), `${clips.length} 段`); const hashes = Object.fromEntries(clips.map((c) => [c.asset, sha(c.asset)])); const jobsBefore = (await api('/api/playground/jobs')).length; // ---------- 生成结果页(检视区)---------- await page.reload(); await page.waitForSelector('.take', { timeout: 20000 }); const exportBtn = page.locator('.inspector .actions button', { hasText: '导出尾帧' }); for (const c of clips) { await page.locator('.take', { hasText: c.prompt }).first().click(); await page.waitForSelector('.inspector .stage-media video', { timeout: 10000 }); await page.waitForTimeout(400); // The user's own player must not jump while we take the frame. await page.evaluate(async () => { const v = document.querySelector('.inspector .stage-media video'); v.pause(); if (v.readyState < 1) await new Promise((r) => (v.onloadedmetadata = r)); v.currentTime = 0.5; await new Promise((r) => (v.onseeked = r)); }); const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 40000 }), exportBtn.click()]); await verifyDownload(page, `检视区·${c.label}`, dl, c.asset, c); const player = await page.evaluate(() => { const v = document.querySelector('.inspector .stage-media video'); return { t: v.currentTime, paused: v.paused }; }); ok(`检视区·${c.label}: 用户播放器位置未被改动`, Math.abs(player.t - 0.5) < 0.01 && player.paused, `t=${player.t}`); await page.waitForTimeout(200); ok(`检视区·${c.label}: 成功提示`, ((await lastToast(page).textContent()) || '').startsWith('已导出尾帧')); } await page.screenshot({ path: path.join(OUT, '01-inspector.png') }); // 加载中:视频响应被拖慢时按钮进入忙碌态且不可重复点 const slow = clips[0]; await page.locator('.take', { hasText: slow.prompt }).first().click(); await page.waitForTimeout(500); await page.route('**/api/file?**', async (route) => { await sleep(1500); await route.continue(); }); const dlSlow = page.waitForEvent('download', { timeout: 40000 }); await exportBtn.click(); await page.waitForTimeout(300); const busyBtn = page.locator('.inspector .actions button', { hasText: '正在导出尾帧' }); ok('加载中:按钮显示「正在导出尾帧…」且禁用', (await busyBtn.count()) === 1 && (await busyBtn.isDisabled())); await page.screenshot({ path: path.join(OUT, '02-inspector-busy.png') }); await dlSlow; await page.unroute('**/api/file?**'); await page.waitForTimeout(200); ok('加载结束:按钮恢复可用', (await exportBtn.count()) === 1 && !(await exportBtn.isDisabled())); ok('导出不改原视频文件', clips.every((c) => sha(c.asset) === hashes[c.asset])); ok('导出不新增/改动生成记录', (await api('/api/playground/jobs')).length === jobsBefore); // 图片结果(生图台)不出现导出尾帧 fs.writeFileSync(MODE_FILE, JSON.stringify({ mode: 'ok', delay_sec: 0 })); await api('/api/playground/generate', { method: 'POST', body: JSON.stringify({ workflow_id: 1, input_values: { 1: '尾帧验证 图片', 2: 42 }, source: 'studio-image' }), }); await sleep(1500); await page.goto(`${WEB}/image`); await page.locator('.take', { hasText: '尾帧验证 图片' }).first().click(); await page.waitForSelector('.inspector .stage-media img', { timeout: 10000 }); ok('图片结果不显示导出尾帧', (await page.locator('.inspector .actions button', { hasText: '导出尾帧' }).count()) === 0); // ---------- 资料库 → 共用播放弹层 ---------- await page.goto(`${WEB}/library`); await page.waitForSelector('.card .media', { timeout: 20000 }); for (const c of clips.filter((x) => x.real).slice(0, 1).concat(clips.filter((x) => x.center).slice(0, 1))) { const name = path.basename(c.asset); await page.locator(`.card .media[title="${name}"]`).first().click(); await page.waitForSelector('.backdrop .player-frame video', { timeout: 10000 }); const tool = page.locator('.backdrop .toolbar button[aria-label="导出尾帧"]'); ok(`弹层·${c.label}: 工具栏有导出尾帧按钮`, (await tool.count()) === 1); const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 40000 }), tool.click()]); await verifyDownload(page, `弹层·${c.label}`, dl, c.asset, c); ok(`弹层·${c.label}: 点击后弹层不关闭`, await page.locator('.backdrop').isVisible()); await page.waitForTimeout(250); const toastOnTop = await page.evaluate(() => { const el = document.querySelector('.toast-host .toast:last-child'); if (!el) return false; const r = el.getBoundingClientRect(); return el.contains(document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2)); }); ok(`弹层·${c.label}: 提示浮在弹层之上可见`, toastOnTop); await page.screenshot({ path: path.join(OUT, `03-lightbox-${c.center ? 'square' : 'real'}.png`) }); await page.keyboard.press('Escape'); await page.waitForTimeout(200); } // ---------- 失败场景(真实提示链路:exportLastFrame → Toast)---------- fs.mkdirSync(path.join(ASSETS, 'e2e-lastframe'), { recursive: true }); const junk = path.join(ASSETS, 'e2e-lastframe', 'corrupt.mp4'); fs.writeFileSync(junk, crypto.randomBytes(200000)); const realSrc = clips.find((c) => c.real)?.asset ?? clips[0].asset; const truncated = path.join(ASSETS, 'e2e-lastframe', 'truncated.mp4'); const whole = fs.readFileSync(realSrc); fs.writeFileSync(truncated, whole.subarray(0, Math.floor(whole.length * 0.35))); const allBlack = path.join(ASSETS, 'e2e-lastframe', 'allblack.mp4'); fs.copyFileSync(synthFiles.allblack, allBlack); const webm = path.join(ASSETS, 'e2e-lastframe', 'recorded.webm'); fs.copyFileSync(synthFiles['landscape-webm'], webm); const servers = await sideServers(); await page.goto(`${WEB}/video`); await page.waitForSelector('#desk-prompt', { timeout: 20000 }); const tryExport = async (src) => { const dl = page.waitForEvent('download', { timeout: 2000 }).catch(() => null); const res = await page.evaluate(async (s) => (await import('/src/lib/media/lastFrame.ts')).exportLastFrame(s), src); await page.waitForTimeout(150); return { res, msg: (await lastToast(page).textContent())?.trim(), dl: await dl }; }; const failures_ = [ ['文件不存在', fileUrl(path.join(ASSETS, 'e2e-lastframe', 'missing.mp4')), '视频文件不存在或已被移除,无法导出尾帧'], ['无权限(越界路径 403)', fileUrl('/etc/hostname'), '没有访问该视频的权限,无法导出尾帧'], ['文件损坏(随机字节)', fileUrl(junk), '当前浏览器不支持该视频格式,或文件已损坏,无法导出尾帧'], ['跨域且无 CORS', 'http://127.0.0.1:18190/synth-square.mp4', '该视频来自其他站点,浏览器禁止读取画面(跨域限制),请先下载原视频'], ['整段片尾黑屏', fileUrl(allBlack), '视频结尾 1 秒内都是黑屏,未导出尾帧'], ]; for (const [label, src, want] of failures_) { const r = await tryExport(src); ok(`失败·${label}: 中文提示且不下载`, r.res === false && r.msg === want && !r.dl, r.msg); } const tr = await tryExport(fileUrl(truncated)); ok('失败·截断的真实视频: 给出中文失败提示或仍导出有效帧', tr.res === false ? /无法|损坏|不支持/.test(tr.msg || '') : !!tr.dl, tr.msg); await page.screenshot({ path: path.join(OUT, '04-error-toast.png') }); const timeout = await page.evaluate(async () => { const m = await import('/src/lib/media/exportFrame.ts'); const t0 = performance.now(); try { await m.captureLastFrame('http://127.0.0.1:18191/hang.mp4', { fileTag: '尾帧', timeoutMs: 2500 }); return { code: 'none' }; } catch (e) { return { code: e.code, ms: performance.now() - t0 }; } }); ok('失败·加载超时: 按时放弃并报 timeout', timeout.code === 'timeout' && timeout.ms < 6000, JSON.stringify(timeout)); const UNSEEKABLE = '无法定位到视频结尾(时长未知或来源不支持拖动进度),未导出尾帧'; const noRange = await tryExport('http://127.0.0.1:18192/synth-square.mp4'); ok('失败·来源不支持拖动且时长未知: 中文提示,不导出首帧冒充', noRange.res === false && noRange.msg === UNSEEKABLE && !noRange.dl, noRange.msg); fs.copyFileSync(realSrc, path.join(SAMPLES, path.basename(realSrc))); const cors = await tryExport(`http://127.0.0.1:18192/${encodeURIComponent(path.basename(realSrc))}`); if (cors.res) { ok('跨域(允许 CORS)的真实视频可导出', !!cors.dl, cors.msg); await verifyDownload(page, '跨域 CORS·真实', cors.dl, realSrc); } else { ok('跨域(允许 CORS、无 Range)的真实视频:明确提示无法定位结尾', cors.msg === UNSEEKABLE, cors.msg); } const wb = await tryExport(fileUrl(webm)); ok('MediaRecorder WebM(时长未知)可导出', wb.res === true && !!wb.dl, wb.msg); if (wb.dl) await verifyDownload(page, 'WebM 1280×720', wb.dl, webm, { center: isMagenta }); servers.kill(); // ---------- 手机 ---------- const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 3, isMobile: true, hasTouch: true, acceptDownloads: true, }); const mp = await phone.newPage(); await mp.goto(`${WEB}/video`); await mp.waitForSelector('.take', { timeout: 20000 }); const pc = clips.find((c) => c.label.startsWith('竖屏')); await mp.locator('.take', { hasText: pc.prompt }).first().tap(); await mp.waitForTimeout(600); const mBtn = mp.locator('.inspector .actions button', { hasText: '导出尾帧' }); const box = await mBtn.boundingBox(); ok('手机:检视区导出尾帧按钮在屏内可点', !!box && box.x >= 0 && box.x + box.width <= 390 && box.height >= 28, JSON.stringify(box)); await mp.screenshot({ path: path.join(OUT, '05-phone-inspector.png') }); const [mdl] = await Promise.all([mp.waitForEvent('download', { timeout: 40000 }), mBtn.tap()]); await verifyDownload(mp, '手机·竖屏', mdl, pc.asset, pc); await mp.goto(`${WEB}/library`); await mp.waitForSelector('.card .media', { timeout: 20000 }); await mp.locator(`.card .media[title="${path.basename(pc.asset)}"]`).first().tap(); await mp.waitForSelector('.backdrop .player-frame video', { timeout: 10000 }); const mTool = mp.locator('.backdrop .toolbar button[aria-label="导出尾帧"]'); const tbox = await mTool.boundingBox(); ok('手机:弹层导出尾帧按钮在屏内', !!tbox && tbox.x >= 0 && tbox.x + tbox.width <= 390, JSON.stringify(tbox)); const [mdl2] = await Promise.all([mp.waitForEvent('download', { timeout: 40000 }), mTool.tap()]); await verifyDownload(mp, '手机·弹层', mdl2, pc.asset, pc); await mp.waitForTimeout(250); await mp.screenshot({ path: path.join(OUT, '06-phone-lightbox.png') }); await browser.close(); console.log(failures ? `\n${failures} check(s) FAILED` : '\nALL PASS'); process.exit(failures ? 1 : 0); }; run().catch((e) => { console.error(e); process.exit(1); });