Files
aigc-home/e2e/refract.mjs
T

344 lines
13 KiB
JavaScript

// Integration checks: disposable local backend + fake ComfyUI only.
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const { chromium } = createRequire(import.meta.url)(
process.env.PLAYWRIGHT_MODULE_PATH || 'playwright',
);
const ROOT = path.dirname(fileURLToPath(import.meta.url));
const SHOTS = process.env.REFRACT_SHOTS || path.join(ROOT, 'shots', 'refract');
fs.mkdirSync(SHOTS, { recursive: true });
const API = process.env.REFRACT_API || 'http://127.0.0.1:8247',
WEB = process.env.REFRACT_WEB || 'http://127.0.0.1:5173';
if (!['127.0.0.1', 'localhost'].includes(new URL(API).hostname))
throw Error('This test writes fixtures: use an isolated local backend.');
let checks = 0,
failures = 0,
browser;
const errors = [],
projects = [],
workflows = [],
jobs = [];
const ok = (name, value) => {
checks++;
console.log(`${value ? 'PASS' : 'FAIL'} ${name}`);
if (!value) failures++;
};
async function api(p, body, method) {
const r = await fetch(API + p, {
method: method || (body ? 'POST' : 'GET'),
headers: { 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
});
if (!r.ok) throw Error(`${p} ${r.status} ${await r.text()}`);
return r.json();
}
async function until(fn) {
const end = Date.now() + 18000;
while (Date.now() < end) {
const r = await fn();
if (r) return r;
await new Promise((r) => setTimeout(r, 200));
}
throw Error('Timed out waiting for API state');
}
const modePath = path.join(ROOT, 'fake_mode.json'),
savedMode = fs.existsSync(modePath) ? fs.readFileSync(modePath) : null;
const mode = (videos = false, photo = 'coast') =>
fs.writeFileSync(
modePath,
JSON.stringify({
mode: 'ok',
delay_sec: 0,
unique_filename: true,
videos,
image_file: path.join(ROOT, '../calliope-web/static/refract/' + photo + '.jpg'),
}),
);
try {
mode();
const rows = await api('/api/workflows?view=meta');
ok('more than 100 imported catalogue entries', rows.length > 100);
const image = rows.find((w) => w.name === '文生图·回归');
if (!image) throw Error('Run e2e/seed.py first.');
const h3 = await api('/api/workflows', {
name: 'H3 首尾帧·折光回归',
kind: 'video',
usage: 'image2video',
workflow_json: {
1: {
class_type: 'CLIPTextEncode',
inputs: { text: 'slow camera' },
_meta: { title: '(Input:prompt) 画面描述' },
},
2: {
class_type: 'LoadImage',
inputs: { image: '' },
_meta: { title: '(Input:first_frame) 首帧' },
},
3: {
class_type: 'LoadImage',
inputs: { image: '' },
_meta: { title: '(Input:last_frame) 尾帧' },
},
9: {
class_type: 'VHS_VideoCombine',
inputs: { images: 'x' },
_meta: { title: '(Output:video) 视频输出' },
},
},
});
workflows.push(h3.id);
const project = await api('/api/projects', {
title: '折光·可删除测试项目',
idea: '从一个想法开始',
});
projects.push(project.id);
await api(
`/api/workbench/projects/${project.id}/stages/assets`,
{
content: {
assets: [
{
id: 'refract-asset',
kind: 'character',
name: '旅人',
prompt: 'traveler on coast',
negative_prompt: '',
},
],
},
},
'PATCH',
);
browser = await chromium.launch({
executablePath: process.env.CHROMIUM_EXECUTABLE_PATH,
args: ['--no-sandbox', '--disable-dev-shm-usage'],
});
const context = await browser.newContext({
viewport: { width: 1440, height: 960 },
locale: 'zh-CN',
});
const page = await context.newPage();
page.setDefaultTimeout(8000);
page.on('pageerror', (e) => errors.push(String(e)));
page.on('console', (m) => {
if (m.type() === 'error') errors.push(m.text());
});
await page.goto(WEB + '/');
await page.locator('.refract-hero').waitFor();
ok(
'six primary entries and approved hero',
(await page.locator('.refract-shell>.sidebar .nav-item').count()) === 6,
);
ok(
'paper palette',
await page.evaluate(
() =>
getComputedStyle(document.documentElement).getPropertyValue('--bg').trim() === '#f4f2ed',
),
);
await page.screenshot({ path: SHOTS + '/home.png' });
await page.goto(WEB + '/workbench');
await page.locator('.project-grid .a-card').first().waitFor();
ok('real project grid', (await page.locator('.project-grid .a-card').count()) > 0);
await page.goto(WEB + `/workbench/${project.id}?stage=assets`);
await page.locator('[data-testid="workbench-page"]').waitFor();
ok(
'five vertical project stages',
(await page.locator('.stage-navigation .step-btn').count()) === 5 &&
(await page.locator('.stepper').evaluate((e) => getComputedStyle(e).flexDirection)) ===
'column',
);
await page.screenshot({ path: SHOTS + '/project.png' });
const desk =
WEB +
`/image?wf=${image.id}&from=workbench&project=${project.id}&stage=assets&label=旅人&source_kind=asset&source_id=refract-asset&prompt=traveler%20on%20coast`;
await page.goto(desk);
await page.locator('#desk-prompt').waitFor();
ok(
'context prompt and return path',
(await page.inputValue('#desk-prompt')) === 'traveler on coast' &&
(await page.locator('.context-bar a.back').count()) === 1,
);
const preview = await page.locator('.inspector.main .stage').boundingBox(),
form = await page.locator('.studio-form').boundingBox();
ok(
'large preview and compact input panel',
preview.width > 600 && preview.x < form.x && form.width < 330,
);
await page.locator('.model-selector').click();
await page.locator('[role="dialog"] .catalogue').waitFor();
await page.locator('[aria-label="搜索工作流"]').fill('文生图·回归');
await until(async () => (await page.locator('[role="dialog"] .workflow-card').count()) === 1);
ok('workflow search in modal', true);
await page.keyboard.press('Escape');
ok(
'Escape restores selector focus',
(await page.locator('[role="dialog"]').count()) === 0 &&
(await page.locator('.model-selector').evaluate((e) => e === document.activeElement)),
);
await page.getByRole('button', { name: '全部参数' }).click();
await page.getByRole('dialog').waitFor();
ok(
'parameters do not replace the artboard',
await page.locator('.inspector.main .stage').isVisible(),
);
await page.keyboard.press('Escape');
let submitted = page.waitForRequest(
(r) => r.url().endsWith('/api/playground/generate') && r.method() === 'POST',
);
await page.locator('.studio-form .gen').click();
ok(
'submit carries project source identity',
(await submitted).postDataJSON().context?.source_id === 'refract-asset',
);
const job = await until(async () =>
(await api('/api/playground/jobs')).find(
(j) => j.status === 'done' && j.payload?.workbench?.source_id === 'refract-asset',
),
);
jobs.push(job.id);
await page.locator('.inspector.main img').first().waitFor();
await page.locator('.save-project').click();
await until(
async () =>
(await api(`/api/workbench/projects/${project.id}`)).stages.find(
(s) => s.stage_key === 'assets',
).content.assets[0].job,
);
ok('output flows to source project asset', true);
await page.reload();
await page
.locator(`.take[data-job="${job.id}"] .actions .a-tag`, {
hasText: '已回流',
})
.waitFor();
ok('attachment survives reload', true);
mode(false, 'arch');
await page.fill('#desk-prompt', 'second variation');
await page.locator('.studio-form .gen').click();
const second = await until(async () =>
(await api('/api/playground/jobs')).find(
(j) =>
j.status === 'done' &&
j.id !== job.id &&
j.payload?.workbench?.source_id === 'refract-asset',
),
);
jobs.push(second.id);
await page.locator(`.take[data-job="${second.id}"] button.hit`).click();
await page.getByRole('button', { name: '对比画面 ◫' }).click();
await page.getByRole('slider', { name: '拖动对比画面' }).fill('70');
ok(
'comparison follows slider using actual files',
await page.locator('.comparison-layer').evaluate((e) => e.style.clipPath.includes('30%')),
);
await page.getByRole('button', { name: '结束对比 ◫' }).click();
await page.getByRole('button', { name: '放大查看 ⤢' }).click();
ok('real image lightbox', (await page.locator('.backdrop[role=dialog]').count()) > 0);
await page.keyboard.press('Escape');
await page.getByRole('button', { name: '专注创作 ⤢' }).click();
ok(
'focus mode keeps creation available',
!(await page.locator('.refract-shell>.sidebar').isVisible()) &&
(await page.locator('.studio-form').isVisible()),
);
await page.getByRole('button', { name: '退出专注 ⤢' }).click();
await page.screenshot({ path: SHOTS + '/studio.png' });
mode(true);
await page.goto(WEB + `/video?wf=${h3.id}`);
await page.locator('#desk-prompt').waitFor();
const uploads = page.locator('.studio-form input[type="file"]');
ok('two first/last frame inputs', (await uploads.count()) === 2);
await uploads.nth(0).setInputFiles(path.join(ROOT, '../calliope-web/static/refract/coast.jpg'));
await uploads.nth(1).setInputFiles(path.join(ROOT, '../calliope-web/static/refract/arch.jpg'));
await until(async () => (await page.locator('.studio-form img').count()) >= 2);
submitted = page.waitForRequest(
(r) => r.url().endsWith('/api/playground/generate') && r.method() === 'POST',
);
await page.locator('.studio-form .gen').click();
const body = (await submitted).postDataJSON();
ok(
'first and last frame distinct in API payload',
typeof body.input_values[2] === 'string' &&
typeof body.input_values[3] === 'string' &&
body.input_values[2] !== body.input_values[3],
);
const video = await until(async () =>
(await api('/api/playground/jobs')).find((j) => j.workflow_id === h3.id && j.status === 'done'),
);
jobs.push(video.id);
await page.locator('.inspector.main video').waitFor();
ok(
'video playback and tail export preserved',
(await page.getByRole('button', { name: '导出尾帧' }).count()) > 0,
);
await page.screenshot({ path: SHOTS + '/video.png' });
await page.goto(WEB + '/workflows');
await page.locator('.workflow-card').first().waitFor();
ok(
'catalogue renders incremental 48-card page',
(await page.locator('.workflow-card').count()) === 48,
);
await page.fill('[aria-label="搜索工作流"]', '文生图·回归');
await until(async () => (await page.locator('.workflow-card').count()) === 1);
const fav = page.locator('.favorite').first(),
before = await fav.getAttribute('aria-pressed');
await fav.click();
await until(async () => (await fav.getAttribute('aria-pressed')) !== before);
ok(
'favorite persisted through API',
(await api('/api/workflows/' + image.id)).favorite === (before !== 'true'),
);
await fav.click();
await page.fill('[aria-label="搜索工作流"]', '');
await page.screenshot({ path: SHOTS + '/catalogue.png' });
await page.getByRole('button', { name: '导入与管理 ↗' }).click();
ok(
'bulk importer remains accessible',
(await page.getByRole('button', { name: /批量导入/ }).count()) > 0,
);
await page.goto(WEB + '/agents');
await page.locator('.agent-list').waitFor();
ok(
'five agent cards and skill editor',
(await page.locator('.agent-row').count()) === 5 &&
(await page.locator('.skill-lib').count()) > 0,
);
await page.locator('.agent-row').nth(1).click();
ok('role selects actual chat', (await page.locator('.chat-head h2').innerText()) === '视觉设计');
await page.screenshot({ path: SHOTS + '/agents.png' });
await page.goto(WEB + '/canvas');
await page.locator('.svelte-flow').waitFor();
ok('canvas opens actual persisted graph', new URL(page.url()).pathname.startsWith('/canvas/'));
await page.screenshot({ path: SHOTS + '/canvas.png' });
for (const width of [1280, 1440, 1920]) {
await page.setViewportSize({ width, height: 960 });
await page.goto(WEB + '/image?wf=' + image.id);
await page.locator('.studio-form').waitFor();
const b = await page.locator('.studio-form').boundingBox();
ok(`desktop ${width}px no horizontal input overflow`, b.x + b.width <= width + 1);
}
await page.emulateMedia({ reducedMotion: 'reduce' });
ok(
'reduced motion disables transitions',
await page
.locator('.studio-form .gen')
.evaluate((e) => parseFloat(getComputedStyle(e).transitionDuration) < 0.02),
);
ok('no JavaScript or console errors', errors.length === 0);
if (errors.length) console.log(errors);
} finally {
if (browser) await browser.close();
for (const id of jobs) await api('/api/playground/jobs/' + id, null, 'DELETE').catch(() => {});
for (const id of workflows) await api('/api/workflows/' + id, null, 'DELETE').catch(() => {});
for (const id of projects) await api('/api/projects/' + id, null, 'DELETE').catch(() => {});
if (savedMode) fs.writeFileSync(modePath, savedMode);
else fs.rmSync(modePath, { force: true });
}
console.log(`${checks - failures}/${checks} passed`);
if (failures) process.exitCode = 1;