266 lines
16 KiB
JavaScript
266 lines
16 KiB
JavaScript
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs/promises';
|
||
import path from 'node:path';
|
||
import os from 'node:os';
|
||
import { randomUUID } from 'node:crypto';
|
||
import { createVideoMedia, buildTimelineArgs } from '../src/video-ffmpeg.mjs';
|
||
import { createVideoToolExecutors, videoTools } from '../src/video-tools.mjs';
|
||
import { pruneHistoricalToolImages } from '../src/image-context-pruning.mjs';
|
||
import { checkOutputCapabilities } from '../src/output-capabilities.mjs';
|
||
import { activitySummary } from '../src/activity-event.mjs';
|
||
import { productionOperationTools, productionVideoTools } from '../src/production-operations.mjs';
|
||
import { openAgent } from './fake-canvas.mjs';
|
||
import { ProjectStore } from '../src/store.mjs';
|
||
import { cleanup } from './cleanup.mjs';
|
||
|
||
const names = [
|
||
'video_generate_clip', 'video_compose_timeline', 'video_inspect',
|
||
'video_plan_storyboard', 'video_slice_clip', 'video_extract_keyframes', 'video_package_delivery',
|
||
];
|
||
|
||
async function fixture(t) {
|
||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-video-'));
|
||
t.after(() => cleanup(root));
|
||
const script = path.join(root, 'mock-media.mjs');
|
||
const log = path.join(root, 'commands.jsonl');
|
||
const source = path.join(root, '源片段 & 参考.mp4');
|
||
const ledgerDir = path.join(root, 'ledger');
|
||
await fs.writeFile(source, 'mock video bytes');
|
||
await fs.writeFile(script, String.raw`
|
||
import fs from 'node:fs';
|
||
const [log, command, ...args] = process.argv.slice(2);
|
||
fs.appendFileSync(log, JSON.stringify({ command, args }) + '\n');
|
||
if (command === 'probe') {
|
||
const file = args.at(-1);
|
||
const video = { index: 2, codec_type: 'video', codec_name: 'h264', width: 720, height: 1280,
|
||
avg_frame_rate: '30/1', duration: file.endsWith('timeline.mp4') ? '4.5' : '3' };
|
||
const audio = { index: 3, codec_type: 'audio', codec_name: 'aac', channels: 2, sample_rate: '48000' };
|
||
fs.statSync(file);
|
||
console.log(JSON.stringify({ format: { format_name: 'mov,mp4,m4a' }, streams: [video, audio] }));
|
||
} else if (args.includes('image2pipe')) {
|
||
process.stdout.write(Buffer.from([255, 216, 255, 217]));
|
||
} else if (args.includes('-filter_complex')) {
|
||
if (args.includes('timeline.mp4')) fs.writeFileSync(args.at(-1), 'rendered mock mp4');
|
||
} else if (args.includes('volumedetect')) {
|
||
console.error('mean_volume: -22.8 dB\nmax_volume: -3.1 dB');
|
||
} else if (args.some(arg => arg.endsWith('broken.mp4'))) {
|
||
process.exitCode = 1;
|
||
}
|
||
`);
|
||
const config = {
|
||
ffmpegPath: process.execPath, ffmpegPrefix: [script, log, 'ffmpeg'],
|
||
ffprobePath: process.execPath, ffprobePrefix: [script, log, 'probe'], ledgerDir,
|
||
};
|
||
return { root, source, config, ledgerDir, tools: createVideoToolExecutors(config),
|
||
async commands() { return (await fs.readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line)); } };
|
||
}
|
||
|
||
function timeline(source) {
|
||
return { clips: [
|
||
{ path: source, start: 0.5, duration: 2, interpolate: true },
|
||
{ path: source, duration: 3, transition: { type: 'fade', duration: 0.5 } },
|
||
], width: 720, height: 1280, fps: 30, name: '种草成品', coverTime: 1, crf: 18, audioBitrateKbps: 160 };
|
||
}
|
||
|
||
test('时间线参数支持硬切、静图关键帧、转场、混音和字幕烧录', () => {
|
||
const args = buildTimelineArgs({
|
||
width: 720, height: 1280, fps: 30, burnSubtitles: true,
|
||
clips: [
|
||
{ path: '静图 & 1.png', still: true, zoom: { from: 1, to: 1.2 }, duration: 2 },
|
||
{ path: '片段 ; 2.mp4', start: 1, duration: 3, hasAudio: true, interpolate: true },
|
||
{ path: '片段 3.mp4', duration: 2, transition: { type: 'dissolve', duration: 0.5 } },
|
||
],
|
||
audioTracks: [{ path: '配音.m4a', offset: 0.25, start: 0.5, gain: 0.75 }],
|
||
});
|
||
const graph = args[args.indexOf('-filter_complex') + 1];
|
||
assert.match(graph, /zoompan=z='1\+\(1\.2-1\)\*on\/59'/);
|
||
assert.match(graph, /trim=start=1:end=4.*minterpolate=fps=30:mi_mode=mci/);
|
||
assert.match(graph, /concat=n=2:v=1:a=0/);
|
||
assert.match(graph, /xfade=transition=dissolve:duration=0\.5:offset=4\.5/);
|
||
assert.match(graph, /acrossfade=d=0\.5/);
|
||
assert.match(graph, /atrim=start=0\.5.*volume=0\.75,adelay=12000S:all=1/);
|
||
assert.match(graph, /amix=inputs=2/);
|
||
assert.match(graph, /subtitles=timeline\.srt/);
|
||
assert.ok(args.includes(path.resolve('片段 ; 2.mp4')));
|
||
assert.ok(args.includes('libx264') && args.includes('aac') && args.includes('+faststart'));
|
||
});
|
||
|
||
test('合成后回读成片、封面和字幕,已存在的成品不被覆盖', async t => {
|
||
const f = await fixture(t);
|
||
const outputDir = path.join(f.root, '交付 & 封面');
|
||
const input = { ...timeline(f.source), outputDir,
|
||
subtitles: { mode: 'both', captions: [{ start: 0.25, end: 1.5, text: '商品细节' }] } };
|
||
const receipt = await f.tools.video_compose_timeline(input);
|
||
assert.deepEqual([receipt.video.width, receipt.video.height, receipt.video.fps, receipt.video.duration], [720, 1280, 30, 4.5]);
|
||
assert.equal(receipt.video.codec, 'h264');
|
||
assert.equal(receipt.video.decoded, true);
|
||
assert.deepEqual(receipt.video.audioStreams, [{ index: 0, codec: 'aac', channels: 2, sampleRate: 48000, meanVolumeDb: -22.8, maxVolumeDb: -3.1 }]);
|
||
assert.equal(receipt.cover.time, 1);
|
||
assert.match(await fs.readFile(receipt.subtitles.path, 'utf8'), /00:00:00,250 --> 00:00:01,500\n商品细节/);
|
||
for (const file of Object.values(receipt)) assert.equal(file.bytes, (await fs.stat(file.path)).size);
|
||
await assert.rejects(f.tools.video_compose_timeline(input), { category: 'video_output_exists' });
|
||
assert.deepEqual((await fs.readdir(outputDir)).sort(), ['种草成品.jpg', '种草成品.mp4', '种草成品.srt']);
|
||
const commands = await f.commands();
|
||
assert.ok(commands.some(({ command, args }) => command === 'probe' && args.includes('-show_streams') && args.includes(f.source)));
|
||
assert.ok(commands.some(({ args }) => args.includes('-ss') && args[args.indexOf('-ss') + 1] === '1' && args.includes('mjpeg')));
|
||
assert.ok(commands.some(({ args }) => args.includes('0:2') && args.includes('-xerror') && args.includes('null')));
|
||
});
|
||
|
||
test('独立字幕复用原文件,非法时间线在渲染前失败', async t => {
|
||
const f = await fixture(t);
|
||
const input = { ...timeline(f.source), outputDir: f.root };
|
||
await assert.rejects(f.tools.video_compose_timeline({ ...input, width: 721 }), { category: 'invalid_video_input' });
|
||
await assert.rejects(f.tools.video_compose_timeline({ ...input, name: '..\\other' }), { category: 'invalid_video_input' });
|
||
await assert.rejects(f.tools.video_compose_timeline({ ...input, clips: [{ path: f.source, duration: 4 }] }), { category: 'invalid_video_input' });
|
||
await assert.rejects(f.tools.video_compose_timeline({ ...input, coverTime: 5 }), { category: 'invalid_video_input' });
|
||
assert.ok((await f.commands()).every(({ command }) => command === 'probe'));
|
||
const srt = path.join(f.root, '原始 : 字幕.srt');
|
||
const content = '1\n00:00:00,000 --> 00:00:01,000\n本地字幕\n';
|
||
await fs.writeFile(srt, content);
|
||
const result = await f.tools.video_compose_timeline({ ...input, subtitles: { mode: 'sidecar', path: srt } });
|
||
assert.equal(await fs.readFile(result.subtitles.path, 'utf8'), content);
|
||
const { args } = (await f.commands()).find(({ args }) => args.includes('-filter_complex'));
|
||
assert.doesNotMatch(args[args.indexOf('-filter_complex') + 1], /subtitles=/);
|
||
});
|
||
|
||
test('媒体命令或适配器缺失提供结构化错误,解码失败不给出验收回执', async t => {
|
||
const f = await fixture(t);
|
||
const missing = path.join(f.root, 'missing.exe');
|
||
await assert.rejects(createVideoMedia({ ...f.config, ffprobePath: missing }).inspect(f.source), { category: 'missing_ffmpeg_binary' });
|
||
await assert.rejects(createVideoMedia({ ...f.config, ffmpegPath: missing }).inspect(f.source), { category: 'missing_ffmpeg_binary' });
|
||
const request = { requestKey: 'shot-1', prompt: '商品慢推镜头' };
|
||
await assert.rejects(f.tools.video_generate_clip(request), { category: 'missing_video_generator_adapter' });
|
||
assert.deepEqual(await fs.readdir(f.ledgerDir), []);
|
||
const broken = path.join(f.root, 'broken.mp4');
|
||
await fs.writeFile(broken, 'corrupt');
|
||
await assert.rejects(f.tools.video_inspect({ path: broken }), { category: 'video_decode_failed' });
|
||
});
|
||
|
||
test('同编号并发和重启后均复用原请求,参数冲突不会再派发', async t => {
|
||
const f = await fixture(t);
|
||
const input = { requestKey: 'shot/1', prompt: ' 商品慢推镜头 ', firstFrame: '首帧.jpg', lastFrame: '尾帧.jpg',
|
||
referenceImages: ['参考图.jpg'], duration: 3, aspectRatio: '9:16', model: 'mock-video' };
|
||
let posts = 0;
|
||
const started = Promise.withResolvers();
|
||
const finish = Promise.withResolvers();
|
||
const generator = { async generate(spec, { requestKey, requestDigest, onDispatched }) {
|
||
posts++;
|
||
assert.equal(requestKey, input.requestKey);
|
||
assert.match(requestDigest, /^[a-f0-9]{64}$/);
|
||
assert.deepEqual(spec, { prompt: input.prompt.trim(), firstFrame: input.firstFrame, lastFrame: input.lastFrame,
|
||
referenceImages: input.referenceImages, duration: 3, aspectRatio: '9:16', model: 'mock-video' });
|
||
const [file] = (await fs.readdir(f.ledgerDir)).filter(file => file.endsWith('.json'));
|
||
assert.equal(JSON.parse(await fs.readFile(path.join(f.ledgerDir, file), 'utf8')).state, 'dispatching');
|
||
await onDispatched('task-1');
|
||
started.resolve();
|
||
await finish.promise;
|
||
return { clipId: 'clip-1', path: f.source };
|
||
}};
|
||
const tools = createVideoToolExecutors({ ...f.config, generator });
|
||
const pending = tools.video_generate_clip(input);
|
||
await Promise.race([started.promise, pending]);
|
||
try {
|
||
assert.equal((await tools.video_generate_clip(input)).pendingOriginal, input.requestKey);
|
||
} finally { finish.resolve(); }
|
||
const first = await pending;
|
||
assert.equal(first.clipId, 'clip-1');
|
||
assert.equal(first.remoteTaskId, 'task-1');
|
||
assert.equal(first.duration, 3);
|
||
assert.deepEqual(await f.tools.video_generate_clip({ ...input, prompt: input.prompt.trim() }), first);
|
||
await assert.rejects(tools.video_generate_clip({ ...input, duration: 4 }), { category: 'video_request_conflict' });
|
||
assert.equal(posts, 1);
|
||
});
|
||
|
||
test('中断仅查原任务,未知任务号继续等待且不会重派', async t => {
|
||
const f = await fixture(t);
|
||
let posts = 0;
|
||
const make = generator => createVideoToolExecutors({ ...f.config, generator });
|
||
const input = { requestKey: 'known', prompt: '观察镜头' };
|
||
const disconnected = make({ async generate(_spec, { onDispatched }) {
|
||
posts++;
|
||
await onDispatched('task-original');
|
||
throw Error('模拟断连');
|
||
}});
|
||
assert.equal((await disconnected.video_generate_clip(input)).remoteTaskId, 'task-original');
|
||
assert.equal((await f.tools.video_generate_clip(input)).status, 'pending');
|
||
const reconnected = make({ async recover(id) {
|
||
assert.equal(id, 'task-original');
|
||
return { clipId: 'recovered', path: f.source };
|
||
}});
|
||
assert.equal((await reconnected.video_generate_clip(input)).clipId, 'recovered');
|
||
const unknown = { ...input, requestKey: 'unknown' };
|
||
const lost = make({ async generate() { posts++; throw Error('模拟提交后的未知结果'); } });
|
||
assert.equal((await lost.video_generate_clip(unknown)).status, 'pending');
|
||
assert.equal((await lost.video_generate_clip(unknown)).pendingOriginal, 'unknown');
|
||
assert.equal(posts, 2);
|
||
});
|
||
|
||
test('检视返回图像及文本,新的查看结果释放旧视频帧', async t => {
|
||
const f = await fixture(t);
|
||
const first = await f.tools.video_inspect({ path: f.source, frameTimes: [0, 1, 1] });
|
||
const latest = await f.tools.video_inspect({ path: f.source, frameTimes: [2] });
|
||
assert.deepEqual(first.details.frameTimes, [0, 1]);
|
||
assert.equal(JSON.parse(first.content[0].text).hasAudio, true);
|
||
assert.ok(first.content.slice(1).every(block => block.type === 'image' && block.mimeType === 'image/jpeg'));
|
||
const messages = [first, latest].map(result => ({ role: 'toolResult', toolName: 'video_inspect', ...result }));
|
||
const pruned = pruneHistoricalToolImages(messages);
|
||
assert.equal(pruned[0].content[0].text, first.content[0].text);
|
||
assert.ok(pruned[0].content.every(block => block.type === 'text'));
|
||
assert.equal(pruned[1], messages[1]);
|
||
await assert.rejects(f.tools.video_inspect({ path: f.source, frameTimes: [3] }), { category: 'invalid_video_input' });
|
||
});
|
||
|
||
test('种草视频预检遵循发布绑定,三项工具活动使用白标标题', () => {
|
||
const outputs = [{ outputId: 'seeding_video', variantId: 'qa' }, { outputId: 'main_images', variantId: 'qa' }];
|
||
const blocked = checkOutputCapabilities(outputs);
|
||
assert.equal(blocked.schemaVersion, 1);
|
||
assert.equal(blocked.status, 'blocked');
|
||
assert.deepEqual(blocked.issues.map(issue => issue.code), ['missing_template_resource', 'missing_published_skill', 'missing_render_adapter']);
|
||
assert.deepEqual(checkOutputCapabilities(outputs, {
|
||
componentRoles: new Map([['seeding_video', new Set(['original', 'mapping'])]]),
|
||
publishedSkills: new Set(['seeding-video-production']), renderAdapters: new Set(['seeding-video-render']),
|
||
}), { schemaVersion: 1, status: 'ready', issues: [] });
|
||
assert.deepEqual(videoTools.map(([name]) => name), names);
|
||
assert.deepEqual(names.map(toolName => activitySummary({ type: 'tool_execution_start', toolName })),
|
||
['开始:生成视频片段', '开始:合成视频成品', '开始:检视视频画面', '开始:规划视频分镜', '开始:裁切视频片段', '开始:提取视频关键帧', '开始:打包视频成品']);
|
||
assert.ok(videoTools.every(([, description]) => !/Pi|PhotoCraft/.test(description)));
|
||
});
|
||
|
||
test('真实会话按视频输出或显式运行时注册,平面工具清单一致', async t => {
|
||
const f = await fixture(t);
|
||
const identity = { scope: 'a'.repeat(64), project: randomUUID() };
|
||
const store = await ProjectStore.open(f.root, identity, {
|
||
brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', version: '1', source: 'test', rules: [],
|
||
});
|
||
const transport = { info: { accountScope: identity.scope, model: { id: 'qa-model', protocol: 'openai-chat' }, pending: [] } };
|
||
const variantId = 'qa';
|
||
const canvas = { detailImages() {} };
|
||
const goal = outputIds => ({ variantId, workspaceId: 'qa', requestedOutputs: outputIds.map(outputId => ({ outputId, variantId })) });
|
||
async function active(options) {
|
||
const host = await openAgent({ store, transport, canvas, ...options });
|
||
try {
|
||
if (options.productionGoal) {
|
||
for (const [name] of productionOperationTools) assert.ok(host.session.getToolDefinition(name),name);
|
||
}
|
||
return host.session.getActiveToolNames();
|
||
}
|
||
finally { await host.dispose(); }
|
||
}
|
||
const seedingNames = ['seeding_plan_pack', 'seeding_package_delivery'];
|
||
const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) });
|
||
assert.ok(plane.includes('plan_production'));
|
||
assert.deepEqual(plane.filter(name => names.includes(name) || seedingNames.includes(name)), []);
|
||
assert.deepEqual(productionVideoTools({ productionGoal: goal(['seeding_images']) }, name => name), []);
|
||
for (const outputId of ['main_video', 'seeding_video']) {
|
||
const video = await active({ productionGoal: goal([outputId]) });
|
||
const expectedExtra = outputId === 'seeding_video' ? [...names, ...seedingNames] : names;
|
||
assert.deepEqual(video.filter(name => !expectedExtra.includes(name)), plane);
|
||
assert.deepEqual(video.filter(name => expectedExtra.includes(name)), expectedExtra);
|
||
}
|
||
const defaultChat = await active({});
|
||
const explicit = await active({ videoRuntime: { generator: { generate() { throw Error('无需提交'); } } } });
|
||
assert.deepEqual(explicit.filter(name => !names.includes(name)), defaultChat);
|
||
assert.deepEqual(explicit.filter(name => names.includes(name)), names);
|
||
});
|