gongxiangp2/apps/detail-agent-pi/test/video-seeding-phase3.test.mjs

323 lines
15 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 { buildSliceArgs } from '../src/video-ffmpeg.mjs';
import { createVideoToolExecutors, videoTools } from '../src/video-tools.mjs';
import { createSeedingToolExecutors, seedingTools } from '../src/seeding-tools.mjs';
import { pruneHistoricalToolImages } from '../src/image-context-pruning.mjs';
import { activitySummary, executionCategory } from '../src/activity-event.mjs';
import { productionSeedingTools, productionVideoTools } from '../src/production-operations.mjs';
import { openAgent } from './fake-canvas.mjs';
import { ProjectStore } from '../src/store.mjs';
import { cleanup } from './cleanup.mjs';
function makeMinimalJpeg(width = 720, height = 1280) {
return Buffer.from([
0xff, 0xd8,
0xff, 0xc0, 0x00, 0x11, 0x08,
(height >> 8) & 0xff, height & 0xff,
(width >> 8) & 0xff, width & 0xff,
0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
0xff, 0xd9,
]);
}
function makeMinimalPng(width = 800, height = 1000) {
const buf = Buffer.alloc(24);
Buffer.from('89504e470d0a1a0a', 'hex').copy(buf, 0);
buf.writeUInt32BE(13, 8);
buf.write('IHDR', 12, 'ascii');
buf.writeUInt32BE(width, 16);
buf.writeUInt32BE(height, 20);
return buf;
}
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-phase3-'));
t.after(() => cleanup(root));
const script = path.join(root, 'mock-media.mjs');
const log = path.join(root, 'commands.jsonl');
const source = path.join(root, 'raw-product-video.mp4');
const ledgerDir = path.join(root, 'ledger');
const deliveryDir = path.join(root, 'delivery');
await fs.writeFile(source, 'mock source 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 isSlice = file.endsWith('slice.mp4');
const video = { index: 0, codec_type: 'video', codec_name: 'h264', width: 720, height: 1280,
avg_frame_rate: '30/1', duration: isSlice ? '2.5' : '6' };
const audio = { index: 1, 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([
0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x05, 0x00, 0x02, 0xd0,
0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xd9,
]));
} else if (args.includes('slice.mp4')) {
fs.writeFileSync(args.at(-1), 'sliced mock mp4');
} else if (args.includes('volumedetect')) {
console.error('mean_volume: -18.5 dB\nmax_volume: -2.0 dB');
}
`);
const config = {
ffmpegPath: process.execPath, ffmpegPrefix: [script, log, 'ffmpeg'],
ffprobePath: process.execPath, ffprobePrefix: [script, log, 'probe'],
ledgerDir, deliveryDir,
};
return {
root, source, config, ledgerDir, deliveryDir,
video: createVideoToolExecutors(config),
seeding: createSeedingToolExecutors(config),
async commands() { return (await fs.readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line)); },
};
}
test('video_plan_storyboard 校验分镜、转场重叠、卖点覆盖并生成定时字幕', async t => {
const f = await fixture(t);
const plan = await f.video.video_plan_storyboard({
outputId: 'main_video',
variantId: 'walnut-120',
title: '实木书桌主图视频',
aspectRatio: '3:4',
targetDuration: 6.5,
sellingPoints: [
{ id: 'sp-wood', text: 'FAS 级北美黑胡桃木', required: true },
{ id: 'sp-frame', text: '加厚碳钢桌腿承重稳固', required: true },
{ id: 'sp-cable', text: '隐藏式理线槽', required: false },
],
shots: [
{
shotId: 'shot-1', intent: '整体亮相', sellingPointIds: ['sp-wood'],
narration: '精选北美黑胡桃木桌面', duration: 2.5, sourceKind: 'still',
},
{
shotId: 'shot-2', intent: '桌腿承重特写', sellingPointIds: ['sp-frame'],
caption: '加厚碳钢桌腿稳固不晃', duration: 3, sourceKind: 'clip',
transition: { type: 'fade', duration: 0.5 },
},
{
shotId: 'shot-3', intent: '收尾展示', duration: 1.5, sourceKind: 'generate',
requestKey: 'tail-shot',
},
],
storyboardKey: 'main-video-plan',
});
assert.equal(plan.totalDuration, 6.5);
assert.equal(plan.durationDelta, 0);
assert.deepEqual(plan.coveredSellingPointIds, ['sp-wood', 'sp-frame']);
assert.deepEqual(plan.uncoveredSellingPointIds, ['sp-cable']);
assert.equal(plan.shots[1].start, 2);
assert.equal(plan.shots[1].end, 5);
assert.deepEqual(plan.captions, [
{ start: 0, end: 2.5, text: '精选北美黑胡桃木桌面' },
{ start: 2, end: 5, text: '加厚碳钢桌腿稳固不晃' },
]);
assert.ok(plan.savedPath.endsWith('main-video-plan.storyboard.json'));
assert.equal(JSON.parse(await fs.readFile(plan.savedPath, 'utf8')).shotCount, 3);
await assert.rejects(f.video.video_plan_storyboard({
outputId: 'main_video',
title: '缺少必选卖点',
sellingPoints: [{ id: 'sp-req', text: '必选卖点', required: true }],
shots: [{ shotId: 's1', intent: '开场', duration: 2, sourceKind: 'still' }],
}), { category: 'invalid_video_input' });
await assert.rejects(f.video.video_plan_storyboard({
outputId: 'main_video',
title: '首镜转场非法',
sellingPoints: [{ id: 'sp-1', text: '卖点' }],
shots: [{ shotId: 's1', intent: '开场', sellingPointIds: ['sp-1'], duration: 2, sourceKind: 'still', transition: { type: 'fade', duration: 0.5 } }],
}), { category: 'invalid_video_input' });
});
test('video_slice_clip 与 buildSliceArgs 精确切片并校验成片,不覆盖已有文件', async t => {
const f = await fixture(t);
const mutedArgs = buildSliceArgs({ path: f.source, start: 1.5, duration: 2.5, mute: true, hasAudio: true });
assert.ok(mutedArgs.includes('-an'));
assert.ok(!mutedArgs.includes('aac'));
assert.equal(mutedArgs[mutedArgs.indexOf('-ss') + 1], '1.5');
assert.equal(mutedArgs[mutedArgs.indexOf('-t') + 1], '2.5');
const receipt = await f.video.video_slice_clip({
path: f.source, start: 1, duration: 2.5, name: '卖点切片-01', sellingPointId: 'sp-wood', variantId: 'walnut',
});
assert.equal(receipt.clipId, '卖点切片-01');
assert.equal(receipt.duration, 2.5);
assert.equal(receipt.width, 720);
assert.equal(receipt.height, 1280);
assert.equal(receipt.sellingPointId, 'sp-wood');
assert.equal(receipt.variantId, 'walnut');
assert.ok(receipt.path.endsWith('卖点切片-01.mp4'));
await assert.rejects(f.video.video_slice_clip({
path: f.source, start: 1, duration: 2.5, name: '卖点切片-01',
}), { category: 'video_output_exists' });
await assert.rejects(f.video.video_slice_clip({
path: f.source, start: 4, duration: 3, name: '越界切片',
}), { category: 'invalid_video_input' });
});
test('video_extract_keyframes 落盘关键帧并支持视觉上下文释放', async t => {
const f = await fixture(t);
const result = await f.video.video_extract_keyframes({
path: f.source,
count: 2,
prefix: 'frame-cut',
sellingPointIds: ['sp-wood', 'sp-frame'],
includeImages: true,
});
assert.equal(result.details.frames.length, 2);
assert.deepEqual(result.details.frames.map(row => row.sellingPointId), ['sp-wood', 'sp-frame']);
assert.equal(result.details.frames[0].width, 720);
assert.equal(result.details.frames[0].height, 1280);
assert.ok(result.details.frames[0].path.endsWith('frame-cut-01.jpg'));
assert.equal(result.content.filter(block => block.type === 'image').length, 2);
const latest = await f.video.video_extract_keyframes({ path: f.source, frameTimes: [1], prefix: 'second', includeImages: true });
const pruned = pruneHistoricalToolImages([
{ role: 'toolResult', toolName: 'video_extract_keyframes', ...result },
{ role: 'toolResult', toolName: 'video_extract_keyframes', ...latest },
]);
assert.ok(pruned[0].content.every(block => block.type === 'text'));
assert.equal(pruned[1].content.filter(block => block.type === 'image').length, 1);
await assert.rejects(f.video.video_extract_keyframes({
path: f.source, frameTimes: [0], prefix: 'frame-cut',
}), { category: 'video_output_exists' });
});
test('video_package_delivery 核验成片、封面、字幕并输出视频/种草入库契约', async t => {
const f = await fixture(t);
await fs.mkdir(f.deliveryDir, { recursive: true });
const cover = path.join(f.deliveryDir, '主图视频封面.jpg');
const subtitle = path.join(f.deliveryDir, '主图视频字幕.srt');
await fs.writeFile(cover, makeMinimalJpeg(720, 1280));
await fs.writeFile(subtitle, '1\n00:00:00,000 --> 00:00:02,000\n北美黑胡桃木\n');
const receipt = await f.video.video_package_delivery({
outputId: 'main_video',
identifier: 'SPU-DESK-01',
variantId: 'walnut',
videoPath: f.source,
coverPath: cover,
subtitlePath: subtitle,
});
assert.equal(receipt.kind, 'video');
assert.equal(receipt.files.length, 3);
assert.equal(receipt.uploadContract.kind, 'video');
assert.equal(receipt.uploadContract.identifier, 'SPU-DESK-01');
assert.equal(receipt.uploadContract.assets.files.length, 3);
assert.match(receipt.uploadContract.assets.files[0].sha256, /^[a-f0-9]{64}$/);
assert.equal(JSON.parse(await fs.readFile(receipt.manifestPath, 'utf8')).kind, 'video');
const seedingVideoReceipt = await f.video.video_package_delivery({
outputId: 'seeding_video',
identifier: 'SPU-DESK-01',
videoPath: f.source,
});
assert.equal(seedingVideoReceipt.kind, 'buyer_show');
const psd = path.join(f.deliveryDir, 'source.psd');
await fs.writeFile(psd, 'mock psd');
await assert.rejects(f.video.video_package_delivery({
outputId: 'main_video', identifier: 'SPU-DESK-01', videoPath: f.source, extraPaths: [psd],
}), { category: 'invalid_media_delivery' });
});
test('seeding_plan_pack 与 seeding_package_delivery 支持种草策划、条码规范与买家秀入库契约', async t => {
const f = await fixture(t);
const plan = await f.seeding.seeding_plan_pack({
outputId: 'seeding_images',
theme: '居家办公原木桌面改造',
audience: '注重质感与收纳的家居设计师',
tone: '真实松弛、自然光实拍感',
sellingPoints: [
{ id: 'sp-grain', text: '自然木纹肌理', required: true },
{ id: 'sp-size', text: '1.4米宽敞台面', required: false },
],
items: [
{ itemId: 'seed-1', role: 'cover', intent: '首图场景种草', barcode: '6901234567890', sellingPointIds: ['sp-grain'], copy: '换了这张黑胡桃木书桌后每天都想坐着办公' },
{ itemId: 'seed-2', role: 'detail', intent: '木纹近景', sellingPointIds: ['sp-size'] },
],
packKey: 'xhs-pack-01',
});
assert.equal(plan.itemCount, 2);
assert.deepEqual(plan.coveredSellingPointIds, ['sp-grain', 'sp-size']);
assert.ok(plan.savedPath.endsWith('xhs-pack-01.seeding-pack.json'));
await fs.mkdir(f.deliveryDir, { recursive: true });
const coverJpg = path.join(f.deliveryDir, '6901234567890.jpg');
const detailPng = path.join(f.deliveryDir, '细节实拍图.png');
await fs.writeFile(coverJpg, makeMinimalJpeg(1080, 1440));
await fs.writeFile(detailPng, makeMinimalPng(1080, 1440));
const delivered = await f.seeding.seeding_package_delivery({
outputId: 'seeding_images',
identifier: 'SPU-DESK-01',
theme: '居家办公原木桌面改造',
items: [
{ path: coverJpg, role: 'cover', barcode: '6901234567890', variantId: 'walnut', variantName: '胡桃色' },
{ path: detailPng, role: 'detail', variantId: 'walnut' },
],
});
assert.equal(delivered.kind, 'buyer_show');
assert.equal(delivered.files.length, 2);
assert.deepEqual(delivered.files.map(file => [file.width, file.height]), [[1080, 1440], [1080, 1440]]);
assert.equal(delivered.uploadContract.kind, 'buyer_show');
assert.equal(delivered.uploadContract.assets.files[0].fileName, '6901234567890.jpg');
assert.equal(JSON.parse(await fs.readFile(delivered.manifestPath, 'utf8')).theme, '居家办公原木桌面改造');
await assert.rejects(f.seeding.seeding_package_delivery({
outputId: 'seeding_images',
identifier: 'SPU-DESK-01',
items: [{ path: detailPng, barcode: '6901234567890' }],
}), { category: 'invalid_seeding_input' });
});
test('种草与视频 Phase 3 工具按需激活、零污染图文主线且符合白标要求', async t => {
const f = await fixture(t);
const allTools = [...videoTools, ...seedingTools];
for (const [name, description] of allTools) {
assert.ok(!/Pi|PhotoCraft/.test(description), name);
assert.match(activitySummary({ type: 'tool_execution_start', toolName: name }), /^开始:/);
}
assert.equal(executionCategory('video_package_delivery'), 'export');
assert.equal(executionCategory('seeding_package_delivery'), 'export');
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 })) });
const active = async options => {
const host = await openAgent({ store, transport, canvas, ...options });
try { return host.session.getActiveToolNames(); }
finally { await host.dispose(); }
};
const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) });
for (const [name] of allTools) assert.ok(!plane.includes(name), `planar goal should not include ${name}`);
const seedingOnly = await active({ productionGoal: goal(['seeding_images']) });
assert.deepEqual(productionVideoTools({ productionGoal: goal(['seeding_images']) }, name => name), []);
assert.equal(productionSeedingTools({ productionGoal: goal(['detail']) }, name => name).length, 0);
for (const [name] of seedingTools) assert.ok(seedingOnly.includes(name));
for (const [name] of videoTools) assert.ok(!seedingOnly.includes(name));
const explicitSeeding = await active({ seedingRuntime: { deliveryDir: f.deliveryDir } });
for (const [name] of seedingTools) assert.ok(explicitSeeding.includes(name));
});