🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(video): add fal H3 Max and Seedance 2.5 with exact request pricing (#20210)
YuTengjing3e6c83aa3b14
diff --git a/apps/server/src/router-hono/webhooks/handlers/video.ts b/apps/server/src/router-hono/webhooks/handlers/video.tsindex 8099407c171..4fede58ab71 100644--- a/apps/server/src/router-hono/webhooks/handlers/video.ts+++ b/apps/server/src/router-hono/webhooks/handlers/video.ts@@ -27,6 +27,7 @@ import { generationBatches } from '@/database/schemas';import { getServerDB } from '@/database/server';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { VideoGenerationService } from '@/server/services/generation/video';+import { measureVideoOutputUsage } from '@/server/services/generation/videoOutputUsage';import { sanitizeFileName } from '@/utils/sanitizeFileName';const log = debug('lobe-video:webhook');@@ -326,6 +327,7 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>try {await chargeAfterGenerate({computePriceParams: {+ duration: (batch?.config as RuntimeVideoGenParams)?.duration,generateAudio: (batch?.config as RuntimeVideoGenParams)?.generateAudio,resolution: (batch?.config as RuntimeVideoGenParams)?.resolution,},@@ -340,7 +342,7 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>model: resolvedModelId,prechargeResult: metadata?.precharge as any,provider,- usage: result.usage,+ usage: result.usage ?? measureVideoOutputUsage(resolvedModelId, processResult),userId: asyncTask.userId,workspaceId: asyncTask.workspaceId ?? undefined,});diff --git a/apps/server/src/routers/async/video.ts b/apps/server/src/routers/async/video.tsindex 0be5e57aac5..a3fc4190d3b 100644--- a/apps/server/src/routers/async/video.ts+++ b/apps/server/src/routers/async/video.ts@@ -22,6 +22,7 @@ import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { VideoGenerationService } from '@/server/services/generation/video';import { buildVideoGenerationFilePayload } from '@/server/services/generation/videoFile';+import { measureVideoOutputUsage } from '@/server/services/generation/videoOutputUsage';import { FileSource } from '@/types/files';const log = debug('lobe-video:async');@@ -226,6 +227,7 @@ export const videoRouter = router({try {await chargeAfterGenerate({computePriceParams: {+ duration: (batch?.config as any)?.duration,generateAudio: (batch?.config as any)?.generateAudio,resolution: (batch?.config as any)?.resolution,},@@ -244,7 +246,7 @@ export const videoRouter = router({model: resolvedModelId,prechargeResult,provider,- usage: undefined,+ usage: measureVideoOutputUsage(resolvedModelId, processResult),userId: ctx.userId,workspaceId,});diff --git a/apps/server/src/routers/lambda/__tests__/video.test.ts b/apps/server/src/routers/lambda/__tests__/video.test.tsindex c49fc02a5ca..66ad76121dd 100644--- a/apps/server/src/routers/lambda/__tests__/video.test.ts+++ b/apps/server/src/routers/lambda/__tests__/video.test.ts@@ -8,6 +8,7 @@ import { AsyncTaskStatus } from '@/types/asyncTask';const {mockCreateVideo,+ mockFillVideoPricingDefaults,mockFindPreviousGeneration,mockFindUserById,mockGenerationTopicFindById,@@ -33,6 +34,7 @@ const {const mockAfter = vi.fn(function (cb: () => void) {return cb();});+ const mockFillVideoPricingDefaults = vi.fn(async ({ params }: { params: unknown }) => params);const mockAppEnv = {APP_URL: 'https://app.example.com',VIDEO_GENERATION_PREFER_WEBHOOK: false,@@ -47,6 +49,7 @@ const {const mockResolveBusinessModelMapping = vi.fn();return {mockCreateVideo,+ mockFillVideoPricingDefaults,mockFindPreviousGeneration,mockFindUserById,mockGenerationTopicFindById,@@ -112,6 +115,9 @@ vi.mock('@lobechat/business-model-bank/model-config', () => ({]) => mockIsLobeHubModelAvailable(...args),}));+vi.mock('@/server/services/generation/videoPricingDefaults', () => ({+ fillVideoPricingDefaults: mockFillVideoPricingDefaults,+}));vi.mock('@/business/server/video-generation/getVideoFreeQuota', () => ({getVideoFreeQuota: vi.fn().mockResolvedValue({ remaining: 10 }),}));@@ -658,6 +664,36 @@ describe('videoRouter', () => {expect(chargeBeforeGenerate).toHaveBeenCalledWith(expect.objectContaining({ spendOrigin }));});+ it('prices and generates with the model defaults the request omitted', async () => {+ setupMocks();+ const { chargeBeforeGenerate } =+ await import('@/business/server/video-generation/chargeBeforeGenerate');+ mockFillVideoPricingDefaults.mockImplementationOnce(async ({ params }) => ({+ ...(params as object),+ duration: 5,+ resolution: '768P',+ }));++ const caller = videoRouter.createCaller(mockCtx);+ await caller.createVideo(defaultInput);++ expect(mockFillVideoPricingDefaults).toHaveBeenCalledWith(+ expect.objectContaining({ params: defaultInput.params }),+ );+ expect(chargeBeforeGenerate).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({ duration: 5, resolution: '768P' }),+ providerParams: expect.objectContaining({ duration: 5, resolution: '768P' }),+ }),+ );+ expect(mockCreateVideo).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({ duration: 5, resolution: '768P' }),+ }),+ expect.anything(),+ );+ });+it('should return error batch when pre-charge fails', async () => {setupMocks();const { chargeBeforeGenerate } =diff --git a/apps/server/src/routers/lambda/video/index.ts b/apps/server/src/routers/lambda/video/index.tsindex b44286e6b6d..2391a5137a1 100644--- a/apps/server/src/routers/lambda/video/index.ts+++ b/apps/server/src/routers/lambda/video/index.ts@@ -45,6 +45,7 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { FileService } from '@/server/services/file';import { getVideoAvgLatencies, getVideoLatencyKey } from '@/server/services/generation/latency';import { processBackgroundVideoPolling } from '@/server/services/generation/videoBackgroundPolling';+import { fillVideoPricingDefaults } from '@/server/services/generation/videoPricingDefaults';import { after } from '@/server/utils/scheduleAfterResponse';import { AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';@@ -104,9 +105,15 @@ export const videoRouter = router({.mutation(async ({ input, ctx }) => {const { userId, serverDB, asyncTaskModel, fileService, generationTopicModel } = ctx;const wsId = ctx.workspaceId ?? undefined;- const { generationTopicId, previousGenerationId, provider, model, params } = input;+ const { generationTopicId, previousGenerationId, provider, model } = input;const { resolvedModelId } = await resolveBusinessModelMapping(provider, model);+ // Everything downstream (billing, stored config, provider request) sees the same params+ const params = await fillVideoPricingDefaults({+ model: resolvedModelId,+ params: input.params,+ provider,+ });// Reject lobehub model ids that are no longer in the model bank so callers get a// clear error instead of an opaque downstream failure when the resolved channel@@ -281,6 +288,7 @@ export const videoRouter = router({model,params,provider,+ providerParams: generationParams,spendOrigin: ctx.spendOrigin,userId,workspaceId: wsId,diff --git a/apps/server/src/services/generation/video.ts b/apps/server/src/services/generation/video.tsindex 4e7b0d56780..662e391b3c3 100644--- a/apps/server/src/services/generation/video.ts+++ b/apps/server/src/services/generation/video.ts@@ -39,6 +39,8 @@ export interface VideoProcessResult {duration: number;fileHash: string;fileSize: number;+ /** Frames in the video stream; `undefined` when ffmpeg could not count them */+ frames?: number;height: number;mimeType: string;thumbnailKey: string;@@ -73,8 +75,9 @@ export class VideoGenerationService {try {tempVideoPath = await this.downloadVideo(videoUrl, options);- const [metadata, videoBuffer] = await Promise.all([+ const [metadata, frames, videoBuffer] = await Promise.all([this.getVideoMetadata(tempVideoPath),+ this.countVideoFrames(tempVideoPath),fs.readFile(String(tempVideoPath)),]);@@ -142,6 +145,7 @@ export class VideoGenerationService {duration: metadata.duration,fileHash,fileSize,+ frames,height: metadata.height,mimeType,thumbnailKey,@@ -287,6 +291,34 @@ export class VideoGenerationService {};}+ /**+ * Count the video stream's frames by remuxing it to a null sink (no decoding). Models billed by+ * output tokens bill every frame, and the container duration cannot recover the count once an+ * audio track is longer than the video.+ */+ private async countVideoFrames(videoPath: string): Promise<number | undefined> {+ try {+ const { stderr } = await execFileAsync(getFfmpegPath(), [+ '-hide_banner',+ '-i',+ videoPath,+ '-map',+ '0:v:0',+ '-c',+ 'copy',+ '-f',+ 'null',+ '-',+ ]);+ const counts = [...stderr.matchAll(/frame=\s*(\d+)/g)];+ const frames = Number(counts.at(-1)?.[1]);+ return frames > 0 ? frames : undefined;+ } catch (error) {+ log('Failed to count video frames: %O', error);+ return undefined;+ }+ }+/*** Take a screenshot at 0.1s and return the temp file path*/diff --git a/apps/server/src/services/generation/videoBackgroundPolling.test.ts b/apps/server/src/services/generation/videoBackgroundPolling.test.tsindex c35a0666c47..52109072b19 100644--- a/apps/server/src/services/generation/videoBackgroundPolling.test.ts+++ b/apps/server/src/services/generation/videoBackgroundPolling.test.ts@@ -192,6 +192,40 @@ describe('videoBackgroundPolling', () => {);});+ it('bills output tokens from the downloaded video when the provider reports no usage', async () => {+ // Resolved once to poll and once to charge+ vi.mocked(resolveBusinessModelMapping)+ .mockResolvedValueOnce({ resolvedModelId: 'bytedance/seedance-2.5' } as any)+ .mockResolvedValueOnce({ resolvedModelId: 'bytedance/seedance-2.5' } as any);+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ });+ mockVideoService.processVideoForGeneration.mockResolvedValue({+ coverKey: 'cover-key',+ duration: 4.04,+ fileHash: 'hash',+ fileSize: 1024,+ frames: 97,+ height: 592,+ mimeType: 'video/mp4',+ thumbnailKey: 'thumb-key',+ videoKey: 'video-key',+ width: 710,+ });++ await processBackgroundVideoPolling(mockDb, mockParams);++ // fal billed 39.815K tokens for this image-to-video output+ const tokens = 39_815;+ expect(chargeAfterGenerate).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'bytedance/seedance-2.5',+ usage: { completionTokens: tokens, totalTokens: tokens },+ }),+ );+ });+it('should poll the pinned route with the mapped model id instead of the alias', async () => {vi.mocked(resolveBusinessModelMapping).mockResolvedValueOnce({resolvedModelId: 'mapped-model',diff --git a/apps/server/src/services/generation/videoBackgroundPolling.ts b/apps/server/src/services/generation/videoBackgroundPolling.tsindex 5b05800ae7d..84a243c1341 100644--- a/apps/server/src/services/generation/videoBackgroundPolling.ts+++ b/apps/server/src/services/generation/videoBackgroundPolling.ts@@ -18,6 +18,7 @@ import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { VideoGenerationService } from '@/server/services/generation/video';import { buildVideoGenerationFilePayload } from '@/server/services/generation/videoFile';+import { measureVideoOutputUsage } from '@/server/services/generation/videoOutputUsage';import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';import { FileSource } from '@/types/files';import type { VideoGenerationAsset } from '@/types/generation';@@ -151,6 +152,7 @@ export async function processBackgroundVideoPolling(const { resolvedModelId } = await resolveBusinessModelMapping(provider, model);await chargeAfterGenerate({computePriceParams: {+ duration: (batch?.config as RuntimeVideoGenParams | undefined)?.duration,generateAudio: (batch?.config as RuntimeVideoGenParams | undefined)?.generateAudio,resolution: (batch?.config as RuntimeVideoGenParams | undefined)?.resolution,},@@ -169,7 +171,7 @@ export async function processBackgroundVideoPolling(model: resolvedModelId,prechargeResult,provider,- usage: pollResult.usage,+ usage: pollResult.usage ?? measureVideoOutputUsage(resolvedModelId, processResult),userId,workspaceId,});diff --git a/apps/server/src/services/generation/videoOutputUsage.test.ts b/apps/server/src/services/generation/videoOutputUsage.test.tsnew file mode 100644index 00000000000..931821ed831--- /dev/null+++ b/apps/server/src/services/generation/videoOutputUsage.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { measureVideoOutputUsage } from './videoOutputUsage';++describe('measureVideoOutputUsage', () => {+ it('counts output tokens from the frame size and frame count', () => {+ // fal billed 39.815K tokens for this Seedance 2.5 image-to-video output+ const tokens = 39_815;++ expect(+ measureVideoOutputUsage('bytedance/seedance-2.5', { frames: 97, height: 592, width: 710 }),+ ).toEqual({ completionTokens: tokens, totalTokens: tokens });+ });++ it('returns undefined when the frame count is unknown', () => {+ expect(+ measureVideoOutputUsage('bytedance/seedance-2.5', { height: 592, width: 710 }),+ ).toBeUndefined();+ });++ it('returns undefined for models not billed by output tokens', () => {+ expect(+ measureVideoOutputUsage('minimax/h3-max', { frames: 121, height: 480, width: 832 }),+ ).toBeUndefined();+ });+});diff --git a/apps/server/src/services/generation/videoOutputUsage.ts b/apps/server/src/services/generation/videoOutputUsage.tsnew file mode 100644index 00000000000..21a7f81e4f7--- /dev/null+++ b/apps/server/src/services/generation/videoOutputUsage.ts@@ -0,0 +1,17 @@+import { countVideoOutputTokens, type VideoGenerationUsage } from '@lobechat/model-runtime';++import type { VideoProcessResult } from './video';++/**+ * Usage of a video whose provider reports none but bills output tokens (fal Seedance 2.5): the+ * tokens follow the downloaded video's frame size and frame count, exactly what the provider bills.+ */+export const measureVideoOutputUsage = (+ model: string,+ { frames, height, width }: Pick<VideoProcessResult, 'frames' | 'height' | 'width'>,+): VideoGenerationUsage | undefined => {+ if (!frames) return undefined;++ const tokens = countVideoOutputTokens(model, { frames, height, width });+ return tokens === undefined ? undefined : { completionTokens: tokens, totalTokens: tokens };+};diff --git a/apps/server/src/services/generation/videoPricingDefaults.test.ts b/apps/server/src/services/generation/videoPricingDefaults.test.tsnew file mode 100644index 00000000000..2b62ffcfea0--- /dev/null+++ b/apps/server/src/services/generation/videoPricingDefaults.test.ts@@ -0,0 +1,98 @@+// @vitest-environment node+import { getModelParameters, getModelPricing } from '@lobechat/model-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { fillVideoPricingDefaults } from './videoPricingDefaults';++vi.mock('@lobechat/model-runtime', async (importOriginal) => ({+ ...((await importOriginal()) as object),+ getModelParameters: vi.fn(),+ getModelPricing: vi.fn(),+}));++const perSecondPricing = {+ units: [+ {+ lookup: { prices: { '480P': 0.05, '768P': 0.08 }, pricingParams: ['resolution'] },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'second',+ },+ ],+};++const parameters = {+ duration: { default: 5, enum: [5, 10] },+ prompt: { default: '' },+ resolution: { default: '768P', enum: ['480P', '768P'] },+ seed: { default: null },+};++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(getModelPricing).mockResolvedValue(perSecondPricing as any);+ vi.mocked(getModelParameters).mockResolvedValue(parameters as any);+});++describe('fillVideoPricingDefaults', () => {+ it('fills omitted pricing params from the model card defaults', async () => {+ const result = await fillVideoPricingDefaults({+ model: 'minimax/h3-max',+ params: { prompt: 'a cat' },+ provider: 'lobehub',+ });++ expect(result).toEqual({ duration: 5, prompt: 'a cat', resolution: '768P' });+ });++ it('keeps params the request already set', async () => {+ const result = await fillVideoPricingDefaults({+ model: 'minimax/h3-max',+ params: { duration: 10, prompt: 'a cat', resolution: '480P' },+ provider: 'lobehub',+ });++ expect(result).toEqual({ duration: 10, prompt: 'a cat', resolution: '480P' });+ });++ it('leaves params untouched when the price does not depend on them', async () => {+ vi.mocked(getModelPricing).mockResolvedValue({ approximatePricePerVideo: 0.4, units: [] });+ const params = { prompt: 'a cat' };++ const result = await fillVideoPricingDefaults({+ model: 'other',+ params,+ provider: 'lobehub',+ });++ expect(result).toBe(params);+ expect(getModelParameters).not.toHaveBeenCalled();+ });+});++describe('fillVideoPricingDefaults for output-token models', () => {+ it('fills the params the output-token meter reads', async () => {+ vi.mocked(getModelPricing).mockResolvedValue({+ units: [{ name: 'videoGeneration', rate: 21.4, strategy: 'fixed', unit: 'millionTokens' }],+ } as any);+ vi.mocked(getModelParameters).mockResolvedValue({+ aspectRatio: { default: '16:9', enum: ['16:9', '1:1'] },+ duration: { default: 5, max: 30, min: 4 },+ prompt: { default: '' },+ resolution: { default: '720p', enum: ['480p', '720p'] },+ } as any);++ const result = await fillVideoPricingDefaults({+ model: 'bytedance/seedance-2.5',+ params: { prompt: 'a kite', resolution: '480p' },+ provider: 'lobehub',+ });++ expect(result).toEqual({+ aspectRatio: '16:9',+ duration: 5,+ prompt: 'a kite',+ resolution: '480p',+ });+ });+});diff --git a/apps/server/src/services/generation/videoPricingDefaults.ts b/apps/server/src/services/generation/videoPricingDefaults.tsnew file mode 100644index 00000000000..7ead8f4790e--- /dev/null+++ b/apps/server/src/services/generation/videoPricingDefaults.ts@@ -0,0 +1,37 @@+import {+ getModelParameters,+ getModelPricing,+ getVideoOutputTokenParamNames,+ getVideoPricingParamNames,+} from '@lobechat/model-runtime';+import type { VideoModelParamsSchema } from 'model-bank';++/**+ * Fill request params the price depends on (e.g. `duration`, `resolution`) from the model card+ * defaults. Callers such as agent tools may omit them; the provider would then generate with its+ * own default while billing could not see it, so the request is made explicit before pricing.+ */+export const fillVideoPricingDefaults = async <T extends Record<string, unknown>>(params: {+ model: string;+ params: T;+ provider: string;+}): Promise<T> => {+ const { model, provider } = params;+ const names = [+ ...new Set([+ ...getVideoPricingParamNames(await getModelPricing(model, provider)),+ ...getVideoOutputTokenParamNames(model),+ ]),+ ];+ if (names.length === 0) return params.params;++ const schema = (await getModelParameters(model, provider)) as VideoModelParamsSchema | undefined;+ const filled: Record<string, unknown> = { ...params.params };+ for (const name of names) {+ const defaultValue = (schema?.[name as keyof VideoModelParamsSchema] as { default?: unknown })+ ?.default;+ if (filled[name] == null && defaultValue != null) filled[name] = defaultValue;+ }++ return filled as T;+};diff --git a/locales/en-US/models.json b/locales/en-US/models.jsonindex 3816c19d47c..a39cb91c25c 100644--- a/locales/en-US/models.json+++ b/locales/en-US/models.json@@ -982,6 +982,7 @@"minimax-m2.5.description": "MiniMax M2.5 — efficient coding model with strong reasoning abilities.","minimax-m2.7.description": "MiniMax M2.7 — latest MiniMax coding model with improved reasoning and tool use.","minimax-m3.description": "MiniMax M3 — latest MiniMax model with vision support, strong reasoning, and improved tool use.",+ "minimax/h3-max.description": "fal's post-trained MiniMax H3 with stronger prompt adherence and aesthetics, supporting text-to-video, first/last-frame image-to-video, and reference-to-video with native audio.","minimax/minimax-m2.1.description": "MiniMax-M2.1 is a lightweight, cutting-edge large language model optimized for coding, proxy workflows, and modern application development, providing cleaner, more concise output and faster perceptual response times.","minimax/minimax-m2.description": "MiniMax-M2 is a high-value model that excels at coding and agent tasks for many engineering scenarios.","minimaxai/minimax-m2.7.description": "MiniMax M2.7 is a 229B-parameter MoE model (~10B active) built for agentic workflows and real-world software engineering. It interleaves thinking with actions across multi-step tasks and is available on Groq for Enterprise customers.",diff --git a/locales/en-US/video.json b/locales/en-US/video.jsonindex 3f799ea6c8f..9f419224371 100644--- a/locales/en-US/video.json+++ b/locales/en-US/video.json@@ -1,16 +1,22 @@{+ "config.aspectRatio.followStartFrame": "Follows the start frame","config.aspectRatio.label": "Aspect Ratio","config.cameraFixed.label": "Fixed Camera","config.duration.label": "Duration","config.endImageUrl.label": "End Frame","config.generateAudio.label": "Generate Audio","config.header.title": "Video",+ "config.imageInputMode.frames": "Frames",+ "config.imageInputMode.reference": "References","config.imageUpload.maxCountReached": "You can add up to {{count}} reference images","config.imageUrl.label": "Start Frame","config.prompt.editPlaceholder": "Describe what you want to change in this video","config.prompt.placeholder": "Describe the video you want to generate","config.prompt.placeholderWithRef": "Describe the scene you want to generate with the image",+ "config.prompt.placeholderWithReference": "Describe the video, referring to the images as Image 1, Image 2…","config.promptExtend.label": "Prompt Extend",+ "config.referenceImage.count": "Reference {{count}}/{{max}}",+ "config.referenceImage.indexedLabel": "Image {{index}}","config.referenceImage.label": "Reference Image","config.resolution.label": "Resolution","config.seed.label": "Seed",diff --git a/locales/zh-CN/models.json b/locales/zh-CN/models.jsonindex 15b9d397771..e70c3ee9ecb 100644--- a/locales/zh-CN/models.json+++ b/locales/zh-CN/models.json@@ -982,6 +982,7 @@"minimax-m2.5.description": "MiniMax M2.5 —— 高效代码模型,具备强推理能力。","minimax-m2.7.description": "MiniMax M2.7 —— MiniMax 最新代码模型,推理与工具调用能力进一步增强。","minimax-m3.description": "MiniMax M3——最新的MiniMax模型,支持视觉功能,具有强大的推理能力和改进的工具使用。",+ "minimax/h3-max.description": "fal 基于 MiniMax H3 后训练的版本,提示词遵循和画面美感更强,支持文生视频、首尾帧图生视频与参考生视频,并原生生成音频。","minimax/minimax-m2.1.description": "MiniMax-M2.1 是一款轻量级、前沿的大语言模型,专为编程、代理工作流和现代应用开发而优化,提供更简洁的输出和更快的响应速度。","minimax/minimax-m2.description": "MiniMax-M2 是一款高性价比模型,擅长编程和智能体任务,适用于多种工程场景。","minimaxai/minimax-m2.7.description": "MiniMax M2.7 是一个拥有 2290 亿参数(约 100 亿激活参数)的 MoE 模型,专为代理工作流和实际软件工程设计。它在多步任务中交替进行思考与行动,并为企业客户提供 Groq 平台支持。",diff --git a/locales/zh-CN/video.json b/locales/zh-CN/video.jsonindex cc4af3b10ca..31c93e2634f 100644--- a/locales/zh-CN/video.json+++ b/locales/zh-CN/video.json@@ -1,16 +1,22 @@{+ "config.aspectRatio.followStartFrame": "跟随起始画面","config.aspectRatio.label": "宽高比","config.cameraFixed.label": "固定镜头","config.duration.label": "时长","config.endImageUrl.label": "结束画面","config.generateAudio.label": "生成音频","config.header.title": "视频",+ "config.imageInputMode.frames": "首尾帧",+ "config.imageInputMode.reference": "参考图","config.imageUpload.maxCountReached": "最多可添加 {{count}} 张参考图","config.imageUrl.label": "起始画面","config.prompt.editPlaceholder": "描述你希望如何修改这个视频","config.prompt.placeholder": "描述你想生成的视频内容","config.prompt.placeholderWithRef": "结合图片,描述你想生成的画面",+ "config.prompt.placeholderWithReference": "描述你想生成的视频,可用“图1”“图2”指代参考图","config.promptExtend.label": "提示词扩展",+ "config.referenceImage.count": "参考图 {{count}}/{{max}}",+ "config.referenceImage.indexedLabel": "图{{index}}","config.referenceImage.label": "参考图像","config.resolution.label": "分辨率","config.seed.label": "种子",diff --git a/packages/business-server/src/video-generation/chargeAfterGenerate.ts b/packages/business-server/src/video-generation/chargeAfterGenerate.tsindex ac56eb8c9ea..7ef2bded756 100644--- a/packages/business-server/src/video-generation/chargeAfterGenerate.ts+++ b/packages/business-server/src/video-generation/chargeAfterGenerate.ts@@ -1,7 +1,7 @@import { type SpendOrigin } from '@lobechat/types';interface ChargeParams {- computePriceParams?: { generateAudio?: boolean; resolution?: string };+ computePriceParams?: { duration?: number; generateAudio?: boolean; resolution?: string };isError?: boolean;/** Total time from task submission to webhook callback (ms) */latency?: number;diff --git a/packages/business-server/src/video-generation/chargeBeforeGenerate.ts b/packages/business-server/src/video-generation/chargeBeforeGenerate.tsindex 5f87d801ae9..75e1a3d60d8 100644--- a/packages/business-server/src/video-generation/chargeBeforeGenerate.ts+++ b/packages/business-server/src/video-generation/chargeBeforeGenerate.ts@@ -8,6 +8,8 @@ interface ChargeParams {model: string;params: CreateVideoServicePayload['params'];provider: string;+ /** Params as sent to the provider, whose image URLs are the ones it fetches */+ providerParams?: CreateVideoServicePayload['params'];/** Origin of the request, preserved for deferred video spend attribution. */spendOrigin?: SpendOrigin;userId: string;diff --git a/packages/locales/src/default/video.ts b/packages/locales/src/default/video.tsindex 02e17c69bb6..3bcc3e91bac 100644--- a/packages/locales/src/default/video.ts+++ b/packages/locales/src/default/video.ts@@ -1,16 +1,23 @@export default {+ 'config.aspectRatio.followStartFrame': 'Follows the start frame','config.aspectRatio.label': 'Aspect Ratio','config.cameraFixed.label': 'Fixed Camera','config.duration.label': 'Duration','config.endImageUrl.label': 'End Frame','config.generateAudio.label': 'Generate Audio','config.header.title': 'Video',+ 'config.imageInputMode.frames': 'Frames',+ 'config.imageInputMode.reference': 'References','config.imageUpload.maxCountReached': 'You can add up to {{count}} reference images','config.imageUrl.label': 'Start Frame','config.prompt.editPlaceholder': 'Describe what you want to change in this video',+ 'config.prompt.placeholderWithReference':+ 'Describe the video, referring to the images as Image 1, Image 2…','config.promptExtend.label': 'Prompt Extend','config.prompt.placeholder': 'Describe the video you want to generate','config.prompt.placeholderWithRef': 'Describe the scene you want to generate with the image',+ 'config.referenceImage.count': 'Reference {{count}}/{{max}}',+ 'config.referenceImage.indexedLabel': 'Image {{index}}','config.referenceImage.label': 'Reference Image','config.resolution.label': 'Resolution','config.seed.label': 'Seed',diff --git a/packages/model-bank/src/aiModels/__tests__/index.test.ts b/packages/model-bank/src/aiModels/__tests__/index.test.tsindex 9967a7390d3..c250c9fd98d 100644--- a/packages/model-bank/src/aiModels/__tests__/index.test.ts+++ b/packages/model-bank/src/aiModels/__tests__/index.test.ts@@ -197,7 +197,7 @@ describe('MiniMax video models', () => {parameters: expect.objectContaining({aspectRatio: expect.objectContaining({ default: '16:9' }),duration: expect.objectContaining({ max: 15, min: 4 }),- imageUrls: expect.objectContaining({ maxCount: 7 }),+ imageUrls: expect.objectContaining({ maxCount: 9 }),resolution: expect.objectContaining({ default: '768P', enum: ['768P', '2K'] }),}),releasedAt: '2026-07-31',@@ -206,26 +206,14 @@ describe('MiniMax video models', () => {);});- it('keeps the combined MiniMax-H3 reference capacity within the v2 limit of 9', () => {+ it('lets References mode fill the whole MiniMax-H3 reference pool of 9', () => {const h3 = LOBE_DEFAULT_MODEL_LIST.find((model) => model.providerId === ModelProvider.Minimax && model.id === 'MiniMax-H3',);- const parameters = (h3?.parameters ?? {}) as {- endImageUrl?: unknown;- imageUrl?: unknown;- imageUrls?: { maxCount?: number };- };-- // The first-frame (imageUrl), reference-list (imageUrls), and last-frame- // (endImageUrl) slots all normalize into a single reference pool that the- // runtime caps at 9. The combined upload capacity must stay within that- // limit so the UI can never assemble a payload createVideo would reject.- const firstFrameSlots = parameters.imageUrl === undefined ? 0 : 1;- const lastFrameSlots = parameters.endImageUrl === undefined ? 0 : 1;- const referenceSlots = parameters.imageUrls?.maxCount ?? 0;-- expect(firstFrameSlots + referenceSlots + lastFrameSlots).toBeLessThanOrEqual(9);+ // The UI's References mode clears the frame slots and submits only imageUrls, so the+ // reference slot alone must allow the full pool the v2 API accepts.+ expect((h3?.parameters as { imageUrls?: { maxCount?: number } })?.imageUrls?.maxCount).toBe(9);});});diff --git a/packages/model-bank/src/aiModels/fal.ts b/packages/model-bank/src/aiModels/fal.tsindex 2dcbacd818e..11a8e9539fd 100644--- a/packages/model-bank/src/aiModels/fal.ts+++ b/packages/model-bank/src/aiModels/fal.ts@@ -1,5 +1,5 @@import type { ModelParamsSchema } from '../standard-parameters';-import type { AIImageModelCard } from '../types/aiModel';+import type { AIImageModelCard, AIVideoModelCard } from '../types/aiModel';export const fluxSchnellParamsSchema: ModelParamsSchema = {height: { default: 1024, max: 1536, min: 512, step: 1 },@@ -221,6 +221,110 @@ const falImageModels: AIImageModelCard[] = [},];-export const allModels = [...falImageModels];+const falVideoModels: AIVideoModelCard[] = [+ {+ description:+ "ByteDance's Seedance 2.5 on fal, generating up to 30-second single-shot videos with native audio from text, first/last frames, or up to 30 reference images.",+ displayName: 'Seedance 2.5',+ enabled: true,+ // One card for the fal app; the runtime picks text-to-video, image-to-video or+ // reference-to-video from the supplied images.+ id: 'bytedance/seedance-2.5',+ organization: 'ByteDance',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['21:9', '16:9', '4:3', '1:1', '3:4', '9:16'],+ },+ duration: { default: 5, max: 30, min: 4, step: 1 },+ endImageUrl: { default: null, maxFileSize: 30 * 1024 * 1024, requiresImageUrl: true },+ generateAudio: { default: true },+ imageUrl: { default: null, maxFileSize: 30 * 1024 * 1024 },+ imageUrls: { default: [], maxCount: 30, maxFileSize: 30 * 1024 * 1024 },+ prompt: { default: '' },+ resolution: { default: '720p', enum: ['480p', '720p', '1080p'] },+ seed: { default: null },+ },+ pricing: {+ // 5 seconds at the default 720p 16:9+ approximatePricePerVideo: 2.33,+ units: [+ {+ // Output tokens: width × height × (24 × seconds + 1) / 1024, with or without audio+ // (see meterVideoOutputTokens); input images are not billed. fal lists $0.0214 / 1K+ // tokens but bills 1080p at 1.094× the tokens (measured on every aspect ratio), so+ // its rate is 21.4 × 1.094+ lookup: {+ prices: { '1080p': 23.4116, '480p': 21.4, '720p': 21.4 },+ pricingParams: ['resolution'],+ },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'millionTokens',+ },+ ],+ },+ releasedAt: '2026-08-12',+ type: 'video',+ },+ {+ description:+ "fal's post-trained MiniMax H3 with stronger prompt adherence and aesthetics, supporting text-to-video, first/last-frame image-to-video, and reference-to-video with native audio.",+ displayName: 'H3 Max',+ enabled: true,+ // One card for the fal app; the runtime picks text-to-video, image-to-video or+ // reference-to-video from the supplied images.+ id: 'minimax/h3-max',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['21:9', '16:9', '4:3', '1:1', '3:4', '9:16'],+ },+ duration: { default: 5, max: 15, min: 5, step: 1 },+ endImageUrl: { default: null },+ imageUrl: { default: null },+ imageUrls: {+ aspectRatio: { max: 2.5, min: 0.4 },+ default: [],+ maxCount: 9,+ },+ prompt: { default: '' },+ promptExtend: { default: 'balanced', enum: ['disabled', 'balanced', 'quality'] },+ resolution: { default: '768P', enum: ['480P', '768P', '1080P'] },+ seed: { default: null },+ },+ pricing: {+ // 5 seconds at the default 768P+ approximatePricePerVideo: 0.4,+ units: [+ {+ lookup: {+ prices: { '1080P': 0.16, '480P': 0.05, '768P': 0.08 },+ pricingParams: ['resolution'],+ },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'second',+ },+ {+ // Reference tokens above 4,096 per request at $0.02 / 1K; tokens per image follow the+ // aspect ratio (see countVideoReferenceImageTokens)+ mode: 'graduated',+ name: 'imageInput',+ strategy: 'tiered',+ tiers: [+ { rate: 0, upTo: 4096 },+ { rate: 20, upTo: 'infinity' },+ ],+ unit: 'millionTokens',+ },+ ],+ },+ releasedAt: '2026-09-01',+ type: 'video',+ },+];++export const allModels = [...falImageModels, ...falVideoModels];export default allModels;diff --git a/packages/model-bank/src/aiModels/minimax.ts b/packages/model-bank/src/aiModels/minimax.tsindex eea6781437d..b0b105a3eef 100644--- a/packages/model-bank/src/aiModels/minimax.ts+++ b/packages/model-bank/src/aiModels/minimax.ts@@ -397,13 +397,10 @@ const minimaxVideoModels: AIVideoModelCard[] = [},imageUrls: {default: [],- // The v2 API accepts at most 9 images total across the first-frame- // (imageUrl), reference-list (imageUrls), and last-frame (endImageUrl)- // slots, which all normalize into a single reference pool at runtime.- // Cap the reference array at 7 so the combined upload capacity- // (1 + 7 + 1) never exceeds 9 — otherwise the UI could assemble a- // payload that createVideo rejects.- maxCount: 7,+ // The v2 API accepts at most 9 images in the reference pool. The UI's+ // References mode submits only imageUrls (the frame slots are cleared),+ // so the whole pool is available here.+ maxCount: 9,},prompt: { default: '' },resolution: {diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex 63ddcf976d7..70a93e347c2 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -198,6 +198,14 @@ export interface FixedPricingUnit extends PricingUnitBase {}export interface TieredPricingUnit extends PricingUnitBase {+ /**+ * How tiers apply to a quantity:+ * - `volume` (default): the whole quantity is billed at the rate of the tier it falls into+ * (e.g. Google's long-context pricing)+ * - `graduated`: each tier bills only the part of the quantity inside it, so a zero-rate first+ * tier expresses a free allowance (e.g. fal's 4,096 free reference tokens per request)+ */+ mode?: 'graduated' | 'volume';strategy: 'tiered';tiers: Array<{/**diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.tsindex f89ec801bf1..694f983b04d 100644--- a/packages/model-runtime/src/core/usageConverters/index.ts+++ b/packages/model-runtime/src/core/usageConverters/index.ts@@ -11,7 +11,15 @@ export {type PricingComputationResult,} from './utils/computeChatCost';export { computeImageCost } from './utils/computeImageCost';-export { computeVideoCost } from './utils/computeVideoCost';+export {+ computeVideoCost,+ computeVideoRequestCost,+ getVideoPricingParamNames,+ getVideoReferenceImages,+ needsVideoReferenceImageTokens,+ type VideoGenerationParams,+ type VideoRequestPricingInputs,+} from './utils/computeVideoCost';export {type ChatCostEstimate,type ChatInputTokenEstimate,@@ -25,3 +33,14 @@ export {} from './utils/estimateChatCost';export { resolveImageSinglePrice } from './utils/resolveImageSinglePrice';export { resolveVideoSinglePrice } from './utils/resolveVideoSinglePrice';+export {+ countVideoOutputTokens,+ getVideoOutputTokenParamNames,+ meterVideoOutputTokens,+ type VideoOutputFrames,+ type VideoOutputTokenEstimate,+} from './utils/videoOutputTokens';+export {+ countVideoReferenceImageTokens,+ type ImageDimensions,+} from './utils/videoReferenceImageTokens';diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.tsindex d039db8cb1b..639241c2bfa 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts@@ -2,7 +2,7 @@ import type { Pricing } from 'model-bank';import { describe, expect, it } from 'vitest';import type { VideoGenerationParams } from './computeVideoCost';-import { computeVideoCost } from './computeVideoCost';+import { computeVideoCost, computeVideoRequestCost } from './computeVideoCost';describe('computeVideoCost', () => {describe('fixed pricing strategy', () => {@@ -287,4 +287,195 @@ describe('computeVideoCost', () => {expect(Number.isInteger(result?.totalCredits)).toBe(true);});});++ describe('per-second pricing', () => {+ const lookupPricing: Pricing = {+ units: [+ {+ lookup: {+ prices: { '1080P': 0.16, '480P': 0.05, '768P': 0.08 },+ pricingParams: ['resolution'],+ },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'second',+ },+ ],+ };++ it('bills requested duration at the resolution rate and ignores tokens', () => {+ const result = computeVideoCost(lookupPricing, 123_456, {+ duration: 10,+ resolution: '768P',+ });++ expect(result?.totalCost).toBeCloseTo(0.8);+ expect(result?.breakdown).toMatchObject({+ durationSeconds: 10,+ lookupKey: '768P',+ pricePerSecond: 0.08,+ });+ });++ it('supports a fixed per-second rate', () => {+ const pricing: Pricing = {+ units: [{ name: 'videoGeneration', rate: 0.05, strategy: 'fixed', unit: 'second' }],+ };++ expect(computeVideoCost(pricing, 0, { duration: 6 })?.totalCost).toBeCloseTo(0.3);+ });++ it('returns undefined without a duration or a matching lookup price', () => {+ expect(computeVideoCost(lookupPricing, 0, { resolution: '768P' })).toBeUndefined();+ expect(computeVideoCost(lookupPricing, 0, { duration: 5, resolution: '4K' })).toBeUndefined();+ });+ });+});++describe('computeVideoRequestCost', () => {+ // fal H3 Max reference-to-video: requested seconds by resolution, plus reference tokens above a+ // 4,096-token allowance at $0.02 / 1K (https://fal.ai/models/minimax/h3-max/reference-to-video)+ const h3MaxPricing: Pricing = {+ units: [+ {+ lookup: {+ prices: { '1080P': 0.16, '480P': 0.05, '768P': 0.08 },+ pricingParams: ['resolution'],+ },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'second',+ },+ {+ mode: 'graduated',+ name: 'imageInput',+ strategy: 'tiered',+ tiers: [+ { rate: 0, upTo: 4096 },+ { rate: 20, upTo: 'infinity' },+ ],+ unit: 'millionTokens',+ },+ ],+ };+ const images = (count: number) => Array.from({ length: count }, (_, i) => `https://img/${i}.png`);++ it('prices text-to-video from the requested duration alone', () => {+ const result = computeVideoRequestCost(h3MaxPricing, { duration: 15, resolution: '1080P' });++ expect(result?.totalCost).toBeCloseTo(2.4, 10);+ expect(result?.breakdown?.units).toEqual([+ {+ cost: expect.closeTo(2.4, 10),+ lookupKey: '1080P',+ name: 'videoGeneration',+ quantity: 15,+ unit: 'second',+ },+ { cost: 0, lookupKey: undefined, name: 'imageInput', quantity: 0, unit: 'millionTokens' },+ ]);+ });++ it('matches fal published examples for reference tokens', () => {+ // 5 square images: 5 × 1,024 tokens, 1,024 above the allowance+ expect(+ computeVideoRequestCost(+ h3MaxPricing,+ { duration: 5, imageUrls: images(5), resolution: '480P' },+ { referenceImageTokens: 5120 },+ )?.totalCost,+ ).toBeCloseTo(0.270_48, 10);+ // Within the allowance, references add nothing+ expect(+ computeVideoRequestCost(+ h3MaxPricing,+ { duration: 5, imageUrls: images(4), resolution: '768P' },+ { referenceImageTokens: 4096 },+ )?.totalCost,+ ).toBeCloseTo(0.4, 10);+ });++ it('matches billed units of calibration requests', () => {+ // fal bills reference-to-video in 480P seconds ($0.05); 4 × 6:5 images → 5.3072 units+ expect(+ computeVideoRequestCost(+ h3MaxPricing,+ { duration: 5, imageUrls: images(4), resolution: '480P' },+ { referenceImageTokens: 4 * 1216 },+ )?.totalCost,+ ).toBeCloseTo(5.3072 * 0.05, 10);+ });++ it('is not exact when reference tokens were not metered', () => {+ expect(+ computeVideoRequestCost(h3MaxPricing, {+ duration: 5,+ imageUrls: images(1),+ resolution: '480P',+ }),+ ).toBeUndefined();+ });++ it('is not exact when a param needed by a unit is missing', () => {+ expect(computeVideoRequestCost(h3MaxPricing, { resolution: '480P' })).toBeUndefined();+ expect(computeVideoRequestCost(h3MaxPricing, { duration: 5 })).toBeUndefined();+ expect(+ computeVideoRequestCost(h3MaxPricing, { duration: 5, resolution: '4K' }),+ ).toBeUndefined();+ });++ it('is not exact when any unit is billed from reported usage', () => {+ const pricing: Pricing = {+ units: [+ ...h3MaxPricing.units,+ { name: 'videoGeneration', rate: 7, strategy: 'fixed', unit: 'millionTokens' },+ ],+ };++ expect(computeVideoRequestCost(pricing, { duration: 5, resolution: '480P' })).toBeUndefined();+ });++ it('prices reference image counts with a graduated free allowance', () => {+ const pricing: Pricing = {+ units: [+ { name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'video' },+ {+ mode: 'graduated',+ name: 'imageInput',+ strategy: 'tiered',+ tiers: [+ { rate: 0, upTo: 5 },+ { rate: 0.04, upTo: 'infinity' },+ ],+ unit: 'image',+ },+ ],+ };++ expect(computeVideoRequestCost(pricing, { imageUrls: images(7) })?.totalCost).toBeCloseTo(+ 0.58,+ 10,+ );+ });++ it('bills the whole quantity at the matched tier for volume tiers', () => {+ const pricing: Pricing = {+ units: [+ {+ name: 'imageInput',+ strategy: 'tiered',+ tiers: [+ { rate: 0, upTo: 5 },+ { rate: 0.04, upTo: 'infinity' },+ ],+ unit: 'image',+ },+ ],+ };++ expect(computeVideoRequestCost(pricing, { imageUrls: images(7) })?.totalCost).toBeCloseTo(+ 0.28,+ 10,+ );+ });});diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.tsindex 1043534b9b7..002e83d1cd3 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts@@ -1,28 +1,276 @@import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '@lobechat/const/currency';import debug from 'debug';-import type { FixedPricingUnit, LookupPricingUnit, Pricing } from 'model-bank';+import type {+ FixedPricingUnit,+ LookupPricingUnit,+ Pricing,+ PricingUnit,+ PricingUnitName,+ PricingUnitType,+ TieredPricingUnit,+} from 'model-bank';const log = debug('lobe-cost:computeVideoCost');export interface VideoGenerationParams {[key: string]: unknown;+ /** Requested output duration in seconds, required by per-second pricing */+ duration?: number;generateAudio?: boolean;resolution?: string;}+/**+ * Request inputs that cannot be read from the params alone and are metered before the request+ * (e.g. by reading the reference images' dimensions).+ */+export interface VideoRequestPricingInputs {+ /**+ * Output-token estimate used only to size the hold when the output size follows an input image+ * (see `meterVideoOutputTokens`); never charged as is+ */+ estimatedOutputTokens?: number;+ /** Output video tokens, known before the request when the output size follows the params */+ outputTokens?: number;+ /** Reference-image tokens, counted by {@link countVideoReferenceImageTokens} */+ referenceImageTokens?: number;+}++export interface VideoRequestCostItem {+ cost: number;+ lookupKey?: string;+ name: PricingUnitName;+ quantity: number;+ unit: PricingUnitType;+}+export interface VideoCostResult {breakdown?: {completionTokens: number;+ /** Billed output seconds, set when the model is priced per second */+ durationSeconds?: number;lookupKey?: string;- pricePerMillionTokens: number;+ pricePerMillionTokens?: number;+ pricePerSecond?: number;+ /** Every pricing unit priced from the request, set by {@link computeVideoRequestCost} */+ units?: VideoRequestCostItem[];};totalCost: number; // Total cost in USDtotalCredits: number; // Total credits (USD * CREDITS_PER_DOLLAR)}+const toUSD = (cost: number, currency: string) => (currency === 'CNY' ? cost / USD_TO_CNY : cost);++const resolveLookupRate = (+ unit: LookupPricingUnit,+ params: VideoGenerationParams,+): { lookupKey: string; rate: number } | undefined => {+ if (!unit.lookup?.pricingParams) {+ log('No pricing params defined for lookup strategy');+ return undefined;+ }++ const lookupParams: string[] = [];+ for (const paramName of unit.lookup.pricingParams) {+ const paramValue = params[paramName];+ if (paramValue === undefined || paramValue === null) {+ log(`Missing required lookup param: ${paramName}`);+ return undefined;+ }+ lookupParams.push(String(paramValue));+ }++ const lookupKey = lookupParams.join('_');+ const rate = unit.lookup.prices?.[lookupKey];+ if (typeof rate !== 'number') {+ log(`No price found for lookup key: ${lookupKey}`);+ return undefined;+ }++ return { lookupKey, rate };+};++const toImageUrl = (value: unknown): string | undefined =>+ typeof value === 'string' && value ? value : undefined;++/**+ * Reference images a request sends. Models that take both frames and references (MiniMax H3,+ * fal H3 Max) fold the first/last frames into the reference pool once references are present,+ * so pricing and the runtimes must agree on this order.+ */+export const getVideoReferenceImages = (params: {+ [key: string]: unknown;+ endImageUrl?: unknown;+ imageUrl?: unknown;+ imageUrls?: unknown;+}): string[] => {+ const references = Array.isArray(params.imageUrls)+ ? params.imageUrls.map(toImageUrl).filter((url): url is string => !!url)+ : [];+ if (references.length === 0) return [];++ return [toImageUrl(params.imageUrl), ...references, toImageUrl(params.endImageUrl)].filter(+ (url): url is string => !!url,+ );+};++const countReferenceImages = (params: VideoGenerationParams) =>+ getVideoReferenceImages(params).length;++/**+ * Request params the pricing reads. A request must carry them explicitly: when one is missing the+ * provider applies its own default, which the price cannot see.+ */+export const getVideoPricingParamNames = (pricing?: Pricing): string[] => {+ const names = new Set<string>();+ for (const unit of pricing?.units ?? []) {+ if (unit.name === 'videoGeneration' && unit.unit === 'second') names.add('duration');+ if (unit.strategy === 'lookup') unit.lookup.pricingParams?.forEach((name) => names.add(name));+ }+ return [...names];+};++/**+ * Whether the pricing bills reference images by token, so callers must meter+ * `referenceImageTokens` from the images before pricing the request.+ */+export const needsVideoReferenceImageTokens = (pricing?: Pricing): boolean =>+ !!pricing?.units.some((unit) => unit.name === 'imageInput' && unit.unit === 'millionTokens');++/**+ * The quantity a pricing unit bills, known from the request alone. `undefined` means the quantity+ * only exists after generation (e.g. output video tokens), so the request cannot be priced exactly.+ */+const resolveRequestQuantity = (+ unit: PricingUnit,+ params: VideoGenerationParams,+ inputs: VideoRequestPricingInputs,+): number | undefined => {+ switch (`${unit.name}:${unit.unit}`) {+ case 'videoGeneration:second': {+ const duration = Number(params.duration);+ return Number.isFinite(duration) && duration > 0 ? duration : undefined;+ }+ case 'videoGeneration:video': {+ return 1;+ }+ case 'videoGeneration:millionTokens': {+ return inputs.outputTokens;+ }+ case 'imageInput:image': {+ return countReferenceImages(params);+ }+ case 'imageInput:millionTokens': {+ if (countReferenceImages(params) === 0) return 0;+ return inputs.referenceImageTokens;+ }+ default: {+ return undefined;+ }+ }+};++/** Price of `quantity` under `rate`, where token units are rated per million */+const toUnitCost = (unit: PricingUnit, rate: number, quantity: number) =>+ unit.unit === 'millionTokens' ? (rate * quantity) / 1_000_000 : rate * quantity;++const computeTieredCost = (unit: TieredPricingUnit, quantity: number): number | undefined => {+ if (unit.mode !== 'graduated') {+ const tier = unit.tiers.find(({ upTo }) => upTo === 'infinity' || quantity <= (upTo as number));+ return tier ? toUnitCost(unit, tier.rate, quantity) : undefined;+ }++ let cost = 0;+ let lowerBound = 0;+ for (const tier of unit.tiers) {+ const upperBound = tier.upTo === 'infinity' ? Number.POSITIVE_INFINITY : tier.upTo;+ const inTier = Math.min(quantity, upperBound) - lowerBound;+ if (inTier > 0) cost += toUnitCost(unit, tier.rate, inTier);+ if (quantity <= upperBound) return cost;+ lowerBound = upperBound;+ }++ // Tiers end before the quantity does: the remainder has no configured rate.+ return undefined;+};++/**+ * Price a video request before it runs. Returns a result only when every pricing unit's quantity+ * is known from the request (see {@link resolveRequestQuantity}) and priced; that result is the+ * exact charge, e.g. fal H3 Max bills requested seconds plus reference tokens above an allowance.+ * `undefined` means the cost depends on provider-reported usage (e.g. output video tokens), so the+ * caller holds an approximate price and settles on completion instead.+ */+export const computeVideoRequestCost = (+ pricing: Pricing,+ params: VideoGenerationParams,+ inputs: VideoRequestPricingInputs = {},+): VideoCostResult | undefined => {+ if (pricing.units.length === 0) return undefined;++ const units: VideoRequestCostItem[] = [];+ for (const unit of pricing.units) {+ const quantity = resolveRequestQuantity(unit, params, inputs);+ if (quantity === undefined) {+ log('Unit %s:%s is not known before the request', unit.name, unit.unit);+ return undefined;+ }++ let cost: number | undefined;+ let lookupKey: string | undefined;+ switch (unit.strategy) {+ case 'fixed': {+ cost = toUnitCost(unit, unit.rate, quantity);+ break;+ }+ case 'lookup': {+ const resolved = resolveLookupRate(unit, params);+ if (resolved) {+ lookupKey = resolved.lookupKey;+ cost = toUnitCost(unit, resolved.rate, quantity);+ }+ break;+ }+ case 'tiered': {+ cost = computeTieredCost(unit, quantity);+ break;+ }+ }++ if (cost === undefined) {+ log('Unit %s:%s cannot be priced from the request', unit.name, unit.unit);+ return undefined;+ }+ units.push({ cost, lookupKey, name: unit.name, quantity, unit: unit.unit });+ }++ const currency = pricing.currency || 'USD';+ const costInUSD = toUSD(+ units.reduce((sum, item) => sum + item.cost, 0),+ currency,+ );+ const outputUnit = units.find(+ (item) => item.name === 'videoGeneration' && item.unit === 'second',+ );+ log('Video request cost: $%d USD, units: %O', costInUSD, units);++ return {+ breakdown: {+ completionTokens: 0,+ durationSeconds: outputUnit?.quantity,+ lookupKey: outputUnit?.lookupKey,+ pricePerSecond: outputUnit ? outputUnit.cost / outputUnit.quantity : undefined,+ units,+ },+ totalCost: costInUSD,+ totalCredits: Math.ceil(costInUSD * CREDITS_PER_DOLLAR),+ };+};+/*** Compute the cost for video generation based on pricing configuration.- * Supports both fixed and lookup pricing strategies.+ * Supports both fixed and lookup pricing strategies; units not rated per token (e.g. per second)+ * are priced from the request by {@link computeVideoRequestCost} and ignore `completionTokens`.* Handles CNY→USD conversion when pricing currency is CNY.*/export const computeVideoCost = (@@ -36,6 +284,8 @@ export const computeVideoCost = (return undefined;}+ if (videoGenUnit.unit !== 'millionTokens') return computeVideoRequestCost(pricing, params);+const currency = pricing.currency || 'USD';let pricePerMillionTokens: number;let lookupKey: string | undefined;@@ -52,31 +302,10 @@ export const computeVideoCost = (break;}case 'lookup': {- const lookupUnit = videoGenUnit as LookupPricingUnit;-- const lookupParams: string[] = [];- if (lookupUnit.lookup?.pricingParams) {- for (const paramName of lookupUnit.lookup.pricingParams) {- const paramValue = params[paramName];- if (paramValue === undefined || paramValue === null) {- log(`Missing required lookup param: ${paramName}`);- return undefined;- }- lookupParams.push(String(paramValue));- }- lookupKey = lookupParams.join('_');- } else {- log('No pricing params defined for lookup strategy');- return undefined;- }-- const lookupPrice = lookupUnit.lookup?.prices?.[lookupKey];- if (typeof lookupPrice !== 'number') {- log(`No price found for lookup key: ${lookupKey}`);- return undefined;- }+ const resolved = resolveLookupRate(videoGenUnit as LookupPricingUnit, params);+ if (!resolved) return undefined;- pricePerMillionTokens = lookupPrice;+ ({ lookupKey, rate: pricePerMillionTokens } = resolved);log(`Lookup pricing for key "${lookupKey}": ${pricePerMillionTokens} per million tokens (${currency})`,);@@ -92,7 +321,7 @@ export const computeVideoCost = (const costInCurrency = (pricePerMillionTokens * completionTokens) / 1_000_000;// Convert to USD if needed- const costInUSD = currency === 'CNY' ? costInCurrency / USD_TO_CNY : costInCurrency;+ const costInUSD = toUSD(costInCurrency, currency);const totalCredits = Math.ceil(costInUSD * CREDITS_PER_DOLLAR);log(diff --git a/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.ts b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.tsindex a60751364e6..f3ed464e0de 100644--- a/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.ts@@ -48,3 +48,96 @@ describe('resolveVideoSinglePrice', () => {expect(result).toEqual({});});});++describe('resolveVideoSinglePrice with request pricing', () => {+ const pricing: Pricing = {+ approximatePricePerVideo: 0.4,+ units: [+ {+ lookup: {+ prices: { '1080P': 0.16, '480P': 0.05, '768P': 0.08 },+ pricingParams: ['resolution'],+ },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'second',+ },+ ],+ };++ it('returns the exact price when the request prices every unit', () => {+ const result = resolveVideoSinglePrice(pricing, { duration: 15, resolution: '1080P' });++ expect(result.approximatePrice).toBe(0.4);+ expect(result.price).toBeCloseTo(2.4, 10);+ });++ it('omits the exact price when params are missing', () => {+ expect(resolveVideoSinglePrice(pricing)).toEqual({ approximatePrice: 0.4 });+ expect(resolveVideoSinglePrice(pricing, { resolution: '1080P' })).toEqual({+ approximatePrice: 0.4,+ });+ // Lookup keys follow the model card enum exactly; an unknown casing is not priced.+ expect(resolveVideoSinglePrice(pricing, { duration: 5, resolution: '480p' })).toEqual({+ approximatePrice: 0.4,+ });+ });++ it('only returns the approximate price for token-priced models', () => {+ const tokenPricing: Pricing = {+ approximatePricePerVideo: 0.76,+ units: [{ name: 'videoGeneration', rate: 7, strategy: 'fixed', unit: 'millionTokens' }],+ };++ expect(resolveVideoSinglePrice(tokenPricing, { duration: 15 })).toEqual({+ approximatePrice: 0.76,+ });+ });+});++describe('resolveVideoSinglePrice with output tokens', () => {+ // fal Seedance 2.5: $0.0214 per 1K output tokens+ const pricing: Pricing = {+ approximatePricePerVideo: 2.33,+ units: [{ name: 'videoGeneration', rate: 21.4, strategy: 'fixed', unit: 'millionTokens' }],+ };++ it('prices the request exactly from metered output tokens', () => {+ expect(resolveVideoSinglePrice(pricing, { duration: 4 }, { outputTokens: 40_000 })).toEqual({+ approximatePrice: 2.33,+ price: expect.closeTo(0.856, 10),+ });+ });++ it('sizes the hold from an estimate without an exact price', () => {+ expect(+ resolveVideoSinglePrice(pricing, { duration: 4 }, { estimatedOutputTokens: 40_000 }),+ ).toEqual({ approximatePrice: expect.closeTo(0.856, 10) });+ });++ it('rates 1080p tokens by resolution', () => {+ const lookupPricing: Pricing = {+ approximatePricePerVideo: 2.33,+ units: [+ {+ lookup: {+ prices: { '1080p': 23.4116, '480p': 21.4, '720p': 21.4 },+ pricingParams: ['resolution'],+ },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'millionTokens',+ },+ ],+ };++ // fal billed 214.88895K units × $0.0214 for 1920×1080, 97 frames+ expect(+ resolveVideoSinglePrice(+ lookupPricing,+ { duration: 4, resolution: '1080p' },+ { outputTokens: 196_425 },+ ),+ ).toEqual({ approximatePrice: 2.33, price: 4.59862353 });+ });+});diff --git a/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.ts b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.tsindex 34e297d09a0..c77ff47fdb0 100644--- a/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.ts@@ -1,15 +1,50 @@import type { Pricing } from 'model-bank';+import type { VideoGenerationParams, VideoRequestPricingInputs } from './computeVideoCost';+import { computeVideoRequestCost } from './computeVideoCost';+export interface VideoSinglePriceResult {+ /**+ * Hold for models priced by reported usage: an estimate from metered inputs when available,+ * otherwise the configured `approximatePricePerVideo`+ */approximatePrice?: number;+ /**+ * Exact price of the request, set only when every pricing unit is known before generation+ * (see `computeVideoRequestCost`); such a request is charged this amount without adjustment.+ */+ price?: number;}-export const resolveVideoSinglePrice = (pricing?: Pricing): VideoSinglePriceResult => {+/**+ * Resolve the per-request video price used for budget holds and price display.+ */+export const resolveVideoSinglePrice = (+ pricing?: Pricing,+ params?: VideoGenerationParams,+ inputs?: VideoRequestPricingInputs,+): VideoSinglePriceResult => {if (!pricing) return {};+ const result: VideoSinglePriceResult = {};if (typeof pricing.approximatePricePerVideo === 'number') {- return { approximatePrice: pricing.approximatePricePerVideo };+ result.approximatePrice = pricing.approximatePricePerVideo;+ }++ if (params) {+ const requestCost = computeVideoRequestCost(pricing, params, inputs);+ if (requestCost) result.price = requestCost.totalCost;++ // Output tokens that follow an input image are only estimated: size the hold with them, while+ // the charge follows the generated video.+ if (!requestCost && inputs?.estimatedOutputTokens !== undefined) {+ const estimate = computeVideoRequestCost(pricing, params, {+ ...inputs,+ outputTokens: inputs.estimatedOutputTokens,+ });+ if (estimate) result.approximatePrice = estimate.totalCost;+ }}- return {};+ return result;};diff --git a/packages/model-runtime/src/core/usageConverters/utils/videoOutputTokens.test.ts b/packages/model-runtime/src/core/usageConverters/utils/videoOutputTokens.test.tsnew file mode 100644index 00000000000..252e9345f55--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/utils/videoOutputTokens.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';++import { countVideoOutputTokens, meterVideoOutputTokens } from './videoOutputTokens';++const SEEDANCE = 'bytedance/seedance-2.5';++describe('countVideoOutputTokens', () => {+ // Billed tokens of real fal requests on 2026-09-30 (4s, 97 frames): fal floors the token count+ it.each([+ [854, 480, 38_830],+ [640, 640, 38_800],+ [560, 752, 39_891],+ [992, 432, 40_594],+ [1470, 630, 87_726],+ [1112, 834, 87_850],+ // 1080p is billed at 1.094× these tokens, which the pricing rate carries+ [2206, 946, 197_682],+ // image-to-video with 6:5 and 10:16 start frames+ [710, 592, 39_815],+ [506, 810, 38_824],+ ])('matches fal billing for %i×%i', (width, height, billedTokens) => {+ expect(countVideoOutputTokens(SEEDANCE, { frames: 97, height, width })).toBe(billedTokens);+ });++ it('skips models not billed by output tokens and unmeasured videos', () => {+ expect(countVideoOutputTokens('minimax/h3-max', { frames: 97, height: 480, width: 854 })).toBe(+ undefined,+ );+ expect(countVideoOutputTokens(SEEDANCE, { frames: 0, height: 480, width: 854 })).toBe(+ undefined,+ );+ });+});++describe('meterVideoOutputTokens', () => {+ it('prices text-to-video exactly from the resolution, aspect ratio and duration', () => {+ expect(+ meterVideoOutputTokens(SEEDANCE, { aspectRatio: '9:16', duration: 4, resolution: '480p' }),+ ).toEqual({ exact: Math.floor((480 * 854 * 97) / 1024) });+ });++ it('prices 1080p from its measured frame size', () => {+ expect(+ meterVideoOutputTokens(SEEDANCE, { aspectRatio: '21:9', duration: 4, resolution: '1080p' }),+ ).toEqual({ exact: 197_682 });+ });++ it('prices reference-to-video exactly, frames folded into the pool included', () => {+ expect(+ meterVideoOutputTokens(SEEDANCE, {+ aspectRatio: '1:1',+ duration: 10,+ imageUrl: 'https://img/start.png',+ imageUrls: ['https://img/a.png'],+ resolution: '480p',+ }),+ ).toEqual({ exact: Math.floor((640 * 640 * 241) / 1024) });+ });++ it('only estimates image-to-video, whose output follows the start frame', () => {+ expect(+ meterVideoOutputTokens(SEEDANCE, {+ aspectRatio: '1:1',+ duration: 4,+ imageUrl: 'https://img/start.png',+ imageUrls: [''],+ resolution: '480p',+ }),+ ).toEqual({ estimated: Math.floor((854 * 480 * 97) / 1024) });+ });++ it('meters nothing without a duration, a known size or an output-token model', () => {+ expect(meterVideoOutputTokens(SEEDANCE, { aspectRatio: '16:9', resolution: '480p' })).toBe(+ undefined,+ );+ expect(+ meterVideoOutputTokens(SEEDANCE, { aspectRatio: 'auto', duration: 4, resolution: '480p' }),+ ).toBe(undefined);+ expect(+ meterVideoOutputTokens('minimax/h3-max', {+ aspectRatio: '16:9',+ duration: 5,+ resolution: '480P',+ }),+ ).toBe(undefined);+ });+});diff --git a/packages/model-runtime/src/core/usageConverters/utils/videoOutputTokens.ts b/packages/model-runtime/src/core/usageConverters/utils/videoOutputTokens.tsnew file mode 100644index 00000000000..a9175a0cac5--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/utils/videoOutputTokens.ts@@ -0,0 +1,131 @@+import { getVideoReferenceImages, type VideoGenerationParams } from './computeVideoCost';++/** A generated video as billed: its frame size and frame count */+export interface VideoOutputFrames {+ frames: number;+ height: number;+ width: number;+}++interface OutputTokenMeter {+ fps: number;+ /** Output frame size by `${resolution}_${aspectRatio}` */+ frameSizes: Record<string, [width: number, height: number]>;+ /**+ * The output follows the start frame's aspect ratio when only frames are sent (image-to-video),+ * so its size is unknown before the request.+ */+ imageToVideoFollowsStartFrame: boolean;+}++/**+ * Output frame sizes of fal Seedance 2.5 text-to-video and reference-to-video, measured from+ * real outputs and their billed units on 2026-09-30. fal's published table matches except for+ * 480p 16:9/9:16, which render at 854×480 instead of 864×496, and lacks 1080p.+ */+const SEEDANCE_2_5_FRAME_SIZES: OutputTokenMeter['frameSizes'] = {+ '480p_1:1': [640, 640],+ '480p_16:9': [854, 480],+ '480p_21:9': [992, 432],+ '480p_3:4': [560, 752],+ '480p_4:3': [752, 560],+ '480p_9:16': [480, 854],+ '720p_1:1': [960, 960],+ '720p_16:9': [1280, 720],+ '720p_21:9': [1470, 630],+ '720p_3:4': [834, 1112],+ '720p_4:3': [1112, 834],+ '720p_9:16': [720, 1280],+ '1080p_1:1': [1440, 1440],+ '1080p_16:9': [1920, 1080],+ '1080p_21:9': [2206, 946],+ '1080p_3:4': [1248, 1664],+ '1080p_4:3': [1664, 1248],+ '1080p_9:16': [1080, 1920],+};++/**+ * Models billed by output video tokens, keyed by model id. Tokens are+ * `width × height × frames / 1024`, where a video of `d` seconds has `fps × d + 1` frames; this+ * matches fal's billed units for Seedance 2.5 exactly (https://fal.ai/models/bytedance/seedance-2.5/text-to-video).+ */+const OUTPUT_TOKEN_METERS: Record<string, OutputTokenMeter> = {+ 'bytedance/seedance-2.5': {+ fps: 24,+ frameSizes: SEEDANCE_2_5_FRAME_SIZES,+ imageToVideoFollowsStartFrame: true,+ },+};++const getMeter = (model: string) =>+ Object.hasOwn(OUTPUT_TOKEN_METERS, model) ? OUTPUT_TOKEN_METERS[model] : undefined;++const toTokens = ({ frames, height, width }: VideoOutputFrames) =>+ Math.floor((width * height * frames) / 1024);++/**+ * Count the output tokens a generated video is billed, or `undefined` when the model is not+ * billed by output tokens.+ */+export const countVideoOutputTokens = (+ model: string,+ output: VideoOutputFrames,+): number | undefined => {+ if (!getMeter(model)) return undefined;+ if (!(output.width > 0 && output.height > 0 && output.frames > 0)) return undefined;+ return toTokens(output);+};++/**+ * Request params the output-token meter reads. Like pricing params, a request must carry them+ * explicitly: an omitted one falls back to a provider default (e.g. fal's `duration: "auto"`)+ * that the meter cannot see.+ */+export const getVideoOutputTokenParamNames = (model: string): string[] =>+ getMeter(model) ? ['aspectRatio', 'duration', 'resolution'] : [];++export interface VideoOutputTokenEstimate {+ /**+ * Output tokens estimated from the resolution's 16:9 frame when the output size follows an+ * input image (the provider keeps the frame area close to it); used to size the hold only+ */+ estimated?: number;+ /** Output tokens known before the request; set when the output size follows the params */+ exact?: number;+}++/**+ * Meter the output tokens of a video request before it runs. Returns `undefined` when the model+ * is not billed by output tokens or the request lacks the duration or resolution.+ */+export const meterVideoOutputTokens = (+ model: string,+ params: VideoGenerationParams & {+ aspectRatio?: unknown;+ endImageUrl?: unknown;+ imageUrl?: unknown;+ imageUrls?: unknown;+ },+): VideoOutputTokenEstimate | undefined => {+ const meter = getMeter(model);+ if (!meter) return undefined;++ const duration = Number(params.duration);+ if (!Number.isFinite(duration) || duration <= 0 || !params.resolution) return undefined;+ const frames = meter.fps * duration + 1;++ const followsStartFrame =+ meter.imageToVideoFollowsStartFrame &&+ getVideoReferenceImages(params).length === 0 &&+ (!!params.imageUrl || !!params.endImageUrl);++ if (followsStartFrame) {+ const nominal = meter.frameSizes[`${params.resolution}_16:9`];+ if (!nominal) return undefined;+ return { estimated: toTokens({ frames, height: nominal[1], width: nominal[0] }) };+ }++ const size = meter.frameSizes[`${params.resolution}_${params.aspectRatio}`];+ if (!size) return undefined;+ return { exact: toTokens({ frames, height: size[1], width: size[0] }) };+};diff --git a/packages/model-runtime/src/core/usageConverters/utils/videoReferenceImageTokens.test.ts b/packages/model-runtime/src/core/usageConverters/utils/videoReferenceImageTokens.test.tsnew file mode 100644index 00000000000..b29c72873f6--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/utils/videoReferenceImageTokens.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { countVideoReferenceImageTokens } from './videoReferenceImageTokens';++describe('countVideoReferenceImageTokens', () => {+ it.each([+ // fal published samples+ [1024, 1024, 1024],+ [2048, 2048, 1024],+ [1024, 768, 1376],+ [1920, 1080, 1824],+ [1080, 1920, 1824],+ [2500, 1000, 2560],+ // Calibrated against billed units of real requests+ [1500, 1000, 1536],+ [1200, 1000, 1216],+ [360, 300, 1216],+ [1000, 1200, 1216],+ [2200, 1000, 2240],+ [1170, 1000, 1184],+ ])('counts %i×%i as %i tokens for H3 Max', (width, height, tokens) => {+ expect(countVideoReferenceImageTokens('minimax/h3-max', [{ height, width }])).toBe(tokens);+ });++ it('sums every image', () => {+ expect(+ countVideoReferenceImageTokens('minimax/h3-max', [+ { height: 1024, width: 1024 },+ { height: 1080, width: 1920 },+ ]),+ ).toBe(2848);+ });++ it('returns undefined for unknown models or unusable dimensions', () => {+ expect(+ countVideoReferenceImageTokens('other/model', [{ height: 1, width: 1 }]),+ ).toBeUndefined();+ expect(+ countVideoReferenceImageTokens('minimax/h3-max', [{ height: 0, width: 1024 }]),+ ).toBeUndefined();+ });+});diff --git a/packages/model-runtime/src/core/usageConverters/utils/videoReferenceImageTokens.ts b/packages/model-runtime/src/core/usageConverters/utils/videoReferenceImageTokens.tsnew file mode 100644index 00000000000..43043de8dde--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/utils/videoReferenceImageTokens.ts@@ -0,0 +1,50 @@+export interface ImageDimensions {+ height: number;+ width: number;+}++type ReferenceImageTokenizer = (image: ImageDimensions) => number;++/**+ * Tokens of an image resized so its short side spans `shortSidePatches` patches: the long side+ * spans the same patch size, rounded to the nearest whole patch, so only the aspect ratio matters.+ */+const aspectRatioPatchGrid =+ (shortSidePatches: number): ReferenceImageTokenizer =>+ ({ height, width }) => {+ const longSide = Math.max(width, height);+ const shortSide = Math.min(width, height);+ return shortSidePatches * Math.round((shortSidePatches * longSide) / shortSide);+ };++/**+ * How providers meter reference images, keyed by model id.+ *+ * fal H3 Max publishes only sample counts (1:1 → 1,024, 4:3 → 1,376, 16:9 → 1,824, 5:2 → 2,560):+ * https://fal.ai/models/minimax/h3-max/reference-to-video. The 32 × 32 patch grid with round-to-+ * nearest matches those samples and was calibrated against billed units of real requests on+ * 2026-09-30 (3:2, 6:5, 5:6, 360×300, 11:5 and 1.17:1 images). Exact .5 ties were not observed;+ * `Math.round` rounds them up, a difference of at most 32 tokens.+ */+const REFERENCE_IMAGE_TOKENIZERS: Record<string, ReferenceImageTokenizer> = {+ 'minimax/h3-max': aspectRatioPatchGrid(32),+};++/**+ * Count the reference-image tokens a model bills for the given images, or `undefined` when the+ * model has no known tokenizer or an image has no usable dimensions.+ */+export const countVideoReferenceImageTokens = (+ model: string,+ images: ImageDimensions[],+): number | undefined => {+ const tokenizer = REFERENCE_IMAGE_TOKENIZERS[model];+ if (!tokenizer) return undefined;++ let total = 0;+ for (const image of images) {+ if (!(image.width > 0 && image.height > 0)) return undefined;+ total += tokenizer(image);+ }+ return total;+};diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.tsindex 22365569f29..a92ec3c610d 100644--- a/packages/model-runtime/src/index.ts+++ b/packages/model-runtime/src/index.ts@@ -89,7 +89,7 @@ export * from './types/error';export { consumeStreamUntilDone } from './utils/consumeStream';export { AgentRuntimeError } from './utils/createError';export { getModelPropertyWithFallback } from './utils/getFallbackModelProperty';-export { getModelPricing } from './utils/getModelPricing';+export { getModelParameters, getModelPricing } from './utils/getModelPricing';export {applyModelExtendParams,type ApplyModelExtendParamsContext,diff --git a/packages/model-runtime/src/providers/fal/createVideo.test.ts b/packages/model-runtime/src/providers/fal/createVideo.test.tsnew file mode 100644index 00000000000..c947dc5f886--- /dev/null+++ b/packages/model-runtime/src/providers/fal/createVideo.test.ts@@ -0,0 +1,253 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFalVideoRequest, parseFalVideoInferenceId } from './createVideo';+import { LobeFalAI } from './index';++const { queue } = vi.hoisted(() => ({+ queue: { result: vi.fn(), status: vi.fn(), submit: vi.fn() },+}));++vi.mock('@fal-ai/client', () => ({+ createFalClient: vi.fn(() => ({ queue })),+ fal: { config: vi.fn(), subscribe: vi.fn() },+}));++const MODEL = 'minimax/h3-max';++describe('buildFalVideoRequest', () => {+ it('routes prompt-only requests to text-to-video', () => {+ expect(+ buildFalVideoRequest(MODEL, {+ aspectRatio: '9:16',+ duration: 10,+ prompt: 'a cat',+ promptExtend: 'quality',+ resolution: '1080P',+ seed: 7,+ }),+ ).toEqual({+ endpoint: 'minimax/h3-max/text-to-video',+ input: {+ aspect_ratio: '9:16',+ duration: 10,+ enable_safety_checker: false,+ prompt: 'a cat',+ prompt_expansion_mode: 'quality',+ resolution: '1080P',+ seed: 7,+ },+ });+ });++ it('routes first/last frames to image-to-video without an aspect ratio', () => {+ const { endpoint, input } = buildFalVideoRequest(MODEL, {+ aspectRatio: '16:9',+ endImageUrl: 'https://img/last.png',+ imageUrl: 'https://img/first.png',+ prompt: 'morph',+ });++ expect(endpoint).toBe('minimax/h3-max/image-to-video');+ expect(input).toMatchObject({+ end_image_url: 'https://img/last.png',+ image_url: 'https://img/first.png',+ prompt_expansion_mode: 'balanced',+ });+ // The output follows the first frame's aspect ratio; the endpoint takes none.+ expect(input).not.toHaveProperty('aspect_ratio');+ });++ it('routes a last frame alone to image-to-video', () => {+ expect(+ buildFalVideoRequest(MODEL, { endImageUrl: 'https://img/last.png', prompt: 'p' }).endpoint,+ ).toBe('minimax/h3-max/image-to-video');+ });++ it('routes reference images to reference-to-video and folds frames into the pool', () => {+ const { endpoint, input } = buildFalVideoRequest(MODEL, {+ aspectRatio: '1:1',+ endImageUrl: 'https://img/last.png',+ imageUrl: 'https://img/first.png',+ imageUrls: ['https://img/a.png', 'https://img/b.png'],+ prompt: 'Image 1 walks with Image 2',+ });++ expect(endpoint).toBe('minimax/h3-max/reference-to-video');+ expect(input).toMatchObject({+ aspect_ratio: '1:1',+ reference_image_urls: [+ 'https://img/first.png',+ 'https://img/a.png',+ 'https://img/b.png',+ 'https://img/last.png',+ ],+ });+ expect(input).not.toHaveProperty('image_url');+ expect(input).not.toHaveProperty('end_image_url');+ });++ it('keeps a last frame as a reference when reference images are present', () => {+ const { endpoint, input } = buildFalVideoRequest(MODEL, {+ endImageUrl: 'https://img/last.png',+ imageUrls: ['https://img/a.png'],+ prompt: 'p',+ });++ expect(endpoint).toBe('minimax/h3-max/reference-to-video');+ expect(input.reference_image_urls).toEqual(['https://img/a.png', 'https://img/last.png']);+ });++ describe('Seedance 2.5', () => {+ const SEEDANCE = 'bytedance/seedance-2.5';++ it('sends audio and a string duration without H3-only fields', () => {+ expect(+ buildFalVideoRequest(SEEDANCE, {+ aspectRatio: '21:9',+ duration: 12,+ generateAudio: false,+ prompt: 'a kite',+ resolution: '480p',+ }),+ ).toEqual({+ endpoint: 'bytedance/seedance-2.5/text-to-video',+ input: {+ aspect_ratio: '21:9',+ duration: '12',+ generate_audio: false,+ prompt: 'a kite',+ resolution: '480p',+ },+ });+ });++ it('sends reference images as image_urls', () => {+ const { endpoint, input } = buildFalVideoRequest(SEEDANCE, {+ aspectRatio: '16:9',+ imageUrls: ['https://img/a.png'],+ prompt: '@Image1 on a beach',+ });++ expect(endpoint).toBe('bytedance/seedance-2.5/reference-to-video');+ expect(input).toMatchObject({ aspect_ratio: '16:9', image_urls: ['https://img/a.png'] });+ expect(input).not.toHaveProperty('reference_image_urls');+ });+ });++ it('rejects a model without a fal video spec', () => {+ expect(() => buildFalVideoRequest('unknown/model', { prompt: 'p' })).toThrow(+ 'Unsupported fal video model',+ );+ });++ it('skips an unset random seed', () => {+ expect(buildFalVideoRequest(MODEL, { prompt: 'p', seed: null }).input).not.toHaveProperty(+ 'seed',+ );+ });+});++describe('LobeFalAI video', () => {+ let runtime: LobeFalAI;++ beforeEach(() => {+ vi.clearAllMocks();+ runtime = new LobeFalAI({ apiKey: 'test-key' });+ });++ it('submits to the task endpoint and returns the fal request path as inference id', async () => {+ queue.submit.mockResolvedValue({ request_id: 'req-1' });++ const result = await runtime.createVideo({+ model: MODEL,+ params: { imageUrl: 'https://img/first.png', prompt: 'p' },+ });++ expect(queue.submit).toHaveBeenCalledWith('minimax/h3-max/image-to-video', {+ input: expect.objectContaining({ image_url: 'https://img/first.png' }),+ });+ expect(result).toEqual({ inferenceId: 'minimax/h3-max/requests/req-1' });+ expect(parseFalVideoInferenceId(result.inferenceId)).toEqual({+ appId: MODEL,+ requestId: 'req-1',+ });+ });++ it('resolves mapped model ids before routing', async () => {+ queue.submit.mockResolvedValue({ request_id: 'req-2' });+ const mapped = new LobeFalAI({ apiKey: 'k', modelIdMapping: { 'h3-max': MODEL } });++ await mapped.createVideo({ model: 'h3-max', params: { prompt: 'p' } });++ expect(queue.submit).toHaveBeenCalledWith('minimax/h3-max/text-to-video', expect.anything());+ });++ it('rejects models without a video endpoint', async () => {+ await expect(+ runtime.createVideo({ model: 'fal-ai/qwen-image', params: { prompt: 'p' } }),+ ).rejects.toMatchObject({ errorType: 'ProviderBizError' });+ expect(queue.submit).not.toHaveBeenCalled();+ });++ it('maps a 401 submit error to InvalidProviderAPIKey', async () => {+ queue.submit.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 401 }));++ await expect(+ runtime.createVideo({ model: MODEL, params: { prompt: 'p' } }),+ ).rejects.toMatchObject({ errorType: 'InvalidProviderAPIKey' });+ });++ it('only declares polling completion', () => {+ expect(runtime.getVideoGenerationCapabilities()).toEqual({ completionModes: ['polling'] });+ });++ describe('handlePollVideoStatus', () => {+ const inferenceId = 'minimax/h3-max/requests/req-1';++ it('stays pending until the request completes', async () => {+ queue.status.mockResolvedValue({ status: 'IN_PROGRESS' });++ await expect(runtime.handlePollVideoStatus(inferenceId)).resolves.toEqual({+ status: 'pending',+ });+ expect(queue.status).toHaveBeenCalledWith(MODEL, { logs: false, requestId: 'req-1' });+ expect(queue.result).not.toHaveBeenCalled();+ });++ it('returns the video url on success', async () => {+ queue.status.mockResolvedValue({ status: 'COMPLETED' });+ queue.result.mockResolvedValue({ data: { video: { url: 'https://v.fal.media/out.mp4' } } });++ await expect(runtime.handlePollVideoStatus(inferenceId)).resolves.toEqual({+ status: 'success',+ videoUrl: 'https://v.fal.media/out.mp4',+ });+ expect(queue.result).toHaveBeenCalledWith(MODEL, { requestId: 'req-1' });+ });++ it('fails with the provider detail when the completed request errored', async () => {+ queue.status.mockResolvedValue({ status: 'COMPLETED' });+ queue.result.mockRejectedValue(+ Object.assign(new Error('Unprocessable Entity'), {+ body: { detail: [{ msg: 'Image aspect ratio is out of range' }] },+ status: 422,+ }),+ );++ await expect(runtime.handlePollVideoStatus(inferenceId)).resolves.toEqual({+ error: 'Image aspect ratio is out of range',+ status: 'failed',+ });+ });++ it('fails when the result has no video', async () => {+ queue.status.mockResolvedValue({ status: 'COMPLETED' });+ queue.result.mockResolvedValue({ data: {} });++ await expect(runtime.handlePollVideoStatus(inferenceId)).resolves.toMatchObject({+ status: 'failed',+ });+ });+ });+});diff --git a/packages/model-runtime/src/providers/fal/createVideo.ts b/packages/model-runtime/src/providers/fal/createVideo.tsnew file mode 100644index 00000000000..c055f63e6dc--- /dev/null+++ b/packages/model-runtime/src/providers/fal/createVideo.ts@@ -0,0 +1,151 @@+import type { FalClient } from '@fal-ai/client';+import debug from 'debug';+import type { RuntimeVideoGenParams } from 'model-bank';++import { getVideoReferenceImages } from '../../core/usageConverters/utils/computeVideoCost';+import type { CreateVideoResult, PollVideoStatusResult } from '../../types/video';++const log = debug('lobe-video:fal');++interface FalVideoModelSpec {+ /** Model-specific input fields sent with every task */+ buildBaseInput: (params: RuntimeVideoGenParams) => Record<string, unknown>;+ /** fal takes `duration` as a string enum (e.g. `"4"`–`"30"`) instead of a number */+ durationAsString?: boolean;+ /** Input field of the reference-to-video endpoint that holds the reference images */+ referenceImagesField: string;+}++/**+ * Video model cards that map to one fal app with a separate endpoint per task. The runtime picks+ * the endpoint from the request params, so the user sees a single model.+ */+const FAL_VIDEO_MODELS: Record<string, FalVideoModelSpec> = {+ 'bytedance/seedance-2.5': {+ buildBaseInput: ({ generateAudio }) =>+ typeof generateAudio === 'boolean' ? { generate_audio: generateAudio } : {},+ durationAsString: true,+ referenceImagesField: 'image_urls',+ },+ 'minimax/h3-max': {+ buildBaseInput: ({ promptExtend }) => ({+ enable_safety_checker: false,+ // Required by fal; the model card exposes the three modes through `promptExtend`.+ prompt_expansion_mode: typeof promptExtend === 'string' ? promptExtend : 'balanced',+ }),+ referenceImagesField: 'reference_image_urls',+ },+};++/**+ * fal queue requests live at `<owner>/<app>/requests/<id>`. Using that path as the inference id+ * keeps polling self-contained: the router polls with the inference id only, and the status and+ * result endpoints need the app id, not the task endpoint.+ */+const REQUEST_PATH_SEPARATOR = '/requests/';++export const isFalVideoModel = (model: string) => Object.hasOwn(FAL_VIDEO_MODELS, model);++export const toFalVideoInferenceId = (appId: string, requestId: string) =>+ `${appId}${REQUEST_PATH_SEPARATOR}${requestId}`;++export const parseFalVideoInferenceId = (inferenceId: string) => {+ const index = inferenceId.lastIndexOf(REQUEST_PATH_SEPARATOR);+ if (index <= 0) throw new Error(`Invalid fal video inference id: ${inferenceId}`);++ return {+ appId: inferenceId.slice(0, index),+ requestId: inferenceId.slice(index + REQUEST_PATH_SEPARATOR.length),+ };+};++/**+ * Build the fal endpoint and input for a task-routed video model:+ * - reference images → `/reference-to-video`; first/last frames join the reference pool (the+ * endpoint has no frame slots), matching how MiniMax H3 is served by its official API+ * - first or last frame → `/image-to-video`, whose output follows the first frame's aspect ratio+ * - otherwise → `/text-to-video`+ */+export const buildFalVideoRequest = (model: string, params: RuntimeVideoGenParams) => {+ const spec = isFalVideoModel(model) ? FAL_VIDEO_MODELS[model] : undefined;+ if (!spec) throw new Error(`Unsupported fal video model: ${model}`);++ const { aspectRatio, duration, endImageUrl, imageUrl, imageUrls, prompt, resolution, seed } =+ params;++ const input: Record<string, unknown> = { ...spec.buildBaseInput(params), prompt };+ if (duration) input.duration = spec.durationAsString ? String(duration) : duration;+ if (resolution) input.resolution = resolution;+ if (typeof seed === 'number' && seed >= 0) input.seed = seed;++ let task: 'image-to-video' | 'reference-to-video' | 'text-to-video';+ if (imageUrls?.length) {+ task = 'reference-to-video';+ // Shared with pricing so the billed reference tokens cover every image sent+ input[spec.referenceImagesField] = getVideoReferenceImages({+ endImageUrl,+ imageUrl,+ imageUrls,+ });+ if (aspectRatio) input.aspect_ratio = aspectRatio;+ } else if (imageUrl || endImageUrl) {+ task = 'image-to-video';+ if (imageUrl) input.image_url = imageUrl;+ if (endImageUrl) input.end_image_url = endImageUrl;+ } else {+ task = 'text-to-video';+ if (aspectRatio) input.aspect_ratio = aspectRatio;+ }++ return { endpoint: `${model}/${task}`, input };+};++const getFalErrorMessage = (error: unknown): string => {+ const detail = (error as { body?: { detail?: unknown } } | undefined)?.body?.detail;+ if (typeof detail === 'string') return detail;+ if (Array.isArray(detail)) {+ const messages = detail+ .map((item) => (item as { msg?: unknown } | undefined)?.msg)+ .filter((msg): msg is string => typeof msg === 'string');+ if (messages.length > 0) return messages.join('; ');+ }++ return error instanceof Error ? error.message : String(error);+};++export const createFalVideo = async (+ client: FalClient,+ model: string,+ params: RuntimeVideoGenParams,+): Promise<CreateVideoResult> => {+ const { endpoint, input } = buildFalVideoRequest(model, params);+ log('Submitting fal video request to %s with input: %O', endpoint, input);++ const { request_id } = await client.queue.submit(endpoint, { input });++ return { inferenceId: toFalVideoInferenceId(model, request_id) };+};++export const pollFalVideoStatus = async (+ client: FalClient,+ inferenceId: string,+): Promise<PollVideoStatusResult> => {+ const { appId, requestId } = parseFalVideoInferenceId(inferenceId);++ const status = await client.queue.status(appId, { logs: false, requestId });+ if (status.status !== 'COMPLETED') return { status: 'pending' };++ // A failed request also reaches COMPLETED; fetching its result throws the provider error.+ let data: unknown;+ try {+ ({ data } = await client.queue.result(appId, { requestId }));+ } catch (error) {+ log('fal video request %s failed: %O', inferenceId, error);+ return { error: getFalErrorMessage(error), status: 'failed' };+ }++ const videoUrl = (data as { video?: { url?: string } } | undefined)?.video?.url;+ if (!videoUrl) return { error: 'fal returned no video', status: 'failed' };++ return { status: 'success', videoUrl };+};diff --git a/packages/model-runtime/src/providers/fal/index.test.ts b/packages/model-runtime/src/providers/fal/index.test.tsindex b808519eccd..e7ef8c5c428 100644--- a/packages/model-runtime/src/providers/fal/index.test.ts+++ b/packages/model-runtime/src/providers/fal/index.test.ts@@ -7,6 +7,7 @@ import { LobeFalAI, resolveFalImageSize } from './index';// Mock the fal clientvi.mock('@fal-ai/client', () => ({+ createFalClient: vi.fn(() => ({})),fal: {config: vi.fn(),subscribe: vi.fn(),diff --git a/packages/model-runtime/src/providers/fal/index.ts b/packages/model-runtime/src/providers/fal/index.tsindex 360c44e3a59..676ec59677c 100644--- a/packages/model-runtime/src/providers/fal/index.ts+++ b/packages/model-runtime/src/providers/fal/index.ts@@ -1,4 +1,4 @@-import { fal } from '@fal-ai/client';+import { createFalClient, fal, type FalClient } from '@fal-ai/client';import debug from 'debug';import { pick } from 'es-toolkit/compat';import type { RuntimeImageGenParamsValue } from 'model-bank';@@ -7,9 +7,16 @@ import type { ClientOptions } from 'openai';import type { LobeRuntimeAI } from '../../core/BaseAI';import { AgentRuntimeErrorType } from '../../types/error';import type { CreateImagePayload, CreateImageResponse } from '../../types/image';+import type {+ CreateVideoPayload,+ CreateVideoResult,+ PollVideoStatusResult,+ VideoGenerationCapabilities,+} from '../../types/video';import { AgentRuntimeError } from '../../utils/createError';import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import { resolveMappedModelId } from '../../utils/modelIdMapping';+import { createFalVideo, isFalVideoModel, pollFalVideoStatus } from './createVideo';// Create debug loggerconst log = debug('lobe-image:fal');@@ -20,7 +27,7 @@ type FluxDevOutput = Awaited<ReturnType<typeof fal.subscribe<'fal-ai/flux/dev'>>* fal hosts models under several namespaces (e.g. `alibaba/qwen-image-3`); only bare* model ids without a known namespace get the default `fal-ai/` prefix.*/-const FAL_NAMESPACES = ['fal-ai/', 'alibaba/'];+const FAL_NAMESPACES = ['fal-ai/', 'alibaba/', 'minimax/'];/*** Model families exposed as one card but served by separate fal endpoints: requests@@ -69,8 +76,39 @@ export const resolveFalImageSize = (return { height: roundDown(ratioHeight * scale), width: roundDown(ratioWidth * scale) };};+// https://docs.fal.ai/model-apis/errors/+const toFalRuntimeError = (error: unknown) => {+ if (error instanceof Error && 'status' in error && error.status === 401) {+ return AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey, { error });+ }++ // 422 ValidationError with content_policy_violation — show a clean message+ if (error instanceof Error && 'status' in error && error.status === 422) {+ const body = 'body' in error ? (error as any).body : undefined;+ const hasContentPolicyViolation =+ Array.isArray(body?.detail) &&+ body.detail.some((d: any) => d.type === 'content_policy_violation');++ if (hasContentPolicyViolation) {+ return AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {+ error,+ message:+ 'The request content violates content policy. Please modify your prompt and try again.',+ });+ }+ }++ return AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, { error });+};+export class LobeFalAI implements LobeRuntimeAI {private readonly modelIdMappingOptions: ModelIdMappingOptions;+ /**+ * Video requests use a client scoped to this instance: the global `fal.config` is shared by+ * every instance, so concurrent router channels with different keys would overwrite it between+ * submitting a request and polling it.+ */+ private readonly client: FalClient;// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only uses the string form.constructor({@@ -82,10 +120,34 @@ export class LobeFalAI implements LobeRuntimeAI {fal.config({credentials: apiKey,});+ this.client = createFalClient({ credentials: apiKey });this.modelIdMappingOptions = { modelIdMapping };log('FalAI initialized with apiKey: %s', apiKey ? '*****' : 'Not set');}+ getVideoGenerationCapabilities(): VideoGenerationCapabilities {+ return { completionModes: ['polling'] };+ }++ async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResult> {+ const requestModel = resolveMappedModelId(payload.model, this.modelIdMappingOptions);+ if (!isFalVideoModel(requestModel)) {+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {+ message: `Video generation is not supported for fal model: ${requestModel}`,+ });+ }++ try {+ return await createFalVideo(this.client, requestModel, payload.params);+ } catch (error) {+ throw toFalRuntimeError(error);+ }+ }++ async handlePollVideoStatus(inferenceId: string): Promise<PollVideoStatusResult> {+ return pollFalVideoStatus(this.client, inferenceId);+ }+async createImage(payload: CreateImagePayload): Promise<CreateImageResponse> {const { model, params } = payload;const requestModel = resolveMappedModelId(model, this.modelIdMappingOptions);@@ -168,30 +230,7 @@ export class LobeFalAI implements LobeRuntimeAI {...pick(image, ['width', 'height']),};} catch (error) {- // https://docs.fal.ai/model-apis/errors/- if (error instanceof Error && 'status' in error && error.status === 401) {- throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey, {- error,- });- }-- // 422 ValidationError with content_policy_violation — show a clean message- if (error instanceof Error && 'status' in error && error.status === 422) {- const body = 'body' in error ? (error as any).body : undefined;- const hasContentPolicyViolation =- Array.isArray(body?.detail) &&- body.detail.some((d: any) => d.type === 'content_policy_violation');-- if (hasContentPolicyViolation) {- throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {- error,- message:- 'The request content violates content policy. Please modify your prompt and try again.',- });- }- }-- throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, { error });+ throw toFalRuntimeError(error);}}}diff --git a/packages/model-runtime/src/providers/minimax/createVideo.test.ts b/packages/model-runtime/src/providers/minimax/createVideo.test.tsindex 96d9dd076e9..ca352e3d166 100644--- a/packages/model-runtime/src/providers/minimax/createVideo.test.ts+++ b/packages/model-runtime/src/providers/minimax/createVideo.test.ts@@ -275,6 +275,34 @@ describe('createMiniMaxVideo', () => {]);});+ it('should keep H3 frames as frames when the reference list has only empty entries', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_id: 'h3-frame-task' }),+ });++ const payload: CreateVideoPayload = {+ model: 'MiniMax-H3',+ params: {+ imageUrl: 'https://example.com/first.jpg',+ imageUrls: [''],+ prompt: 'Animate the frame',+ },+ };++ await createMiniMaxVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.content).toEqual([+ { text: 'Animate the frame', type: 'text' },+ {+ image_url: { url: 'https://example.com/first.jpg' },+ role: 'first_frame',+ type: 'image_url',+ },+ ]);+ });+it('should reject more than nine normalized H3 reference images', async () => {const payload: CreateVideoPayload = {model: 'MiniMax-H3',diff --git a/packages/model-runtime/src/providers/minimax/createVideo.ts b/packages/model-runtime/src/providers/minimax/createVideo.tsindex dfb7d103df0..3f4005a2e22 100644--- a/packages/model-runtime/src/providers/minimax/createVideo.ts+++ b/packages/model-runtime/src/providers/minimax/createVideo.ts@@ -1,6 +1,7 @@import createDebug from 'debug';import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import { getVideoReferenceImages } from '../../core/usageConverters/utils/computeVideoCost';import type { CreateVideoPayload, CreateVideoResult } from '../../types/video';import { resolveMappedModelId } from '../../utils/modelIdMapping';@@ -233,12 +234,8 @@ export async function createMiniMaxVideo(if (isMiniMaxH3(model) || isMiniMaxH3(requestModel)) {const content: Record<string, unknown>[] = [{ text: prompt, type: 'text' }];- const hasReferenceImages = Boolean(imageUrls?.length);- const referenceImageUrls = hasReferenceImages- ? [imageUrl, ...(imageUrls ?? []), endImageUrl].filter(- (url): url is string => typeof url === 'string' && url.length > 0,- )- : [];+ const referenceImageUrls = getVideoReferenceImages({ endImageUrl, imageUrl, imageUrls });+ const hasReferenceImages = referenceImageUrls.length > 0;if (referenceImageUrls.length > 9) {throw new Error('MiniMax-H3 supports up to 9 reference images');diff --git a/packages/model-runtime/src/utils/getModelPricing.ts b/packages/model-runtime/src/utils/getModelPricing.tsindex f9d79d9fa8a..a3effce9808 100644--- a/packages/model-runtime/src/utils/getModelPricing.ts+++ b/packages/model-runtime/src/utils/getModelPricing.ts@@ -1,4 +1,9 @@-import type { LobeDefaultAiModelListItem, Pricing } from 'model-bank';+import type {+ LobeDefaultAiModelListItem,+ ModelParamsSchema,+ Pricing,+ VideoModelParamsSchema,+} from 'model-bank';import type { ModelPricingContext } from '../types';@@ -9,37 +14,55 @@ interface BusinessModelConfigModule {}/**- * 1. First try to get pricing from the specified provider- * 2. If not found, try to get pricing from other providers with the same model name+ * Find the model card that prices `model`:+ * 1. First try the specified provider+ * 2. If not found, try other providers with the same model name** TODO: Add a fallback provider priority list. When no provider is specified,* first try official providers, then other providers. Same applies to getFallbackModelProperty*/-export async function getModelPricing(+const findModelCard = async (model: string,- provider?: string,- pricingContext?: ModelPricingContext,-): Promise<Pricing | undefined> {+ provider: string | undefined,+ pricingContext: ModelPricingContext | undefined,+ hasProperty: (card: LobeDefaultAiModelListItem) => boolean,+): Promise<LobeDefaultAiModelListItem | undefined> => {const { loadModels } =(await import('@lobechat/business-model-bank/model-config')) as BusinessModelConfigModule;const models = await loadModels(pricingContext ? { pricingContext } : undefined);- // 1. First try to get pricing from the specified providerif (provider) {const exactMatch = models.find((m) => m.id === model && m.providerId === provider);-- if (exactMatch?.pricing) {- return exactMatch.pricing;- }+ if (exactMatch && hasProperty(exactMatch)) return exactMatch;}- // 2. If not found, try to get pricing from other providers with the same model nameconst fallbackMatch = models.find((m) => m.id === model);+ return fallbackMatch && hasProperty(fallbackMatch) ? fallbackMatch : undefined;+};- if (fallbackMatch?.pricing) {- return fallbackMatch.pricing;- }+export async function getModelPricing(+ model: string,+ provider?: string,+ pricingContext?: ModelPricingContext,+): Promise<Pricing | undefined> {+ const card = await findModelCard(model, provider, pricingContext, (m) => !!m.pricing);+ return card?.pricing;+}- // 3. Return undefined if no pricing information is found- return undefined;+/**+ * Parameter schema of a generation model card, resolved like {@link getModelPricing} so the+ * defaults used for a request come from the same card that prices it.+ */+export async function getModelParameters(+ model: string,+ provider?: string,+ pricingContext?: ModelPricingContext,+): Promise<ModelParamsSchema | VideoModelParamsSchema | undefined> {+ const card = await findModelCard(+ model,+ provider,+ pricingContext,+ (m) => 'parameters' in m && !!m.parameters,+ );+ return card && 'parameters' in card ? card.parameters : undefined;}diff --git a/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx b/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsxindex 4fdef57d675..c595e215f72 100644--- a/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx+++ b/src/routes/(main)/(create)/features/GenerationInput/InlineVideoFrames.tsx@@ -39,12 +39,19 @@ const styles = createStaticStyles(({ css }) => ({}));interface InlineVideoFramesProps {+ /** Label of the empty add card; defaults to the reference image label. */+ addLabel?: string;endImageUrl?: string | null;imageUrl?: string | null;imageUrls?: string[] | null;isSupportEndImage?: boolean;maxCount?: number;maxFileSize?: number;+ /**+ * Label images as "Image 1", "Image 2"… so prompts can refer to them, and show the used+ * count on the add card. Used when every image is a reference.+ */+ numberReferences?: boolean;onEndImageChange: (data: UploadData | null) => void;onImageChange: (data: UploadData | null) => void;onImageUrlsChange?: (data: UploadData) => void;@@ -57,6 +64,7 @@ interface InlineVideoFramesProps {const InlineVideoFrames = memo<InlineVideoFramesProps>(({+ addLabel,imageUrl,imageUrls,endImageUrl,@@ -68,6 +76,7 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>(isSupportEndImage = true,maxCount = 5,maxFileSize,+ numberReferences = false,uploadingPreviews = [],}) => {const { t } = useTranslation('video');@@ -114,6 +123,11 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>(key={url}label={label}maxFileSize={maxFileSize}+ badge={+ numberReferences+ ? t('config.referenceImage.indexedLabel', { index: String(index + 1) })+ : undefined+ }style={{marginInlineStart:index > 0 ? (shouldCollapse ? STACK_OFFSET : EXPAND_OFFSET) : 0,@@ -177,9 +191,13 @@ const InlineVideoFrames = memo<InlineVideoFramesProps>() : (<UploadCardimageUrl={null}- label={t('config.referenceImage.label')}maxFileSize={maxFileSize}multiple={!!onUploadFiles}+ label={+ numberReferences && hasItems+ ? t('config.referenceImage.count', { count: totalCount, max: String(maxCount) })+ : (addLabel ?? t('config.referenceImage.label'))+ }style={{marginInlineStart: hasItems ? EXPAND_OFFSET : 0,zIndex: totalCount + 1,diff --git a/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx b/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsxindex ff67bb34db4..a1a6920f20e 100644--- a/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx+++ b/src/routes/(main)/(create)/features/GenerationInput/UploadCard.tsx@@ -87,6 +87,24 @@ export const uploadCardStyles = createStaticStyles(({ css }) => ({height: 100%;border-radius: 3px;`,+ badge: css`+ pointer-events: none;++ position: absolute;+ z-index: 4;+ inset-block-end: 4px;+ inset-inline-start: 4px;++ padding-block: 1px;+ padding-inline: 4px;+ border-radius: 4px;++ font-size: 10px;+ line-height: 14px;+ color: ${cssVar.colorWhite};++ background: ${cssVar.colorBgMask};+ `,label: css`padding-inline: 4px;@@ -128,6 +146,8 @@ export const uploadCardStyles = createStaticStyles(({ css }) => ({}));interface UploadCardProps {+ /** Short tag drawn on the filled preview, e.g. "Image 1" for prompt references. */+ badge?: string;className?: string;closeClassName?: string;imageUrl?: string | null;@@ -151,6 +171,7 @@ interface UploadCardProps {const UploadCard = memo<UploadCardProps>(({+ badge,imageUrl,label,loading = false,@@ -269,6 +290,7 @@ const UploadCard = memo<UploadCardProps>(src={uploadPreview || imageUrl!}style={{ objectFit: 'cover' }}/>+ {badge && !uploading && <span className={uploadCardStyles.badge}>{badge}</span>}{uploading && (<div className={uploadCardStyles.uploadOverlay}><Spin size="small" />diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsxindex a87e1d60a97..747a35fa1a7 100644--- a/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx@@ -5,7 +5,7 @@ import { Button, Tag, Text, toast } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';import dayjs from 'dayjs';import { CopyIcon, RotateCcwSquareIcon, SquarePenIcon, Trash2, XIcon } from 'lucide-react';-import { type RuntimeVideoGenParamsKeys, type RuntimeVideoGenParamsValue } from 'model-bank';+import { type RuntimeVideoGenParams } from 'model-bank';import { supportsConversationalVideoEdit } from 'model-bank/standardParameters';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -57,8 +57,7 @@ export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(const useCheckGenerationStatus = useVideoStore((s) => s.useCheckGenerationStatus);const removeGeneration = useVideoStore((s) => s.removeGeneration);const removeGenerationBatch = useVideoStore((s) => s.removeGenerationBatch);- const setModelAndProviderOnSelect = useVideoStore((s) => s.setModelAndProviderOnSelect);- const setParamOnInput = useVideoStore((s) => s.setParamOnInput);+ const reuseVideoSettings = useVideoStore((s) => s.reuseVideoSettings);const startEditingVideo = useVideoStore((s) => s.startEditingVideo);const cancelEditingVideo = useVideoStore((s) => s.cancelEditingVideo);const editingGenerationId = useVideoStore(createVideoSelectors.editingGenerationId);@@ -131,19 +130,8 @@ export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(}, [batch.prompt, t]);const handleReuseSettings = useCallback(() => {- setModelAndProviderOnSelect(batch.model, batch.provider);-- if (!batch.config) return;-- for (const [paramName, value] of Object.entries(batch.config)) {- if (value === undefined) continue;-- setParamOnInput(- paramName as RuntimeVideoGenParamsKeys,- value as RuntimeVideoGenParamsValue,- );- }- }, [batch.config, batch.model, batch.provider, setModelAndProviderOnSelect, setParamOnInput]);+ reuseVideoSettings(batch.model, batch.provider, batch.config as RuntimeVideoGenParams);+ }, [batch.config, batch.model, batch.provider, reuseVideoSettings]);const handleEdit = useCallback(() => {if (!generation?.asset || !('interactionId' in generation.asset)) return;diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/VideoReferenceFrames.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/VideoReferenceFrames.tsxindex 5960975b767..4e45c3bf8d2 100644--- a/src/routes/(main)/(create)/video/features/GenerationFeed/VideoReferenceFrames.tsx+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/VideoReferenceFrames.tsx@@ -43,10 +43,14 @@ interface VideoReferenceFramesProps {const VideoReferenceFrames = memo<VideoReferenceFramesProps>(({ imageUrl, imageUrls, endImageUrl }) => {- const allImages: string[] = [];- if (imageUrl) allImages.push(imageUrl);- if (imageUrls && imageUrls.length > 0) allImages.push(...imageUrls);- if (endImageUrl) allImages.push(endImageUrl);+ // Providers treat every image as a reference once `imageUrls` is set, so label them as such.+ const isReference = !!imageUrls?.length;+ const allImages: { alt: string; url: string }[] = [];+ if (imageUrl)+ allImages.push({ alt: isReference ? 'Reference image' : 'Start frame', url: imageUrl });+ if (isReference) allImages.push(...imageUrls.map((url) => ({ alt: 'Reference image', url })));+ if (endImageUrl)+ allImages.push({ alt: isReference ? 'Reference image' : 'End frame', url: endImageUrl });if (allImages.length === 0) return null;@@ -60,10 +64,10 @@ const VideoReferenceFrames = memo<VideoReferenceFramesProps>(size={'small'}variant={'filled'}/>- {allImages.map((url, index) => (+ {allImages.map(({ alt, url }, index) => (<div className={styles.container} key={`${url}-${index}`}><Image- alt={index === 0 ? 'Start frame' : 'End frame'}+ alt={alt}className={styles.image}height={'100%'}src={url}diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsxindex 443c5d32e22..b81fe988014 100644--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx@@ -5,6 +5,7 @@ import {ActionIcon,Divider,InputNumber,+ Segmented,SliderWithInput,Switch,Tabs,@@ -47,6 +48,7 @@ import {videoGenerationTopicSelectors,} from '@/store/video/selectors';import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';+import type { VideoImageInputMode } from '@/store/video/slices/generationConfig/imageInputMode';import type { VideoGenerationAsset } from '@/types/generation';import { generateUniqueSeeds } from '@/utils/number';@@ -61,6 +63,7 @@ interface PromptInputProps {}const isSupportedParamSelector = videoGenerationConfigSelectors.isSupportedParam;+const isImageInputSlotEnabledSelector = videoGenerationConfigSelectors.isImageInputSlotEnabled;const AspectRatioItem = memo(() => {const { allowed: canCreate } = usePermission('create_content');@@ -347,9 +350,12 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {);const { notice: modelNotice, isModelUnavailable } = useVideoGenerationModelNotice();const isInit = useVideoStore((s) => s.isInit);- const isSupportImageUrl = useVideoStore(isSupportedParamSelector('imageUrl'));- const isSupportImageUrls = useVideoStore(isSupportedParamSelector('imageUrls'));- const isSupportEndImageUrl = useVideoStore(isSupportedParamSelector('endImageUrl'));+ const isSupportImageUrl = useVideoStore(isImageInputSlotEnabledSelector('imageUrl'));+ const isSupportImageUrls = useVideoStore(isImageInputSlotEnabledSelector('imageUrls'));+ const isSupportEndImageUrl = useVideoStore(isImageInputSlotEnabledSelector('endImageUrl'));+ const hasImageInputMode = useVideoStore(videoGenerationConfigSelectors.hasImageInputMode);+ const imageInputMode = useVideoStore(videoGenerationConfigSelectors.imageInputMode);+ const setImageInputMode = useVideoStore((s) => s.setImageInputMode);const isSupportAspectRatio = useVideoStore(isSupportedParamSelector('aspectRatio'));const isSupportResolution = useVideoStore(isSupportedParamSelector('resolution'));const isSupportSize = useVideoStore(isSupportedParamSelector('size'));@@ -479,6 +485,13 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {[imageUrl, imageUrls],);const hasRefImages = framePreviewUrls.length > 0 || Boolean(endImageUrl);+ const isReferenceMode = hasImageInputMode && imageInputMode === 'reference';+ /**+ * Frame-mode requests of models with both frames and references (MiniMax H3) take the output+ * aspect ratio from the frames, so the selector would have no effect.+ */+ const aspectRatioFollowsFrames =+ hasImageInputMode && imageInputMode === 'frames' && (!!imageUrl || !!endImageUrl);const editingGeneration = editingBatch?.generations.find((generation) => generation.id === editingGenerationId,);@@ -589,26 +602,46 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {}inlineContent={!editingGenerationId && showInlineFrames ? (- <InlineVideoFrames- endImageUrl={endImageUrl}- imageUrl={imageUrl}- imageUrls={imageUrls}- isSupportEndImage={isSupportEndImageUrl}- maxCount={maxCount}- maxFileSize={imageUrlsMaxFileSize ?? imageUrlMaxFileSize}- uploadingPreviews={uploadingPreviews}- onEndImageChange={handleEndImageChange}- onImageUrlsChange={handleAddImage}- onRemoveImageUrl={handleRemoveImage}- onUploadFiles={handleUploadFiles}- onImageChange={(data) => {- if (data === null) {- handleRemoveImage(imageUrl || '');- return;+ <Flexbox gap={6}>+ {hasImageInputMode && (+ <Segmented<VideoImageInputMode>+ disabled={!canCreate}+ size={'small'}+ value={imageInputMode}+ options={[+ { label: t('config.imageInputMode.frames'), value: 'frames' },+ { label: t('config.imageInputMode.reference'), value: 'reference' },+ ]}+ onChange={setImageInputMode}+ />+ )}+ <InlineVideoFrames+ endImageUrl={endImageUrl}+ imageUrl={imageUrl}+ imageUrls={imageUrls}+ isSupportEndImage={isSupportEndImageUrl}+ maxCount={maxCount}+ maxFileSize={imageUrlsMaxFileSize ?? imageUrlMaxFileSize}+ numberReferences={isReferenceMode}+ uploadingPreviews={uploadingPreviews}+ addLabel={+ hasImageInputMode && !isReferenceMode && !imageUrl+ ? t('config.imageUrl.label')+ : undefined}- handleAddImage(data);- }}- />+ onEndImageChange={handleEndImageChange}+ onImageUrlsChange={handleAddImage}+ onRemoveImageUrl={handleRemoveImage}+ onUploadFiles={handleUploadFiles}+ onImageChange={(data) => {+ if (data === null) {+ handleRemoveImage(imageUrl || '');+ return;+ }+ handleAddImage(data);+ }}+ />+ </Flexbox>) : undefined}leftActions={@@ -660,7 +693,13 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {{isSupportAspectRatio && (<Flexbox gap={6}><Text fontSize={12}>{t('config.aspectRatio.label')}</Text>- <AspectRatioItem />+ {aspectRatioFollowsFrames ? (+ <Text fontSize={12} type={'secondary'}>+ {t('config.aspectRatio.followStartFrame')}+ </Text>+ ) : (+ <AspectRatioItem />+ )}</Flexbox>)}{isSupportResolution && (@@ -727,9 +766,11 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {placeholder={editingGenerationId? t('config.prompt.editPlaceholder')- : hasRefImages- ? t('config.prompt.placeholderWithRef')- : t('config.prompt.placeholder')+ : isReferenceMode && hasRefImages+ ? t('config.prompt.placeholderWithReference')+ : hasRefImages+ ? t('config.prompt.placeholderWithRef')+ : t('config.prompt.placeholder')}rightActions={<>diff --git a/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.ts b/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.tsindex 80ceb95053d..514b922a0e2 100644--- a/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.ts+++ b/src/routes/(main)/(create)/video/features/PromptInput/useVideoReferenceUpload.ts@@ -13,7 +13,7 @@ import { useVideoStore } from '@/store/video';import { videoGenerationConfigSelectors } from '@/store/video/selectors';import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';-const isSupportedParamSelector = videoGenerationConfigSelectors.isSupportedParam;+const isSlotEnabledSelector = videoGenerationConfigSelectors.isImageInputSlotEnabled;/*** Video-page binding for the shared {@link useReferenceImageUpload} core.@@ -22,39 +22,38 @@ const isSupportedParamSelector = videoGenerationConfigSelectors.isSupportedParam* (`imageUrl`) → reference array (`imageUrls`) → end frame (`endImageUrl`) — so a* drop fills them in order. Single-image models accept one; first/end-frame* models map a 2-image drop to start + end (the end frame's `requiresImageUrl`- * is satisfied because the start frame slot fills first).+ * is satisfied because the start frame slot fills first). Models accepting both+ * frames and references only expose the active image input mode's slots.*/export const useVideoReferenceUpload = () => {const { t } = useTranslation('video');const { allowed: canCreate } = usePermission('create_content');- const isSupportImageUrl = useVideoStore(isSupportedParamSelector('imageUrl'));- const isSupportImageUrls = useVideoStore(isSupportedParamSelector('imageUrls'));- const isSupportEndImageUrl = useVideoStore(isSupportedParamSelector('endImageUrl'));+ const isSupportImageUrl = useVideoStore(isSlotEnabledSelector('imageUrl'));+ const isSupportImageUrls = useVideoStore(isSlotEnabledSelector('imageUrls'));+ const isSupportEndImageUrl = useVideoStore(isSlotEnabledSelector('endImageUrl'));- const {- value: imageUrl,- setValue: setImageUrl,- maxFileSize: imageUrlMaxFileSize,- } = useVideoGenerationConfigParam('imageUrl');+ const { value: imageUrl, maxFileSize: imageUrlMaxFileSize } =+ useVideoGenerationConfigParam('imageUrl');const {value: imageUrls,- setValue: setImageUrls,maxCount: imageUrlsMaxCount,maxFileSize: imageUrlsMaxFileSize,} = useVideoGenerationConfigParam('imageUrls');- const {- value: endImageUrl,- setValue: setEndImageUrl,- maxFileSize: endImageUrlMaxFileSize,- } = useVideoGenerationConfigParam('endImageUrl');+ const { value: endImageUrl, maxFileSize: endImageUrlMaxFileSize } =+ useVideoGenerationConfigParam('endImageUrl');+ const imageInputMode = useVideoStore(videoGenerationConfigSelectors.imageInputMode);+ const setImageInputForMode = useVideoStore((s) => s.setImageInputForMode);const uploadingPreviews = useVideoStore(videoGenerationConfigSelectors.uploadingImagePreviews);const addUploadingImagePreviews = useVideoStore((s) => s.addUploadingImagePreviews);const removeUploadingImagePreviews = useVideoStore((s) => s.removeUploadingImagePreviews);+ // Slots are bound to the mode active when the upload starts, so an upload that lands after a+ // mode switch fills the mode it was dropped into rather than the one now shown.const slots = useMemo<ReferenceUploadSlot[]>(() => {- const readParams = () => videoGenerationConfigSelectors.parameters(useVideoStore.getState());+ const readParams = () =>+ videoGenerationConfigSelectors.imageInputsOfMode(imageInputMode)(useVideoStore.getState());const list: ReferenceUploadSlot[] = [];if (isSupportImageUrl) {list.push({@@ -63,7 +62,7 @@ export const useVideoReferenceUpload = () => {const v = readParams()?.imageUrl;return v ? [v] : [];},- set: (urls) => setImageUrl((urls[0] ?? null) as any),+ set: (urls) => setImageInputForMode(imageInputMode, 'imageUrl', urls[0] ?? null),values: imageUrl ? [imageUrl] : [],});}@@ -74,7 +73,7 @@ export const useVideoReferenceUpload = () => {const v = readParams()?.imageUrls;return Array.isArray(v) ? v : [];},- set: (urls) => setImageUrls(urls as any),+ set: (urls) => setImageInputForMode(imageInputMode, 'imageUrls', urls),values: imageUrls ?? [],});}@@ -85,7 +84,7 @@ export const useVideoReferenceUpload = () => {const v = readParams()?.endImageUrl;return v ? [v] : [];},- set: (urls) => setEndImageUrl((urls[0] ?? null) as any),+ set: (urls) => setImageInputForMode(imageInputMode, 'endImageUrl', urls[0] ?? null),values: endImageUrl ? [endImageUrl] : [],});}@@ -98,9 +97,8 @@ export const useVideoReferenceUpload = () => {imageUrls,endImageUrl,imageUrlsMaxCount,- setImageUrl,- setImageUrls,- setEndImageUrl,+ imageInputMode,+ setImageInputForMode,]);const onLimitExceeded = useCallback(diff --git a/src/store/video/slices/createVideo/action.ts b/src/store/video/slices/createVideo/action.tsindex 505a5c155fe..01193e10163 100644--- a/src/store/video/slices/createVideo/action.ts+++ b/src/store/video/slices/createVideo/action.ts@@ -34,6 +34,7 @@ const EDIT_INPUT_PARAMETER_KEYS = new Set([]);const cloneEditingDraft = (store: VideoStore): VideoEditingDraftSnapshot => ({+ imageInputMode: store.imageInputMode,model: store.model,parameters: {...store.parameters,@@ -41,6 +42,7 @@ const cloneEditingDraft = (store: VideoStore): VideoEditingDraftSnapshot => ({},parametersSchema: store.parametersSchema,provider: store.provider,+ stashedImageInputs: store.stashedImageInputs,uploadingImagePreviews: [...store.uploadingImagePreviews],});@@ -54,10 +56,12 @@ const restoreEditingDraft = (state: VideoStore) => {return {editingDraftSnapshot: undefined,editingGenerationId: undefined,+ imageInputMode: snapshot.imageInputMode,model: snapshot.model,parameters: snapshot.parameters,parametersSchema: snapshot.parametersSchema,provider: snapshot.provider,+ stashedImageInputs: snapshot.stashedImageInputs,uploadingImagePreviews: snapshot.uploadingImagePreviews,};};diff --git a/src/store/video/slices/createVideo/initialState.ts b/src/store/video/slices/createVideo/initialState.tsindex 12d2fcdb49e..f1c03f94883 100644--- a/src/store/video/slices/createVideo/initialState.ts+++ b/src/store/video/slices/createVideo/initialState.ts@@ -1,10 +1,14 @@import type { RuntimeVideoGenParams, VideoModelParamsSchema } from 'model-bank';+import type { VideoImageInputMode, VideoImageInputs } from '../generationConfig/imageInputMode';+export interface VideoEditingDraftSnapshot {+ imageInputMode: VideoImageInputMode;model: string;parameters: RuntimeVideoGenParams;parametersSchema: VideoModelParamsSchema;provider: string;+ stashedImageInputs: Partial<Record<VideoImageInputMode, VideoImageInputs>>;uploadingImagePreviews: string[];}diff --git a/src/store/video/slices/generationConfig/action.test.ts b/src/store/video/slices/generationConfig/action.test.tsindex 47d44017516..e6b9b329bb0 100644--- a/src/store/video/slices/generationConfig/action.test.ts+++ b/src/store/video/slices/generationConfig/action.test.ts@@ -8,6 +8,7 @@ import {import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useVideoStore } from '@/store/video';+import { videoGenerationConfigSelectors } from '@/store/video/selectors';const modelASchema: VideoModelParamsSchema = {prompt: { default: '' },@@ -155,8 +156,10 @@ describe('video generationConfig actions', () => {result.current.setModelAndProviderOnSelect('minimax-h3', 'provider-b');});+ // References switch MiniMax H3 into reference mode, where the end frame joins the pool+ expect(result.current.imageInputMode).toBe('reference');expect(result.current.parameters).toEqual({- endImageUrl: 'end-frame.png',+ endImageUrl: null,imageUrl: null,imageUrls: imageUrls.slice(0, 7),prompt: 'preserve references',@@ -164,6 +167,127 @@ describe('video generationConfig actions', () => {});});+describe('image input mode', () => {+ const setMinimaxH3 = (parameters: RuntimeVideoGenParams) =>+ useVideoStore.setState({+ editingGenerationId: undefined,+ imageInputMode: 'frames',+ model: 'minimax-h3',+ parameters,+ parametersSchema: minimaxH3Schema,+ provider: 'provider-b',+ stashedImageInputs: {},+ });++ it('keeps frames mode when switching to a model with frames and references', () => {+ const { result } = renderHook(() => useVideoStore());++ act(() => {+ result.current.setModelAndProviderOnSelect('minimax-h3', 'provider-b');+ });++ expect(result.current.imageInputMode).toBe('frames');+ expect(result.current.parameters).toMatchObject({+ endImageUrl: 'end-frame.png',+ imageUrl: 'start-frame.png',+ imageUrls: [],+ });+ });++ it('submits only the active mode images and restores the other mode on switch back', () => {+ setMinimaxH3({+ endImageUrl: 'end.png',+ imageUrl: 'start.png',+ imageUrls: [],+ prompt: 'p',+ } as RuntimeVideoGenParams);+ const { result } = renderHook(() => useVideoStore());++ act(() => {+ result.current.setImageInputMode('reference');+ });+ expect(result.current.parameters).toMatchObject({+ endImageUrl: null,+ imageUrl: null,+ imageUrls: [],+ });++ act(() => {+ result.current.setParamOnInput('imageUrls', ['ref.png']);+ result.current.setImageInputMode('frames');+ });+ expect(result.current.parameters).toMatchObject({+ endImageUrl: 'end.png',+ imageUrl: 'start.png',+ imageUrls: [],+ });++ act(() => {+ result.current.setImageInputMode('reference');+ });+ expect(result.current.parameters).toMatchObject({+ endImageUrl: null,+ imageUrl: null,+ imageUrls: ['ref.png'],+ });+ });++ it('lands an upload that finishes after a mode switch in the mode it started in', () => {+ setMinimaxH3({ imageUrl: null, imageUrls: [], prompt: 'p' } as RuntimeVideoGenParams);+ const { result } = renderHook(() => useVideoStore());++ act(() => {+ result.current.setImageInputMode('reference');+ });+ // The user switches to Frames while a References upload is still in flight.+ act(() => {+ result.current.setImageInputMode('frames');+ result.current.setImageInputForMode('reference', 'imageUrls', ['late-ref.png']);+ });+ expect(result.current.parameters).toMatchObject({ imageUrl: null, imageUrls: [] });+ expect(+ videoGenerationConfigSelectors.imageInputsOfMode('reference')(useVideoStore.getState()),+ ).toEqual({ imageUrls: ['late-ref.png'] });++ act(() => {+ result.current.setImageInputForMode('frames', 'imageUrl', 'start.png');+ result.current.setImageInputMode('reference');+ });+ expect(result.current.parameters).toMatchObject({+ imageUrl: null,+ imageUrls: ['late-ref.png'],+ });+ });++ it('reuses settings in the mode their images imply', () => {+ const { result } = renderHook(() => useVideoStore());++ act(() => {+ result.current.reuseVideoSettings('minimax-h3', 'provider-b', {+ imageUrl: 'start.png',+ imageUrls: ['ref.png'],+ prompt: 'reuse',+ } as RuntimeVideoGenParams);+ });+ expect(result.current.imageInputMode).toBe('reference');+ expect(result.current.parameters).toMatchObject({+ imageUrl: null,+ imageUrls: ['start.png', 'ref.png'],+ prompt: 'reuse',+ });++ act(() => {+ result.current.reuseVideoSettings('minimax-h3', 'provider-b', {+ imageUrl: 'start.png',+ imageUrls: [],+ prompt: 'reuse frames',+ } as RuntimeVideoGenParams);+ });+ expect(result.current.imageInputMode).toBe('frames');+ expect(result.current.parameters).toMatchObject({ imageUrl: 'start.png', imageUrls: [] });+ });+});+describe('uploading image previews', () => {it('should append and remove in-flight upload previews', () => {const { result } = renderHook(() => useVideoStore());diff --git a/src/store/video/slices/generationConfig/action.ts b/src/store/video/slices/generationConfig/action.tsindex 6cc57cda917..e5891ae3a28 100644--- a/src/store/video/slices/generationConfig/action.ts+++ b/src/store/video/slices/generationConfig/action.ts@@ -18,6 +18,13 @@ import {preserveSupportedParams,} from '../../../utils/preserveSupportedParams';import type { VideoStore } from '../../store';+import {+ applyImageInputs,+ normalizeImageInputMode,+ pickImageInputs,+ type VideoImageInputMode,+ type VideoImageInputs,+} from './imageInputMode';export function getVideoModelAndDefaults(model: string, provider: string) {const enabledVideoModelList = aiProviderSelectors.enabledVideoModelList(getAiInfraStoreState());@@ -113,22 +120,25 @@ export class GenerationConfigActionImpl {};setModelAndProviderOnSelect = (model: string, provider: string): void => {- const previousParameters = this.#get().parameters;+ const { imageInputMode: previousMode, parameters: previousParameters } = this.#get();const { defaultValues, parametersSchema } = getVideoModelAndDefaults(model, provider);- const parameters = preserveVideoInputParams(- previousParameters,- defaultValues,+ const { imageInputMode, parameters } = normalizeImageInputMode(+ preserveVideoInputParams(previousParameters, defaultValues, parametersSchema),parametersSchema,+ previousMode,);this.#set({editingDraftSnapshot: undefined,editingGenerationId: undefined,+ imageInputMode,model,parameters,parametersSchema,provider,+ // Stashed images were sized for the previous model's slots+ stashedImageInputs: {},},false,`setModelAndProviderOnSelect/${model}/${provider}`,@@ -143,6 +153,82 @@ export class GenerationConfigActionImpl {}};+ /**+ * Load a previous generation's model and settings, including its images. The image input mode+ * follows the images, so reference-mode settings reopen in reference mode.+ */+ reuseVideoSettings = (model: string, provider: string, config?: RuntimeVideoGenParams): void => {+ this.setModelAndProviderOnSelect(model, provider);+ if (!config) return;++ const { imageInputMode, parameters, parametersSchema } = this.#get();+ // The reused images replace the draft's instead of mixing with them+ const merged: Record<string, unknown> = { ...parameters };+ for (const key of ['imageUrl', 'imageUrls', 'endImageUrl']) {+ if (key in merged) merged[key] = key === 'imageUrls' ? [] : null;+ }+ for (const [key, value] of Object.entries(config)) {+ if (value !== undefined) merged[key] = value;+ }++ this.#set(+ normalizeImageInputMode(merged as RuntimeVideoGenParams, parametersSchema, imageInputMode),+ false,+ `reuseVideoSettings/${model}/${provider}`,+ );+ };++ /**+ * Switch between start/end frames and references. The outgoing mode's images are stashed and+ * the incoming mode's stash restored, so only the active mode's images are submitted.+ */+ setImageInputMode = (mode: VideoImageInputMode): void => {+ const { imageInputMode, parameters, stashedImageInputs } = this.#get();+ if (mode === imageInputMode) return;++ this.#set(+ {+ imageInputMode: mode,+ parameters: applyImageInputs(parameters, mode, stashedImageInputs[mode]),+ stashedImageInputs: {+ ...stashedImageInputs,+ [imageInputMode]: pickImageInputs(parameters, imageInputMode),+ [mode]: undefined,+ },+ },+ false,+ `setImageInputMode/${mode}`,+ );+ };++ /**+ * Set one image input of `mode`. Uploads land here with the mode they started in: when the user+ * switched modes while they were in flight, the images join that mode's stash instead of the+ * submitted parameters, which would otherwise mix both modes and change the provider endpoint.+ */+ setImageInputForMode = <K extends keyof VideoImageInputs>(+ mode: VideoImageInputMode,+ key: K,+ value: VideoImageInputs[K],+ ): void => {+ const { imageInputMode, stashedImageInputs } = this.#get();+ if (mode === imageInputMode) {+ this.setParamOnInput(key, value as RuntimeVideoGenParamsValue);+ return;+ }++ this.#set(+ {+ stashedImageInputs: {+ ...stashedImageInputs,+ [mode]: { ...stashedImageInputs[mode], [key]: value },+ },+ },+ false,+ `setImageInputForMode/${mode}/${key}`,+ );+ };+setParamOnInput = <K extends RuntimeVideoGenParamsKeys>(paramName: K,value: RuntimeVideoGenParamsValue,diff --git a/src/store/video/slices/generationConfig/imageInputMode.ts b/src/store/video/slices/generationConfig/imageInputMode.tsnew file mode 100644index 00000000000..1891d611d8f--- /dev/null+++ b/src/store/video/slices/generationConfig/imageInputMode.ts@@ -0,0 +1,105 @@+import type { RuntimeVideoGenParams, VideoModelParamsSchema } from 'model-bank';++/**+ * How a model that accepts both a start frame (`imageUrl`) and reference images (`imageUrls`)+ * uses the uploaded images:+ * - `frames`: start frame + optional end frame; the video opens on the start frame+ * - `reference`: reference images only; subjects/style carry over, composition follows the prompt+ *+ * Providers such as MiniMax H3 merge every image into one reference pool as soon as `imageUrls`+ * is non-empty, so a single upload could otherwise never be used as a reference.+ */+export type VideoImageInputMode = 'frames' | 'reference';++export type VideoImageInputs = Pick<+ RuntimeVideoGenParams,+ 'endImageUrl' | 'imageUrl' | 'imageUrls'+>;++export interface VideoImageInputSlots {+ endImageUrl: boolean;+ imageUrl: boolean;+ imageUrls: boolean;+}++export const supportsImageInputMode = (schema?: VideoModelParamsSchema) =>+ !!schema && 'imageUrl' in schema && 'imageUrls' in schema;++/**+ * Upload slots shown for the schema. Models with both start frame and reference support expose+ * only the slots of the active mode; other models keep every slot their schema declares.+ */+export const getImageInputSlots = (+ schema: VideoModelParamsSchema | undefined,+ mode: VideoImageInputMode,+): VideoImageInputSlots => {+ const slots = {+ endImageUrl: !!schema && 'endImageUrl' in schema,+ imageUrl: !!schema && 'imageUrl' in schema,+ imageUrls: !!schema && 'imageUrls' in schema,+ };+ if (!supportsImageInputMode(schema)) return slots;++ return mode === 'reference'+ ? { endImageUrl: false, imageUrl: false, imageUrls: true }+ : { endImageUrl: slots.endImageUrl, imageUrl: true, imageUrls: false };+};++export const pickImageInputs = (+ parameters: RuntimeVideoGenParams,+ mode: VideoImageInputMode,+): VideoImageInputs =>+ mode === 'reference'+ ? { imageUrls: parameters.imageUrls ?? [] }+ : { endImageUrl: parameters.endImageUrl ?? null, imageUrl: parameters.imageUrl ?? null };++/**+ * Return the parameters with only the given mode's images, taken from `inputs`.+ */+export const applyImageInputs = (+ parameters: RuntimeVideoGenParams,+ mode: VideoImageInputMode,+ inputs: VideoImageInputs = {},+): RuntimeVideoGenParams =>+ mode === 'reference'+ ? { ...parameters, endImageUrl: null, imageUrl: null, imageUrls: inputs.imageUrls ?? [] }+ : {+ ...parameters,+ endImageUrl: inputs.endImageUrl ?? null,+ imageUrl: inputs.imageUrl ?? null,+ imageUrls: [],+ };++/**+ * Derive the mode from parameters loaded from elsewhere (model switch, reused settings) and keep+ * them consistent with it. Reference images win, mirroring the runtime: when `imageUrls` is set,+ * start and end frames are folded into the reference pool in the order providers receive them.+ */+export const normalizeImageInputMode = (+ parameters: RuntimeVideoGenParams,+ schema: VideoModelParamsSchema,+ fallbackMode: VideoImageInputMode,+): { imageInputMode: VideoImageInputMode; parameters: RuntimeVideoGenParams } => {+ if (!supportsImageInputMode(schema)) return { imageInputMode: 'frames', parameters };++ const { endImageUrl, imageUrl, imageUrls } = parameters;+ const imageInputMode: VideoImageInputMode = imageUrls?.length+ ? 'reference'+ : imageUrl || endImageUrl+ ? 'frames'+ : fallbackMode;++ if (imageInputMode === 'frames') {+ return { imageInputMode, parameters: applyImageInputs(parameters, 'frames', parameters) };+ }++ const pool = [imageUrl, ...(imageUrls ?? []), endImageUrl].filter((url): url is string => !!url);+ const maxCount = schema.imageUrls?.maxCount;++ return {+ imageInputMode,+ parameters: applyImageInputs(parameters, 'reference', {+ imageUrls: typeof maxCount === 'number' ? pool.slice(0, maxCount) : pool,+ }),+ };+};diff --git a/src/store/video/slices/generationConfig/initialState.ts b/src/store/video/slices/generationConfig/initialState.tsindex 8e746e23e24..ba269275460 100644--- a/src/store/video/slices/generationConfig/initialState.ts+++ b/src/store/video/slices/generationConfig/initialState.ts@@ -8,6 +8,8 @@ import {type VideoModelParamsSchema,} from 'model-bank/standardParameters';+import type { VideoImageInputMode, VideoImageInputs } from './imageInputMode';+export const DEFAULT_AI_VIDEO_PROVIDER = ModelProvider.LobeHub;export const DEFAULT_AI_VIDEO_MODEL = 'dreamina-seedance-2-0-260128';@@ -56,6 +58,17 @@ export interface VideoGenerationConfigState {*/uploadingImagePreviews: string[];+ /**+ * Whether uploaded images act as start/end frames or references, for models that accept both.+ * Ignored by models without both `imageUrl` and `imageUrls`.+ */+ imageInputMode: VideoImageInputMode;+ /**+ * Images of the inactive mode, restored when the user switches back so toggling never discards+ * uploads. Only the active mode's images live in `parameters` and get submitted.+ */+ stashedImageInputs: Partial<Record<VideoImageInputMode, VideoImageInputs>>;+/*** Marks whether the configuration has been initialized (including restoration from memory)*/@@ -71,5 +84,7 @@ export const initialGenerationConfigState: VideoGenerationConfigState = {parameters: DEFAULT_VIDEO_GENERATION_PARAMETERS,parametersSchema: seedance20Params,uploadingImagePreviews: [],+ imageInputMode: 'frames',+ stashedImageInputs: {},isInit: false,};diff --git a/src/store/video/slices/generationConfig/selectors.ts b/src/store/video/slices/generationConfig/selectors.tsindex 2735b81a8c7..fced2fe835b 100644--- a/src/store/video/slices/generationConfig/selectors.ts+++ b/src/store/video/slices/generationConfig/selectors.ts@@ -1,5 +1,12 @@import { type RuntimeVideoGenParamsKeys } from 'model-bank';+import {+ getImageInputSlots,+ supportsImageInputMode,+ type VideoImageInputMode,+ type VideoImageInputs,+ type VideoImageInputSlots,+} from './imageInputMode';import { type VideoGenerationConfigState } from './initialState';const model = (s: VideoGenerationConfigState) => s.model;@@ -15,7 +22,26 @@ const isSupportedParam = (paramName: RuntimeVideoGenParamsKeys) => {};};+/** Whether the current model accepts both start frames and references, i.e. shows the mode toggle */+const hasImageInputMode = (s: VideoGenerationConfigState) =>+ supportsImageInputMode(s.parametersSchema);+const imageInputMode = (s: VideoGenerationConfigState) => s.imageInputMode;+/** Whether an upload slot is shown for the current model and active image input mode */+const isImageInputSlotEnabled =+ (slot: keyof VideoImageInputSlots) => (s: VideoGenerationConfigState) =>+ getImageInputSlots(s.parametersSchema, s.imageInputMode)[slot];++/** Image inputs of `mode`: the submitted parameters when it is active, otherwise its stash */+const imageInputsOfMode =+ (mode: VideoImageInputMode) =>+ (s: VideoGenerationConfigState): VideoImageInputs =>+ mode === s.imageInputMode ? s.parameters : (s.stashedImageInputs[mode] ?? {});+export const videoGenerationConfigSelectors = {+ hasImageInputMode,+ imageInputMode,+ imageInputsOfMode,+ isImageInputSlotEnabled,isSupportedParam,model,parameters,