sync: 同步总仓库 luoguang/monkey-ai weiyuan@bfdfb339 的 web/ 改动

同步基准:总仓库 a2ca13cb(= 本仓库初始导入 d8f3aee2)
范围:a2ca13cb..bfdfb339 中触及 web/ 的提交(不含 web/.claude/settings.local.json)

- 8490ac02 feat(aliyun): integrate Wan 3 and Qwen Image models
- 2aff08ec perf(analytics): 运营看板概览改读汇总表,首屏从 19s 降到 0.4s
- dc69335e feat(experience): 体验中心图像/视频创作升级(能力 schema、估价、新创作台)
- b059c657 fix(org): 下线 /org/create 自助加入企业页与 POST /api/org/join
- 4fcf47e6 fix(i18n): 修复中/英/韩/繁体多语言错乱,补齐日/越/泰译文
- e4c301d5 fix: merge enterprise task record date filters
- c9369b95 feat: expose enterprise image and video task records
- a410fee5 feat(claude): 无断点请求自动注入 cache_control 断点(方案 2)
- 521b3376 feat(claude): 缓存命中率优化——上游粘性路由 + 缓存时长强制改写
- 73b615dd feat(pricing): 企业成员不论登录身份均按所属企业等级计价与扣费
- f73f55c3 feat(client): 新增 WeyAi 版本说明管理与公开读取接口
- 8cdf1994 fix(topup): reset amount when switching from PayPal
- 93a4ac34 feat(baidu): configure Seedance liveness header by channel
- cb1818c5 fix(weyai): 按评审修正内容清理竞态、默认适用端与中文退回(M21)
- 04214d83 feat(weyai): WeyAi 内容管理与客户端内容接口(M21 第二部分)
- e3c4a57c feat(weyai): 设置页新增 WeyAi 页签与内容专用 COS 桶(M21 第一部分)
- b5ee8e70 fix(auth): 会话角色/状态以 DB 为准,修复提升管理员后管理接口报权限不足
- e4618fc2 fix: 修复企业看板日志聚合死循环导致 CPU 打满,并降低看板查询开销
- 584aad52 style(web): 个人中心侧边栏按 prettier 换行
- b8d87064 fix: 小程序教程隐藏充值后保留原步骤编号,企业充值判断直接用 isMiniProgramWebView
- eee7f5b2 fix: 小程序里企业首页不落到充值页,隐藏钱包入口与教程充值步骤
- 8b254d49 fix: 小程序里隐藏企业充值入口与页面
- a67661b4 fix(web): 小程序里个人中心默认页跳过充值和发票,避免来回跳转
- cff6c543 feat(web): WeyAi 小程序里打开个人中心时不出现充值和开票
- c6c99eb6 feat(billing): Claude 全部缓存写入统一按 1h 倍率计费
- 0699d1bf fix(web): 小程序 web-view 里注册页同样只显示站内方式
- 04853331 feat(web): WeyAi 小程序 web-view 里登录页只显示站内登录方式
This commit is contained in:
qiubaishen
2026-11-10 11:05:34 +08:00
parent d8f3aee261
commit 6160a23117
275 changed files with 38656 additions and 7694 deletions
+4 -1
View File
@@ -19,10 +19,13 @@ For commercial licensing, please contact support@quantumnous.com
import { useCallback, useEffect, useRef, useState } from 'react';
import { API } from '../../helpers';
import i18next from 'i18next';
const errorCode = (error) => error?.response?.data?.error?.code || '';
const errorMessage = (error) =>
error?.response?.data?.error?.message || error?.message || '请求失败';
error?.response?.data?.error?.message ||
error?.message ||
i18next.t('请求失败');
const readFileAsDataURL = (file) =>
new Promise((resolve, reject) => {
File diff suppressed because it is too large Load Diff
+602
View File
@@ -0,0 +1,602 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 体验中心视频页(WP A1-12)schema 驱动的纯函数:模式 / 图片槽 / 参数合成 / 请求体 / 草稿。
// 无 React / i18n 依赖,可直接 node --test。schema 见 controller/creation_models.go。
import {
getDefaultValues,
getParamDefault,
paramsForMode,
snapValues,
} from '../../components/creation/params/constraints.js';
export const DRAFT_STORAGE_KEY = 'video_generation_draft_v3';
const LEGACY_DRAFT_KEY = 'video_generation_draft_v2';
export const MODE_ORDER = [
'text2video',
'image2video',
'first_last_frame',
'reference2video',
];
/** 模式显示名(i18n key)。 */
export const MODE_LABEL_KEYS = {
text2video: '文生视频',
image2video: '图生视频',
first_last_frame: '首尾帧生视频',
reference2video: '参考图生视频',
};
/** 视频请求(VideoGenerateRequest)认识的 schema 参数;其余参数不渲染也不提交。 */
export const REQUEST_PARAM_KEYS = new Set([
'aspect_ratio',
'resolution',
'duration',
'generate_audio',
'watermark',
'seed',
'negative_prompt',
'camera',
'return_last_frame',
'prompt_extend',
]);
export const EMPTY_IMAGES = Object.freeze({
first_frame: null,
last_frame: null,
reference_images: [],
});
export const DEFAULT_VIDEO_FORM = Object.freeze({
mode: 'text2video',
selectedTemplate: '',
prompt: '',
modelName: '',
params: {},
images: EMPTY_IMAGES,
// 按模型记忆的参数(切换模型时优先级第 2 位,方案 §4.3)
paramMemory: {},
});
export const modelNameOf = (model) => {
if (!model) return '';
if (typeof model === 'string') return model;
return model.model || model.model_name || model.id || '';
};
/** schema 中可渲染 / 可提交的参数。 */
export const requestParamsOf = (model) =>
((model && model.params) || []).filter(
(p) => p && p.key && REQUEST_PARAM_KEYS.has(p.key),
);
/** 当前模式下可渲染 / 可提交的参数(schema 参数的 modes 不含当前模式时隐藏且不提交)。 */
export const requestParamsForMode = (model, mode) =>
paramsForMode(requestParamsOf(model), mode || 'text2video');
/** 模式列表:可用模式 + 因系统配置禁用的模式(带原因),按固定顺序。 */
export const modeOptionsOf = (model) => {
if (!model) return [];
const enabled = new Set(model.modes || []);
const disabled = {};
(model.disabled_modes || []).forEach((d) => {
if (d && d.mode && !enabled.has(d.mode)) disabled[d.mode] = d.reason || '';
});
const all = new Set([...enabled, ...Object.keys(disabled)]);
const order = (m) => {
const i = MODE_ORDER.indexOf(m);
return i < 0 ? MODE_ORDER.length : i;
};
return [...all]
.sort((a, b) => order(a) - order(b))
.map((mode) => ({
mode,
disabled: !enabled.has(mode),
reason: disabled[mode] || '',
}));
};
export const isModeEnabled = (model, mode) =>
Boolean(model && (model.modes || []).includes(mode));
const inputUsedBy = (input, mode) =>
Boolean(input && Array.isArray(input.modes) && input.modes.includes(mode));
/** 当前模型 × 模式使用的图片输入:{ first_frame, last_frame, reference_images(max) }。 */
export const activeInputsOf = (model, mode) => {
const inputs = (model && model.inputs) || {};
const out = { first_frame: false, last_frame: false, reference_max: 0 };
if (!isModeEnabled(model, mode)) return out;
out.first_frame = inputUsedBy(inputs.first_frame, mode);
out.last_frame = inputUsedBy(inputs.last_frame, mode);
if (inputUsedBy(inputs.reference_images, mode)) {
const max = Number(inputs.reference_images.max);
out.reference_max = Number.isFinite(max) && max > 0 ? max : 1;
}
return out;
};
const isReady = (slot) =>
Boolean(slot && slot.ref && (slot.status || 'ready') === 'ready');
/**
* 面板要渲染的图片槽。当前模式用到的槽正常显示;用不到但已有图片的槽保留并标为 unused
* (方案 §4.3:新模型用不到的图片不删除,置灰标注,切回去自动恢复)。
*
* @returns {Array<{ key: string, index?: number, label: string, labelIndex?: number,
* slot: object|null, active: boolean }>}
*/
export const imageSlotsOf = (model, mode, images = EMPTY_IMAGES) => {
const active = activeInputsOf(model, mode);
const list = [];
const inputs = (model && model.inputs) || {};
if (active.first_frame || images.first_frame) {
list.push({
key: 'first_frame',
label: (inputs.first_frame && inputs.first_frame.label) || '首帧',
slot: images.first_frame || null,
active: active.first_frame,
});
}
if (active.last_frame || images.last_frame) {
list.push({
key: 'last_frame',
label: (inputs.last_frame && inputs.last_frame.label) || '尾帧',
slot: images.last_frame || null,
active: active.last_frame,
});
}
const refs = images.reference_images || [];
const refActive = active.reference_max > 0;
refs.forEach((slot, index) => {
list.push({
key: 'reference_images',
index,
label: '参考图',
labelIndex: index + 1,
slot,
// 超过当前模型上限的参考图同样不提交
active: refActive && index < active.reference_max,
});
});
if (refActive && refs.length < active.reference_max) {
list.push({
key: 'reference_images',
index: refs.length,
label: '参考图',
labelIndex: refs.length + 1,
slot: null,
active: true,
});
}
return list;
};
/** 当前模式真正会提交的图片槽。 */
export const activeImageSlots = (model, mode, images) =>
imageSlotsOf(model, mode, images).filter((s) => s.active && s.slot);
/**
* 提交前的阻断原因(i18n key + 插值),无阻断返回 null。
* 只检查与图片相关的条件;提示词 / 模型 / 并发 / 余额由调用方检查。
*/
export const imageBlockReason = (model, mode, images = EMPTY_IMAGES) => {
if (!model) return null;
if (!isModeEnabled(model, mode)) {
return { key: '当前模型不支持该生成模式,请切换模式' };
}
const slots = activeImageSlots(model, mode, images);
if (slots.some((s) => s.slot.status === 'uploading')) {
return { key: '图片上传中,请稍候' };
}
if (slots.some((s) => s.slot.status === 'error')) {
return { key: '图片上传失败,请重试或移除' };
}
if (slots.some((s) => s.slot.status === 'expired')) {
return { key: '原图已失效,请重新上传' };
}
const active = activeInputsOf(model, mode);
if (active.first_frame && !isReady(images.first_frame)) {
return { key: mode === 'image2video' ? '请上传首帧图片' : '缺少首帧' };
}
if (active.last_frame && !isReady(images.last_frame)) {
return { key: '缺少尾帧' };
}
if (
active.reference_max > 0 &&
!slots.some((s) => s.key === 'reference_images' && isReady(s.slot))
) {
return { key: '请至少上传一张参考图' };
}
return null;
};
/**
* 切换模型后的模式:当前模式可用则保持;否则在可用模式里优先保留已上传的图片(首帧 → 图生),
* 再退回文生视频 / 第一个可用模式。
*/
export const pickModeForModel = (model, mode, images = EMPTY_IMAGES) => {
if (!model) return mode || 'text2video';
if (isModeEnabled(model, mode)) return mode;
const modes = model.modes || [];
if (
images.first_frame &&
images.last_frame &&
modes.includes('first_last_frame')
) {
return 'first_last_frame';
}
if (images.first_frame && modes.includes('image2video')) return 'image2video';
if (
(images.reference_images || []).length &&
modes.includes('reference2video')
) {
return 'reference2video';
}
if (modes.includes('text2video')) return 'text2video';
return modes[0] || 'text2video';
};
/**
* 合成某模型的参数取值(方案 §4.3 优先级):
* 1. 本次会话用户手动设置的值(sessionValues);2. 该模型上次使用时记住的值(memory);
* 3. schema 默认值。不合法的值吸附到最近的合法值。
*
* @returns {{ values: object, adjustments: Array<{key, from, to}> }}
*/
export const composeParams = (
model,
{ sessionValues = {}, memory = {} } = {},
) => {
const params = requestParamsOf(model);
const merged = getDefaultValues(params);
params.forEach((p) => {
if (memory && memory[p.key] !== undefined) merged[p.key] = memory[p.key];
if (sessionValues && sessionValues[p.key] !== undefined) {
merged[p.key] = sessionValues[p.key];
}
});
const { values, adjustments } = snapValues(
params,
merged,
(model && model.constraints) || [],
);
// 只保留 schema 内的键:其它模型的参数不随请求提交
const out = {};
params.forEach((p) => {
if (values[p.key] !== undefined) out[p.key] = values[p.key];
});
return { values: out, adjustments };
};
/**
* 复用参数 / 再生成 / 换种子再来:任务快照对请求参数是权威的。只按快照参数合成,
* 快照缺省的可选参数(随机种子、空负向提示词等)取 schema 默认值,不合并此前的会话值
* 与按模型记忆(否则上一次"换种子"的固定种子会泄漏到本次请求)。
* @returns {{ values: object, adjustments: Array<{key, from, to}> }}
*/
export const composePrefillParams = (model, snapshotParams) =>
composeParams(model, {
sessionValues: { ...(snapshotParams || {}) },
memory: {},
});
const isRandomSeed = (v) =>
v === undefined || v === null || v === '' || Number.isNaN(Number(v));
/**
* 构造 POST /api/video/generate 请求体(不含 model)。
* - 参数只取 schema 内、请求认识、且适用于当前模式(modes)的键;未设置的取 schema 默认值。
* - 比例 / 音频同时写入旧字段别名(ratio / audio),兼容旧转换器路径。
* - 图片按模式放入 image / last_image / reference_images;当前模式用不到的图片不提交。
*/
export const buildVideoRequest = (model, form) => {
const mode = form.mode || 'text2video';
const values = form.params || {};
const payload = { mode, prompt: form.prompt || '' };
requestParamsForMode(model, mode).forEach((p) => {
const v = values[p.key] !== undefined ? values[p.key] : getParamDefault(p);
switch (p.key) {
case 'seed':
if (!isRandomSeed(v)) payload.seed = Math.trunc(Number(v));
break;
case 'negative_prompt':
case 'camera':
if (typeof v === 'string' && v.trim()) payload[p.key] = v.trim();
break;
case 'aspect_ratio':
if (v !== undefined && v !== null && v !== '') {
payload.aspect_ratio = String(v);
payload.ratio = String(v);
}
break;
case 'generate_audio':
if (typeof v === 'boolean') {
payload.generate_audio = v;
payload.audio = v;
}
break;
case 'duration': {
const n = Number(v);
if (Number.isFinite(n) && n > 0) payload.duration = n;
break;
}
default:
if (v !== undefined && v !== null && v !== '') payload[p.key] = v;
}
});
const images = form.images || EMPTY_IMAGES;
const active = activeInputsOf(model, mode);
if (active.first_frame && isReady(images.first_frame)) {
payload.image = images.first_frame.ref;
}
if (active.last_frame && isReady(images.last_frame)) {
payload.last_image = images.last_frame.ref;
}
if (active.reference_max > 0) {
const refs = (images.reference_images || [])
.slice(0, active.reference_max)
.filter(isReady)
.map((s) => s.ref);
if (refs.length) payload.reference_images = refs;
}
return payload;
};
// ---------------------------------------------------------------------------
// 再生成:把任务详情的 request(ExperienceVideoRequestDTO)回填为表单
// ---------------------------------------------------------------------------
const isDisplayableURL = (v) => /^(https?:|data:|blob:)/i.test(String(v || ''));
const taskImageSlot = (ref, display, id) => {
const value = typeof ref === 'string' ? ref.trim() : '';
if (!value) return null;
const isAsset = value.startsWith('asset://');
const preview = isDisplayableURL(display)
? display
: isDisplayableURL(value)
? value
: null;
return {
id,
status: 'ready',
ref: value,
previewUrl: preview,
source: isAsset ? 'asset' : 'task',
identityType: isAsset ? 'real_person' : 'aigc',
};
};
const isBool = (v) => typeof v === 'boolean';
const nonEmptyString = (v) => typeof v === 'string' && v.trim() !== '';
/**
* 任务详情 request → 表单回填值(未按 schema 吸附,调用方再走 composeParams)。
* 字段映射见 controller/video_generation.go ExperienceVideoRequestDTO:
* image_ref|image → 首帧,last_image_ref|last_image → 尾帧,
* reference_image_refs[i]|reference_images[i] → 参考图;*_ref 为提交值,无 *_ref 时退回展示地址。
*
* @returns {{ modelName, mode, prompt, params, images }}
*/
export const formFromTaskRequest = (request, { newId } = {}) => {
const req = request || {};
let seq = 0;
const makeId =
newId || (() => `slot-task-${Date.now().toString(36)}-${seq++}`);
const params = {};
const aspect = req.aspect_ratio || req.ratio;
if (nonEmptyString(aspect)) params.aspect_ratio = aspect;
if (nonEmptyString(req.resolution)) params.resolution = req.resolution;
if (Number(req.duration) > 0) params.duration = Number(req.duration);
if (isBool(req.generate_audio)) params.generate_audio = req.generate_audio;
else if (isBool(req.audio)) params.generate_audio = req.audio;
// watermark / audio 为 omitempty:缺省即 false
params.watermark = req.watermark === true;
if (typeof req.seed === 'number' && Number.isFinite(req.seed)) {
params.seed = req.seed;
}
if (nonEmptyString(req.negative_prompt)) {
params.negative_prompt = req.negative_prompt;
}
if (nonEmptyString(req.camera)) params.camera = req.camera;
if (isBool(req.return_last_frame)) {
params.return_last_frame = req.return_last_frame;
}
if (isBool(req.prompt_extend)) params.prompt_extend = req.prompt_extend;
const refs = Array.isArray(req.reference_image_refs)
? req.reference_image_refs
: [];
const displays = Array.isArray(req.reference_images)
? req.reference_images
: [];
const refList = refs.length ? refs : displays;
const images = {
first_frame: taskImageSlot(req.image_ref || req.image, req.image, makeId()),
last_frame: taskImageSlot(
req.last_image_ref || req.last_image,
req.last_image,
makeId(),
),
reference_images: refList
.map((ref, i) => taskImageSlot(ref, displays[i], makeId()))
.filter(Boolean),
};
return {
modelName: typeof req.model === 'string' ? req.model : '',
mode: MODE_ORDER.includes(req.mode) ? req.mode : '',
prompt: typeof req.prompt === 'string' ? req.prompt : '',
params,
images,
};
};
/** 估价请求的 params(只带定价相关参数)。 */
export const quoteParamsOf = (payload) => {
const out = {};
['duration', 'resolution', 'aspect_ratio'].forEach((k) => {
if (payload[k] !== undefined) out[k] = payload[k];
});
return out;
};
// ---------------------------------------------------------------------------
// 草稿(localStorage v3,读写全部 try/catch)
// ---------------------------------------------------------------------------
const PERSISTABLE_SLOT_FIELDS = [
'id',
'ref',
'previewUrl',
'name',
'source',
'identityType',
];
const persistSlot = (slot, keepInline) => {
if (!isReady(slot)) return null;
if (!keepInline && String(slot.ref).startsWith('data:')) return null;
const out = { status: 'ready' };
PERSISTABLE_SLOT_FIELDS.forEach((k) => {
if (slot[k] !== undefined && slot[k] !== null) out[k] = slot[k];
});
// 内联图片的预览就是它自己,不重复存
if (String(out.ref).startsWith('data:') && out.previewUrl === out.ref) {
delete out.previewUrl;
}
return out;
};
export const serializeDraft = (form, { keepInline = true } = {}) => {
const images = form.images || EMPTY_IMAGES;
return JSON.stringify({
mode: form.mode,
selectedTemplate: form.selectedTemplate || '',
prompt: form.prompt || '',
modelName: form.modelName || '',
params: form.params || {},
paramMemory: form.paramMemory || {},
images: {
first_frame: persistSlot(images.first_frame, keepInline),
last_frame: persistSlot(images.last_frame, keepInline),
reference_images: (images.reference_images || [])
.map((s) => persistSlot(s, keepInline))
.filter(Boolean),
},
});
};
const restoreSlot = (slot) => {
if (!slot || typeof slot !== 'object' || typeof slot.ref !== 'string') {
return null;
}
const out = { ...slot, status: 'ready' };
if (!out.previewUrl && out.ref.startsWith('data:')) out.previewUrl = out.ref;
if (!out.id) out.id = `slot-${Math.random().toString(36).slice(2, 10)}`;
return out;
};
const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
export const parseDraft = (raw) => {
if (!raw) return null;
const data = JSON.parse(raw);
if (!isPlainObject(data)) return null;
const images = isPlainObject(data.images) ? data.images : {};
return {
...DEFAULT_VIDEO_FORM,
mode: MODE_ORDER.includes(data.mode) ? data.mode : 'text2video',
selectedTemplate:
typeof data.selectedTemplate === 'string' ? data.selectedTemplate : '',
prompt: typeof data.prompt === 'string' ? data.prompt : '',
modelName: typeof data.modelName === 'string' ? data.modelName : '',
params: isPlainObject(data.params) ? data.params : {},
paramMemory: isPlainObject(data.paramMemory) ? data.paramMemory : {},
images: {
first_frame: restoreSlot(images.first_frame),
last_frame: restoreSlot(images.last_frame),
reference_images: Array.isArray(images.reference_images)
? images.reference_images.map(restoreSlot).filter(Boolean)
: [],
},
};
};
/** 读取草稿;v3 不存在时只从 v2 迁移提示词与模板(旧参数口径不同,不迁移)。 */
export const loadDraft = (storage) => {
try {
const v3 = parseDraft(storage.getItem(DRAFT_STORAGE_KEY));
if (v3) return v3;
} catch (e) {
// 草稿损坏时忽略
}
try {
const raw = storage.getItem(LEGACY_DRAFT_KEY);
const v2 = raw ? JSON.parse(raw) : null;
if (isPlainObject(v2)) {
return {
...DEFAULT_VIDEO_FORM,
prompt: typeof v2.prompt === 'string' ? v2.prompt : '',
selectedTemplate:
typeof v2.selectedTemplate === 'string' ? v2.selectedTemplate : '',
};
}
} catch (e) {
// 忽略
}
return { ...DEFAULT_VIDEO_FORM };
};
/** 保存草稿;配额不足时退而不存内联 base64 图片,仍失败则放弃。 */
export const saveDraft = (storage, form) => {
try {
storage.setItem(DRAFT_STORAGE_KEY, serializeDraft(form));
return true;
} catch (e) {
try {
storage.setItem(
DRAFT_STORAGE_KEY,
serializeDraft(form, { keepInline: false }),
);
return true;
} catch (e2) {
return false;
}
}
};
// ---------------------------------------------------------------------------
// 轮询退避
// ---------------------------------------------------------------------------
export const POLL_STEPS_MS = [3000, 5000, 10000];
export const POLL_HIDDEN_MS = 30000;
/** 第 n 次(从 0 起)连续无变化轮询后的间隔;页面隐藏时降频。 */
export const pollDelay = (step, hidden) => {
if (hidden) return POLL_HIDDEN_MS;
return POLL_STEPS_MS[Math.min(step, POLL_STEPS_MS.length - 1)];
};
+362
View File
@@ -0,0 +1,362 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import {
DRAFT_STORAGE_KEY,
buildVideoRequest,
composeParams,
formFromTaskRequest,
imageBlockReason,
imageSlotsOf,
loadDraft,
modeOptionsOf,
pickModeForModel,
pollDelay,
saveDraft,
} from './videoCreation.js';
const seedance = {
model: 'seedance',
modes: ['text2video', 'image2video', 'first_last_frame'],
params: [
{
key: 'aspect_ratio',
type: 'ratio',
options: ['16:9', '9:16', '1:1'],
default: '16:9',
placement: 'dock',
},
{
key: 'duration',
type: 'segmented',
options: [5, 10],
default: 5,
unit: 's',
placement: 'dock',
},
{
key: 'generate_audio',
type: 'switch',
default: true,
placement: 'advanced',
},
{ key: 'seed', type: 'seed', placement: 'advanced' },
{
key: 'camera_fixed',
type: 'switch',
default: false,
placement: 'advanced',
},
{
key: 'return_last_frame',
type: 'switch',
default: true,
placement: 'hidden',
},
],
inputs: {
first_frame: { label: '首帧', modes: ['image2video', 'first_last_frame'] },
last_frame: { label: '尾帧', modes: ['first_last_frame'] },
},
};
const vidu = {
model: 'vidu',
modes: ['text2video', 'reference2video'],
disabled_modes: [{ mode: 'image2video', reason: 'COS 未开启' }],
params: [
{
key: 'duration',
type: 'segmented',
options: [4, 8],
default: 4,
placement: 'dock',
},
],
inputs: {
reference_images: { label: '参考图', modes: ['reference2video'], max: 2 },
},
};
const ready = (ref) => ({ id: ref, ref, status: 'ready' });
test('modeOptionsOf 列出可用与禁用模式并保持顺序', () => {
assert.deepEqual(modeOptionsOf(vidu), [
{ mode: 'text2video', disabled: false, reason: '' },
{ mode: 'image2video', disabled: true, reason: 'COS 未开启' },
{ mode: 'reference2video', disabled: false, reason: '' },
]);
});
test('首尾帧模式按 inputs 生成带标签的两个槽', () => {
const slots = imageSlotsOf(seedance, 'first_last_frame', {
first_frame: null,
last_frame: null,
reference_images: [],
});
assert.deepEqual(
slots.map((s) => [s.key, s.label, s.active]),
[
['first_frame', '首帧', true],
['last_frame', '尾帧', true],
],
);
});
test('当前模式用不到的图片保留为非激活槽且不提交', () => {
const images = {
first_frame: ready('cos://playground/1/a.png'),
last_frame: ready('cos://playground/1/b.png'),
reference_images: [],
};
const slots = imageSlotsOf(seedance, 'image2video', images);
assert.equal(slots.find((s) => s.key === 'last_frame').active, false);
const body = buildVideoRequest(seedance, {
mode: 'image2video',
prompt: 'p',
params: {},
images,
});
assert.equal(body.image, 'cos://playground/1/a.png');
assert.equal(body.last_image, undefined);
});
test('参考图槽数受 max 限制,超出的不提交', () => {
const images = {
first_frame: null,
last_frame: null,
reference_images: [ready('r1'), ready('r2'), ready('r3')],
};
const slots = imageSlotsOf(vidu, 'reference2video', images);
assert.deepEqual(
slots.map((s) => [s.labelIndex, s.active]),
[
[1, true],
[2, true],
[3, false],
],
);
const body = buildVideoRequest(vidu, {
mode: 'reference2video',
prompt: 'p',
params: {},
images,
});
assert.deepEqual(body.reference_images, ['r1', 'r2']);
});
test('请求体只带 schema 内参数,比例 / 音频写入别名,随机种子不提交', () => {
const body = buildVideoRequest(seedance, {
mode: 'text2video',
prompt: 'hello',
params: { aspect_ratio: '9:16', duration: 10, seed: null, fps: 30 },
images: undefined,
});
assert.deepEqual(body, {
mode: 'text2video',
prompt: 'hello',
aspect_ratio: '9:16',
ratio: '9:16',
duration: 10,
generate_audio: true,
audio: true,
return_last_frame: true,
});
});
test('缺图 / 上传中 / 失败时给出阻断原因', () => {
const base = { first_frame: null, last_frame: null, reference_images: [] };
assert.deepEqual(imageBlockReason(seedance, 'image2video', base), {
key: '请上传首帧图片',
});
assert.deepEqual(
imageBlockReason(seedance, 'first_last_frame', {
...base,
first_frame: ready('a'),
}),
{ key: '缺少尾帧' },
);
assert.deepEqual(
imageBlockReason(seedance, 'image2video', {
...base,
first_frame: { id: 'x', status: 'uploading' },
}),
{ key: '图片上传中,请稍候' },
);
assert.equal(
imageBlockReason(seedance, 'image2video', {
...base,
first_frame: ready('a'),
}),
null,
);
assert.deepEqual(imageBlockReason(vidu, 'image2video', base), {
key: '当前模型不支持该生成模式,请切换模式',
});
});
test('切换模型:会话值优先、记忆其次,不合法值吸附并报告', () => {
const { values, adjustments } = composeParams(vidu, {
sessionValues: { duration: 10, aspect_ratio: '9:16' },
memory: { duration: 4 },
});
assert.deepEqual(values, { duration: 8 });
assert.deepEqual(adjustments, [{ key: 'duration', from: 10, to: 8 }]);
const kept = composeParams(seedance, { memory: { duration: 10 } });
assert.equal(kept.values.duration, 10);
assert.equal(kept.values.camera_fixed, undefined);
});
test('切换模型时的模式选择', () => {
const images = {
first_frame: ready('a'),
last_frame: null,
reference_images: [],
};
assert.equal(
pickModeForModel(seedance, 'reference2video', images),
'image2video',
);
assert.equal(pickModeForModel(vidu, 'image2video', images), 'text2video');
assert.equal(
pickModeForModel(seedance, 'first_last_frame', images),
'first_last_frame',
);
});
const memoryStorage = (quota = Infinity) => {
const map = new Map();
return {
getItem: (k) => (map.has(k) ? map.get(k) : null),
setItem: (k, v) => {
if (v.length > quota) throw new Error('QuotaExceededError');
map.set(k, v);
},
map,
};
};
test('草稿 v3 往返;配额不足时丢弃内联图片', () => {
const storage = memoryStorage(400);
const form = {
mode: 'image2video',
prompt: 'cat',
selectedTemplate: '',
modelName: 'seedance',
params: { duration: 5 },
paramMemory: {},
images: {
first_frame: ready(`data:image/png;base64,${'A'.repeat(500)}`),
last_frame: { id: 'u', status: 'uploading' },
reference_images: [],
},
};
assert.equal(saveDraft(storage, form), true);
const loaded = loadDraft(storage);
assert.equal(loaded.prompt, 'cat');
assert.equal(loaded.images.first_frame, null);
assert.equal(loaded.images.last_frame, null);
assert.ok(storage.map.has(DRAFT_STORAGE_KEY));
});
test('损坏的草稿与抛异常的存储不影响加载', () => {
const broken = {
getItem: () => '{not json',
};
assert.equal(loadDraft(broken).mode, 'text2video');
const throwing = {
getItem: () => {
throw new Error('SecurityError');
},
setItem: () => {
throw new Error('SecurityError');
},
};
assert.equal(loadDraft(throwing).prompt, '');
assert.equal(saveDraft(throwing, loadDraft(throwing)), false);
});
test('轮询退避 3s → 5s → 10s,隐藏时降频', () => {
assert.deepEqual(
[0, 1, 2, 5].map((s) => pollDelay(s, false)),
[3000, 5000, 10000, 10000],
);
assert.equal(pollDelay(0, true), 30000);
});
test('formFromTaskRequest maps v2 request refs and params', () => {
let n = 0;
const form = formFromTaskRequest(
{
model: 'seedance',
mode: 'first_last_frame',
prompt: 'p',
resolution: '1080p',
duration: 10,
ratio: '9:16',
aspect_ratio: '9:16',
generate_audio: false,
audio: true,
seed: 0,
image: 'https://cos/first.png?sig',
image_ref: 'task://t1#first',
last_image: 'https://cos/last.png?sig',
last_image_ref: 'cos://u/last.png',
reference_images: ['asset://a1'],
reference_image_refs: ['asset://a1'],
},
{ newId: () => `id${n++}` },
);
assert.equal(form.modelName, 'seedance');
assert.equal(form.mode, 'first_last_frame');
assert.deepEqual(form.params, {
aspect_ratio: '9:16',
resolution: '1080p',
duration: 10,
generate_audio: false,
watermark: false,
seed: 0,
});
assert.equal(form.images.first_frame.ref, 'task://t1#first');
assert.equal(form.images.first_frame.previewUrl, 'https://cos/first.png?sig');
assert.equal(form.images.last_frame.ref, 'cos://u/last.png');
assert.equal(form.images.reference_images[0].ref, 'asset://a1');
assert.equal(form.images.reference_images[0].previewUrl, null);
assert.equal(form.images.reference_images[0].identityType, 'real_person');
// 吸附后 seedance 不支持 resolution,不会出现在请求里
const { values } = composeParams(seedance, { sessionValues: form.params });
const payload = buildVideoRequest(seedance, { ...form, params: values });
assert.equal(payload.resolution, undefined);
assert.equal(payload.image, 'task://t1#first');
assert.equal(payload.last_image, 'cos://u/last.png');
});
test('formFromTaskRequest falls back to legacy image field', () => {
const form = formFromTaskRequest({
mode: 'image2video',
image: 'https://x/a.png',
watermark: true,
});
assert.equal(form.images.first_frame.ref, 'https://x/a.png');
assert.equal(form.images.last_frame, null);
assert.equal(form.params.watermark, true);
});