Skip to content

🤯 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.

✨ feat: add video generation feature

YuTengjingabe4c969a5c5
diff --git a/.agents/skills/drizzle/references/db-migrations.md b/.agents/skills/drizzle/references/db-migrations.md
index a5afec8275e..e781b2dd07f 100644
--- a/.agents/skills/drizzle/references/db-migrations.md
+++ b/.agents/skills/drizzle/references/db-migrations.md
@@ -38,13 +38,3 @@ ALTER TABLE "users" ADD COLUMN "avatar" text;
DROP TABLE "old_table";
CREATE INDEX "users_email_idx" ON "users" ("email");
```
-
-## Important
-
-After modifying migration SQL (e.g., adding `IF NOT EXISTS` clauses), run:
-
-```bash
-bun run db:generate:client
-```
-
-This updates the hash in `packages/database/src/core/migrations.json`.
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 39c3f35a684..d7dc7e271db 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -53,7 +53,8 @@
"typescriptreact"
],
"typescript.tsdk": "node_modules/typescript/lib",
- "vitest.maximumConfigs": 20,
+ "vitest.disableWorkspaceWarning": true,
+ "vitest.maximumConfigs": 10,
"workbench.editor.customLabels.patterns": {
"**/app/**/[[]*[]]/[[]*[]]/page.tsx": "${dirname(2)}/${dirname(1)}/${dirname} • page component",
"**/app/**/[[]*[]]/page.tsx": "${dirname(1)}/${dirname} • page component",
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 6397a257ef2..b9fd6cd11dd 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -55,8 +55,10 @@ export default eslint(
{
rules: {
'@next/next/no-img-element': 0,
+ '@typescript-eslint/consistent-type-imports': 0,
'@typescript-eslint/no-use-before-define': 0,
'@typescript-eslint/no-useless-constructor': 0,
+ 'import-x/consistent-type-specifier-style': 0,
'no-extra-boolean-cast': 0,
'react/no-unknown-property': 0,
'regexp/match-any': 0,
diff --git a/locales/en-US/spend.json b/locales/en-US/spend.json
index 6e31a195d87..e3fc1265398 100644
--- a/locales/en-US/spend.json
+++ b/locales/en-US/spend.json
@@ -14,6 +14,7 @@
"table.columns.totalTokens": "Token Usage",
"table.columns.type.enums.chat": "Text Generation",
"table.columns.type.enums.imageGeneration": "Image Generation",
+ "table.columns.type.enums.videoGeneration": "Video Generation",
"table.columns.type.title": "Type",
"table.desc": "Details of computing credits usage for text generation, embedding, image generation, etc.",
"table.more": "View Details",
diff --git a/locales/en-US/video.json b/locales/en-US/video.json
new file mode 100644
index 00000000000..2e483d1079b
--- /dev/null
+++ b/locales/en-US/video.json
@@ -0,0 +1,23 @@
+{
+ "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.imageUrl.label": "Start Frame",
+ "config.prompt.placeholder": "Describe the video you want to generate",
+ "config.referenceImage.label": "Reference Image",
+ "config.resolution.label": "Resolution",
+ "config.seed.label": "Seed",
+ "config.seed.random": "Random",
+ "generation.actions.generate": "Generate",
+ "generation.validation.endFrameRequiresStartFrame": "End frame cannot be used without a start frame. Please set a start frame first.",
+ "generation.status.generating": "Generating...",
+ "topic.createNew": "New Topic",
+ "topic.deleteConfirm": "Delete Video Topic",
+ "topic.deleteConfirmDesc": "You are about to delete this video topic. This action cannot be undone.",
+ "topic.empty": "No video topics",
+ "topic.title": "Video Topics",
+ "topic.untitled": "Default Topic"
+}
diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.json
index ab985cb45ef..80c97c06dd9 100644
--- a/locales/zh-CN/spend.json
+++ b/locales/zh-CN/spend.json
@@ -14,6 +14,7 @@
"table.columns.totalTokens": "令牌使用量",
"table.columns.type.enums.chat": "文本生成",
"table.columns.type.enums.imageGeneration": "图像生成",
+ "table.columns.type.enums.videoGeneration": "视频生成",
"table.columns.type.title": "类型",
"table.desc": "展示文本生成、嵌入、图像生成等功能的计算积分使用详情。",
"table.more": "查看详情",
diff --git a/locales/zh-CN/video.json b/locales/zh-CN/video.json
new file mode 100644
index 00000000000..f0c2adebe81
--- /dev/null
+++ b/locales/zh-CN/video.json
@@ -0,0 +1,23 @@
+{
+ "config.aspectRatio.label": "画面比例",
+ "config.cameraFixed.label": "固定镜头",
+ "config.duration.label": "时长",
+ "config.endImageUrl.label": "结束帧",
+ "config.generateAudio.label": "生成音频",
+ "config.header.title": "AI 视频",
+ "config.imageUrl.label": "起始帧",
+ "config.prompt.placeholder": "描述你想生成的视频",
+ "config.referenceImage.label": "参考图",
+ "config.resolution.label": "分辨率",
+ "config.seed.label": "种子",
+ "config.seed.random": "随机",
+ "generation.actions.generate": "生成",
+ "generation.validation.endFrameRequiresStartFrame": "不支持单独设置尾帧,请先设置起始帧",
+ "generation.status.generating": "生成中...",
+ "topic.createNew": "新建主题",
+ "topic.deleteConfirm": "删除视频主题",
+ "topic.deleteConfirmDesc": "确认删除该视频主题吗?删除后无法恢复",
+ "topic.empty": "暂无视频主题",
+ "topic.title": "视频主题",
+ "topic.untitled": "默认主题"
+}
diff --git a/next.config.ts b/next.config.ts
index 95b3b76d2a8..da85eccb2e1 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -18,6 +18,11 @@ const nextConfig = defineConfig({
],
}
: undefined,
+ // Include ffmpeg binary for video webhook processing
+ // refs: https://github.com/vercel-labs/ffmpeg-on-vercel
+ outputFileTracingIncludes: {
+ '/api/webhooks/video/*': ['./node_modules/ffmpeg-static/ffmpeg'],
+ },
webpack: (webpackConfig, context) => {
const { dev } = context;
if (!dev) {
diff --git a/package.json b/package.json
index 6ad2d68e86c..7cfe34a1adb 100644
--- a/package.json
+++ b/package.json
@@ -275,6 +275,7 @@
"es-toolkit": "^1.44.0",
"fast-deep-equal": "^3.1.3",
"fflate": "^0.8.2",
+ "ffmpeg-static": "^5.3.0",
"file-type": "^21.3.0",
"gray-matter": "^4.0.3",
"html-to-text": "^9.0.5",
@@ -472,6 +473,9 @@
"registry": "https://registry.npmjs.org"
},
"pnpm": {
+ "onlyBuiltDependencies": [
+ "ffmpeg-static"
+ ],
"overrides": {
"@types/react": "19.2.13",
"better-auth": "1.4.6",
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index 85a7ec9fcc7..c5d96e791eb 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -37,6 +37,12 @@ export class AsyncTaskModel {
return this.db.query.asyncTasks.findFirst({ where: and(eq(asyncTasks.id, id)) });
};
+ findByInferenceId = async (inferenceId: string) => {
+ return this.db.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.inferenceId, inferenceId),
+ });
+ };
+
update(taskId: string, value: Partial<AsyncTaskSelectItem>) {
return this.db
.update(asyncTasks)
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index 5b5f1c0e4ab..55559b42833 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -49,14 +49,17 @@ export class FileModel {
): Promise<{ id: string }> => {
const executeInTransaction = async (tx: Transaction): Promise<FileItem> => {
if (insertToGlobalFiles) {
- await tx.insert(globalFiles).values({
- creator: this.userId,
- fileType: params.fileType,
- hashId: params.fileHash!,
- metadata: params.metadata,
- size: params.size,
- url: params.url,
- });
+ await tx
+ .insert(globalFiles)
+ .values({
+ creator: this.userId,
+ fileType: params.fileType,
+ hashId: params.fileHash!,
+ metadata: params.metadata,
+ size: params.size,
+ url: params.url,
+ })
+ .onConflictDoNothing();
}
const result = (await tx
diff --git a/packages/database/src/models/generation.ts b/packages/database/src/models/generation.ts
index f95d953cda9..58a6845649e 100644
--- a/packages/database/src/models/generation.ts
+++ b/packages/database/src/models/generation.ts
@@ -2,7 +2,9 @@ import type {
AsyncTaskError,
AsyncTaskStatus,
Generation,
+ GenerationAsset,
ImageGenerationAsset,
+ VideoGenerationAsset,
} from '@lobechat/types';
import { FileSource } from '@lobechat/types';
import debug from 'debug';
@@ -93,8 +95,9 @@ export class GenerationModel {
async createAssetAndFile(
id: string,
- asset: ImageGenerationAsset,
+ asset: GenerationAsset,
file: Omit<NewFile, 'id' | 'userId'>,
+ source: FileSource = FileSource.ImageGeneration,
) {
log('Creating generation asset and file with transaction: %s', id);
@@ -105,7 +108,7 @@ export class GenerationModel {
{
...file,
parentId: file.parentId ?? undefined,
- source: FileSource.ImageGeneration,
+ source,
},
true,
tx,
@@ -129,6 +132,14 @@ export class GenerationModel {
});
}
+ async findByAsyncTaskId(asyncTaskId: string) {
+ log('Finding generation by asyncTaskId: %s', asyncTaskId);
+
+ return this.db.query.generations.findFirst({
+ where: eq(generations.asyncTaskId, asyncTaskId),
+ });
+ }
+
async delete(id: string, trx?: Transaction) {
log('Deleting generation: %s for user: %s', id, this.userId);
@@ -168,14 +179,26 @@ export class GenerationModel {
*/
async transformGeneration(generation: GenerationWithAsyncTask): Promise<Generation> {
// Process asset URLs if they exist, following the same logic as in generationBatch.ts
- const asset = generation.asset as ImageGenerationAsset | null;
+ const asset = generation.asset as ImageGenerationAsset | VideoGenerationAsset | null;
if (asset && asset.url && asset.thumbnailUrl) {
- const [url, thumbnailUrl] = await Promise.all([
+ const urlPromises: Promise<string>[] = [
this.fileService.getFullFileUrl(asset.url),
this.fileService.getFullFileUrl(asset.thumbnailUrl),
- ]);
- asset.url = url;
- asset.thumbnailUrl = thumbnailUrl;
+ ];
+
+ // Also convert coverUrl for video assets
+ const videoAsset = asset as VideoGenerationAsset;
+ const hasCoverUrl = videoAsset.coverUrl;
+ if (hasCoverUrl) {
+ urlPromises.push(this.fileService.getFullFileUrl(videoAsset.coverUrl!));
+ }
+
+ const urls = await Promise.all(urlPromises);
+ asset.url = urls[0];
+ asset.thumbnailUrl = urls[1];
+ if (hasCoverUrl) {
+ videoAsset.coverUrl = urls[2];
+ }
}
// Build the Generation object following the same structure as in generationBatch.ts
diff --git a/packages/database/src/models/generationBatch.ts b/packages/database/src/models/generationBatch.ts
index 4d5620ca1cf..4e0d9ebde28 100644
--- a/packages/database/src/models/generationBatch.ts
+++ b/packages/database/src/models/generationBatch.ts
@@ -132,6 +132,11 @@ export class GenerationBatchModel {
config.imageUrl = await this.fileService.getFullFileUrl(config.imageUrl);
}
+ // Handle endImageUrl (video start/end frame)
+ if (config.endImageUrl) {
+ config.endImageUrl = await this.fileService.getFullFileUrl(config.endImageUrl);
+ }
+
// Handle imageUrls array
if (Array.isArray(config.imageUrls)) {
config.imageUrls = await Promise.all(
diff --git a/packages/database/src/models/generationTopic.ts b/packages/database/src/models/generationTopic.ts
index 66919faa7ce..bf3aa24ace4 100644
--- a/packages/database/src/models/generationTopic.ts
+++ b/packages/database/src/models/generationTopic.ts
@@ -18,12 +18,17 @@ export class GenerationTopicModel {
this.fileService = new FileService(db, userId);
}
- queryAll = async () => {
+ queryAll = async (type?: string) => {
+ const conditions = [eq(generationTopics.userId, this.userId)];
+ if (type) {
+ conditions.push(eq(generationTopics.type, type));
+ }
+
const topics = await this.db
.select()
.from(generationTopics)
.orderBy(desc(generationTopics.updatedAt))
- .where(eq(generationTopics.userId, this.userId));
+ .where(and(...conditions));
return Promise.all(
topics.map(async (topic) => {
@@ -38,11 +43,12 @@ export class GenerationTopicModel {
);
};
- create = async (title: string) => {
+ create = async (title: string, type?: string) => {
const [newGenerationTopic] = await this.db
.insert(generationTopics)
.values({
title,
+ type: type ?? 'image',
userId: this.userId,
})
.returning();
diff --git a/packages/database/src/repositories/aiInfra/index.test.ts b/packages/database/src/repositories/aiInfra/index.test.ts
index b90947d3184..4a4ff8fae39 100644
--- a/packages/database/src/repositories/aiInfra/index.test.ts
+++ b/packages/database/src/repositories/aiInfra/index.test.ts
@@ -1628,6 +1628,7 @@ describe('AiInfraRepos', () => {
{ id: 'openai', logo: 'logo1', name: 'OpenAI', source: 'builtin' },
],
enabledImageAiProviders: [],
+ enabledVideoAiProviders: [],
runtimeConfig: {
openai: {
apiKey: 'test-key',
@@ -1718,6 +1719,7 @@ describe('AiInfraRepos', () => {
name: 'Fal',
}),
],
+ enabledVideoAiProviders: [],
runtimeConfig: {
fal: {
apiKey: 'test-fal-key',
@@ -1782,6 +1784,7 @@ describe('AiInfraRepos', () => {
enabledAiProviders: [],
enabledChatAiProviders: [],
enabledImageAiProviders: [],
+ enabledVideoAiProviders: [],
runtimeConfig: {},
});
diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.ts
index 6e55b45815d..b54d645a81e 100644
--- a/packages/database/src/repositories/aiInfra/index.ts
+++ b/packages/database/src/repositories/aiInfra/index.ts
@@ -270,12 +270,18 @@ export class AiInfraRepos {
const enabledImageAiProviders = enabledAiProviders.filter((provider) => {
return allModels.some((model) => model.providerId === provider.id && model.type === 'image');
});
+ const enabledVideoAiProviders = enabledAiProviders.filter((provider) => {
+ return allModels.some(
+ (model) => model.providerId === provider.id && model.type === 'video',
+ );
+ });
return {
enabledAiModels,
enabledAiProviders,
enabledChatAiProviders,
enabledImageAiProviders,
+ enabledVideoAiProviders,
runtimeConfig,
};
};
diff --git a/packages/database/src/schemas/generation.ts b/packages/database/src/schemas/generation.ts
index 9222e0c826e..15583fbaaf0 100644
--- a/packages/database/src/schemas/generation.ts
+++ b/packages/database/src/schemas/generation.ts
@@ -1,5 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix */
-import type { ImageGenerationAsset } from '@lobechat/types';
+import type { GenerationAsset } from '@lobechat/types';
import { index, integer, jsonb, pgTable, text, uuid, varchar } from 'drizzle-orm/pg-core';
import { createInsertSchema } from 'drizzle-zod';
@@ -131,7 +131,7 @@ export const generations = pgTable(
seed: integer('seed'),
/** Generated asset information, including S3 storage key, actual image dimensions, thumbnail key, etc. */
- asset: jsonb('asset').$type<ImageGenerationAsset>(),
+ asset: jsonb('asset').$type<GenerationAsset>(),
...timestamps,
},
diff --git a/packages/model-bank/src/aiModels/lobehub/index.ts b/packages/model-bank/src/aiModels/lobehub/index.ts
index 238698e8702..aab9acbe181 100644
--- a/packages/model-bank/src/aiModels/lobehub/index.ts
+++ b/packages/model-bank/src/aiModels/lobehub/index.ts
@@ -1,10 +1,12 @@
import { lobehubChatModels } from './chat';
import { lobehubImageModels } from './image';
+import { lobehubVideoModels } from './video';
export { lobehubChatModels } from './chat';
export { lobehubImageModels } from './image';
export * from './utils';
+export { lobehubVideoModels, seedance15ProParams } from './video';
-export const allModels = [...lobehubChatModels, ...lobehubImageModels];
+export const allModels = [...lobehubChatModels, ...lobehubImageModels, ...lobehubVideoModels];
export default allModels;
diff --git a/packages/model-bank/src/aiModels/lobehub/video.ts b/packages/model-bank/src/aiModels/lobehub/video.ts
new file mode 100644
index 00000000000..2113c965417
--- /dev/null
+++ b/packages/model-bank/src/aiModels/lobehub/video.ts
@@ -0,0 +1,52 @@
+import {
+ PRESET_VIDEO_ASPECT_RATIOS,
+ PRESET_VIDEO_RESOLUTIONS,
+ type VideoModelParamsSchema,
+} from '../../standard-parameters/video';
+import { type AIVideoModelCard } from '../../types/aiModel';
+
+export const seedance15ProParams: VideoModelParamsSchema = {
+ aspectRatio: {
+ default: 'adaptive',
+ enum: ['adaptive', ...PRESET_VIDEO_ASPECT_RATIOS],
+ },
+ cameraFixed: { default: false },
+ duration: { default: 5, max: 12, min: 4 },
+ endImageUrl: { default: null, maxFileSize: 30 * 1024 * 1024, requiresImageUrl: true },
+ generateAudio: { default: true },
+ imageUrl: { default: null, maxFileSize: 30 * 1024 * 1024 },
+ prompt: { default: '' },
+ resolution: {
+ default: '720p',
+ enum: PRESET_VIDEO_RESOLUTIONS,
+ },
+ seed: { default: null },
+};
+
+export const lobehubVideoModels: AIVideoModelCard[] = [
+ {
+ description:
+ 'Seedance 1.5 Pro by ByteDance supports text-to-video, image-to-video (first frame, first+last frame), and audio generation synchronized with visuals.',
+ displayName: 'Seedance 1.5 Pro',
+ enabled: true,
+ id: 'seedance-1-5-pro-251215',
+ organization: 'ByteDance',
+ parameters: seedance15ProParams,
+ pricing: {
+ approximatePricePerVideo: 0.25,
+ units: [
+ {
+ lookup: {
+ pricingParams: ['generateAudio'],
+ prices: { false: 1.2, true: 2.4 },
+ },
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ },
+ releasedAt: '2025-12-15',
+ type: 'video',
+ },
+];
diff --git a/packages/model-bank/src/standard-parameters/index.ts b/packages/model-bank/src/standard-parameters/index.ts
index ea57bef4e98..f05fa94f327 100644
--- a/packages/model-bank/src/standard-parameters/index.ts
+++ b/packages/model-bank/src/standard-parameters/index.ts
@@ -261,3 +261,5 @@ export function extractDefaultValues(paramsSchema: ModelParamsSchema) {
}),
) as RuntimeImageGenParams;
}
+
+export * from './video';
diff --git a/packages/model-bank/src/standard-parameters/video.ts b/packages/model-bank/src/standard-parameters/video.ts
new file mode 100644
index 00000000000..d0ea64a3f58
--- /dev/null
+++ b/packages/model-bank/src/standard-parameters/video.ts
@@ -0,0 +1,144 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import type { Simplify } from 'type-fest';
+import { z } from 'zod';
+
+export const MAX_VIDEO_SEED = 2 ** 32 - 1;
+
+export const PRESET_VIDEO_ASPECT_RATIOS = [
+ '16:9', // Landscape video standard
+ '9:16', // Portrait/short-form video
+ '1:1', // Square
+ '4:3', // Traditional
+ '3:4', // Portrait traditional
+ '21:9', // Ultra-wide cinematic
+];
+
+export const PRESET_VIDEO_RESOLUTIONS = ['480p', '720p', '1080p'];
+
+export const VideoModelParamsMetaSchema = z.object({
+ prompt: z.object({
+ default: z.string().optional().default(''),
+ description: z.string().optional(),
+ type: z.literal('string').optional(),
+ }),
+
+ imageUrl: z
+ .object({
+ default: z.string().nullable().optional(),
+ description: z.string().optional(),
+ maxFileSize: z.number().optional(),
+ type: z.tuple([z.literal('string'), z.literal('null')]).optional(),
+ })
+ .optional(),
+
+ endImageUrl: z
+ .object({
+ default: z.string().nullable().optional(),
+ description: z.string().optional(),
+ maxFileSize: z.number().optional(),
+ requiresImageUrl: z.boolean().optional(),
+ type: z.tuple([z.literal('string'), z.literal('null')]).optional(),
+ })
+ .optional(),
+
+ aspectRatio: z
+ .object({
+ default: z.string(),
+ description: z.string().optional(),
+ enum: z.array(z.string()),
+ type: z.literal('string').optional(),
+ })
+ .optional(),
+
+ resolution: z
+ .object({
+ default: z.string(),
+ description: z.string().optional(),
+ enum: z.array(z.string()),
+ type: z.literal('string').optional(),
+ })
+ .optional(),
+
+ duration: z
+ .object({
+ default: z.number(),
+ description: z.string().optional(),
+ max: z.number(),
+ min: z.number(),
+ step: z.number().optional().default(1),
+ type: z.literal('number').optional(),
+ })
+ .optional(),
+
+ cameraFixed: z
+ .object({
+ default: z.boolean().default(false),
+ description: z.string().optional(),
+ type: z.literal('boolean').optional(),
+ })
+ .optional(),
+
+ generateAudio: z
+ .object({
+ default: z.boolean().default(true),
+ description: z.string().optional(),
+ type: z.literal('boolean').optional(),
+ })
+ .optional(),
+
+ seed: z
+ .object({
+ default: z.number().nullable().default(null),
+ description: z.string().optional(),
+ max: z.number().optional().default(MAX_VIDEO_SEED),
+ min: z.number().optional().default(-1),
+ type: z.tuple([z.literal('number'), z.literal('null')]).optional(),
+ })
+ .optional(),
+});
+
+export type VideoModelParamsSchema = z.input<typeof VideoModelParamsMetaSchema>;
+export type VideoModelParamsOutputSchema = z.output<typeof VideoModelParamsMetaSchema>;
+export type VideoModelParamsKeys = Simplify<keyof VideoModelParamsOutputSchema>;
+
+type VideoTypeMapping<T> = T extends 'string'
+ ? string
+ : T extends 'number'
+ ? number
+ : T extends ['number', 'null']
+ ? number | null
+ : T extends ['string', 'null']
+ ? string | null
+ : T extends 'boolean'
+ ? boolean
+ : never;
+
+type VideoTypeType<K extends VideoModelParamsKeys> = NonNullable<
+ VideoModelParamsOutputSchema[K]
+>['type'];
+type _StandardVideoGenerationParameters<P extends VideoModelParamsKeys = VideoModelParamsKeys> = {
+ [key in P]: VideoTypeMapping<VideoTypeType<key>>;
+};
+
+export type RuntimeVideoGenParams = Pick<_StandardVideoGenerationParameters, 'prompt'> &
+ Partial<Omit<_StandardVideoGenerationParameters, 'prompt'>>;
+export type RuntimeVideoGenParamsKeys = keyof RuntimeVideoGenParams;
+export type RuntimeVideoGenParamsValue = RuntimeVideoGenParams[RuntimeVideoGenParamsKeys];
+
+export function validateVideoModelParamsSchema(
+ paramsSchema: unknown,
+): VideoModelParamsOutputSchema {
+ return VideoModelParamsMetaSchema.parse(paramsSchema);
+}
+
+/**
+ * Extract default values from video parameter definition object
+ */
+export function extractVideoDefaultValues(paramsSchema: VideoModelParamsSchema) {
+ const schemaWithDefault = VideoModelParamsMetaSchema.parse(paramsSchema);
+ return Object.fromEntries(
+ Object.entries(schemaWithDefault).map(([key, value]) => {
+ return [key, value.default];
+ }),
+ ) as RuntimeVideoGenParams;
+}
diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.ts
index 6a58d92008a..fb049a5ef59 100644
--- a/packages/model-bank/src/types/aiModel.ts
+++ b/packages/model-bank/src/types/aiModel.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
-import type { ModelParamsSchema } from '../standard-parameters';
+import type { ModelParamsSchema, VideoModelParamsSchema } from '../standard-parameters';
export type ModelPriceCurrency = 'CNY' | 'USD';
@@ -18,7 +18,7 @@ export const AiModelTypeSchema = z.enum([
'tts',
'stt',
'image',
- 'text2video',
+ 'video',
'text2music',
'realtime',
] as const);
@@ -144,7 +144,10 @@ export type PricingUnitName =
| 'imageGeneration' // for image generation models
| 'imageInput'
| 'imageInput_cacheRead'
- | 'imageOutput';
+ | 'imageOutput'
+
+ // Video-based pricing units
+ | 'videoGeneration';
export type PricingUnitType =
| 'millionTokens' // per 1M tokens
@@ -189,6 +192,10 @@ export interface Pricing {
* Fallback approximate per-image price (USD) when detailed pricing table is unavailable
*/
approximatePricePerImage?: number;
+ /**
+ * Fallback approximate per-video price (USD) when detailed pricing table is unavailable
+ */
+ approximatePricePerVideo?: number;
currency?: ModelPriceCurrency;
units: PricingUnit[];
}
@@ -312,6 +319,12 @@ export interface AIImageModelCard extends AIBaseModelCard {
type: 'image';
}
+export interface AIVideoModelCard extends AIBaseModelCard {
+ parameters?: VideoModelParamsSchema;
+ pricing?: Pricing;
+ type: 'video';
+}
+
export interface AITTSModelCard extends AIBaseModelCard {
pricing?: Pricing;
type: 'tts';
diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.ts
index f5e47d7f871..a9590aa43f5 100644
--- a/packages/model-runtime/src/core/BaseAI.ts
+++ b/packages/model-runtime/src/core/BaseAI.ts
@@ -6,11 +6,15 @@ import type {
ChatStreamPayload,
CreateImagePayload,
CreateImageResponse,
+ CreateVideoPayload,
+ CreateVideoResponse,
Embeddings,
EmbeddingsOptions,
EmbeddingsPayload,
GenerateObjectOptions,
GenerateObjectPayload,
+ HandleCreateVideoWebhookPayload,
+ HandleCreateVideoWebhookResult,
ModelRequestOptions,
PullModelParams,
TextToSpeechOptions,
@@ -23,6 +27,8 @@ export interface LobeRuntimeAI {
chat?: (payload: ChatStreamPayload, options?: ChatMethodOptions) => Promise<Response>;
createImage?: (payload: CreateImagePayload) => Promise<CreateImageResponse>;
+ createVideo?: (payload: CreateVideoPayload) => Promise<CreateVideoResponse>;
+
embeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<Embeddings[]>;
generateObject?: (
@@ -30,6 +36,10 @@ export interface LobeRuntimeAI {
options?: GenerateObjectOptions,
) => Promise<any>;
+ handleCreateVideoWebhook?: (
+ payload: HandleCreateVideoWebhookPayload,
+ ) => Promise<HandleCreateVideoWebhookResult>;
+
models?: () => Promise<any>;
// Model management related interface
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index a835e8b0608..6311079021e 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -17,6 +17,7 @@ import type {
} from '../types';
import { AgentRuntimeErrorType } from '../types/error';
import type { AuthenticatedImageRuntime, CreateImagePayload } from '../types/image';
+import type { CreateVideoPayload, HandleCreateVideoWebhookPayload } from '../types/video';
import { AgentRuntimeError } from '../utils/createError';
import type { LobeRuntimeAI } from './BaseAI';
@@ -82,6 +83,14 @@ export class ModelRuntime {
return this._runtime.createImage?.(payload);
}
+ async createVideo(payload: CreateVideoPayload) {
+ return this._runtime.createVideo?.(payload);
+ }
+
+ async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
+ return this._runtime.handleCreateVideoWebhook?.(payload);
+ }
+
async models() {
return this._runtime.models?.();
}
diff --git a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
index 6c8009652df..a74329f2d2d 100644
--- a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
@@ -13,6 +13,7 @@ export type ApiType =
| 'openai'
| 'qwen'
| 'vertexai'
+ | 'volcengine'
| 'xai';
export type RuntimeClass = new (options?: any) => LobeRuntimeAI;
diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
index c6052fc591c..477493295a3 100644
--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
@@ -10,6 +10,7 @@ import { LobeMoonshotAI } from '../../providers/moonshot';
import { LobeOpenAI } from '../../providers/openai';
import { LobeQwenAI } from '../../providers/qwen';
import { LobeVertexAI } from '../../providers/vertexai';
+import { LobeVolcengineAI } from '../../providers/volcengine';
import { LobeXAI } from '../../providers/xai';
import type { ApiType, RuntimeClass } from './apiTypes';
@@ -26,5 +27,6 @@ export const baseRuntimeMap = {
openai: LobeOpenAI,
qwen: LobeQwenAI,
vertexai: LobeVertexAI,
+ volcengine: LobeVolcengineAI,
xai: LobeXAI,
} satisfies Record<ApiType, RuntimeClass>;
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 7dace1e88df..774a23680cc 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -12,8 +12,12 @@ import { LobeVertexAI } from '../../providers/vertexai';
import {
CreateImagePayload,
CreateImageResponse,
+ CreateVideoPayload,
+ CreateVideoResponse,
GenerateObjectOptions,
GenerateObjectPayload,
+ HandleCreateVideoWebhookPayload,
+ HandleCreateVideoWebhookResult,
ILobeAgentRuntimeErrorType,
} from '../../types';
import {
@@ -28,7 +32,11 @@ import {
import { postProcessModelList } from '../../utils/postProcessModelList';
import { safeParseJSON } from '../../utils/safeParseJSON';
import { LobeRuntimeAI } from '../BaseAI';
-import { CreateImageOptions, CustomClientOptions } from '../openaiCompatibleFactory';
+import {
+ CreateImageOptions,
+ CreateVideoOptions,
+ CustomClientOptions,
+} from '../openaiCompatibleFactory';
import type { ApiType, RuntimeClass } from './apiTypes';
const log = debug('lobe-model-runtime:router-runtime');
@@ -120,6 +128,10 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
payload: CreateImagePayload,
options: CreateImageOptions,
) => Promise<CreateImageResponse>;
+ createVideo?: (
+ payload: CreateVideoPayload,
+ options: CreateVideoOptions,
+ ) => Promise<CreateVideoResponse>;
customClient?: CustomClientOptions<T>;
debug?: {
chatCompletion: () => boolean;
@@ -130,6 +142,10 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
bizError: ILobeAgentRuntimeErrorType;
invalidAPIKey: ILobeAgentRuntimeErrorType;
};
+ handleCreateVideoWebhook?: (
+ payload: HandleCreateVideoWebhookPayload,
+ options: CreateVideoOptions,
+ ) => Promise<HandleCreateVideoWebhookResult>;
id: string;
models?:
| ((params: { client: OpenAI }) => Promise<ChatModelCard[]>)
@@ -324,36 +340,40 @@ export const createRouterRuntime = ({
);
}
- params.onRouteAttempt?.({
- apiType: resolvedApiType,
- channelId,
- durationMs: Date.now() - startTime,
- model,
- providerId: id,
- remark,
- routerId: matchedRouter.id,
- success: true,
- }).catch((e) => {
- log('onRouteAttempt callback error: %O', e);
- });
+ params
+ .onRouteAttempt?.({
+ apiType: resolvedApiType,
+ channelId,
+ durationMs: Date.now() - startTime,
+ model,
+ providerId: id,
+ remark,
+ routerId: matchedRouter.id,
+ success: true,
+ })
+ .catch((e) => {
+ log('onRouteAttempt callback error: %O', e);
+ });
return result;
} catch (error) {
lastError = error;
- params.onRouteAttempt?.({
- apiType: resolvedApiType,
- channelId,
- durationMs: Date.now() - startTime,
- error,
- model,
- providerId: id,
- remark,
- routerId: matchedRouter.id,
- success: false,
- }).catch((e) => {
- log('onRouteAttempt callback error: %O', e);
- });
+ params
+ .onRouteAttempt?.({
+ apiType: resolvedApiType,
+ channelId,
+ durationMs: Date.now() - startTime,
+ error,
+ model,
+ providerId: id,
+ remark,
+ routerId: matchedRouter.id,
+ success: false,
+ })
+ .catch((e) => {
+ log('onRouteAttempt callback error: %O', e);
+ });
if (attempt < totalOptions) {
log(
@@ -439,6 +459,18 @@ export const createRouterRuntime = ({
return this.runWithFallback(payload.model, (runtime) => runtime.createImage!(payload));
}
+ async createVideo(payload: CreateVideoPayload) {
+ return this.runWithFallback(payload.model, (runtime) => runtime.createVideo!(payload));
+ }
+
+ async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
+ const model = (payload.body as any)?.model;
+ const resolvedRouters = await this.resolveRouters(model);
+ const routerOptions = this.normalizeRouterOptions(resolvedRouters[0]);
+ const { runtime } = await this.createRuntimeFromOption(resolvedRouters[0], routerOptions[0]);
+ return runtime.handleCreateVideoWebhook!(payload);
+ }
+
async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
return this.runWithFallback(payload.model, (runtime) =>
runtime.generateObject!(payload, options),
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 4424b88d04a..61e11965271 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -26,6 +26,12 @@ import type {
import type { ILobeAgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeErrorType } from '../../types/error';
import type { CreateImagePayload, CreateImageResponse } from '../../types/image';
+import type {
+ CreateVideoPayload,
+ CreateVideoResponse,
+ HandleCreateVideoWebhookPayload,
+ HandleCreateVideoWebhookResult,
+} from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
import { debugResponse, debugStream } from '../../utils/debugStream';
import { desensitizeUrl } from '../../utils/desensitizeUrl';
@@ -62,6 +68,11 @@ export type CreateImageOptions = Omit<ClientOptions, 'apiKey'> & {
provider: string;
};
+export type CreateVideoOptions = Omit<ClientOptions, 'apiKey'> & {
+ apiKey: string;
+ provider: string;
+};
+
export interface CustomClientOptions<T extends Record<string, any> = any> {
createChatCompletionStream?: (
client: any,
@@ -112,6 +123,10 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
payload: CreateImagePayload,
options: CreateImageOptions,
) => Promise<CreateImageResponse>;
+ createVideo?: (
+ payload: CreateVideoPayload,
+ options: CreateVideoOptions,
+ ) => Promise<CreateVideoResponse>;
customClient?: CustomClientOptions<T>;
debug?: {
chatCompletion: () => boolean;
@@ -140,6 +155,10 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
*/
useToolsCalling?: boolean;
};
+ handleCreateVideoWebhook?: (
+ payload: HandleCreateVideoWebhookPayload,
+ options: CreateVideoOptions,
+ ) => Promise<HandleCreateVideoWebhookResult>;
models?:
| ((params: { client: OpenAI }) => Promise<ChatModelCard[]>)
| {
@@ -166,6 +185,8 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
customClient,
responses,
createImage: customCreateImage,
+ createVideo: customCreateVideo,
+ handleCreateVideoWebhook: customHandleCreateVideoWebhook,
generateObject: generateObjectConfig,
}: OpenAICompatibleFactoryOptions<T>) => {
const ErrorType = {
@@ -517,6 +538,28 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
return createOpenAICompatibleImage(this.client, payload, this.id);
}
+ async createVideo(payload: CreateVideoPayload) {
+ if (!customCreateVideo) {
+ throw new Error('createVideo is not supported by this provider');
+ }
+ return customCreateVideo(payload, {
+ ...this._options,
+ apiKey: this._options.apiKey!,
+ provider,
+ });
+ }
+
+ async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
+ if (!customHandleCreateVideoWebhook) {
+ throw new Error('handleCreateVideoWebhook is not supported by this provider');
+ }
+ return customHandleCreateVideoWebhook(payload, {
+ ...this._options,
+ apiKey: this._options.apiKey!,
+ provider,
+ });
+ }
+
async models() {
const log = debug(`${this.logPrefix}:models`);
log('fetching available models');
diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.ts
index e0c93135f14..16a3d378b3b 100644
--- a/packages/model-runtime/src/core/usageConverters/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/index.ts
@@ -2,4 +2,6 @@ export { convertAnthropicUsage } from './anthropic';
export { convertGoogleAIUsage } from './google-ai';
export { convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';
export { computeImageCost } from './utils/computeImageCost';
+export { computeVideoCost } from './utils/computeVideoCost';
export { resolveImageSinglePrice } from './utils/resolveImageSinglePrice';
+export { resolveVideoSinglePrice } from './utils/resolveVideoSinglePrice';
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts
new file mode 100644
index 00000000000..d49195f5798
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts
@@ -0,0 +1,115 @@
+import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '@lobechat/const/currency';
+import debug from 'debug';
+import type { FixedPricingUnit, LookupPricingUnit, Pricing } from 'model-bank';
+
+const log = debug('lobe-cost:computeVideoCost');
+
+export interface VideoGenerationParams {
+ [key: string]: any;
+ generateAudio?: boolean;
+}
+
+export interface VideoCostResult {
+ breakdown?: {
+ completionTokens: number;
+ lookupKey?: string;
+ pricePerMillionTokens: number;
+ };
+ totalCost: number; // Total cost in USD
+ totalCredits: number; // Total credits (USD * CREDITS_PER_DOLLAR)
+}
+
+/**
+ * Compute the cost for video generation based on pricing configuration.
+ * Supports both fixed and lookup pricing strategies.
+ * Handles CNY→USD conversion when pricing currency is CNY.
+ */
+export const computeVideoCost = (
+ pricing: Pricing,
+ completionTokens: number,
+ params: VideoGenerationParams,
+): VideoCostResult | undefined => {
+ const videoGenUnit = pricing.units.find((unit) => unit.name === 'videoGeneration');
+ if (!videoGenUnit) {
+ log('No videoGeneration unit found in pricing configuration');
+ return undefined;
+ }
+
+ const currency = pricing.currency || 'USD';
+ let pricePerMillionTokens = 0;
+ let lookupKey: string | undefined;
+
+ switch (videoGenUnit.strategy) {
+ case 'fixed': {
+ const fixedUnit = videoGenUnit as FixedPricingUnit;
+ if (fixedUnit.unit !== 'millionTokens') {
+ log(`Unsupported unit type for fixed pricing: ${fixedUnit.unit}`);
+ return undefined;
+ }
+ pricePerMillionTokens = fixedUnit.rate;
+ log(`Fixed pricing: ${pricePerMillionTokens} per million tokens (${currency})`);
+ 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;
+ }
+
+ pricePerMillionTokens = lookupPrice;
+ log(`Lookup pricing for key "${lookupKey}": ${pricePerMillionTokens} per million tokens (${currency})`);
+ break;
+ }
+ default: {
+ log(`Unsupported pricing strategy: ${videoGenUnit.strategy}`);
+ return undefined;
+ }
+ }
+
+ // Calculate cost in original currency
+ const costInCurrency = (pricePerMillionTokens * completionTokens) / 1_000_000;
+
+ // Convert to USD if needed
+ const costInUSD = currency === 'CNY' ? costInCurrency / USD_TO_CNY : costInCurrency;
+ const totalCredits = Math.ceil(costInUSD * CREDITS_PER_DOLLAR);
+
+ log(
+ `Video cost: %d tokens × %d/%s per million = %d %s = $%d USD (%d credits)`,
+ completionTokens,
+ pricePerMillionTokens,
+ currency,
+ costInCurrency,
+ currency,
+ costInUSD,
+ totalCredits,
+ );
+
+ return {
+ breakdown: {
+ completionTokens,
+ lookupKey,
+ pricePerMillionTokens,
+ },
+ totalCost: costInUSD,
+ totalCredits,
+ };
+};
diff --git a/packages/model-runtime/src/core/usageConverters/utils/index.ts b/packages/model-runtime/src/core/usageConverters/utils/index.ts
index 7258e2471f6..4c39a682284 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/index.ts
@@ -8,4 +8,9 @@ export {
type ImageCostResult,
type ImageGenerationParams,
} from './computeImageCost';
+export {
+ computeVideoCost,
+ type VideoCostResult,
+ type VideoGenerationParams,
+} from './computeVideoCost';
export { withUsageCost } from './withUsageCost';
diff --git a/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.ts b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.ts
new file mode 100644
index 00000000000..34e297d09a0
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.ts
@@ -0,0 +1,15 @@
+import type { Pricing } from 'model-bank';
+
+export interface VideoSinglePriceResult {
+ approximatePrice?: number;
+}
+
+export const resolveVideoSinglePrice = (pricing?: Pricing): VideoSinglePriceResult => {
+ if (!pricing) return {};
+
+ if (typeof pricing.approximatePricePerVideo === 'number') {
+ return { approximatePrice: pricing.approximatePricePerVideo };
+ }
+
+ return {};
+};
diff --git a/packages/model-runtime/src/providers/volcengine/index.ts b/packages/model-runtime/src/providers/volcengine/index.ts
index 2d1f63a2ff9..f2ea26bb7f7 100644
--- a/packages/model-runtime/src/providers/volcengine/index.ts
+++ b/packages/model-runtime/src/providers/volcengine/index.ts
@@ -2,6 +2,8 @@ import { ModelProvider } from 'model-bank';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
import { createVolcengineImage } from './createImage';
+import { createVolcengineVideo } from './video/createVideo';
+import { handleVolcengineVideoWebhook } from './video/handleCreateVideoWebhook';
export const LobeVolcengineAI = createOpenAICompatibleRuntime({
baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
@@ -18,8 +20,10 @@ export const LobeVolcengineAI = createOpenAICompatibleRuntime({
},
},
createImage: createVolcengineImage,
+ createVideo: createVolcengineVideo,
debug: {
chatCompletion: () => process.env.DEBUG_VOLCENGINE_CHAT_COMPLETION === '1',
},
+ handleCreateVideoWebhook: handleVolcengineVideoWebhook,
provider: ModelProvider.Volcengine,
});
diff --git a/packages/model-runtime/src/providers/volcengine/video/createVideo.ts b/packages/model-runtime/src/providers/volcengine/video/createVideo.ts
new file mode 100644
index 00000000000..9f296bc8904
--- /dev/null
+++ b/packages/model-runtime/src/providers/volcengine/video/createVideo.ts
@@ -0,0 +1,85 @@
+import createDebug from 'debug';
+
+import { CreateVideoOptions } from '../../../core/openaiCompatibleFactory';
+import { CreateVideoPayload, CreateVideoResponse } from '../../../types/video';
+
+const log = createDebug('lobe-video:volcengine');
+
+/**
+ * Volcengine video generation implementation
+ * API docs: https://www.volcengine.com/docs/232791/1399051
+ */
+export async function createVolcengineVideo(
+ payload: CreateVideoPayload,
+ options: CreateVideoOptions,
+): Promise<CreateVideoResponse> {
+ const { model, params } = payload;
+ const {
+ prompt,
+ imageUrl,
+ endImageUrl,
+ aspectRatio,
+ duration,
+ generateAudio,
+ seed,
+ resolution,
+ cameraFixed,
+ } = params;
+
+ log('Creating video with Volcengine API - model: %s, params: %O', model, params);
+
+ const baseURL = options.baseURL || 'https://ark.cn-beijing.volces.com/api/v3';
+
+ // Build content array
+ const content: Record<string, unknown>[] = [{ text: prompt, type: 'text' }];
+
+ if (imageUrl) {
+ content.push({ image_url: { url: imageUrl }, role: 'first_frame', type: 'image_url' });
+ }
+
+ if (endImageUrl) {
+ content.push({ image_url: { url: endImageUrl }, role: 'last_frame', type: 'image_url' });
+ }
+
+ // Build request body
+ const body: Record<string, unknown> = {
+ content,
+ model,
+ watermark: false,
+ };
+
+ if (aspectRatio !== undefined) body.ratio = aspectRatio;
+ if (duration !== undefined) body.duration = duration;
+ if (generateAudio !== undefined) body.generate_audio = generateAudio;
+ if (seed !== undefined && seed !== null) body.seed = seed;
+ if (resolution !== undefined) body.resolution = resolution;
+ if (cameraFixed !== undefined) body.camera_fixed = cameraFixed;
+ if (payload.callbackUrl) body.callback_url = payload.callbackUrl;
+
+ log('Volcengine video API request body: %s', JSON.stringify(body, null, 2));
+
+ const response = await fetch(`${baseURL}/contents/generations/tasks`, {
+ body: JSON.stringify(body),
+ headers: {
+ 'Authorization': `Bearer ${options.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log('Volcengine video API error: %s %s', response.status, errorText);
+ throw new Error(`Volcengine video API error: ${response.status} ${errorText}`);
+ }
+
+ const data = await response.json();
+
+ log('Volcengine video API response: %O', data);
+
+ if (!data?.id) {
+ throw new Error('Invalid response: missing task id');
+ }
+
+ return { inferenceId: data.id };
+}
diff --git a/packages/model-runtime/src/providers/volcengine/video/handleCreateVideoWebhook.ts b/packages/model-runtime/src/providers/volcengine/video/handleCreateVideoWebhook.ts
new file mode 100644
index 00000000000..fb715e2f3d5
--- /dev/null
+++ b/packages/model-runtime/src/providers/volcengine/video/handleCreateVideoWebhook.ts
@@ -0,0 +1,80 @@
+import createDebug from 'debug';
+
+import {
+ HandleCreateVideoWebhookPayload,
+ HandleCreateVideoWebhookResult,
+} from '../../../types/video';
+
+const log = createDebug('lobe-video:volcengine:webhook');
+
+interface VolcengineVideoWebhookBody {
+ content?: {
+ video_url?: string;
+ };
+ error?: {
+ code?: string;
+ message?: string;
+ };
+ generate_audio?: boolean;
+ id?: string;
+ model?: string;
+ status?: string;
+ usage?: {
+ completion_tokens?: number;
+ total_tokens?: number;
+ };
+}
+
+export async function handleVolcengineVideoWebhook(
+ payload: HandleCreateVideoWebhookPayload,
+): Promise<HandleCreateVideoWebhookResult> {
+ const body = payload.body as VolcengineVideoWebhookBody;
+
+ log('Received Volcengine video webhook: %O', body);
+
+ const status = body.status;
+
+ // Skip intermediate statuses
+ if (status === 'queued' || status === 'running') {
+ log('Skipping intermediate status: %s', status);
+ return { status: 'pending' };
+ }
+
+ const inferenceId = body.id;
+ if (!inferenceId) {
+ throw new Error('Missing task id in webhook body');
+ }
+
+ if (status === 'succeeded') {
+ const videoUrl = body.content?.video_url;
+ if (!videoUrl) {
+ throw new Error('Missing video_url in succeeded webhook body');
+ }
+
+ log('Video generation succeeded: %s, videoUrl: %s', inferenceId, videoUrl);
+
+ return {
+ generateAudio: body.generate_audio,
+ inferenceId,
+ model: body.model,
+ status: 'success' as const,
+ usage:
+ typeof body.usage?.completion_tokens === 'number'
+ ? {
+ completionTokens: body.usage.completion_tokens,
+ totalTokens: body.usage.total_tokens ?? body.usage.completion_tokens,
+ }
+ : undefined,
+ videoUrl,
+ };
+ }
+
+ // failed / expired
+ const errorMessage =
+ body.error?.message ||
+ (status === 'expired' ? 'Video generation task expired' : 'Unknown error');
+
+ log('Video generation failed: %s, error: %s', inferenceId, errorMessage);
+
+ return { error: errorMessage, inferenceId, status: 'error' };
+}
diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.ts
index 896093e60af..f36ab902b9a 100644
--- a/packages/model-runtime/src/types/index.ts
+++ b/packages/model-runtime/src/types/index.ts
@@ -7,3 +7,4 @@ export * from './structureOutput';
export * from './toolsCalling';
export * from './tts';
export * from './type';
+export * from './video';
diff --git a/packages/model-runtime/src/types/video.ts b/packages/model-runtime/src/types/video.ts
new file mode 100644
index 00000000000..fe4ca10df3d
--- /dev/null
+++ b/packages/model-runtime/src/types/video.ts
@@ -0,0 +1,29 @@
+/* eslint-disable typescript-sort-keys/interface */
+import { RuntimeVideoGenParams } from 'model-bank';
+
+export type CreateVideoPayload = {
+ callbackUrl?: string;
+ model: string;
+ params: RuntimeVideoGenParams;
+};
+
+export type CreateVideoResponse = {
+ inferenceId: string;
+};
+
+export type HandleCreateVideoWebhookPayload = {
+ body: unknown;
+ headers?: Record<string, string>;
+};
+
+export type HandleCreateVideoWebhookResult =
+ | { status: 'pending' }
+ | {
+ generateAudio?: boolean;
+ inferenceId: string;
+ model?: string;
+ status: 'success';
+ usage?: { completionTokens: number; totalTokens: number };
+ videoUrl: string;
+ }
+ | { error: string; inferenceId: string; status: 'error' };
diff --git a/packages/types/src/aiProvider.ts b/packages/types/src/aiProvider.ts
index 830a01d4d00..37a55bd85e8 100644
--- a/packages/types/src/aiProvider.ts
+++ b/packages/types/src/aiProvider.ts
@@ -379,5 +379,6 @@ export interface AiProviderRuntimeState {
enabledAiProviders: EnabledProvider[];
enabledChatAiProviders: EnabledProvider[];
enabledImageAiProviders: EnabledProvider[];
+ enabledVideoAiProviders: EnabledProvider[];
runtimeConfig: Record<string, AiProviderRuntimeConfig>;
}
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index 63a8f358be2..b1d13768810 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -3,6 +3,7 @@ export enum AsyncTaskType {
Embedding = 'embedding',
ImageGeneration = 'image_generation',
UserMemoryExtractionWithChatTopic = 'user_memory_extraction:chat_topic',
+ VideoGeneration = 'video_generation',
}
export enum AsyncTaskStatus {
diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.ts
index bf9a0ba6685..31d26db2556 100644
--- a/packages/types/src/files/index.ts
+++ b/packages/types/src/files/index.ts
@@ -12,6 +12,7 @@ export enum FilesTabs {
export enum FileSource {
ImageGeneration = 'image_generation',
PageEditor = 'page-editor',
+ VideoGeneration = 'video_generation',
}
export interface FileItem {
diff --git a/packages/types/src/generation/index.ts b/packages/types/src/generation/index.ts
index 64baeb67543..f731247f1ac 100644
--- a/packages/types/src/generation/index.ts
+++ b/packages/types/src/generation/index.ts
@@ -35,15 +35,27 @@ export interface ImageGenerationAsset extends BaseGenerationAsset {
width?: number;
}
-export type GenerationAsset = ImageGenerationAsset;
+export interface VideoGenerationAsset extends BaseGenerationAsset {
+ coverUrl?: string;
+ duration?: number;
+ height?: number;
+ originalUrl?: string;
+ thumbnailUrl?: string;
+ url?: string;
+ width?: number;
+}
+
+export type GenerationAsset = ImageGenerationAsset | VideoGenerationAsset;
export interface GenerationConfig {
aspectRatio?: string;
cfg?: number;
+ endImageUrl?: string | null;
height?: number;
imageUrl?: string | null;
imageUrls?: string[];
prompt: string;
+ resolution?: string;
size?: string;
steps?: number;
width?: number;
diff --git a/src/app/(backend)/api/webhooks/video/[provider]/route.ts b/src/app/(backend)/api/webhooks/video/[provider]/route.ts
new file mode 100644
index 00000000000..c7ff106f284
--- /dev/null
+++ b/src/app/(backend)/api/webhooks/video/[provider]/route.ts
@@ -0,0 +1,227 @@
+import { ModelRuntime } from '@lobechat/model-runtime';
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ FileSource,
+ type VideoGenerationAsset,
+} from '@lobechat/types';
+import debug from 'debug';
+import { eq } from 'drizzle-orm';
+import { NextResponse } from 'next/server';
+
+import { chargeAfterGenerate } from '@/business/server/video-generation/chargeAfterGenerate';
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { GenerationModel } from '@/database/models/generation';
+import { generationBatches } from '@/database/schemas';
+import { getServerDB } from '@/database/server';
+import { VideoGenerationService } from '@/server/services/generation/video';
+
+const log = debug('lobe-video:webhook');
+
+export const POST = async (req: Request, { params }: { params: Promise<{ provider: string }> }) => {
+ const { provider } = await params;
+
+ let body: any;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
+ }
+
+ log('Received video webhook for provider: %s, body: %O', provider, body);
+
+ let asyncTaskModel: AsyncTaskModel | undefined;
+ let asyncTaskId: string | undefined;
+ let asyncTaskUserId: string | undefined;
+ let asyncTaskMetadata: any;
+
+ try {
+ // Parse webhook body using provider-specific handler
+ const runtime = ModelRuntime.initializeWithProvider(provider, {});
+ const result = await runtime.handleCreateVideoWebhook({ body });
+
+ if (!result) {
+ return NextResponse.json(
+ { error: `Provider ${provider} does not support video webhook` },
+ { status: 400 },
+ );
+ }
+
+ // Skip intermediate statuses (e.g. queued, running)
+ if (result.status === 'pending') {
+ log('Skipping intermediate status for provider: %s', provider);
+ return NextResponse.json({ success: true });
+ }
+
+ log('Webhook parse result: %O', result);
+
+ const db = await getServerDB();
+ asyncTaskModel = new AsyncTaskModel(db, '');
+
+ // Find asyncTask by inferenceId
+ const asyncTask = await asyncTaskModel.findByInferenceId(result.inferenceId);
+ if (!asyncTask) {
+ log('AsyncTask not found for inferenceId: %s', result.inferenceId);
+ return NextResponse.json(
+ { error: `AsyncTask not found for inferenceId: ${result.inferenceId}` },
+ { status: 404 },
+ );
+ }
+
+ asyncTaskId = asyncTask.id;
+ asyncTaskUserId = asyncTask.userId;
+ asyncTaskMetadata = asyncTask.metadata;
+
+ log(
+ 'Found asyncTask: %s, userId: %s, status: %s',
+ asyncTask.id,
+ asyncTask.userId,
+ asyncTask.status,
+ );
+
+ // Idempotency: skip if already in terminal state (provider may retry callbacks)
+ if (
+ asyncTask.status === AsyncTaskStatus.Success ||
+ asyncTask.status === AsyncTaskStatus.Error
+ ) {
+ log('AsyncTask %s already in terminal state: %s, skipping', asyncTask.id, asyncTask.status);
+ return NextResponse.json({ success: true });
+ }
+
+ const generationModel = new GenerationModel(db, asyncTask.userId);
+
+ // Find generation by asyncTaskId
+ const generation = await generationModel.findByAsyncTaskId(asyncTask.id);
+ if (!generation) {
+ log('Generation not found for asyncTaskId: %s', asyncTask.id);
+ return NextResponse.json(
+ { error: `Generation not found for asyncTaskId: ${asyncTask.id}` },
+ { status: 404 },
+ );
+ }
+
+ log('Found generation: %s', generation.id);
+
+ // Handle error result: refund precharge and mark task as error
+ if (result.status === 'error') {
+ log('Video generation failed: %s', result.error);
+ await asyncTaskModel.update(asyncTask.id, {
+ error: new AsyncTaskError(AsyncTaskErrorType.ServerError, result.error),
+ status: AsyncTaskStatus.Error,
+ });
+
+ try {
+ await chargeAfterGenerate({
+ isError: true,
+ metadata: {
+ asyncTaskId: asyncTask.id,
+ generationBatchId: generation.generationBatchId!,
+ modelId: '',
+ topicId: undefined,
+ },
+ model: '',
+ prechargeResult: (asyncTask.metadata as any)?.precharge,
+ provider,
+ userId: asyncTask.userId,
+ });
+ } catch (refundError) {
+ console.error('[video-webhook] Failed to refund precharge on error:', refundError);
+ }
+
+ return NextResponse.json({ success: true });
+ }
+
+ // Handle success result: download video → process → upload S3 → create asset and file
+ const videoService = new VideoGenerationService(db, asyncTask.userId);
+ const processResult = await videoService.processVideoForGeneration(result.videoUrl);
+
+ const asset: VideoGenerationAsset = {
+ coverUrl: processResult.coverKey,
+ duration: processResult.duration,
+ height: processResult.height,
+ originalUrl: result.videoUrl,
+ thumbnailUrl: processResult.thumbnailKey,
+ type: 'video',
+ url: processResult.videoKey,
+ width: processResult.width,
+ };
+
+ await generationModel.createAssetAndFile(
+ generation.id,
+ asset,
+ {
+ fileHash: processResult.fileHash,
+ fileType: processResult.mimeType,
+ name: `video_${generation.id}.mp4`,
+ size: processResult.fileSize,
+ url: processResult.videoKey,
+ },
+ FileSource.VideoGeneration,
+ );
+
+ await asyncTaskModel.update(asyncTask.id, {
+ status: AsyncTaskStatus.Success,
+ });
+
+ // Charge after successful video generation
+ try {
+ const batch = await db.query.generationBatches.findFirst({
+ where: eq(generationBatches.id, generation.generationBatchId!),
+ });
+
+ await chargeAfterGenerate({
+ generateAudio: result.generateAudio,
+ metadata: {
+ asyncTaskId: asyncTask.id,
+ generationBatchId: generation.generationBatchId!,
+ modelId: result.model ?? batch?.model ?? '',
+ topicId: batch?.generationTopicId,
+ },
+ model: result.model ?? batch?.model ?? '',
+ prechargeResult: (asyncTask.metadata as any)?.precharge,
+ provider,
+ usage: result.usage,
+ userId: asyncTask.userId,
+ });
+ } catch (chargeError) {
+ console.error('[video-webhook] Failed to charge after generate:', chargeError);
+ }
+
+ log('Video webhook processing completed successfully for generation: %s', generation.id);
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error('[video-webhook] Processing failed:', error);
+
+ // Mark asyncTask as Error so the user sees failure instead of stuck "processing"
+ if (asyncTaskModel && asyncTaskId) {
+ try {
+ await asyncTaskModel.update(asyncTaskId, {
+ error: new AsyncTaskError(AsyncTaskErrorType.ServerError, (error as Error).message),
+ status: AsyncTaskStatus.Error,
+ });
+ } catch (updateError) {
+ console.error('[video-webhook] Failed to update asyncTask status:', updateError);
+ }
+ }
+
+ // Refund precharge on unexpected failure
+ if (asyncTaskUserId && asyncTaskMetadata?.precharge) {
+ try {
+ await chargeAfterGenerate({
+ isError: true,
+ metadata: { asyncTaskId: asyncTaskId ?? '', generationBatchId: '', modelId: '' },
+ model: '',
+ prechargeResult: asyncTaskMetadata.precharge,
+ provider,
+ userId: asyncTaskUserId,
+ });
+ } catch (refundError) {
+ console.error('[video-webhook] Failed to refund precharge on failure:', refundError);
+ }
+ }
+
+ return NextResponse.json({ error: (error as Error).message }, { status: 500 });
+ }
+};
diff --git a/src/app/[variants]/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx b/src/app/[variants]/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx
index a516c87786a..7fac94de162 100644
--- a/src/app/[variants]/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx
+++ b/src/app/[variants]/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx
@@ -22,8 +22,8 @@ const icons: Record<AiModelType, LucideIcon> = {
realtime: PhoneIcon,
stt: MicIcon,
text2music: MusicIcon,
- text2video: VideoIcon,
tts: AudioLines,
+ video: VideoIcon,
};
const ModelTypeIcon = memo<{ size?: number; type: AiModelType }>(({ type, size = 20 }) => {
diff --git a/src/app/[variants]/(main)/home/_layout/Header/components/Nav.tsx b/src/app/[variants]/(main)/home/_layout/Header/components/Nav.tsx
index 6ff5f6aedcf..d6d0555f8d5 100644
--- a/src/app/[variants]/(main)/home/_layout/Header/components/Nav.tsx
+++ b/src/app/[variants]/(main)/home/_layout/Header/components/Nav.tsx
@@ -53,6 +53,12 @@ const Nav = memo(() => {
title: t('tab.pages'),
url: '/page',
},
+ {
+ icon: getRouteById('video')!.icon,
+ key: SidebarTabKey.Video,
+ title: t('tab.video'),
+ url: '/video',
+ },
{
hidden: !showAiImage,
icon: getRouteById('image')!.icon,
diff --git a/src/app/[variants]/(main)/home/features/InputArea/ModeTag.tsx b/src/app/[variants]/(main)/home/features/InputArea/ModeTag.tsx
index 25c2c124fec..a40f779f7c0 100644
--- a/src/app/[variants]/(main)/home/features/InputArea/ModeTag.tsx
+++ b/src/app/[variants]/(main)/home/features/InputArea/ModeTag.tsx
@@ -1,7 +1,7 @@
import { ActionIcon, Block, Text } from '@lobehub/ui';
import { GroupBotSquareIcon } from '@lobehub/ui/icons';
import { createStaticStyles, cssVar } from 'antd-style';
-import { BotIcon, FilePenIcon, ImageIcon, PenLineIcon, X } from 'lucide-react';
+import { BotIcon, FilePenIcon, ImageIcon, PenLineIcon, VideoIcon, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,6 +24,7 @@ const modeConfig = {
group: { icon: GroupBotSquareIcon, titleKey: 'starter.createGroup' },
image: { icon: ImageIcon, titleKey: 'starter.image' },
research: { icon: FilePenIcon, titleKey: 'starter.deepResearch' },
+ video: { icon: VideoIcon, titleKey: 'starter.seedance' },
write: { icon: PenLineIcon, titleKey: 'starter.write' },
} as const;
diff --git a/src/app/[variants]/(main)/home/features/InputArea/StarterList.tsx b/src/app/[variants]/(main)/home/features/InputArea/StarterList.tsx
index 21ff764734e..d7eeec35fea 100644
--- a/src/app/[variants]/(main)/home/features/InputArea/StarterList.tsx
+++ b/src/app/[variants]/(main)/home/features/InputArea/StarterList.tsx
@@ -3,7 +3,7 @@ import { type ButtonProps } from '@lobehub/ui';
import { Button, Center, Tooltip } from '@lobehub/ui';
import { GroupBotSquareIcon } from '@lobehub/ui/icons';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { BotIcon, PenLineIcon } from 'lucide-react';
+import { BotIcon, PenLineIcon, VideoIcon } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,10 +33,12 @@ type StarterTitleKey =
| 'starter.createAgent'
| 'starter.createGroup'
| 'starter.write'
+ | 'starter.seedance'
| 'starter.deepResearch';
interface StarterItem {
disabled?: boolean;
+ hot?: boolean;
icon?: ButtonProps['icon'];
key: StarterMode;
titleKey: StarterTitleKey;
@@ -49,9 +51,10 @@ const StarterList = memo(() => {
useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.groupAgentBuilder);
useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.pageAgent);
- const [inputActiveMode, setInputActiveMode] = useHomeStore((s) => [
+ const [inputActiveMode, setInputActiveMode, navigate] = useHomeStore((s) => [
s.inputActiveMode,
s.setInputActiveMode,
+ s.navigate,
]);
const items: StarterItem[] = useMemo(
@@ -71,6 +74,12 @@ const StarterList = memo(() => {
key: 'write',
titleKey: 'starter.write',
},
+ {
+ hot: true,
+ icon: VideoIcon,
+ key: 'video',
+ titleKey: 'starter.seedance',
+ },
// {
// disabled: true,
// icon: MicroscopeIcon,
@@ -83,6 +92,11 @@ const StarterList = memo(() => {
const handleClick = useCallback(
(key: StarterMode) => {
+ if (key === 'video') {
+ navigate?.('/video');
+ return;
+ }
+
// Toggle mode: if clicking the active mode, clear it; otherwise set it
if (inputActiveMode === key) {
setInputActiveMode(null);
@@ -111,6 +125,7 @@ const StarterList = memo(() => {
onClick={() => handleClick(item.key)}
>
{t(item.titleKey)}
+ {item.hot && ' 🔥'}
</Button>
);
diff --git a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/AspectRatioSelect/index.tsx b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/AspectRatioSelect/index.tsx
index 103fbfa4848..4eea52ee938 100644
--- a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/AspectRatioSelect/index.tsx
+++ b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/AspectRatioSelect/index.tsx
@@ -1,13 +1,24 @@
'use client';
-import { type GridProps } from '@lobehub/ui';
+import type { GridProps } from '@lobehub/ui';
import { Block, Center, Grid, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
+import type { ReactNode } from 'react';
import { memo } from 'react';
import useMergeState from 'use-merge-value';
import { useIsDark } from '@/hooks/useIsDark';
+/**
+ * Check if a value can be parsed as a valid aspect ratio (e.g. "16:9")
+ */
+const isRatioValue = (value: string): boolean => {
+ const parts = value.split(':');
+ if (parts.length !== 2) return false;
+ const [w, h] = parts.map(Number);
+ return !isNaN(w) && !isNaN(h) && w > 0 && h > 0;
+};
+
export interface AspectRatioSelectProps extends Omit<GridProps, 'children' | 'onChange'> {
defaultValue?: string;
onChange?: (value: string) => void;
@@ -28,9 +39,36 @@ const AspectRatioSelect = memo<AspectRatioSelectProps>(
<Block padding={4} variant={'filled'} {...rest}>
<Grid gap={4} maxItemWidth={48} rows={16}>
{options?.map((item) => {
- const [width, height] = item.value.split(':').map(Number);
- const isWidthGreater = width > height;
const isActive = active === item.value;
+ let content: ReactNode;
+
+ if (isRatioValue(item.value)) {
+ const [width, height] = item.value.split(':').map(Number);
+ const isWidthGreater = width > height;
+ content = (
+ <div
+ style={{
+ aspectRatio: `${width} / ${height}`,
+ border: `2px solid ${isActive ? cssVar.colorText : cssVar.colorTextDescription}`,
+ borderRadius: 3,
+ height: isWidthGreater ? undefined : 16,
+ width: isWidthGreater ? 16 : undefined,
+ }}
+ />
+ );
+ } else {
+ content = (
+ <div
+ style={{
+ border: `2px dashed ${isActive ? cssVar.colorText : cssVar.colorTextDescription}`,
+ borderRadius: 3,
+ height: 16,
+ width: 16,
+ }}
+ />
+ );
+ }
+
return (
<Block
clickable
@@ -50,15 +88,7 @@ const AspectRatioSelect = memo<AspectRatioSelectProps>(
}}
>
<Center height={16} style={{ marginTop: 4 }} width={16}>
- <div
- style={{
- aspectRatio: `${width} / ${height}`,
- border: `2px solid ${isActive ? cssVar.colorText : cssVar.colorTextDescription}`,
- borderRadius: 3,
- height: isWidthGreater ? undefined : 16,
- width: isWidthGreater ? 16 : undefined,
- }}
- />
+ {content}
</Center>
<Text fontSize={12} type={isActive ? undefined : 'secondary'}>
{item.label || item.value}
diff --git a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx
index 5b364fcf4bd..dadde5fe805 100644
--- a/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx
+++ b/src/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload.tsx
@@ -26,6 +26,8 @@ export interface ImageUploadProps {
| string // Old API: just URL
| { dimensions?: { height: number; width: number }; url: string }, // New API: URL with dimensions
) => void;
+ /** Height of the empty placeholder area. Defaults to 160. */
+ placeholderHeight?: number;
style?: React.CSSProperties;
value?: string | null;
}
@@ -301,11 +303,12 @@ CircularProgress.displayName = 'CircularProgress';
* 占位视图组件
*/
interface PlaceholderProps {
+ height?: number;
isDragOver?: boolean;
onClick?: () => void;
}
-const Placeholder: FC<PlaceholderProps> = memo(({ isDragOver, onClick }) => {
+const Placeholder: FC<PlaceholderProps> = memo(({ isDragOver, onClick, height }) => {
const configStyles = configPanelStyles;
const { t } = useTranslation('components');
@@ -319,6 +322,7 @@ const Placeholder: FC<PlaceholderProps> = memo(({ isDragOver, onClick }) => {
isDragOver && configStyles.dragOver,
)}
onClick={onClick}
+ style={height ? { height } : undefined}
>
<ImageIcon className={styles.placeholderIcon} size={48} strokeWidth={1.5} />
<div className={styles.placeholderText}>
@@ -422,7 +426,7 @@ SuccessDisplay.displayName = 'SuccessDisplay';
// ======== Main Component ======== //
const ImageUpload: FC<ImageUploadProps> = memo(
- ({ value, onChange, style, className, maxFileSize }) => {
+ ({ value, onChange, style, className, maxFileSize, placeholderHeight }) => {
const inputRef = useRef<HTMLInputElement>(null);
const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
const [uploadState, setUploadState] = useState<UploadState | null>(null);
@@ -636,7 +640,11 @@ const ImageUpload: FC<ImageUploadProps> = memo(
onDelete={handleDelete}
/>
) : (
- <Placeholder isDragOver={isDragOver} onClick={handleFileSelect} />
+ <Placeholder
+ height={placeholderHeight}
+ isDragOver={isDragOver}
+ onClick={handleFileSelect}
+ />
)}
</div>
);
diff --git a/src/app/[variants]/(main)/image/_layout/TopicSidebar.tsx b/src/app/[variants]/(main)/image/_layout/TopicSidebar.tsx
index b403e1e9251..76f5ab3a9b4 100644
--- a/src/app/[variants]/(main)/image/_layout/TopicSidebar.tsx
+++ b/src/app/[variants]/(main)/image/_layout/TopicSidebar.tsx
@@ -1,19 +1,24 @@
-import React, { memo,Suspense } from 'react';
+import { Suspense, memo } from 'react';
+import {
+ GenerationTopicStoreProvider,
+ SkeletonList,
+ TopicList,
+ TopicUrlSync,
+} from '@/features/GenerationTopicList';
import ImageTopicPanel from '@/features/ImageTopicPanel';
-
-import Topics from './Topics';
-import TopicsSkeleton from './Topics/SkeletonList';
-import TopicUrlSync from './Topics/TopicUrlSync';
+import { useImageStore } from '@/store/image';
const TopicSidebar = memo(() => {
return (
- <ImageTopicPanel>
- <Suspense fallback={<TopicsSkeleton />}>
- <Topics />
- <TopicUrlSync />
- </Suspense>
- </ImageTopicPanel>
+ <GenerationTopicStoreProvider value={{ namespace: 'image', useStore: useImageStore as any }}>
+ <ImageTopicPanel>
+ <Suspense fallback={<SkeletonList />}>
+ <TopicList />
+ <TopicUrlSync />
+ </Suspense>
+ </ImageTopicPanel>
+ </GenerationTopicStoreProvider>
);
});
diff --git a/src/app/[variants]/(main)/image/_layout/Topics/TopicUrlSync.tsx b/src/app/[variants]/(main)/image/_layout/Topics/TopicUrlSync.tsx
deleted file mode 100644
index 073babf8c8c..00000000000
--- a/src/app/[variants]/(main)/image/_layout/Topics/TopicUrlSync.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-'use client';
-
-import { useLayoutEffect } from 'react';
-import { createStoreUpdater } from 'zustand-utils';
-
-import { useQueryState } from '@/hooks/useQueryParam';
-import { useImageStore } from '@/store/image';
-
-/**
- * 双向绑定 url 的 topic 参数到 image store 的 activeGenerationTopicId
- */
-const TopicUrlSync = () => {
- const useStoreUpdater = createStoreUpdater(useImageStore);
-
- const [topic, setTopic] = useQueryState('topic', { history: 'replace', throttleMs: 500 });
- useStoreUpdater('activeGenerationTopicId', topic);
-
- useLayoutEffect(() => {
- const unsubscribeTopic = useImageStore.subscribe(
- (s) => s.activeGenerationTopicId,
- (state) => {
- setTopic(state || null);
- },
- );
-
- return () => {
- unsubscribeTopic();
- };
- }, [setTopic]);
-
- // 这个组件不渲染任何UI,仅用于同步状态
- return null;
-};
-
-export default TopicUrlSync;
diff --git a/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
index 1b8cfc9f981..839ac9fea38 100644
--- a/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
+++ b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
@@ -35,8 +35,8 @@ const ModelConfigForm = memo<ModelConfigFormProps>(
'embedding',
'tts',
'stt',
- 'image',
- // 'text2video',
+ // 'image',
+ // 'video',
// 'text2music',
'realtime',
] as AiModelType[]
diff --git a/src/app/[variants]/(main)/video/_layout/ConfigPanel/VideoConfigSkeleton.tsx b/src/app/[variants]/(main)/video/_layout/ConfigPanel/VideoConfigSkeleton.tsx
new file mode 100644
index 00000000000..c85b60f05bd
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/ConfigPanel/VideoConfigSkeleton.tsx
@@ -0,0 +1,65 @@
+'use client';
+
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { memo } from 'react';
+
+const VideoConfigSkeleton = memo(() => {
+ return (
+ <Flexbox gap={16} padding={10}>
+ {/* ModelSelect */}
+ <Skeleton.Button active size="large" style={{ width: '100%' }} />
+
+ {/* FrameUpload: imageUrl */}
+ <Flexbox gap={8}>
+ <Skeleton.Button active size="small" style={{ width: 60 }} />
+ <Skeleton.Block active style={{ borderRadius: 8, height: 120, width: '100%' }} />
+ </Flexbox>
+
+ {/* FrameUpload: endImageUrl */}
+ <Flexbox gap={8}>
+ <Skeleton.Button active size="small" style={{ width: 50 }} />
+ <Skeleton.Block active style={{ borderRadius: 8, height: 120, width: '100%' }} />
+ </Flexbox>
+
+ {/* AspectRatio */}
+ <Flexbox gap={8}>
+ <Skeleton.Button active size="small" style={{ width: 70 }} />
+ <Skeleton.Block active style={{ borderRadius: 8, height: 64, width: '100%' }} />
+ </Flexbox>
+
+ {/* Resolution */}
+ <Flexbox gap={8}>
+ <Skeleton.Button active size="small" style={{ width: 50 }} />
+ <Skeleton.Button active size="default" style={{ width: '100%' }} />
+ </Flexbox>
+
+ {/* Duration */}
+ <Flexbox gap={8}>
+ <Skeleton.Button active size="small" style={{ width: 40 }} />
+ <Skeleton.Button active size="default" style={{ width: '100%' }} />
+ </Flexbox>
+
+ {/* Seed */}
+ <Flexbox gap={8}>
+ <Skeleton.Button active size="small" style={{ width: 40 }} />
+ <Skeleton.Button active size="default" style={{ width: '100%' }} />
+ </Flexbox>
+
+ {/* generateAudio switch */}
+ <Flexbox align="center" horizontal justify="space-between">
+ <Skeleton.Button active size="small" style={{ width: 70 }} />
+ <Skeleton.Button active size="small" style={{ borderRadius: 12, width: 44 }} />
+ </Flexbox>
+
+ {/* cameraFixed switch */}
+ <Flexbox align="center" horizontal justify="space-between">
+ <Skeleton.Button active size="small" style={{ width: 70 }} />
+ <Skeleton.Button active size="small" style={{ borderRadius: 12, width: 44 }} />
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+VideoConfigSkeleton.displayName = 'VideoConfigSkeleton';
+
+export default VideoConfigSkeleton;
diff --git a/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/FrameUpload.tsx b/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/FrameUpload.tsx
new file mode 100644
index 00000000000..5864ced2585
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/FrameUpload.tsx
@@ -0,0 +1,30 @@
+import { memo } from 'react';
+
+import ImageUpload from '@/app/[variants]/(main)/image/_layout/ConfigPanel/components/ImageUpload';
+import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';
+
+interface FrameUploadProps {
+ paramName: 'endImageUrl' | 'imageUrl';
+}
+
+const FrameUpload = memo<FrameUploadProps>(({ paramName }) => {
+ const { value, setValue, maxFileSize } = useVideoGenerationConfigParam(paramName);
+
+ const handleChange = (
+ data?: string | { dimensions?: { height: number; width: number }; url: string },
+ ) => {
+ const url = typeof data === 'string' ? data : data?.url;
+ setValue((url ?? null) as any);
+ };
+
+ return (
+ <ImageUpload
+ maxFileSize={maxFileSize}
+ onChange={handleChange}
+ placeholderHeight={120}
+ value={value}
+ />
+ );
+});
+
+export default FrameUpload;
diff --git a/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/ModelSelect/VideoModelItem.tsx b/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/ModelSelect/VideoModelItem.tsx
new file mode 100644
index 00000000000..079452d27fd
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/ModelSelect/VideoModelItem.tsx
@@ -0,0 +1,79 @@
+import { ModelIcon } from '@lobehub/icons';
+import { Flexbox, Popover, Text } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import type { AiModelForSelect } from 'model-bank';
+import { memo, useMemo } from 'react';
+
+import NewModelBadge from '@/components/ModelSelect/NewModelBadge';
+import { useIsDark } from '@/hooks/useIsDark';
+
+const POPOVER_MAX_WIDTH = 320;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ descriptionText: css`
+ color: ${cssVar.colorTextSecondary};
+ `,
+ descriptionText_dark: css`
+ color: ${cssVar.colorText};
+ `,
+ popover: css`
+ .ant-popover-inner {
+ background: ${cssVar.colorBgElevated};
+ }
+ `,
+ popover_dark: css`
+ .ant-popover-inner {
+ background: ${cssVar.colorBgSpotlight};
+ }
+ `,
+}));
+
+type VideoModelItemProps = AiModelForSelect & {
+ providerId?: string;
+ showBadge?: boolean;
+ showPopover?: boolean;
+};
+
+const VideoModelItem = memo<VideoModelItemProps>(
+ ({ description, showPopover = true, showBadge = true, ...model }) => {
+ const isDarkMode = useIsDark();
+
+ const popoverContent = useMemo(() => {
+ if (!description) return null;
+
+ return (
+ <Flexbox gap={8} style={{ maxWidth: POPOVER_MAX_WIDTH }}>
+ <Text className={cx(styles.descriptionText, isDarkMode && styles.descriptionText_dark)}>
+ {description}
+ </Text>
+ </Flexbox>
+ );
+ }, [description, isDarkMode]);
+
+ const content = (
+ <Flexbox align={'center'} gap={8} horizontal style={{ overflow: 'hidden' }}>
+ <ModelIcon model={model.id} size={20} />
+ <Text ellipsis title={model.displayName || model.id}>
+ {model.displayName || model.id}
+ </Text>
+ {showBadge && <NewModelBadge releasedAt={model.releasedAt} />}
+ </Flexbox>
+ );
+
+ if (!showPopover || !popoverContent) return content;
+
+ return (
+ <Popover
+ classNames={{ root: cx(styles.popover, isDarkMode && styles.popover_dark) }}
+ content={popoverContent}
+ placement="rightTop"
+ >
+ {content}
+ </Popover>
+ );
+ },
+);
+
+VideoModelItem.displayName = 'VideoModelItem';
+
+export default VideoModelItem;
diff --git a/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/ModelSelect/index.tsx b/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/ModelSelect/index.tsx
new file mode 100644
index 00000000000..d72af95e5d9
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/ConfigPanel/components/ModelSelect/index.tsx
@@ -0,0 +1,166 @@
+import type { SelectProps } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Icon, Select } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { LucideArrowRight, LucideBolt } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { ProviderItemRender } from '@/components/ModelSelect';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiProviderSelectors } from '@/store/aiInfra/slices/aiProvider/selectors';
+import { useVideoStore } from '@/store/video';
+import { videoGenerationConfigSelectors } from '@/store/video/selectors';
+import type { EnabledProviderWithModels } from '@/types/index';
+
+import VideoModelItem from './VideoModelItem';
+
+const prefixCls = 'ant';
+
+const styles = createStaticStyles(({ css }) => ({
+ popup: css`
+ &.${prefixCls}-select-dropdown .${prefixCls}-select-item-option-grouped {
+ padding-inline-start: 12px;
+ }
+ `,
+}));
+
+interface ModelOption {
+ label: any;
+ provider: string;
+ value: string;
+}
+
+const ModelSelect = memo(() => {
+ const { t } = useTranslation('components');
+ const navigate = useNavigate();
+
+ const [currentModel, currentProvider] = useVideoStore((s) => [
+ videoGenerationConfigSelectors.model(s),
+ videoGenerationConfigSelectors.provider(s),
+ ]);
+ const setModelAndProviderOnSelect = useVideoStore((s) => s.setModelAndProviderOnSelect);
+
+ const enabledVideoModelList = useAiInfraStore(aiProviderSelectors.enabledVideoModelList);
+
+ const options = useMemo<SelectProps['options']>(() => {
+ const getVideoModels = (provider: EnabledProviderWithModels) => {
+ const modelOptions = provider.children.map((model) => ({
+ label: <VideoModelItem {...model} providerId={provider.id} />,
+ provider: provider.id,
+ value: `${provider.id}/${model.id}`,
+ }));
+
+ if (modelOptions.length === 0) {
+ return [
+ {
+ disabled: true,
+ label: (
+ <Flexbox gap={8} horizontal style={{ color: cssVar.colorTextTertiary }}>
+ {t('ModelSwitchPanel.emptyModel')}
+ <Icon icon={LucideArrowRight} />
+ </Flexbox>
+ ),
+ onClick: () => {
+ navigate(`/settings/provider/${provider.id}`);
+ },
+ value: `${provider.id}/empty`,
+ },
+ ];
+ }
+
+ return modelOptions;
+ };
+
+ if (enabledVideoModelList.length === 0) {
+ return [
+ {
+ disabled: true,
+ label: (
+ <Flexbox gap={8} horizontal style={{ color: cssVar.colorTextTertiary }}>
+ {t('ModelSwitchPanel.emptyProvider')}
+ <Icon icon={LucideArrowRight} />
+ </Flexbox>
+ ),
+ onClick: () => {
+ navigate('/settings/provider/all');
+ },
+ value: 'no-provider',
+ },
+ ];
+ }
+
+ if (enabledVideoModelList.length === 1) {
+ const provider = enabledVideoModelList[0];
+ return getVideoModels(provider);
+ }
+
+ return enabledVideoModelList.map((provider) => ({
+ label: (
+ <Flexbox horizontal justify="space-between">
+ <ProviderItemRender
+ logo={provider.logo}
+ name={provider.name}
+ provider={provider.id}
+ source={provider.source}
+ />
+ <ActionIcon
+ icon={LucideBolt}
+ onClick={(e) => {
+ e.stopPropagation();
+ navigate(`/settings/provider/${provider.id}`);
+ }}
+ size={'small'}
+ title={t('ModelSwitchPanel.goToSettings')}
+ />
+ </Flexbox>
+ ),
+ options: getVideoModels(provider),
+ }));
+ }, [enabledVideoModelList, t, navigate]);
+
+ const labelRender: SelectProps['labelRender'] = (props) => {
+ const modelInfo = enabledVideoModelList
+ .flatMap((provider) =>
+ provider.children.map((model) => ({ ...model, providerId: provider.id })),
+ )
+ .find((model) => props.value === `${model.providerId}/${model.id}`);
+
+ if (!modelInfo) return props.label;
+
+ return (
+ <VideoModelItem
+ {...modelInfo}
+ providerId={modelInfo.providerId}
+ showBadge={false}
+ showPopover={false}
+ />
+ );
+ };
+
+ return (
+ <Select
+ classNames={{
+ root: styles.popup,
+ }}
+ labelRender={labelRender}
+ onChange={(value, option) => {
+ if (value === 'no-provider' || value.includes('/empty')) return;
+ const model = value.split('/').slice(1).join('/');
+ const provider = (option as unknown as ModelOption).provider;
+ if (model !== currentModel || provider !== currentProvider) {
+ setModelAndProviderOnSelect(model, provider);
+ }
+ }}
+ options={options}
+ shadow
+ size={'large'}
+ style={{
+ width: '100%',
+ }}
+ value={currentProvider && currentModel ? `${currentProvider}/${currentModel}` : undefined}
+ />
+ );
+});
+
+export default ModelSelect;
diff --git a/src/app/[variants]/(main)/video/_layout/ConfigPanel/index.tsx b/src/app/[variants]/(main)/video/_layout/ConfigPanel/index.tsx
new file mode 100644
index 00000000000..1a0a5232355
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/ConfigPanel/index.tsx
@@ -0,0 +1,214 @@
+'use client';
+
+import {
+ Button,
+ Flexbox,
+ InputNumber,
+ Segmented,
+ SliderWithInput,
+ Text,
+ Tooltip,
+} from '@lobehub/ui';
+import { Switch } from 'antd';
+import { Dices } from 'lucide-react';
+import { MAX_VIDEO_SEED } from 'model-bank';
+import type { ReactNode } from 'react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AspectRatioSelect from '@/app/[variants]/(main)/image/_layout/ConfigPanel/components/AspectRatioSelect';
+import { useFetchAiVideoConfig } from '@/hooks/useFetchAiVideoConfig';
+import { videoGenerationConfigSelectors } from '@/store/video/selectors';
+import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';
+import { useVideoStore } from '@/store/video/store';
+import { generateUniqueSeeds } from '@/utils/number';
+
+import FrameUpload from './components/FrameUpload';
+import ModelSelect from './components/ModelSelect';
+import VideoConfigSkeleton from './VideoConfigSkeleton';
+
+interface ConfigItemLayoutProps {
+ children: ReactNode;
+ label?: string;
+}
+
+const ConfigItemLayout = memo<ConfigItemLayoutProps>(({ label, children }) => {
+ return (
+ <Flexbox gap={8}>
+ {label && <Text weight={500}>{label}</Text>}
+ {children}
+ </Flexbox>
+ );
+});
+
+const isSupportedParamSelector = videoGenerationConfigSelectors.isSupportedParam;
+
+const AspectRatioItem = memo(() => {
+ const { value, setValue, enumValues } = useVideoGenerationConfigParam('aspectRatio');
+
+ const options = useMemo(() => (enumValues ?? []).map((v) => ({ value: v })), [enumValues]);
+
+ return <AspectRatioSelect options={options} value={value} onChange={(v) => setValue(v as any)} />;
+});
+
+const ResolutionItem = memo(() => {
+ const { value, setValue, enumValues } = useVideoGenerationConfigParam('resolution');
+
+ const options = useMemo(() => {
+ if (!enumValues || enumValues.length === 0) return [];
+ return enumValues.map((v) => ({ label: v, value: v }));
+ }, [enumValues]);
+
+ if (options.length === 0) return null;
+
+ return (
+ <Segmented
+ block
+ options={options}
+ style={{ width: '100%' }}
+ value={value}
+ variant="filled"
+ onChange={(v) => setValue(String(v) as any)}
+ />
+ );
+});
+
+const DurationItem = memo(() => {
+ const { value, setValue, min, max, step } = useVideoGenerationConfigParam('duration');
+
+ return (
+ <SliderWithInput
+ max={max}
+ min={min}
+ step={step ?? 1}
+ value={value ?? min}
+ onChange={(v) => setValue(v as any)}
+ />
+ );
+});
+
+const SeedItem = memo(() => {
+ const { t } = useTranslation('video');
+ const { value, setValue } = useVideoGenerationConfigParam('seed');
+
+ const handleRandomize = useCallback(() => {
+ setValue(generateUniqueSeeds(1)[0] as any);
+ }, [setValue]);
+
+ return (
+ <Flexbox horizontal gap={4}>
+ <InputNumber
+ max={MAX_VIDEO_SEED}
+ min={0}
+ placeholder={t('config.seed.random')}
+ step={1}
+ style={{ width: '100%' }}
+ value={value}
+ onChange={(v) => setValue(v as any)}
+ />
+ <Tooltip title={t('config.seed.random')}>
+ <Button
+ icon={Dices}
+ style={{ flex: 'none', width: 48 }}
+ variant={'outlined'}
+ onClick={handleRandomize}
+ />
+ </Tooltip>
+ </Flexbox>
+ );
+});
+
+interface SwitchItemProps {
+ label: string;
+ paramName: 'cameraFixed' | 'generateAudio';
+}
+
+const SwitchItem = memo<SwitchItemProps>(({ label, paramName }) => {
+ const { value, setValue } = useVideoGenerationConfigParam(paramName);
+
+ return (
+ <Flexbox horizontal align="center" justify="space-between" padding={'0 2px'}>
+ <Text weight={500}>{label}</Text>
+ <Switch checked={!!value} onChange={(checked) => setValue(checked as any)} />
+ </Flexbox>
+ );
+});
+
+const ConfigPanel = memo(() => {
+ const { t } = useTranslation('video');
+
+ // Initialize video configuration
+ useFetchAiVideoConfig();
+
+ const isInit = useVideoStore((s) => s.isInit);
+ const isSupportImageUrl = useVideoStore(isSupportedParamSelector('imageUrl'));
+ const isSupportEndImageUrl = useVideoStore(isSupportedParamSelector('endImageUrl'));
+ const isSupportAspectRatio = useVideoStore(isSupportedParamSelector('aspectRatio'));
+ const isSupportResolution = useVideoStore(isSupportedParamSelector('resolution'));
+ const isSupportDuration = useVideoStore(isSupportedParamSelector('duration'));
+ const isSupportSeed = useVideoStore(isSupportedParamSelector('seed'));
+ const isSupportGenerateAudio = useVideoStore(isSupportedParamSelector('generateAudio'));
+ const isSupportCameraFixed = useVideoStore(isSupportedParamSelector('cameraFixed'));
+
+ // Show loading state if not initialized
+ if (!isInit) {
+ return <VideoConfigSkeleton />;
+ }
+
+ const imageUrlLabel = isSupportEndImageUrl
+ ? t('config.imageUrl.label')
+ : t('config.referenceImage.label');
+
+ return (
+ <Flexbox gap={16} padding={10}>
+ <ConfigItemLayout>
+ <ModelSelect />
+ </ConfigItemLayout>
+
+ {isSupportImageUrl && (
+ <ConfigItemLayout label={imageUrlLabel}>
+ <FrameUpload paramName="imageUrl" />
+ </ConfigItemLayout>
+ )}
+
+ {isSupportEndImageUrl && (
+ <ConfigItemLayout label={t('config.endImageUrl.label')}>
+ <FrameUpload paramName="endImageUrl" />
+ </ConfigItemLayout>
+ )}
+
+ {isSupportAspectRatio && (
+ <ConfigItemLayout label={t('config.aspectRatio.label')}>
+ <AspectRatioItem />
+ </ConfigItemLayout>
+ )}
+
+ {isSupportResolution && (
+ <ConfigItemLayout label={t('config.resolution.label')}>
+ <ResolutionItem />
+ </ConfigItemLayout>
+ )}
+
+ {isSupportDuration && (
+ <ConfigItemLayout label={t('config.duration.label')}>
+ <DurationItem />
+ </ConfigItemLayout>
+ )}
+
+ {isSupportSeed && (
+ <ConfigItemLayout label={t('config.seed.label')}>
+ <SeedItem />
+ </ConfigItemLayout>
+ )}
+
+ {isSupportGenerateAudio && (
+ <SwitchItem label={t('config.generateAudio.label')} paramName="generateAudio" />
+ )}
+ {isSupportCameraFixed && (
+ <SwitchItem label={t('config.cameraFixed.label')} paramName="cameraFixed" />
+ )}
+ </Flexbox>
+ );
+});
+
+export default ConfigPanel;
diff --git a/src/app/[variants]/(main)/video/_layout/Header.tsx b/src/app/[variants]/(main)/video/_layout/Header.tsx
new file mode 100644
index 00000000000..27cdbaf8141
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/Header.tsx
@@ -0,0 +1,13 @@
+'use client';
+
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+
+const Header = memo(() => {
+ const { t } = useTranslation('common');
+ return <SideBarHeaderLayout breadcrumb={[{ href: '/video', title: t('tab.video') }]} />;
+});
+
+export default Header;
diff --git a/src/app/[variants]/(main)/video/_layout/Sidebar.tsx b/src/app/[variants]/(main)/video/_layout/Sidebar.tsx
new file mode 100644
index 00000000000..97415d4186b
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/Sidebar.tsx
@@ -0,0 +1,19 @@
+import React, { memo } from 'react';
+
+import { NavPanelPortal } from '@/features/NavPanel';
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import ConfigPanel from './ConfigPanel';
+import Header from './Header';
+
+const Sidebar = memo(() => {
+ return (
+ <NavPanelPortal navKey="video">
+ <SideBarLayout body={<ConfigPanel />} header={<Header />} />
+ </NavPanelPortal>
+ );
+});
+
+Sidebar.displayName = 'VideoSidebar';
+
+export default Sidebar;
diff --git a/src/app/[variants]/(main)/video/_layout/TopicSidebar.tsx b/src/app/[variants]/(main)/video/_layout/TopicSidebar.tsx
new file mode 100644
index 00000000000..c1949b60220
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/TopicSidebar.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { Suspense, memo } from 'react';
+
+import {
+ GenerationTopicStoreProvider,
+ SkeletonList,
+ TopicList,
+ TopicUrlSync,
+} from '@/features/GenerationTopicList';
+import GenerationTopicPanel from '@/features/GenerationTopicPanel';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useVideoStore } from '@/store/video';
+
+const TopicSidebar = memo(() => {
+ const [videoTopicPanelWidth, showVideoTopicPanel, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.videoTopicPanelWidth(s),
+ systemStatusSelectors.showVideoTopicPanel(s),
+ s.updateSystemStatus,
+ ]);
+
+ return (
+ <GenerationTopicStoreProvider value={{ namespace: 'video', useStore: useVideoStore as any }}>
+ <GenerationTopicPanel
+ onExpandChange={(expand) => updateSystemStatus({ showVideoTopicPanel: expand })}
+ onSizeChange={(width) => updateSystemStatus({ videoTopicPanelWidth: width })}
+ panelWidth={videoTopicPanelWidth ?? 256}
+ showPanel={showVideoTopicPanel ?? true}
+ >
+ <Suspense fallback={<SkeletonList />}>
+ <TopicList />
+ <TopicUrlSync />
+ </Suspense>
+ </GenerationTopicPanel>
+ </GenerationTopicStoreProvider>
+ );
+});
+
+TopicSidebar.displayName = 'VideoTopicSidebar';
+
+export default TopicSidebar;
diff --git a/src/app/[variants]/(main)/video/_layout/index.tsx b/src/app/[variants]/(main)/video/_layout/index.tsx
new file mode 100644
index 00000000000..23fd47e16cc
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/index.tsx
@@ -0,0 +1,23 @@
+import { Flexbox } from '@lobehub/ui';
+import type { FC } from 'react';
+import { Outlet } from 'react-router-dom';
+
+import Sidebar from './Sidebar';
+import { styles } from './style';
+import TopicSidebar from './TopicSidebar';
+
+const Layout: FC = () => {
+ return (
+ <>
+ <Sidebar />
+ <Flexbox horizontal className={styles.mainContainer} flex={1} height={'100%'}>
+ <Flexbox className={styles.contentContainer} flex={1} height={'100%'}>
+ <Outlet />
+ </Flexbox>
+ <TopicSidebar />
+ </Flexbox>
+ </>
+ );
+};
+
+export default Layout;
diff --git a/src/app/[variants]/(main)/video/_layout/style.ts b/src/app/[variants]/(main)/video/_layout/style.ts
new file mode 100644
index 00000000000..beeb0b5a36a
--- /dev/null
+++ b/src/app/[variants]/(main)/video/_layout/style.ts
@@ -0,0 +1,13 @@
+import { createStaticStyles } from 'antd-style';
+
+export const styles = createStaticStyles(({ css, cssVar }) => ({
+ contentContainer: css`
+ position: relative;
+ overflow: hidden;
+ `,
+ mainContainer: css`
+ position: relative;
+ overflow: hidden;
+ background: ${cssVar.colorBgContainer};
+ `,
+}));
diff --git a/src/app/[variants]/(main)/video/features/GenerationFeed/BatchItem.tsx b/src/app/[variants]/(main)/video/features/GenerationFeed/BatchItem.tsx
new file mode 100644
index 00000000000..96c4c418a4b
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/GenerationFeed/BatchItem.tsx
@@ -0,0 +1,176 @@
+'use client';
+
+import { ModelTag } from '@lobehub/icons';
+import { Block, Flexbox, Markdown, Tag, Text } from '@lobehub/ui';
+import { App } from 'antd';
+import dayjs from 'dayjs';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import useRenderBusinessVideoBatchItem from '@/business/client/hooks/useRenderBusinessVideoBatchItem';
+import { useVideoStore } from '@/store/video';
+import { AsyncTaskStatus } from '@/types/asyncTask';
+import type { GenerationBatch } from '@/types/generation';
+import { downloadFile } from '@/utils/client/downloadFile';
+
+import VideoErrorItem from './VideoErrorItem';
+import VideoLoadingItem from './VideoLoadingItem';
+import VideoReferenceFrames from './VideoReferenceFrames';
+import VideoSuccessItem from './VideoSuccessItem';
+
+interface VideoGenerationBatchItemProps {
+ batch: GenerationBatch;
+}
+
+export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(({ batch }) => {
+ const { message } = App.useApp();
+ const { t } = useTranslation('video');
+ const useCheckGenerationStatus = useVideoStore((s) => s.useCheckGenerationStatus);
+ const removeGeneration = useVideoStore((s) => s.removeGeneration);
+ const activeTopicId = useVideoStore((s) => s.activeGenerationTopicId);
+ const { shouldRenderBusinessBatchItem, businessBatchItem } =
+ useRenderBusinessVideoBatchItem(batch);
+
+ const time = useMemo(() => {
+ return dayjs(batch.createdAt).format('YYYY-MM-DD HH:mm:ss');
+ }, [batch.createdAt]);
+
+ const generation = batch.generations[0];
+
+ const isFinalized =
+ generation?.task.status === AsyncTaskStatus.Success ||
+ generation?.task.status === AsyncTaskStatus.Error;
+
+ useCheckGenerationStatus(
+ generation?.id ?? '',
+ generation?.task.id ?? '',
+ activeTopicId!,
+ !isFinalized,
+ );
+
+ const handleDelete = useCallback(async () => {
+ if (!generation) return;
+ try {
+ await removeGeneration(generation.id);
+ } catch (error) {
+ console.error('Failed to delete generation:', error);
+ }
+ }, [removeGeneration, generation?.id]);
+
+ const handleDownload = useCallback(async () => {
+ if (!generation?.asset?.url) return;
+
+ const timestamp = dayjs(generation.createdAt).format('YYYY-MM-DD_HH-mm-ss');
+ const baseName = batch.prompt.slice(0, 30).trim();
+ const sanitizedBaseName = baseName.replaceAll(/["%*/:<>?\\|]/g, '').replaceAll(/\s+/g, '_');
+ const safePrompt = sanitizedBaseName || 'Untitled';
+ const fileName = `${safePrompt}_${timestamp}.mp4`;
+
+ try {
+ await downloadFile(generation.asset.url, fileName, false);
+ } catch (error) {
+ console.error('Failed to download video:', error);
+ }
+ }, [generation?.asset?.url, generation?.createdAt, batch.prompt]);
+
+ const handleCopyError = useCallback(async () => {
+ if (!generation?.task.error) return;
+
+ const errorMessage =
+ typeof generation.task.error.body === 'string'
+ ? generation.task.error.body
+ : generation.task.error.body?.detail || generation.task.error.name || 'Unknown error';
+
+ try {
+ await navigator.clipboard.writeText(errorMessage);
+ message.success(t('generation.actions.errorCopied'));
+ } catch (error) {
+ console.error('Failed to copy error message:', error);
+ message.error(t('generation.actions.errorCopyFailed'));
+ }
+ }, [generation?.task.error, message, t]);
+
+ const displayAspectRatio = useMemo(() => {
+ const ratio = batch.config?.aspectRatio;
+ if (ratio && ratio !== 'adaptive') return ratio;
+
+ // Compute from video asset dimensions
+ const asset = generation?.asset;
+ if (asset && asset.width && asset.height && asset.width > 0 && asset.height > 0) {
+ const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
+ const d = gcd(asset.width, asset.height);
+ return `${asset.width / d}:${asset.height / d}`;
+ }
+ return undefined;
+ }, [batch.config?.aspectRatio, generation?.asset]);
+
+ if (!generation) {
+ return null;
+ }
+
+ if (shouldRenderBusinessBatchItem) {
+ return businessBatchItem;
+ }
+
+ const renderContent = () => {
+ if (generation.task.status === AsyncTaskStatus.Success && generation.asset?.url) {
+ return (
+ <VideoSuccessItem
+ generation={generation}
+ onDelete={handleDelete}
+ onDownload={handleDownload}
+ />
+ );
+ }
+
+ if (generation.task.status === AsyncTaskStatus.Error) {
+ return (
+ <VideoErrorItem
+ aspectRatio={batch.config?.aspectRatio}
+ generation={generation}
+ onCopyError={handleCopyError}
+ onDelete={handleDelete}
+ />
+ );
+ }
+
+ return <VideoLoadingItem aspectRatio={batch.config?.aspectRatio} generation={generation} />;
+ };
+
+ const hasReferenceFrames = batch.config?.imageUrl || batch.config?.endImageUrl;
+
+ const promptAndMetadata = (
+ <>
+ <Markdown variant={'chat'}>{batch.prompt}</Markdown>
+ <Flexbox gap={4} horizontal style={{ marginBottom: 10 }}>
+ <ModelTag model={batch.model} />
+ {batch.config?.resolution && <Tag>{batch.config.resolution}</Tag>}
+ {displayAspectRatio && <Tag>{displayAspectRatio}</Tag>}
+ </Flexbox>
+ </>
+ );
+
+ return (
+ <Block gap={8} variant={'borderless'}>
+ {hasReferenceFrames ? (
+ <Flexbox align={'center'} gap={16} horizontal>
+ <VideoReferenceFrames
+ endImageUrl={batch.config?.endImageUrl}
+ imageUrl={batch.config?.imageUrl}
+ />
+ <Flexbox flex={1} gap={8}>
+ {promptAndMetadata}
+ </Flexbox>
+ </Flexbox>
+ ) : (
+ promptAndMetadata
+ )}
+ {renderContent()}
+ <Text as={'time'} fontSize={12} type={'secondary'}>
+ {time}
+ </Text>
+ </Block>
+ );
+});
+
+VideoGenerationBatchItem.displayName = 'VideoGenerationBatchItem';
diff --git a/src/app/[variants]/(main)/video/features/GenerationFeed/VideoErrorItem.tsx b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoErrorItem.tsx
new file mode 100644
index 00000000000..c52e95fd50a
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoErrorItem.tsx
@@ -0,0 +1,99 @@
+'use client';
+
+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { Block, Center, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { VideoOffIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ActionButtons } from '@/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/ActionButtons';
+import { styles } from '@/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/styles';
+import type { Generation } from '@/types/generation';
+
+interface VideoErrorItemProps {
+ aspectRatio?: string;
+ generation: Generation;
+ onCopyError: () => void;
+ onDelete: () => void;
+}
+
+const VideoErrorItem = memo<VideoErrorItemProps>(
+ ({ generation, aspectRatio, onDelete, onCopyError }) => {
+ const { t } = useTranslation('video');
+ const { t: tError } = useTranslation('error');
+
+ const errorMessage = useMemo(() => {
+ if (!generation.task.error) return '';
+
+ const error = generation.task.error;
+ const errorBody = typeof error.body === 'string' ? error.body : error.body?.detail;
+
+ if (errorBody) {
+ const knownErrorTypes = Object.values(AgentRuntimeErrorType);
+ if (
+ knownErrorTypes.includes(
+ errorBody as (typeof AgentRuntimeErrorType)[keyof typeof AgentRuntimeErrorType],
+ )
+ ) {
+ const translationKey = `response.${errorBody}`;
+ const translated = tError(translationKey as any);
+
+ if (translated === translationKey || (translated as string).startsWith('response.')) {
+ const directTranslated = tError(errorBody as any);
+ if (directTranslated !== errorBody) {
+ return directTranslated as string;
+ }
+ return errorBody;
+ }
+
+ return translated as string;
+ }
+ }
+
+ return errorBody || error.name || 'Unknown error';
+ }, [generation.task.error, tError]);
+
+ return (
+ <Block
+ align={'center'}
+ className={styles.placeholderContainer}
+ justify={'center'}
+ padding={16}
+ variant={'filled'}
+ style={{
+ aspectRatio: aspectRatio?.includes(':') ? aspectRatio.replace(':', '/') : '16/9',
+ cursor: 'pointer',
+ width: '100%',
+ }}
+ onClick={onCopyError}
+ >
+ <Center gap={8}>
+ <Icon color={cssVar.colorTextDescription} icon={VideoOffIcon} size={24} />
+ <Text strong type={'secondary'}>
+ {t('generation.status.failed')}
+ </Text>
+ {generation.task.error && (
+ <Text
+ code
+ ellipsis={{ rows: 2 }}
+ fontSize={10}
+ title={t('generation.actions.copyError')}
+ type={'secondary'}
+ style={{
+ wordBreak: 'break-all',
+ }}
+ >
+ {errorMessage}
+ </Text>
+ )}
+ </Center>
+ <ActionButtons onDelete={onDelete} />
+ </Block>
+ );
+ },
+);
+
+VideoErrorItem.displayName = 'VideoErrorItem';
+
+export default VideoErrorItem;
diff --git a/src/app/[variants]/(main)/video/features/GenerationFeed/VideoLoadingItem.tsx b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoLoadingItem.tsx
new file mode 100644
index 00000000000..76c419c00a9
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoLoadingItem.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { LoadingOutlined } from '@ant-design/icons';
+import { Block, Center } from '@lobehub/ui';
+import { Spin } from 'antd';
+import { memo } from 'react';
+
+import { ElapsedTime } from '@/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/ElapsedTime';
+import { AsyncTaskStatus } from '@/types/asyncTask';
+import type { Generation } from '@/types/generation';
+
+interface VideoLoadingItemProps {
+ aspectRatio?: string;
+ generation: Generation;
+}
+
+const VideoLoadingItem = memo<VideoLoadingItemProps>(({ generation, aspectRatio }) => {
+ const isGenerating =
+ generation.task.status === AsyncTaskStatus.Processing ||
+ generation.task.status === AsyncTaskStatus.Pending;
+
+ return (
+ <Block
+ align={'center'}
+ justify={'center'}
+ variant={'filled'}
+ style={{
+ aspectRatio: aspectRatio?.includes(':') ? aspectRatio.replace(':', '/') : '16/9',
+ }}
+ >
+ <Center gap={8}>
+ <Spin indicator={<LoadingOutlined spin />} />
+ <ElapsedTime generationId={generation.id} isActive={isGenerating} />
+ </Center>
+ </Block>
+ );
+});
+
+VideoLoadingItem.displayName = 'VideoLoadingItem';
+
+export default VideoLoadingItem;
diff --git a/src/app/[variants]/(main)/video/features/GenerationFeed/VideoReferenceFrames.tsx b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoReferenceFrames.tsx
new file mode 100644
index 00000000000..3750b101937
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoReferenceFrames.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+
+import ImageItem from '@/components/ImageItem';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ frameEnd: css`
+ position: relative;
+ transform: rotate(3deg);
+
+ flex-shrink: 0;
+
+ width: 64px;
+ height: 64px;
+
+ transition: transform 0.2s ease;
+
+ &::before {
+ content: '';
+
+ position: absolute;
+ z-index: -1;
+ inset: -4px;
+
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: ${cssVar.borderRadius}px;
+
+ background: ${cssVar.colorBgContainer};
+ box-shadow: 0 2px 8px ${cssVar.colorBgMask};
+ }
+
+ &:hover {
+ transform: rotate(1deg) scale(1.05);
+ }
+ `,
+ frameInner: css`
+ overflow: hidden;
+
+ width: 100%;
+ height: 100%;
+ border-radius: ${cssVar.borderRadiusSM}px;
+
+ background: ${cssVar.colorBgLayout};
+ `,
+ frameStart: css`
+ position: relative;
+ transform: rotate(-3deg);
+
+ flex-shrink: 0;
+
+ width: 64px;
+ height: 64px;
+
+ transition: transform 0.2s ease;
+
+ &::before {
+ content: '';
+
+ position: absolute;
+ z-index: -1;
+ inset: -4px;
+
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: ${cssVar.borderRadius}px;
+
+ background: ${cssVar.colorBgContainer};
+ box-shadow: 0 2px 8px ${cssVar.colorBgMask};
+ }
+
+ &:hover {
+ transform: rotate(-1deg) scale(1.05);
+ }
+ `,
+}));
+
+interface VideoReferenceFramesProps {
+ endImageUrl?: string | null;
+ imageUrl?: string | null;
+}
+
+const VideoReferenceFrames = memo<VideoReferenceFramesProps>(({ imageUrl, endImageUrl }) => {
+ if (!imageUrl && !endImageUrl) return null;
+
+ return (
+ <Flexbox align={'center'} gap={12} horizontal>
+ {imageUrl && (
+ <div className={styles.frameStart}>
+ <div className={styles.frameInner}>
+ <ImageItem
+ alt="Start frame"
+ preview={{ src: imageUrl }}
+ style={{ height: '100%', width: '100%' }}
+ url={imageUrl}
+ />
+ </div>
+ </div>
+ )}
+ {endImageUrl && (
+ <div className={styles.frameEnd}>
+ <div className={styles.frameInner}>
+ <ImageItem
+ alt="End frame"
+ preview={{ src: endImageUrl }}
+ style={{ height: '100%', width: '100%' }}
+ url={endImageUrl}
+ />
+ </div>
+ </div>
+ )}
+ </Flexbox>
+ );
+});
+
+VideoReferenceFrames.displayName = 'VideoReferenceFrames';
+
+export default VideoReferenceFrames;
diff --git a/src/app/[variants]/(main)/video/features/GenerationFeed/VideoSuccessItem.tsx b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoSuccessItem.tsx
new file mode 100644
index 00000000000..fd05971ab7e
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/GenerationFeed/VideoSuccessItem.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { Block } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { ActionButtons } from '@/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/ActionButtons';
+import { styles } from '@/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/styles';
+import type { Generation, VideoGenerationAsset } from '@/types/generation';
+
+interface VideoSuccessItemProps {
+ generation: Generation;
+ onDelete: () => void;
+ onDownload: () => void;
+}
+
+const VideoSuccessItem = memo<VideoSuccessItemProps>(({ generation, onDelete, onDownload }) => {
+ const asset = generation.asset as VideoGenerationAsset;
+
+ return (
+ <Block className={styles.imageContainer} style={{ width: 'fit-content' }} variant={'filled'}>
+ <video
+ controls
+ loop
+ playsInline
+ poster={asset.coverUrl || asset.thumbnailUrl}
+ src={asset.url}
+ style={{ display: 'block', maxHeight: '50vh', maxWidth: '100%' }}
+ />
+ <ActionButtons onDelete={onDelete} onDownload={onDownload} showDownload />
+ </Block>
+ );
+});
+
+VideoSuccessItem.displayName = 'VideoSuccessItem';
+
+export default VideoSuccessItem;
diff --git a/src/app/[variants]/(main)/video/features/GenerationFeed/index.tsx b/src/app/[variants]/(main)/video/features/GenerationFeed/index.tsx
new file mode 100644
index 00000000000..f7d0ba48233
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/GenerationFeed/index.tsx
@@ -0,0 +1,85 @@
+'use client';
+
+import { useAutoAnimate } from '@formkit/auto-animate/react';
+import { Flexbox } from '@lobehub/ui';
+import { Divider } from 'antd';
+import { Fragment, memo, useEffect, useRef } from 'react';
+
+import { useVideoStore } from '@/store/video';
+import { generationBatchSelectors } from '@/store/video/selectors';
+
+import { VideoGenerationBatchItem } from './BatchItem';
+
+const GenerationFeed = memo(() => {
+ const [parent, enableAnimations] = useAutoAnimate();
+ const containerRef = useRef<HTMLDivElement>(null);
+ const isInitialLoadRef = useRef(true);
+ const prevBatchesCountRef = useRef(0);
+
+ const currentGenerationBatches = useVideoStore(generationBatchSelectors.currentGenerationBatches);
+
+ const scrollToBottom = (behavior: 'smooth' | 'auto' = 'smooth') => {
+ if (!containerRef.current) return;
+
+ const scrollableParent =
+ containerRef.current.closest('[style*="overflow"]') || document.documentElement;
+
+ const targetRect = containerRef.current.getBoundingClientRect();
+ const scrollableRect = scrollableParent.getBoundingClientRect();
+
+ const scrollTop = scrollableParent.scrollTop + targetRect.bottom - scrollableRect.bottom + 999;
+
+ scrollableParent.scrollTo({
+ behavior: behavior,
+ top: scrollTop,
+ });
+ };
+
+ useEffect(() => {
+ const currentBatches = currentGenerationBatches || [];
+ const currentBatchesCount = currentBatches.length;
+ const prevBatchesCount = prevBatchesCountRef.current;
+
+ if (currentBatchesCount === 0) {
+ prevBatchesCountRef.current = 0;
+ return;
+ }
+
+ if (isInitialLoadRef.current) {
+ scrollToBottom('auto');
+ isInitialLoadRef.current = false;
+ } else if (currentBatchesCount > prevBatchesCount) {
+ enableAnimations(false);
+ const timer = setTimeout(() => {
+ scrollToBottom('smooth');
+ enableAnimations(true);
+ }, 50);
+
+ return () => clearTimeout(timer);
+ }
+
+ prevBatchesCountRef.current = currentBatchesCount;
+ }, [currentGenerationBatches, enableAnimations]);
+
+ if (!currentGenerationBatches || currentGenerationBatches.length === 0) {
+ return null;
+ }
+
+ return (
+ <Flexbox flex={1} style={{ overflowY: 'auto' }}>
+ <Flexbox gap={16} ref={parent} style={{ paddingBottom: 48 }} width="100%">
+ {currentGenerationBatches.map((batch, index) => (
+ <Fragment key={batch.id}>
+ {Boolean(index !== 0) && <Divider dashed style={{ margin: 0 }} />}
+ <VideoGenerationBatchItem batch={batch} key={batch.id} />
+ </Fragment>
+ ))}
+ </Flexbox>
+ <div ref={containerRef} style={{ height: 1 }} />
+ </Flexbox>
+ );
+});
+
+GenerationFeed.displayName = 'GenerationFeed';
+
+export default GenerationFeed;
diff --git a/src/app/[variants]/(main)/video/features/PromptInput/Title.tsx b/src/app/[variants]/(main)/video/features/PromptInput/Title.tsx
new file mode 100644
index 00000000000..84e090a7c14
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/PromptInput/Title.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { Center, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { Video } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+const PromptTitle = () => {
+ const { t } = useTranslation('video');
+
+ return (
+ <Center gap={16} horizontal style={{ width: '100%' }}>
+ <Center
+ flex={'none'}
+ height={54}
+ style={{
+ backgroundColor: cssVar.colorText,
+ borderRadius: 16,
+ }}
+ width={54}
+ >
+ <Icon color={cssVar.colorBgLayout} icon={Video} size={32} />
+ </Center>
+ <Text
+ as={'h1'}
+ style={{
+ margin: 0,
+ }}
+ >
+ {t('config.header.title')}
+ </Text>
+ </Center>
+ );
+};
+
+export default PromptTitle;
diff --git a/src/app/[variants]/(main)/video/features/PromptInput/index.tsx b/src/app/[variants]/(main)/video/features/PromptInput/index.tsx
new file mode 100644
index 00000000000..0b89a75ece9
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/PromptInput/index.tsx
@@ -0,0 +1,132 @@
+'use client';
+
+import { ChatInput } from '@lobehub/editor/react';
+import { Button, Flexbox, TextArea } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { Sparkles } from 'lucide-react';
+import type { KeyboardEvent } from 'react';
+import { useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { loginRequired } from '@/components/Error/loginRequiredNotification';
+import { useIsDark } from '@/hooks/useIsDark';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/slices/auth/selectors';
+import { useVideoStore } from '@/store/video';
+import { createVideoSelectors } from '@/store/video/selectors';
+import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';
+
+import PromptTitle from './Title';
+
+interface PromptInputProps {
+ disableAnimation?: boolean;
+ showTitle?: boolean;
+}
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ box-shadow:
+ ${cssVar.boxShadowTertiary},
+ 0 0 0 ${cssVar.colorBgContainer},
+ 0 32px 0 ${cssVar.colorBgContainer};
+ `,
+ container_dark: css`
+ box-shadow:
+ ${cssVar.boxShadowTertiary},
+ 0 0 48px 32px ${cssVar.colorBgContainer},
+ 0 32px 0 ${cssVar.colorBgContainer};
+ `,
+}));
+
+const PromptInput = ({ showTitle = false }: PromptInputProps) => {
+ const isDarkMode = useIsDark();
+ const { t } = useTranslation('video');
+ const { value, setValue } = useVideoGenerationConfigParam('prompt');
+ const isCreating = useVideoStore(createVideoSelectors.isCreating);
+ const createVideo = useVideoStore((s) => s.createVideo);
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ // Read prompt from query parameter
+ const [promptParam, setPromptParam] = useQueryState('prompt');
+ const hasProcessedPrompt = useRef(false);
+
+ const handleGenerate = async () => {
+ if (!isLogin) {
+ loginRequired.redirect({ timeout: 2000 });
+ return;
+ }
+
+ await createVideo();
+ };
+
+ // Auto-fill and auto-send when prompt query parameter is present
+ useEffect(() => {
+ if (promptParam && !hasProcessedPrompt.current && isLogin) {
+ const decodedPrompt = decodeURIComponent(promptParam);
+
+ setValue(decodedPrompt);
+
+ hasProcessedPrompt.current = true;
+
+ setPromptParam(null);
+
+ setTimeout(async () => {
+ await createVideo();
+ }, 100);
+ }
+ }, [promptParam, isLogin, setValue, setPromptParam, createVideo]);
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ if (!isCreating && value.trim()) {
+ handleGenerate();
+ }
+ }
+ };
+
+ return (
+ <Flexbox gap={32} width={'100%'}>
+ {showTitle && <PromptTitle />}
+ <ChatInput
+ className={cx(styles.container, isDarkMode && styles.container_dark)}
+ styles={{ body: { padding: 8 } }}
+ >
+ <Flexbox align="flex-end" gap={12} height={'100%'} horizontal width={'100%'}>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 3 }}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder={t('config.prompt.placeholder')}
+ style={{
+ borderRadius: 0,
+ padding: 0,
+ }}
+ value={value}
+ variant={'borderless'}
+ />
+ <Button
+ disabled={!value}
+ icon={Sparkles}
+ loading={isCreating}
+ onClick={handleGenerate}
+ size={'large'}
+ style={{
+ fontWeight: 500,
+ height: 64,
+ minWidth: 64,
+ width: 64,
+ }}
+ title={
+ isCreating ? t('generation.status.generating') : t('generation.actions.generate')
+ }
+ type={'primary'}
+ />
+ </Flexbox>
+ </ChatInput>
+ </Flexbox>
+ );
+};
+
+export default PromptInput;
diff --git a/src/app/[variants]/(main)/video/features/VideoWorkspace/Content.tsx b/src/app/[variants]/(main)/video/features/VideoWorkspace/Content.tsx
new file mode 100644
index 00000000000..5e5fe4cb234
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/VideoWorkspace/Content.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import { useVideoStore } from '@/store/video';
+import { generationBatchSelectors, videoGenerationTopicSelectors } from '@/store/video/selectors';
+
+import GenerationFeed from '../GenerationFeed';
+import PromptInput from '../PromptInput';
+import EmptyState from './EmptyState';
+
+const VideoWorkspaceContent = () => {
+ const activeTopicId = useVideoStore(videoGenerationTopicSelectors.activeGenerationTopicId);
+ const useFetchGenerationBatches = useVideoStore((s) => s.useFetchGenerationBatches);
+ const isCurrentGenerationTopicLoaded = useVideoStore(
+ generationBatchSelectors.isCurrentGenerationTopicLoaded,
+ );
+ useFetchGenerationBatches(activeTopicId);
+ const currentBatches = useVideoStore(generationBatchSelectors.currentGenerationBatches);
+ const hasGenerations = currentBatches && currentBatches.length > 0;
+
+ if (!isCurrentGenerationTopicLoaded) {
+ return <PromptInput disableAnimation={true} showTitle={false} />;
+ }
+
+ if (!hasGenerations) return <EmptyState />;
+
+ return (
+ <>
+ <GenerationFeed key={activeTopicId} />
+ <PromptInput disableAnimation={true} showTitle={false} />
+ </>
+ );
+};
+
+export default VideoWorkspaceContent;
diff --git a/src/app/[variants]/(main)/video/features/VideoWorkspace/EmptyState.tsx b/src/app/[variants]/(main)/video/features/VideoWorkspace/EmptyState.tsx
new file mode 100644
index 00000000000..0c1b68b1fcf
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/VideoWorkspace/EmptyState.tsx
@@ -0,0 +1,14 @@
+import { Center } from '@lobehub/ui';
+import { memo } from 'react';
+
+import PromptInput from '../PromptInput';
+
+const EmptyState = memo(() => {
+ return (
+ <Center height={'calc(100vh - 180px)'}>
+ <PromptInput showTitle={true} />
+ </Center>
+ );
+});
+
+export default EmptyState;
diff --git a/src/app/[variants]/(main)/video/features/VideoWorkspace/index.tsx b/src/app/[variants]/(main)/video/features/VideoWorkspace/index.tsx
new file mode 100644
index 00000000000..f5aa548902f
--- /dev/null
+++ b/src/app/[variants]/(main)/video/features/VideoWorkspace/index.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useVideoStore } from '@/store/video';
+
+import Content from './Content';
+import EmptyState from './EmptyState';
+
+const VideoWorkspace = () => {
+ const [topic] = useQueryState('topic');
+ const isCreatingWithNewTopic = useVideoStore((s) => s.isCreatingWithNewTopic);
+
+ if (!topic || isCreatingWithNewTopic) {
+ return <EmptyState />;
+ }
+
+ return <Content />;
+};
+
+export default VideoWorkspace;
diff --git a/src/app/[variants]/(main)/video/index.tsx b/src/app/[variants]/(main)/video/index.tsx
new file mode 100644
index 00000000000..796475d55d0
--- /dev/null
+++ b/src/app/[variants]/(main)/video/index.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+
+import VideoWorkspace from './features/VideoWorkspace';
+
+const DesktopVideoPage = memo(() => {
+ return (
+ <>
+ <NavHeader right={<WideScreenButton />} />
+ <Flexbox height={'100%'} style={{ overflowY: 'auto', position: 'relative' }} width={'100%'}>
+ <WideScreenContainer height={'100%'} wrapperStyle={{ height: '100%' }}>
+ <VideoWorkspace />
+ </WideScreenContainer>
+ </Flexbox>
+ </>
+ );
+});
+
+DesktopVideoPage.displayName = 'DesktopVideoPage';
+
+export default DesktopVideoPage;
diff --git a/src/app/[variants]/(main)/video/loading.tsx b/src/app/[variants]/(main)/video/loading.tsx
new file mode 100644
index 00000000000..f5906433e8a
--- /dev/null
+++ b/src/app/[variants]/(main)/video/loading.tsx
@@ -0,0 +1,3 @@
+import Loading from '@/components/Loading/BrandTextLoading';
+
+export default () => <Loading debugId="Video Page" />;
diff --git a/src/app/[variants]/router/desktopRouter.config.tsx b/src/app/[variants]/router/desktopRouter.config.tsx
index f1d2c4f7c0f..3c07215544f 100644
--- a/src/app/[variants]/router/desktopRouter.config.tsx
+++ b/src/app/[variants]/router/desktopRouter.config.tsx
@@ -15,6 +15,7 @@ import DesktopGroupLayout from '../(main)/group/_layout';
import DesktopImageLayout from '../(main)/image/_layout';
import DesktopMemoryLayout from '../(main)/memory/_layout';
import DesktopPageLayout from '../(main)/page/_layout';
+import DesktopVideoLayout from '../(main)/video/_layout';
// Desktop router configuration (declarative mode)
export const desktopRoutes: RouteConfig[] = [
@@ -364,6 +365,19 @@ export const desktopRoutes: RouteConfig[] = [
path: 'memory',
},
+ // Video routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('../(main)/video'), 'Desktop > Video'),
+ index: true,
+ },
+ ],
+ element: <DesktopVideoLayout />,
+ errorElement: <ErrorBoundary resetPath="/video" />,
+ path: 'video',
+ },
+
// Image routes
{
children: [
diff --git a/src/business/client/hooks/useRenderBusinessVideoBatchItem.tsx b/src/business/client/hooks/useRenderBusinessVideoBatchItem.tsx
new file mode 100644
index 00000000000..cfd72162541
--- /dev/null
+++ b/src/business/client/hooks/useRenderBusinessVideoBatchItem.tsx
@@ -0,0 +1,9 @@
+import { type GenerationBatch } from '@/types/generation';
+
+// eslint-disable-next-line unused-imports/no-unused-vars
+export default function useRenderBusinessVideoBatchItem(batch: GenerationBatch) {
+ return {
+ businessBatchItem: null,
+ shouldRenderBusinessBatchItem: false,
+ };
+}
diff --git a/src/business/server/video-generation/chargeAfterGenerate.ts b/src/business/server/video-generation/chargeAfterGenerate.ts
new file mode 100644
index 00000000000..ae38dd4083e
--- /dev/null
+++ b/src/business/server/video-generation/chargeAfterGenerate.ts
@@ -0,0 +1,18 @@
+interface ChargeParams {
+ generateAudio?: boolean;
+ isError?: boolean;
+ metadata: {
+ asyncTaskId: string;
+ generationBatchId: string;
+ modelId: string;
+ topicId?: string;
+ };
+ model: string;
+ prechargeResult?: Record<string, unknown>;
+ provider: string;
+ usage?: { completionTokens: number; totalTokens: number };
+ userId: string;
+}
+
+// eslint-disable-next-line unused-imports/no-unused-vars
+export async function chargeAfterGenerate(params: ChargeParams): Promise<void> {}
diff --git a/src/business/server/video-generation/chargeBeforeGenerate.ts b/src/business/server/video-generation/chargeBeforeGenerate.ts
new file mode 100644
index 00000000000..5410df5e180
--- /dev/null
+++ b/src/business/server/video-generation/chargeBeforeGenerate.ts
@@ -0,0 +1,30 @@
+import type { NewGeneration, NewGenerationBatch } from '@/database/schemas';
+import type { CreateVideoServicePayload } from '@/server/routers/lambda/video';
+
+interface ChargeParams {
+ generationTopicId: string;
+ model: string;
+ params: CreateVideoServicePayload['params'];
+ provider: string;
+ userId: string;
+}
+
+interface ErrorBatch {
+ data: {
+ batch: NewGenerationBatch;
+ generations: NewGeneration[];
+ };
+ success: true;
+}
+
+interface ChargeBeforeResult {
+ errorBatch?: ErrorBatch;
+ prechargeResult?: Record<string, unknown>;
+}
+
+export async function chargeBeforeGenerate(
+ // eslint-disable-next-line unused-imports/no-unused-vars
+ params: ChargeParams,
+): Promise<ChargeBeforeResult> {
+ return {};
+}
diff --git a/src/config/routes/index.ts b/src/config/routes/index.ts
index 2020654385a..2015fe9c78f 100644
--- a/src/config/routes/index.ts
+++ b/src/config/routes/index.ts
@@ -6,6 +6,7 @@ import {
LibraryBigIcon,
Settings,
ShapesIcon,
+ Video,
} from 'lucide-react';
export interface NavigationRoute {
@@ -44,6 +45,16 @@ export const NAVIGATION_ROUTES: NavigationRoute[] = [
path: '/community',
pathPrefix: '/community',
},
+ {
+ cmdkKey: 'cmdk.video',
+ electronKey: 'navigation.video',
+ icon: Video,
+ id: 'video',
+ keywords: ['video', 'generate', 'seedance', 'kling'],
+ keywordsKey: 'cmdk.keywords.video',
+ path: '/video',
+ pathPrefix: '/video',
+ },
{
cmdkKey: 'cmdk.painting',
electronKey: 'navigation.image',
@@ -108,5 +119,5 @@ export const getRouteById = (id: string): NavigationRoute | undefined =>
*/
export const getNavigableRoutes = (): NavigationRoute[] =>
NAVIGATION_ROUTES.filter((r) =>
- ['community', 'image', 'resource', 'page', 'memory'].includes(r.id),
+ ['community', 'video', 'image', 'resource', 'page', 'memory'].includes(r.id),
);
diff --git a/src/app/[variants]/(main)/image/_layout/Topics/NewTopicButton.tsx b/src/features/GenerationTopicList/NewTopicButton.tsx
similarity index 88%
rename from src/app/[variants]/(main)/image/_layout/Topics/NewTopicButton.tsx
rename to src/features/GenerationTopicList/NewTopicButton.tsx
index e21e90714ce..1b893adcf34 100644
--- a/src/app/[variants]/(main)/image/_layout/Topics/NewTopicButton.tsx
+++ b/src/features/GenerationTopicList/NewTopicButton.tsx
@@ -5,6 +5,8 @@ import { Plus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useGenerationTopicContext } from './StoreContext';
+
interface NewTopicButtonProps {
count?: number;
onClick?: () => void;
@@ -12,7 +14,8 @@ interface NewTopicButtonProps {
}
const NewTopicButton = memo<NewTopicButtonProps>(({ count, onClick, showMoreInfo }) => {
- const { t } = useTranslation('image');
+ const { namespace } = useGenerationTopicContext();
+ const { t } = useTranslation(namespace);
if (showMoreInfo)
return (
diff --git a/src/app/[variants]/(main)/image/_layout/Topics/SkeletonList.tsx b/src/features/GenerationTopicList/SkeletonList.tsx
similarity index 67%
rename from src/app/[variants]/(main)/image/_layout/Topics/SkeletonList.tsx
rename to src/features/GenerationTopicList/SkeletonList.tsx
index 5c18b5da2df..43274cfa5c7 100644
--- a/src/app/[variants]/(main)/image/_layout/Topics/SkeletonList.tsx
+++ b/src/features/GenerationTopicList/SkeletonList.tsx
@@ -1,18 +1,23 @@
'use client';
-import { Flexbox, Skeleton } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Skeleton } from '@lobehub/ui';
+import { Plus } from 'lucide-react';
import { memo } from 'react';
-import NewTopicButton from './NewTopicButton';
-
const borderRadius = 6;
const SkeletonList = memo(() => {
return (
<Flexbox align="center" gap={6} width={'100%'}>
- <NewTopicButton />
+ <ActionIcon
+ icon={Plus}
+ size={{
+ blockSize: 48,
+ size: 20,
+ }}
+ variant={'filled'}
+ />
- {/* Topic items skeleton */}
{Array.from({ length: 5 }).map((_, index) => (
<div key={index}>
<Skeleton.Avatar
diff --git a/src/features/GenerationTopicList/StoreContext.tsx b/src/features/GenerationTopicList/StoreContext.tsx
new file mode 100644
index 00000000000..5a9b462d6de
--- /dev/null
+++ b/src/features/GenerationTopicList/StoreContext.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { createContext, useContext } from 'react';
+import type { SWRResponse } from 'swr';
+import type { StoreApi, UseBoundStore } from 'zustand';
+
+import { type ImageGenerationTopic } from '@/types/generation';
+
+export interface GenerationTopicStoreSlice {
+ activeGenerationTopicId: string | null;
+ generationTopics: ImageGenerationTopic[];
+ loadingGenerationTopicIds: string[];
+ openNewGenerationTopic: () => void;
+ removeGenerationTopic: (id: string) => Promise<void>;
+ switchGenerationTopic: (topicId: string) => void;
+ useFetchGenerationTopics: (enabled: boolean) => SWRResponse<ImageGenerationTopic[]>;
+}
+
+export interface GenerationTopicContextValue {
+ /** i18n namespace */
+ namespace: 'image' | 'video';
+ useStore: UseBoundStore<StoreApi<GenerationTopicStoreSlice>>;
+}
+
+const GenerationTopicContext = createContext<GenerationTopicContextValue | null>(null);
+
+export const useGenerationTopicContext = () => {
+ const ctx = useContext(GenerationTopicContext);
+ if (!ctx) {
+ throw new Error('useGenerationTopicContext must be used within GenerationTopicStoreProvider');
+ }
+ return ctx;
+};
+
+export const GenerationTopicStoreProvider = GenerationTopicContext.Provider;
diff --git a/src/app/[variants]/(main)/image/_layout/Topics/TopicItem.tsx b/src/features/GenerationTopicList/TopicItem.tsx
similarity index 84%
rename from src/app/[variants]/(main)/image/_layout/Topics/TopicItem.tsx
rename to src/features/GenerationTopicList/TopicItem.tsx
index 1c677b9634d..6ad6023a15e 100644
--- a/src/app/[variants]/(main)/image/_layout/Topics/TopicItem.tsx
+++ b/src/features/GenerationTopicList/TopicItem.tsx
@@ -9,10 +9,10 @@ import { useTranslation } from 'react-i18next';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
-import { useImageStore } from '@/store/image';
-import { generationTopicSelectors } from '@/store/image/slices/generationTopic/selectors';
import { type ImageGenerationTopic } from '@/types/generation';
+import { useGenerationTopicContext } from './StoreContext';
+
const formatTime = (date: Date, locale: string) => {
return new Intl.DateTimeFormat(locale, {
day: 'numeric',
@@ -27,15 +27,15 @@ interface TopicItemProps {
}
const TopicItem = memo<TopicItemProps>(({ topic, showMoreInfo, style }) => {
- const { t } = useTranslation('image');
+ const { useStore, namespace } = useGenerationTopicContext();
+ const { t } = useTranslation(namespace);
const { modal } = App.useApp();
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
- // 检查当前 topic 是否在加载中
- const isLoading = useImageStore(generationTopicSelectors.isLoadingGenerationTopic(topic.id));
- const removeGenerationTopic = useImageStore((s) => s.removeGenerationTopic);
- const switchGenerationTopic = useImageStore((s) => s.switchGenerationTopic);
- const activeTopicId = useImageStore(generationTopicSelectors.activeGenerationTopicId);
+ const isLoading = useStore((s) => s.loadingGenerationTopicIds.includes(topic.id));
+ const removeGenerationTopic = useStore((s) => s.removeGenerationTopic);
+ const switchGenerationTopic = useStore((s) => s.switchGenerationTopic);
+ const activeTopicId = useStore((s) => s.activeGenerationTopicId);
const isActive = activeTopicId === topic.id;
diff --git a/src/app/[variants]/(main)/image/_layout/Topics/index.tsx b/src/features/GenerationTopicList/TopicList.tsx
similarity index 79%
rename from src/app/[variants]/(main)/image/_layout/Topics/index.tsx
rename to src/features/GenerationTopicList/TopicList.tsx
index c7dd73a1191..d6f0e18d24d 100644
--- a/src/app/[variants]/(main)/image/_layout/Topics/index.tsx
+++ b/src/features/GenerationTopicList/TopicList.tsx
@@ -5,23 +5,23 @@ import { Flexbox } from '@lobehub/ui';
import { useSize } from 'ahooks';
import { memo, useRef } from 'react';
-import { useImageStore } from '@/store/image';
-import { generationTopicSelectors } from '@/store/image/selectors';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/slices/auth/selectors';
import NewTopicButton from './NewTopicButton';
+import { useGenerationTopicContext } from './StoreContext';
import TopicItem from './TopicItem';
const TopicsList = memo(() => {
+ const { useStore } = useGenerationTopicContext();
const isLogin = useUserStore(authSelectors.isLogin);
- const useFetchGenerationTopics = useImageStore((s) => s.useFetchGenerationTopics);
+ const useFetchGenerationTopics = useStore((s) => s.useFetchGenerationTopics);
useFetchGenerationTopics(!!isLogin);
const ref = useRef(null);
const { width = 80 } = useSize(ref) || {};
const [parent] = useAutoAnimate();
- const generationTopics = useImageStore(generationTopicSelectors.generationTopics);
- const openNewGenerationTopic = useImageStore((s) => s.openNewGenerationTopic);
+ const generationTopics = useStore((s) => s.generationTopics);
+ const openNewGenerationTopic = useStore((s) => s.openNewGenerationTopic);
const showMoreInfo = Boolean(width > 120);
@@ -55,7 +55,6 @@ const TopicsList = memo(() => {
topic={topic}
style={{
padding:
- // fix the avatar border is clipped by overflow hidden
generationTopics.length === 1
? '4px 0'
: index === generationTopics.length - 1
diff --git a/src/features/GenerationTopicList/TopicUrlSync.tsx b/src/features/GenerationTopicList/TopicUrlSync.tsx
new file mode 100644
index 00000000000..0f749b97110
--- /dev/null
+++ b/src/features/GenerationTopicList/TopicUrlSync.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { useLayoutEffect } from 'react';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useQueryState } from '@/hooks/useQueryParam';
+
+import { useGenerationTopicContext } from './StoreContext';
+
+/**
+ * Bidirectional sync between URL 'topic' param and store's activeGenerationTopicId
+ */
+const TopicUrlSync = () => {
+ const { useStore } = useGenerationTopicContext();
+ const useStoreUpdater = createStoreUpdater(useStore);
+
+ const [topic, setTopic] = useQueryState('topic', { history: 'replace', throttleMs: 500 });
+ useStoreUpdater('activeGenerationTopicId', topic);
+
+ useLayoutEffect(() => {
+ let prevTopicId = useStore.getState().activeGenerationTopicId;
+ const unsubscribeTopic = useStore.subscribe((state) => {
+ if (state.activeGenerationTopicId !== prevTopicId) {
+ prevTopicId = state.activeGenerationTopicId;
+ setTopic(state.activeGenerationTopicId || null);
+ }
+ });
+
+ return () => {
+ unsubscribeTopic();
+ };
+ }, [setTopic]);
+
+ return null;
+};
+
+export default TopicUrlSync;
diff --git a/src/features/GenerationTopicList/index.tsx b/src/features/GenerationTopicList/index.tsx
new file mode 100644
index 00000000000..b04e52a0c16
--- /dev/null
+++ b/src/features/GenerationTopicList/index.tsx
@@ -0,0 +1,7 @@
+export { default as NewTopicButton } from './NewTopicButton';
+export { default as SkeletonList } from './SkeletonList';
+export type { GenerationTopicContextValue, GenerationTopicStoreSlice } from './StoreContext';
+export { GenerationTopicStoreProvider, useGenerationTopicContext } from './StoreContext';
+export { default as TopicItem } from './TopicItem';
+export { default as TopicList } from './TopicList';
+export { default as TopicUrlSync } from './TopicUrlSync';
diff --git a/src/features/GenerationTopicPanel/index.tsx b/src/features/GenerationTopicPanel/index.tsx
new file mode 100644
index 00000000000..6d7a68c2f19
--- /dev/null
+++ b/src/features/GenerationTopicPanel/index.tsx
@@ -0,0 +1,86 @@
+'use client';
+
+import { DraggablePanel, DraggablePanelContainer, type DraggablePanelProps } from '@lobehub/ui';
+import { createStaticStyles, cssVar, useResponsive } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { type PropsWithChildren, memo, useEffect, useState } from 'react';
+
+export const styles = createStaticStyles(({ css }) => ({
+ content: css`
+ height: 100%;
+ background: ${cssVar.colorBgContainer};
+ `,
+ handle: css`
+ background: ${cssVar.colorBgContainer} !important;
+ `,
+}));
+
+interface GenerationTopicPanelProps extends PropsWithChildren {
+ onExpandChange: (expand: boolean) => void;
+ onSizeChange: (width: number) => void;
+ panelWidth: number;
+ showPanel: boolean;
+}
+
+const GenerationTopicPanel = memo<GenerationTopicPanelProps>(
+ ({ children, panelWidth, showPanel, onExpandChange, onSizeChange }) => {
+ const { md = true } = useResponsive();
+
+ const [tmpWidth, setWidth] = useState(panelWidth);
+ if (tmpWidth !== panelWidth) setWidth(panelWidth);
+ const [cacheExpand, setCacheExpand] = useState<boolean>(Boolean(showPanel));
+
+ const handleExpand = (expand: boolean) => {
+ if (isEqual(expand, showPanel)) return;
+ onExpandChange(expand);
+ setCacheExpand(expand);
+ };
+
+ useEffect(() => {
+ if (md && cacheExpand) onExpandChange(true);
+ if (!md) onExpandChange(false);
+ }, [md, cacheExpand]);
+
+ const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {
+ if (!size) return;
+ const nextWidth = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;
+ if (!nextWidth) return;
+
+ if (isEqual(nextWidth, panelWidth)) return;
+ setWidth(nextWidth);
+ onSizeChange(nextWidth);
+ };
+
+ return (
+ <DraggablePanel
+ classNames={{
+ content: styles.content,
+ handle: styles.handle,
+ }}
+ defaultSize={{ width: tmpWidth }}
+ expand={showPanel}
+ maxWidth={320}
+ minWidth={80}
+ mode={md ? 'fixed' : 'float'}
+ onExpandChange={handleExpand}
+ onSizeChange={handleSizeChange}
+ placement="right"
+ size={{ height: '100%', width: panelWidth }}
+ >
+ <DraggablePanelContainer
+ style={{
+ flex: 'none',
+ height: '100%',
+ minWidth: 80,
+ }}
+ >
+ {children}
+ </DraggablePanelContainer>
+ </DraggablePanel>
+ );
+ },
+);
+
+GenerationTopicPanel.displayName = 'GenerationTopicPanel';
+
+export default GenerationTopicPanel;
diff --git a/src/features/ImageTopicPanel/index.tsx b/src/features/ImageTopicPanel/index.tsx
index 9745fd066f3..d1d01468456 100644
--- a/src/features/ImageTopicPanel/index.tsx
+++ b/src/features/ImageTopicPanel/index.tsx
@@ -1,84 +1,31 @@
'use client';
-import { type DraggablePanelProps } from '@lobehub/ui';
-import { DraggablePanel, DraggablePanelContainer } from '@lobehub/ui';
-import { createStaticStyles, cssVar, useResponsive } from 'antd-style';
-import isEqual from 'fast-deep-equal';
import { type PropsWithChildren } from 'react';
-import { memo, useEffect, useState } from 'react';
+import { memo } from 'react';
+import GenerationTopicPanel from '@/features/GenerationTopicPanel';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-export const styles = createStaticStyles(({ css }) => ({
- content: css`
- height: 100%;
- background: ${cssVar.colorBgContainer};
- `,
- handle: css`
- background: ${cssVar.colorBgContainer} !important;
- `,
-}));
-
const ImageTopicPanel = memo<PropsWithChildren>(({ children }) => {
- const { md = true } = useResponsive();
const [imageTopicPanelWidth, showImageTopicPanel, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.imageTopicPanelWidth(s),
systemStatusSelectors.showImageTopicPanel(s),
s.updateSystemStatus,
]);
- const [tmpWidth, setWidth] = useState(imageTopicPanelWidth);
- if (tmpWidth !== imageTopicPanelWidth) setWidth(imageTopicPanelWidth);
- const [cacheExpand, setCacheExpand] = useState<boolean>(Boolean(showImageTopicPanel));
-
- const handleExpand = (expand: boolean) => {
- if (isEqual(expand, showImageTopicPanel)) return;
- updateSystemStatus({ showImageTopicPanel: expand });
- setCacheExpand(expand);
- };
- useEffect(() => {
- if (md && cacheExpand) updateSystemStatus({ showImageTopicPanel: true });
- if (!md) updateSystemStatus({ showImageTopicPanel: false });
- }, [md, cacheExpand]);
-
- const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {
- if (!size) return;
- const nextWidth = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;
- if (!nextWidth) return;
-
- if (isEqual(nextWidth, imageTopicPanelWidth)) return;
- setWidth(nextWidth);
- updateSystemStatus({ imageTopicPanelWidth: nextWidth });
- };
-
return (
- <DraggablePanel
- defaultSize={{ width: tmpWidth }}
- expand={showImageTopicPanel}
- maxWidth={320}
- minWidth={80}
- mode={md ? 'fixed' : 'float'}
- placement="right"
- size={{ height: '100%', width: imageTopicPanelWidth }}
- classNames={{
- content: styles.content,
- handle: styles.handle,
- }}
- onExpandChange={handleExpand}
- onSizeChange={handleSizeChange}
+ <GenerationTopicPanel
+ onExpandChange={(expand) => updateSystemStatus({ showImageTopicPanel: expand })}
+ onSizeChange={(width) => updateSystemStatus({ imageTopicPanelWidth: width })}
+ panelWidth={imageTopicPanelWidth ?? 256}
+ showPanel={showImageTopicPanel ?? true}
>
- <DraggablePanelContainer
- style={{
- flex: 'none',
- height: '100%',
- minWidth: 80,
- }}
- >
- {children}
- </DraggablePanelContainer>
- </DraggablePanel>
+ {children}
+ </GenerationTopicPanel>
);
});
+ImageTopicPanel.displayName = 'ImageTopicPanel';
+
export default ImageTopicPanel;
diff --git a/src/hooks/useFetchAiVideoConfig.ts b/src/hooks/useFetchAiVideoConfig.ts
new file mode 100644
index 00000000000..788cb3db4df
--- /dev/null
+++ b/src/hooks/useFetchAiVideoConfig.ts
@@ -0,0 +1,88 @@
+import { useEffect, useMemo } from 'react';
+
+import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useVideoStore } from '@/store/video';
+import {
+ DEFAULT_AI_VIDEO_MODEL,
+ DEFAULT_AI_VIDEO_PROVIDER,
+} from '@/store/video/slices/generationConfig/initialState';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+const checkModelEnabled = (
+ enabledVideoModelList: ReturnType<typeof aiProviderSelectors.enabledVideoModelList>,
+ provider: string,
+ model: string,
+) => {
+ return enabledVideoModelList.some(
+ (p) => p.id === provider && p.children.some((m) => m.id === model),
+ );
+};
+
+export const useFetchAiVideoConfig = () => {
+ const isStatusInit = useGlobalStore(systemStatusSelectors.isStatusInit);
+ const isInitAiProviderRuntimeState = useAiInfraStore(
+ aiProviderSelectors.isInitAiProviderRuntimeState,
+ );
+
+ const isAuthLoaded = useUserStore(authSelectors.isLoaded);
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const isActualLogout = isAuthLoaded && isLogin === false;
+
+ const isUserStateInit = useUserStore((s) => s.isUserStateInit);
+ const isUserStateReady = isUserStateInit || isActualLogout;
+
+ const isReadyForInit = isStatusInit && isInitAiProviderRuntimeState && isUserStateReady;
+
+ const { lastSelectedVideoModel, lastSelectedVideoProvider } = useGlobalStore((s) => ({
+ lastSelectedVideoModel: s.status.lastSelectedVideoModel,
+ lastSelectedVideoProvider: s.status.lastSelectedVideoProvider,
+ }));
+ const isInitializedVideoConfig = useVideoStore((s) => s.isInit);
+ const initializeVideoConfig = useVideoStore((s) => s.initializeVideoConfig);
+
+ const enabledVideoModelList = useAiInfraStore(aiProviderSelectors.enabledVideoModelList);
+
+ // Determine which model/provider to use for initialization
+ const initParams = useMemo(() => {
+ // 1. Try lastSelected if enabled
+ if (
+ lastSelectedVideoModel &&
+ lastSelectedVideoProvider &&
+ checkModelEnabled(enabledVideoModelList, lastSelectedVideoProvider, lastSelectedVideoModel)
+ ) {
+ return { model: lastSelectedVideoModel, provider: lastSelectedVideoProvider };
+ }
+
+ // 2. Try default model from any enabled provider (prefer default provider first)
+ if (
+ checkModelEnabled(enabledVideoModelList, DEFAULT_AI_VIDEO_PROVIDER, DEFAULT_AI_VIDEO_MODEL)
+ ) {
+ return { model: undefined, provider: undefined }; // Use initialState defaults
+ }
+ const providerWithDefaultModel = enabledVideoModelList.find((p) =>
+ p.children.some((m) => m.id === DEFAULT_AI_VIDEO_MODEL),
+ );
+ if (providerWithDefaultModel) {
+ return { model: DEFAULT_AI_VIDEO_MODEL, provider: providerWithDefaultModel.id };
+ }
+
+ // 3. Fallback to first enabled model
+ const firstProvider = enabledVideoModelList[0];
+ const firstModel = firstProvider?.children[0];
+ if (firstProvider && firstModel) {
+ return { model: firstModel.id, provider: firstProvider.id };
+ }
+
+ // No enabled models
+ return { model: undefined, provider: undefined };
+ }, [lastSelectedVideoModel, lastSelectedVideoProvider, enabledVideoModelList]);
+
+ useEffect(() => {
+ if (!isInitializedVideoConfig && isReadyForInit) {
+ initializeVideoConfig(isLogin, initParams.model, initParams.provider);
+ }
+ }, [isReadyForInit, isInitializedVideoConfig, isLogin, initParams, initializeVideoConfig]);
+};
diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.ts
index 78e47c8709a..ac95f35ba99 100644
--- a/src/libs/next/config/define-config.ts
+++ b/src/libs/next/config/define-config.ts
@@ -9,6 +9,7 @@ interface CustomNextConfig {
experimental?: NextConfig['experimental'];
headers?: Header[];
outputFileTracingExcludes?: NextConfig['outputFileTracingExcludes'];
+ outputFileTracingIncludes?: NextConfig['outputFileTracingIncludes'];
redirects?: Redirect[];
serverExternalPackages?: NextConfig['serverExternalPackages'];
turbopack?: NextConfig['turbopack'];
@@ -260,6 +261,9 @@ export function defineConfig(config: CustomNextConfig) {
...(config.outputFileTracingExcludes && {
outputFileTracingExcludes: config.outputFileTracingExcludes,
}),
+ ...(config.outputFileTracingIncludes && {
+ outputFileTracingIncludes: config.outputFileTracingIncludes,
+ }),
reactStrictMode: true,
redirects: async () => [
{
diff --git a/src/locales/default/common.ts b/src/locales/default/common.ts
index 845ef6a6380..7c5cec9d8b2 100644
--- a/src/locales/default/common.ts
+++ b/src/locales/default/common.ts
@@ -183,6 +183,8 @@ export default {
'cmdk.keywords.usage': 'usage statistics consumption quota',
+ 'cmdk.keywords.video': 'video,generate,seedance,kling',
+
'cmdk.memory': 'Memory',
'cmdk.mentionAgent': 'Mention Agent',
@@ -259,6 +261,8 @@ export default {
'cmdk.toOpen': 'Open',
'cmdk.toSelect': 'Select',
+ 'cmdk.video': 'AI Video',
+
'confirm': 'Confirm',
'contact': 'Contact Us',
'copy': 'Copy',
diff --git a/src/locales/default/home.ts b/src/locales/default/home.ts
index 4545cb89b42..8bcd90f0839 100644
--- a/src/locales/default/home.ts
+++ b/src/locales/default/home.ts
@@ -11,5 +11,6 @@ export default {
'starter.deepResearch': 'Deep Research',
'starter.developing': 'Coming soon',
'starter.image': 'Image',
+ 'starter.seedance': 'Seedance 2.0',
'starter.write': 'Write',
};
diff --git a/src/locales/default/index.ts b/src/locales/default/index.ts
index fa2f1562643..c1dbafec152 100644
--- a/src/locales/default/index.ts
+++ b/src/locales/default/index.ts
@@ -37,6 +37,7 @@ import thread from './thread';
import tool from './tool';
import topic from './topic';
import ui from './ui';
+import video from './video';
import welcome from './welcome';
const resources = {
@@ -81,6 +82,7 @@ const resources = {
tool,
topic,
ui,
+ video,
welcome,
} as const;
diff --git a/src/locales/default/modelProvider.ts b/src/locales/default/modelProvider.ts
index 413f06cca4b..1a33638f16f 100644
--- a/src/locales/default/modelProvider.ts
+++ b/src/locales/default/modelProvider.ts
@@ -318,8 +318,8 @@ export default {
'providerModels.item.modelConfig.type.options.realtime': 'Real-time Chat',
'providerModels.item.modelConfig.type.options.stt': 'Speech-to-Text',
'providerModels.item.modelConfig.type.options.text2music': 'Text-to-Music',
- 'providerModels.item.modelConfig.type.options.text2video': 'Text-to-Video',
'providerModels.item.modelConfig.type.options.tts': 'Text-to-Speech',
+ 'providerModels.item.modelConfig.type.options.video': 'Video Generation',
'providerModels.item.modelConfig.type.placeholder': 'Please select a model type',
'providerModels.item.modelConfig.type.title': 'Model Type',
'providerModels.item.modelConfig.video.extra':
diff --git a/src/locales/default/spend.ts b/src/locales/default/spend.ts
index ea1acc99ca5..aa439fe2276 100644
--- a/src/locales/default/spend.ts
+++ b/src/locales/default/spend.ts
@@ -14,6 +14,7 @@ export default {
'table.columns.totalTokens': 'Token Usage',
'table.columns.type.enums.chat': 'Text Generation',
'table.columns.type.enums.imageGeneration': 'Image Generation',
+ 'table.columns.type.enums.videoGeneration': 'Video Generation',
'table.columns.type.title': 'Type',
'table.desc': 'Details of computing credits usage for text generation, embedding, image generation, etc.',
'table.more': 'View Details',
diff --git a/src/locales/default/subscription.ts b/src/locales/default/subscription.ts
index 718a68061c8..f69b18e334d 100644
--- a/src/locales/default/subscription.ts
+++ b/src/locales/default/subscription.ts
@@ -128,6 +128,14 @@ export default {
'limitation.image.topupSuccess.desc':
'Your top-up credits are now active. Enjoy AI image generation. Your current plan includes:',
'limitation.image.topupSuccess.title': 'Top-up Successful',
+ 'limitation.video.success.action': 'Continue Generating',
+ 'limitation.video.success.desc':
+ 'Your {{plan}} subscription has been upgraded successfully. Enjoy AI video generation. Your current plan includes:',
+ 'limitation.video.success.title': 'Upgrade Successful',
+ 'limitation.video.topupSuccess.action': 'Continue Generating',
+ 'limitation.video.topupSuccess.desc':
+ 'Your top-up credits are now active. Enjoy AI video generation. Your current plan includes:',
+ 'limitation.video.topupSuccess.title': 'Top-up Successful',
'limitation.limited.action': 'Upgrade Now',
'limitation.limited.advanceFeature': 'Upgrade to enjoy premium features:',
'limitation.limited.desc':
diff --git a/src/locales/default/video.ts b/src/locales/default/video.ts
new file mode 100644
index 00000000000..bb29f958795
--- /dev/null
+++ b/src/locales/default/video.ts
@@ -0,0 +1,29 @@
+export default {
+ '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.imageUrl.label': 'Start Frame',
+ 'config.prompt.placeholder': 'Describe the video you want to generate',
+ 'config.referenceImage.label': 'Reference Image',
+ 'config.resolution.label': 'Resolution',
+ 'config.seed.label': 'Seed',
+ 'config.seed.random': 'Random',
+ 'generation.actions.copyError': 'Copy Error Message',
+ 'generation.actions.errorCopied': 'Error Message Copied to Clipboard',
+ 'generation.actions.errorCopyFailed': 'Failed to Copy Error Message',
+ 'generation.actions.generate': 'Generate',
+ 'generation.validation.endFrameRequiresStartFrame':
+ 'End frame cannot be used without a start frame. Please set a start frame first.',
+ 'generation.status.failed': 'Generation Failed',
+ 'generation.status.generating': 'Generating...',
+ 'topic.createNew': 'New Topic',
+ 'topic.deleteConfirm': 'Delete Video Topic',
+ 'topic.deleteConfirmDesc':
+ 'You are about to delete this video topic. This action cannot be undone.',
+ 'topic.empty': 'No video topics',
+ 'topic.title': 'Video Topics',
+ 'topic.untitled': 'Default Topic',
+} as const;
diff --git a/src/server/modules/S3/index.ts b/src/server/modules/S3/index.ts
index 4ce9f600915..4dfb0c7e3d6 100644
--- a/src/server/modules/S3/index.ts
+++ b/src/server/modules/S3/index.ts
@@ -9,9 +9,10 @@ import {
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { z } from 'zod';
+import mime from 'mime';
+
import { fileEnv } from '@/envs/file';
import { YEAR } from '@/utils/units';
-import { inferContentTypeFromImageUrl } from '@/utils/url';
export const fileSchema = z.object({
Key: z.string(),
@@ -178,12 +179,13 @@ export class S3 {
}
public async uploadMedia(key: string, buffer: Buffer) {
+ const contentType = mime.getType(key) || 'application/octet-stream';
const command = new PutObjectCommand({
ACL: this.setAcl ? 'public-read' : undefined,
Body: buffer,
Bucket: this.bucket,
CacheControl: `public, max-age=${YEAR}`,
- ContentType: inferContentTypeFromImageUrl(key)!,
+ ContentType: contentType,
Key: key,
});
diff --git a/src/server/routers/lambda/__tests__/aiProvider.test.ts b/src/server/routers/lambda/__tests__/aiProvider.test.ts
index d4b25ea90e9..2836a007629 100644
--- a/src/server/routers/lambda/__tests__/aiProvider.test.ts
+++ b/src/server/routers/lambda/__tests__/aiProvider.test.ts
@@ -38,8 +38,9 @@ describe('aiProviderRouter', () => {
enabledAiModels: [],
enabledAiProviders: [],
enabledChatAiProviders: [],
- runtimeConfig: {},
enabledImageAiProviders: [],
+ enabledVideoAiProviders: [],
+ runtimeConfig: {},
};
beforeEach(() => {
diff --git a/src/server/routers/lambda/generationTopic.ts b/src/server/routers/lambda/generationTopic.ts
index 068da4f9c0a..bd81079ed52 100644
--- a/src/server/routers/lambda/generationTopic.ts
+++ b/src/server/routers/lambda/generationTopic.ts
@@ -34,10 +34,12 @@ const updateTopicCoverSchema = z.object({
});
export const generationTopicRouter = router({
- createTopic: generationTopicProcedure.input(z.void()).mutation(async ({ ctx }) => {
- const data = await ctx.generationTopicModel.create('');
- return data.id;
- }),
+ createTopic: generationTopicProcedure
+ .input(z.object({ type: z.enum(['image', 'video']).optional() }).optional())
+ .mutation(async ({ ctx, input }) => {
+ const data = await ctx.generationTopicModel.create('', input?.type);
+ return data.id;
+ }),
deleteTopic: generationTopicProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
@@ -66,9 +68,11 @@ export const generationTopicRouter = router({
return deletedTopic;
}),
- getAllGenerationTopics: generationTopicProcedure.query(async ({ ctx }) => {
- return ctx.generationTopicModel.queryAll();
- }),
+ getAllGenerationTopics: generationTopicProcedure
+ .input(z.object({ type: z.enum(['image', 'video']).optional() }).optional())
+ .query(async ({ ctx, input }) => {
+ return ctx.generationTopicModel.queryAll(input?.type);
+ }),
updateTopic: generationTopicProcedure
.input(updateTopicSchema)
.mutation(async ({ ctx, input }) => {
diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.ts
index 73ba0402ebb..53794d748fe 100644
--- a/src/server/routers/lambda/index.ts
+++ b/src/server/routers/lambda/index.ts
@@ -47,6 +47,7 @@ import { usageRouter } from './usage';
import { userRouter } from './user';
import { userMemoriesRouter } from './userMemories';
import { userMemoryRouter } from './userMemory';
+import { videoRouter } from './video';
export const lambdaRouter = router({
agent: agentRouter,
@@ -89,6 +90,7 @@ export const lambdaRouter = router({
user: userRouter,
userMemories: userMemoriesRouter,
userMemory: userMemoryRouter,
+ video: videoRouter,
/* eslint-disable sort-keys-fix/sort-keys-fix */
accountDeletion: accountDeletionRouter,
referral: referralRouter,
diff --git a/src/server/routers/lambda/video/index.ts b/src/server/routers/lambda/video/index.ts
new file mode 100644
index 00000000000..fda694a0568
--- /dev/null
+++ b/src/server/routers/lambda/video/index.ts
@@ -0,0 +1,243 @@
+import debug from 'debug';
+import { and, eq } from 'drizzle-orm';
+import { z } from 'zod';
+
+import { chargeBeforeGenerate } from '@/business/server/video-generation/chargeBeforeGenerate';
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import {
+ asyncTasks,
+ generationBatches,
+ generations,
+ type NewGeneration,
+ type NewGenerationBatch,
+} from '@/database/schemas';
+import { appEnv } from '@/envs/app';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { keyVaults, serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { FileService } from '@/server/services/file';
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ AsyncTaskType,
+} from '@/types/asyncTask';
+
+const log = debug('lobe-video:lambda');
+
+const videoProcedure = authedProcedure
+ .use(keyVaults)
+ .use(serverDatabase)
+ .use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),
+ fileService: new FileService(ctx.serverDB, ctx.userId),
+ },
+ });
+ });
+
+const createVideoInputSchema = z.object({
+ generationTopicId: z.string(),
+ model: z.string(),
+ params: z
+ .object({
+ aspectRatio: z.string().optional(),
+ cameraFixed: z.boolean().optional(),
+ duration: z.number().optional(),
+ endImageUrl: z.string().nullable().optional(),
+ generateAudio: z.boolean().optional(),
+ imageUrl: z.string().nullable().optional(),
+ prompt: z.string(),
+ resolution: z.string().optional(),
+ seed: z.number().nullable().optional(),
+ })
+ .passthrough(),
+ provider: z.string(),
+});
+export type CreateVideoServicePayload = z.infer<typeof createVideoInputSchema>;
+
+export const videoRouter = router({
+ createVideo: videoProcedure.input(createVideoInputSchema).mutation(async ({ input, ctx }) => {
+ const { userId, serverDB, asyncTaskModel, fileService } = ctx;
+ const { generationTopicId, provider, model, params } = input;
+
+ log('Starting video creation process, input: %O', input);
+
+ // Normalize image URLs to S3 keys for database storage
+ let configForDatabase = { ...params };
+
+ // Process first-frame imageUrl
+ if (typeof params.imageUrl === 'string' && params.imageUrl) {
+ try {
+ const key = await fileService.getKeyFromFullUrl(params.imageUrl);
+ if (key) {
+ log('Converted imageUrl to key: %s -> %s', params.imageUrl, key);
+ configForDatabase = { ...configForDatabase, imageUrl: key };
+ }
+ } catch (error) {
+ console.error('Error converting imageUrl to key: %O', error);
+ }
+ }
+
+ // Process last-frame endImageUrl
+ if (typeof params.endImageUrl === 'string' && params.endImageUrl) {
+ try {
+ const key = await fileService.getKeyFromFullUrl(params.endImageUrl);
+ if (key) {
+ log('Converted endImageUrl to key: %s -> %s', params.endImageUrl, key);
+ configForDatabase = { ...configForDatabase, endImageUrl: key };
+ }
+ } catch (error) {
+ console.error('Error converting endImageUrl to key: %O', error);
+ }
+ }
+
+ // In development, convert localhost proxy URLs to S3 URLs for API access
+ let generationParams = params;
+ if (process.env.NODE_ENV === 'development') {
+ const updates: Record<string, unknown> = {};
+
+ if (typeof params.imageUrl === 'string' && params.imageUrl) {
+ const s3Url = await fileService.getFullFileUrl(configForDatabase.imageUrl as string);
+ if (s3Url) {
+ log('Dev: converted imageUrl proxy URL to S3 URL: %s -> %s', params.imageUrl, s3Url);
+ updates.imageUrl = s3Url;
+ }
+ }
+
+ if (typeof params.endImageUrl === 'string' && params.endImageUrl) {
+ const s3Url = await fileService.getFullFileUrl(configForDatabase.endImageUrl as string);
+ if (s3Url) {
+ log(
+ 'Dev: converted endImageUrl proxy URL to S3 URL: %s -> %s',
+ params.endImageUrl,
+ s3Url,
+ );
+ updates.endImageUrl = s3Url;
+ }
+ }
+
+ if (Object.keys(updates).length > 0) {
+ generationParams = { ...params, ...updates };
+ }
+ }
+
+ // Step 0: Pre-charge (atomic budget deduction to prevent concurrent abuse)
+ const { errorBatch, prechargeResult } = await chargeBeforeGenerate({
+ generationTopicId,
+ model,
+ params,
+ provider,
+ userId,
+ });
+ if (errorBatch) return errorBatch;
+
+ // Step 1: Atomically create all database records in a transaction
+ const {
+ batch: createdBatch,
+ generation: createdGeneration,
+ asyncTaskId,
+ } = await serverDB.transaction(async (tx) => {
+ log('Starting database transaction for video generation');
+
+ // 1. Create generationBatch
+ const newBatch: NewGenerationBatch = {
+ config: configForDatabase,
+ generationTopicId,
+ model,
+ prompt: params.prompt,
+ provider,
+ userId,
+ };
+ log('Creating generation batch: %O', newBatch);
+ const [batch] = await tx.insert(generationBatches).values(newBatch).returning();
+ log('Generation batch created: %s', batch.id);
+
+ // 2. Create single generation (video is always 1)
+ const newGeneration: NewGeneration = {
+ generationBatchId: batch.id,
+ seed: params.seed ?? null,
+ userId,
+ };
+ const [generation] = await tx.insert(generations).values(newGeneration).returning();
+ log('Generation created: %s', generation.id);
+
+ // 3. Create asyncTask with precharge metadata
+ const [asyncTask] = await tx
+ .insert(asyncTasks)
+ .values({
+ metadata: prechargeResult ? { precharge: prechargeResult } : {},
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.VideoGeneration,
+ userId,
+ })
+ .returning();
+ log('Async task created: %s', asyncTask.id);
+
+ // 4. Link asyncTask to generation
+ await tx
+ .update(generations)
+ .set({ asyncTaskId: asyncTask.id })
+ .where(and(eq(generations.id, generation.id), eq(generations.userId, userId)));
+
+ return {
+ asyncTaskId: asyncTask.id,
+ batch,
+ generation,
+ };
+ });
+
+ log('Database transaction completed. Calling model runtime for video generation.');
+
+ // Step 2: Call model runtime to submit video generation task
+ try {
+ const modelRuntime = await initModelRuntimeFromDB(serverDB, userId, provider);
+
+ const callbackBaseUrl = process.env.WEBHOOK_PROXY_URL || appEnv.APP_URL;
+ const callbackUrl = `${callbackBaseUrl}/api/webhooks/video/${provider}`;
+ log('Using callback URL: %s', callbackUrl);
+
+ const response = await modelRuntime.createVideo({
+ callbackUrl,
+ model,
+ params: generationParams,
+ });
+
+ log('Video task submitted successfully, inferenceId: %s', response?.inferenceId);
+
+ // Update asyncTask with inferenceId and set status to Processing
+ await asyncTaskModel.update(asyncTaskId, {
+ inferenceId: response?.inferenceId,
+ status: AsyncTaskStatus.Processing,
+ });
+ } catch (e) {
+ console.error('Failed to submit video generation task:', e);
+
+ await asyncTaskModel.update(asyncTaskId, {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.TaskTriggerError,
+ 'Failed to submit video task: ' + (e instanceof Error ? e.message : 'Unknown error'),
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ }
+
+ log('Video creation process completed: %O', {
+ batchId: createdBatch.id,
+ generationId: createdGeneration.id,
+ });
+
+ return {
+ data: {
+ batch: createdBatch,
+ generations: [createdGeneration],
+ },
+ success: true,
+ };
+ }),
+});
+
+export type VideoRouter = typeof videoRouter;
diff --git a/src/server/services/generation/video.ts b/src/server/services/generation/video.ts
new file mode 100644
index 00000000000..25e680e4ea8
--- /dev/null
+++ b/src/server/services/generation/video.ts
@@ -0,0 +1,239 @@
+import { execFile } from 'node:child_process';
+import { createWriteStream, promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { Readable } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import { promisify } from 'node:util';
+
+import { type LobeChatDatabase } from '@lobechat/database';
+import debug from 'debug';
+import { sha256 } from 'js-sha256';
+import { nanoid } from 'nanoid';
+import sharp from 'sharp';
+
+import { FileService } from '@/server/services/file';
+import { calculateThumbnailDimensions } from '@/utils/number';
+import { getYYYYmmddHHMMss } from '@/utils/time';
+
+const log = debug('lobe-video:generation-service');
+const execFileAsync = promisify(execFile);
+
+let _ffmpegPath: string | null = null;
+
+function getFfmpegPath(): string {
+ if (_ffmpegPath) return _ffmpegPath;
+ _ffmpegPath = require('ffmpeg-static') as string;
+ return _ffmpegPath;
+}
+
+interface VideoMetadata {
+ duration: number;
+ height: number;
+ width: number;
+}
+
+export interface VideoProcessResult {
+ coverKey: string;
+ duration: number;
+ fileHash: string;
+ fileSize: number;
+ height: number;
+ mimeType: string;
+ thumbnailKey: string;
+ videoKey: string;
+ width: number;
+}
+
+export class VideoGenerationService {
+ private fileService: FileService;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.fileService = new FileService(db, userId);
+ }
+
+ /**
+ * Download video, extract metadata, generate cover/thumbnail, upload all to S3
+ */
+ async processVideoForGeneration(videoUrl: string): Promise<VideoProcessResult> {
+ log('Processing video from URL: %s', videoUrl);
+
+ let tempVideoPath: string | null = null;
+ let tempCoverPath: string | null = null;
+
+ try {
+ tempVideoPath = await this.downloadVideo(videoUrl);
+
+ const [metadata, videoBuffer] = await Promise.all([
+ this.getVideoMetadata(tempVideoPath),
+ fs.readFile(tempVideoPath),
+ ]);
+
+ log('Video metadata: %O', metadata);
+
+ const fileHash = sha256(videoBuffer);
+ const fileSize = videoBuffer.length;
+
+ // Determine MIME type from URL or default to mp4
+ const ext = path.extname(new URL(videoUrl).pathname).toLowerCase();
+ const mimeType = ext === '.webm' ? 'video/webm' : 'video/mp4';
+ const videoExt = ext || '.mp4';
+
+ // Generate S3 keys
+ const uuid = nanoid();
+ const dateTime = getYYYYmmddHHMMss(new Date());
+ const generationsFolder = 'generations/videos';
+
+ // Upload video
+ const videoKey = `${generationsFolder}/${uuid}_${metadata.width}x${metadata.height}_${dateTime}_raw${videoExt}`;
+ log('Uploading video to: %s', videoKey);
+ await this.fileService.uploadMedia(videoKey, videoBuffer);
+
+ // Generate cover screenshot and thumbnail
+ tempCoverPath = await this.generateScreenshot(tempVideoPath, metadata.width, metadata.height);
+ const coverBuffer = await fs.readFile(tempCoverPath);
+
+ // Convert cover to webp
+ const coverWebpBuffer = await sharp(coverBuffer).webp({ quality: 100 }).toBuffer();
+ const coverKey = `${generationsFolder}/${uuid}_${metadata.width}x${metadata.height}_${dateTime}_cover.webp`;
+ log('Uploading cover to: %s', coverKey);
+
+ // Calculate thumbnail dimensions
+ const { shouldResize, thumbnailWidth, thumbnailHeight } = calculateThumbnailDimensions(
+ metadata.width,
+ metadata.height,
+ );
+
+ let thumbnailKey: string;
+
+ if (shouldResize) {
+ const thumbnailBuffer = await sharp(coverBuffer)
+ .resize(thumbnailWidth, thumbnailHeight, {
+ fit: 'inside',
+ withoutEnlargement: true,
+ })
+ .webp({ quality: 100 })
+ .toBuffer();
+
+ thumbnailKey = `${generationsFolder}/${uuid}_${thumbnailWidth}x${thumbnailHeight}_${dateTime}_thumb.webp`;
+ log('Uploading thumbnail to: %s', thumbnailKey);
+
+ // Upload cover and thumbnail in parallel
+ await Promise.all([
+ this.fileService.uploadMedia(coverKey, coverWebpBuffer),
+ this.fileService.uploadMedia(thumbnailKey, thumbnailBuffer),
+ ]);
+ } else {
+ // Cover and thumbnail are the same size, reuse the same key
+ thumbnailKey = coverKey;
+ await this.fileService.uploadMedia(coverKey, coverWebpBuffer);
+ }
+
+ log('Video processing completed successfully');
+
+ return {
+ coverKey,
+ duration: metadata.duration,
+ fileHash,
+ fileSize,
+ height: metadata.height,
+ mimeType,
+ thumbnailKey,
+ videoKey,
+ width: metadata.width,
+ };
+ } finally {
+ // Clean up temp files
+ if (tempVideoPath) {
+ await fs.unlink(tempVideoPath).catch((err) => {
+ log('Failed to cleanup temp video file: %O', err);
+ });
+ }
+ if (tempCoverPath) {
+ await fs.unlink(tempCoverPath).catch((err) => {
+ log('Failed to cleanup temp cover file: %O', err);
+ });
+ }
+ }
+ }
+
+ private async downloadVideo(url: string): Promise<string> {
+ const ext = path.extname(new URL(url).pathname).toLowerCase() || '.mp4';
+ const tempVideoPath = path.join(os.tmpdir(), `lobe-video-${nanoid()}${ext}`);
+ log('Downloading video to: %s', tempVideoPath);
+
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to download video: ${response.status} ${response.statusText}`);
+ }
+
+ if (!response.body) {
+ throw new Error(`Response body is empty for video URL: ${url}`);
+ }
+
+ await pipeline(Readable.fromWeb(response.body as any), createWriteStream(tempVideoPath));
+
+ log('Video downloaded successfully');
+ return tempVideoPath;
+ }
+
+ private async getVideoMetadata(videoPath: string): Promise<VideoMetadata> {
+ const ffmpegPath = getFfmpegPath();
+
+ // ffmpeg -i exits with code 1 when no output is specified, but stderr contains metadata
+ let stderr = '';
+ try {
+ const result = await execFileAsync(ffmpegPath, ['-i', videoPath, '-hide_banner']);
+ stderr = result.stderr;
+ } catch (error: any) {
+ stderr = error.stderr || '';
+ // Exit code 1 is expected when no output is specified
+ if (!stderr) throw error;
+ }
+
+ // Parse duration: "Duration: 00:05:30.12"
+ const durationMatch = stderr.match(/Duration:\s*(\d+):(\d+):([\d.]+)/);
+ const duration = durationMatch
+ ? Number.parseInt(durationMatch[1]) * 3600 +
+ Number.parseInt(durationMatch[2]) * 60 +
+ Number.parseFloat(durationMatch[3])
+ : 0;
+
+ // Parse video stream dimensions: "Stream #0:0...: Video: ..., 1920x1080"
+ const streamMatch = stderr.match(/Stream.*Video.*?(\d{2,5})x(\d{2,5})/);
+ if (!streamMatch) {
+ throw new Error(`Failed to parse video dimensions from ffmpeg output:\n${stderr}`);
+ }
+
+ return {
+ duration,
+ height: Number.parseInt(streamMatch[2]),
+ width: Number.parseInt(streamMatch[1]),
+ };
+ }
+
+ /**
+ * Take a screenshot at 0.1s and return the temp file path
+ */
+ private async generateScreenshot(
+ videoPath: string,
+ width: number,
+ height: number,
+ ): Promise<string> {
+ const ffmpegPath = getFfmpegPath();
+ const outputPath = path.join(os.tmpdir(), `lobe-cover-${nanoid()}.jpg`);
+
+ log('Generating screenshot from video');
+
+ await execFileAsync(ffmpegPath, [
+ '-ss', '0.1',
+ '-i', videoPath,
+ '-frames:v', '1',
+ '-s', `${width}x${height}`,
+ '-y',
+ outputPath,
+ ]);
+
+ return outputPath;
+ }
+}
diff --git a/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts b/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts
index 4b1836ca845..0ac92368a1a 100644
--- a/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts
+++ b/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts
@@ -12,6 +12,7 @@ const createRuntimeState = (models: EnabledAiModel[], keyVaults: Record<string,
enabledAiProviders: [],
enabledChatAiProviders: [],
enabledImageAiProviders: [],
+ enabledVideoAiProviders: [],
runtimeConfig: Object.fromEntries(
Object.entries(keyVaults).map(([providerId, vault]) => [
providerId,
diff --git a/src/services/generationTopic.ts b/src/services/generationTopic.ts
index a94dc28167c..06e5b25f157 100644
--- a/src/services/generationTopic.ts
+++ b/src/services/generationTopic.ts
@@ -4,12 +4,12 @@ import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
import { type ImageGenerationTopic } from '@/types/generation';
export class ServerService {
- async getAllGenerationTopics(): Promise<ImageGenerationTopic[]> {
- return lambdaClient.generationTopic.getAllGenerationTopics.query();
+ async getAllGenerationTopics(type?: 'image' | 'video'): Promise<ImageGenerationTopic[]> {
+ return lambdaClient.generationTopic.getAllGenerationTopics.query(type ? { type } : undefined);
}
- async createTopic(): Promise<string> {
- return lambdaClient.generationTopic.createTopic.mutate(undefined);
+ async createTopic(type?: 'image' | 'video'): Promise<string> {
+ return lambdaClient.generationTopic.createTopic.mutate(type ? { type } : undefined);
}
async updateTopic(id: string, data: UpdateTopicValue): Promise<GenerationTopicItem | undefined> {
diff --git a/src/services/video.ts b/src/services/video.ts
new file mode 100644
index 00000000000..f489d6b24eb
--- /dev/null
+++ b/src/services/video.ts
@@ -0,0 +1,32 @@
+import debug from 'debug';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { type CreateVideoServicePayload } from '@/server/routers/lambda/video';
+
+const log = debug('lobe-video:service');
+
+export class AiVideoService {
+ async createVideo(payload: CreateVideoServicePayload) {
+ log('Creating video with payload: %O', payload);
+
+ try {
+ const result = await lambdaClient.video.createVideo.mutate(payload);
+ log('Video creation service call completed: %O', {
+ batchId: result.data?.batch?.id,
+ generationCount: result.data?.generations?.length,
+ success: result.success,
+ });
+
+ return result;
+ } catch (error) {
+ log('Video creation service call failed: %O', {
+ error: (error as Error).message,
+ payload,
+ });
+
+ throw error;
+ }
+ }
+}
+
+export const videoService = new AiVideoService();
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index 5679a9a5fd6..55ac14e2e28 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -126,12 +126,50 @@ export const normalizeImageModel = async (
};
};
+export const normalizeVideoModel = async (
+ model: EnabledAiModel,
+): Promise<ProviderModelListItem> => {
+ const fallbackParametersPromise = model.parameters
+ ? Promise.resolve<ModelParamsSchema | undefined>(model.parameters)
+ : getModelPropertyWithFallback<ModelParamsSchema | undefined>(
+ model.id,
+ 'parameters',
+ model.providerId,
+ );
+
+ const fallbackDescriptionPromise = getModelPropertyWithFallback<string | undefined>(
+ model.id,
+ 'description',
+ model.providerId,
+ );
+
+ const [fallbackParameters, fallbackDescription] = await Promise.all([
+ fallbackParametersPromise,
+ fallbackDescriptionPromise,
+ ]);
+
+ const parameters = model.parameters ?? fallbackParameters;
+ const description = fallbackDescription;
+
+ return {
+ abilities: (model.abilities || {}) as ModelAbilities,
+ contextWindowTokens: model.contextWindowTokens,
+ displayName: model.displayName ?? '',
+ id: model.id,
+ releasedAt: model.releasedAt,
+ ...(parameters && { parameters }),
+ ...(description && { description }),
+ };
+};
+
export const getChatModelList = createProviderModelCollector('chat', async (model) =>
normalizeChatModel(model),
);
export const getImageModelList = createProviderModelCollector('image', normalizeImageModel);
+export const getVideoModelList = createProviderModelCollector('video', normalizeVideoModel);
+
const buildProviderModelLists = async (
providers: EnabledProvider[],
enabledAiModels: EnabledAiModel[],
@@ -165,6 +203,14 @@ const buildChatProviderModelLists = async (
enabledAiModels: EnabledAiModel[],
) => buildProviderModelLists(providers, enabledAiModels, getChatModelList);
+/**
+ * Build video provider model lists with proper async handling
+ */
+const buildVideoProviderModelLists = async (
+ providers: EnabledProvider[],
+ enabledAiModels: EnabledAiModel[],
+) => buildProviderModelLists(providers, enabledAiModels, getVideoModelList);
+
enum AiProviderSwrKey {
fetchAiProviderItem = 'FETCH_AI_PROVIDER_ITEM',
fetchAiProviderList = 'FETCH_AI_PROVIDER',
@@ -175,6 +221,7 @@ type AiProviderRuntimeStateWithBuiltinModels = AiProviderRuntimeState & {
builtinAiModelList: LobeDefaultAiModelListItem[];
enabledChatModelList?: EnabledProviderWithModels[];
enabledImageModelList?: EnabledProviderWithModels[];
+ enabledVideoModelList?: EnabledProviderWithModels[];
};
type Setter = StoreSetter<AiInfraStore>;
@@ -418,16 +465,19 @@ export class AiProviderActionImpl {
if (isLogin) {
const data = await aiProviderService.getAiProviderRuntimeState();
// Build model lists with proper async handling
- const [enabledChatModelList, enabledImageModelList] = await Promise.all([
- buildChatProviderModelLists(data.enabledChatAiProviders, data.enabledAiModels),
- buildImageProviderModelLists(data.enabledImageAiProviders, data.enabledAiModels),
- ]);
+ const [enabledChatModelList, enabledImageModelList, enabledVideoModelList] =
+ await Promise.all([
+ buildChatProviderModelLists(data.enabledChatAiProviders, data.enabledAiModels),
+ buildImageProviderModelLists(data.enabledImageAiProviders, data.enabledAiModels),
+ buildVideoProviderModelLists(data.enabledVideoAiProviders, data.enabledAiModels),
+ ]);
return {
...data,
builtinAiModelList,
enabledChatModelList,
enabledImageModelList,
+ enabledVideoModelList,
};
}
@@ -449,12 +499,22 @@ export class AiProviderActionImpl {
})
.map((item) => ({ id: item.id, name: item.name, source: AiProviderSourceEnum.Builtin }));
+ const enabledVideoAiProviders = enabledAiProviders
+ .filter((provider) => {
+ return builtinAiModelList.some(
+ (model) => model.providerId === provider.id && model.type === 'video',
+ );
+ })
+ .map((item) => ({ id: item.id, name: item.name, source: AiProviderSourceEnum.Builtin }));
+
// Build model lists for non-login state as well
const enabledAiModels = builtinAiModelList.filter((m) => m.enabled);
- const [enabledChatModelList, enabledImageModelList] = await Promise.all([
- buildChatProviderModelLists(enabledChatAiProviders, enabledAiModels),
- buildImageProviderModelLists(enabledImageAiProviders, enabledAiModels),
- ]);
+ const [enabledChatModelList, enabledImageModelList, enabledVideoModelList] =
+ await Promise.all([
+ buildChatProviderModelLists(enabledChatAiProviders, enabledAiModels),
+ buildImageProviderModelLists(enabledImageAiProviders, enabledAiModels),
+ buildVideoProviderModelLists(enabledVideoAiProviders, enabledAiModels),
+ ]);
return {
builtinAiModelList,
@@ -464,6 +524,8 @@ export class AiProviderActionImpl {
enabledChatModelList,
enabledImageAiProviders,
enabledImageModelList,
+ enabledVideoAiProviders,
+ enabledVideoModelList,
runtimeConfig: {},
};
},
@@ -479,6 +541,7 @@ export class AiProviderActionImpl {
enabledAiProviders: data.enabledAiProviders,
enabledChatModelList: data.enabledChatModelList || [],
enabledImageModelList: data.enabledImageModelList || [],
+ enabledVideoModelList: data.enabledVideoModelList || [],
isInitAiProviderRuntimeState: true,
},
false,
diff --git a/src/store/aiInfra/slices/aiProvider/initialState.ts b/src/store/aiInfra/slices/aiProvider/initialState.ts
index 89b3901d626..7a7bb6949c1 100644
--- a/src/store/aiInfra/slices/aiProvider/initialState.ts
+++ b/src/store/aiInfra/slices/aiProvider/initialState.ts
@@ -25,6 +25,7 @@ export interface AIProviderState {
// used for select
enabledChatModelList?: EnabledProviderWithModels[];
enabledImageModelList?: EnabledProviderWithModels[];
+ enabledVideoModelList?: EnabledProviderWithModels[];
initAiProviderList: boolean;
isInitAiProviderRuntimeState: boolean;
providerSearchKeyword: string;
diff --git a/src/store/aiInfra/slices/aiProvider/selectors.ts b/src/store/aiInfra/slices/aiProvider/selectors.ts
index 982a392543d..3f67cd34d50 100644
--- a/src/store/aiInfra/slices/aiProvider/selectors.ts
+++ b/src/store/aiInfra/slices/aiProvider/selectors.ts
@@ -17,6 +17,8 @@ const disabledCustomAiProviderList = (s: AIProviderStoreState) =>
const enabledImageModelList = (s: AIProviderStoreState) => s.enabledImageModelList || [];
+const enabledVideoModelList = (s: AIProviderStoreState) => s.enabledVideoModelList || [];
+
const isProviderEnabled = (id: string) => (s: AIProviderStoreState) =>
enabledAiProviderList(s).some((i) => i.id === id);
@@ -136,6 +138,7 @@ export const aiProviderSelectors = {
disabledCustomAiProviderList,
enabledAiProviderList,
enabledImageModelList,
+ enabledVideoModelList,
isActiveProviderApiKeyNotEmpty,
isActiveProviderEndpointNotEmpty,
isAiProviderConfigLoading,
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index e40733777ce..b016eb5aaf7 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -17,6 +17,7 @@ export enum SidebarTabKey {
Pages = 'pages',
Resource = 'resource',
Setting = 'settings',
+ Video = 'video',
}
export enum ChatSettingsTabs {
@@ -121,6 +122,8 @@ export interface SystemStatus {
* Remember user's last selected image generation provider
*/
lastSelectedImageProvider?: string;
+ lastSelectedVideoModel?: string;
+ lastSelectedVideoProvider?: string;
latestChangelogId?: string;
leftPanelWidth: number;
mobileShowPortal?: boolean;
@@ -157,6 +160,8 @@ export interface SystemStatus {
showLeftPanel?: boolean;
showRightPanel?: boolean;
showSystemRole?: boolean;
+ showVideoPanel?: boolean;
+ showVideoTopicPanel?: boolean;
systemRoleExpandedMap: Record<string, boolean>;
/**
* Whether to display tokens in short format
@@ -166,6 +171,8 @@ export interface SystemStatus {
* number of topics to display per page
*/
topicPageSize?: number;
+ videoPanelWidth: number;
+ videoTopicPanelWidth?: number;
zenMode?: boolean;
}
@@ -241,9 +248,13 @@ export const INITIAL_STATUS = {
showLeftPanel: true,
showRightPanel: true,
showSystemRole: false,
+ showVideoPanel: true,
+ showVideoTopicPanel: true,
systemRoleExpandedMap: {},
tokenDisplayFormatShort: true,
topicPageSize: 20,
+ videoPanelWidth: 320,
+ videoTopicPanelWidth: 80,
zenMode: false,
} satisfies SystemStatus;
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 4a2d97031da..2bb2c328c7e 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -43,6 +43,10 @@ const filePanelWidth = (s: GlobalState) => s.status.filePanelWidth;
const groupAgentBuilderPanelWidth = (s: GlobalState) => s.status.groupAgentBuilderPanelWidth || 360;
const imagePanelWidth = (s: GlobalState) => s.status.imagePanelWidth;
const imageTopicPanelWidth = (s: GlobalState) => s.status.imageTopicPanelWidth;
+const videoPanelWidth = (s: GlobalState) => s.status.videoPanelWidth;
+const videoTopicPanelWidth = (s: GlobalState) => s.status.videoTopicPanelWidth;
+const showVideoPanel = (s: GlobalState) => s.status.showVideoPanel;
+const showVideoTopicPanel = (s: GlobalState) => s.status.showVideoTopicPanel;
const wideScreen = (s: GlobalState) => !s.status.noWideScreen;
const chatInputHeight = (s: GlobalState) => s.status.chatInputHeight || 64;
const expandInputActionbar = (s: GlobalState) => s.status.expandInputActionbar;
@@ -102,9 +106,13 @@ export const systemStatusSelectors = {
showLeftPanel,
showRightPanel,
showSystemRole,
+ showVideoPanel,
+ showVideoTopicPanel,
systemStatus,
tokenDisplayFormatShort,
topicGroupKeys,
topicPageSize,
+ videoPanelWidth,
+ videoTopicPanelWidth,
wideScreen,
};
diff --git a/src/store/home/slices/homeInput/initialState.ts b/src/store/home/slices/homeInput/initialState.ts
index c2abae89cde..255df726525 100644
--- a/src/store/home/slices/homeInput/initialState.ts
+++ b/src/store/home/slices/homeInput/initialState.ts
@@ -1,6 +1,6 @@
import { type NavigateFunction } from 'react-router-dom';
-export type StarterMode = 'agent' | 'group' | 'write' | 'research' | null;
+export type StarterMode = 'agent' | 'group' | 'write' | 'video' | 'research' | null;
export interface HomeInputState {
homeInputLoading: boolean;
diff --git a/src/store/image/slices/generationTopic/action.ts b/src/store/image/slices/generationTopic/action.ts
index 4c16526603d..a409ce7797f 100644
--- a/src/store/image/slices/generationTopic/action.ts
+++ b/src/store/image/slices/generationTopic/action.ts
@@ -147,7 +147,7 @@ export class GenerationTopicActionImpl {
this.#get().internal_updateGenerationTopicLoading(tmpId, true);
// 2. Call backend service
- const topicId = await generationTopicService.createTopic();
+ const topicId = await generationTopicService.createTopic('image');
this.#get().internal_updateGenerationTopicLoading(tmpId, false);
// 3. Refresh data to ensure consistency
@@ -210,7 +210,7 @@ export class GenerationTopicActionImpl {
useFetchGenerationTopics = (enabled: boolean): SWRResponse<ImageGenerationTopic[]> => {
return useClientDataSWR<ImageGenerationTopic[]>(
enabled ? [FETCH_GENERATION_TOPICS_KEY] : null,
- () => generationTopicService.getAllGenerationTopics(),
+ () => generationTopicService.getAllGenerationTopics('image'),
{
suspense: true,
onSuccess: (data) => {
diff --git a/src/store/video/index.ts b/src/store/video/index.ts
new file mode 100644
index 00000000000..a06a4502a32
--- /dev/null
+++ b/src/store/video/index.ts
@@ -0,0 +1,2 @@
+export type { VideoStore } from './store';
+export { getVideoStoreState, useVideoStore } from './store';
diff --git a/src/store/video/initialState.ts b/src/store/video/initialState.ts
new file mode 100644
index 00000000000..59a507e181b
--- /dev/null
+++ b/src/store/video/initialState.ts
@@ -0,0 +1,25 @@
+import { type CreateVideoState, initialCreateVideoState } from './slices/createVideo/initialState';
+import {
+ type GenerationBatchState,
+ initialGenerationBatchState,
+} from './slices/generationBatch/initialState';
+import {
+ type VideoGenerationConfigState,
+ initialGenerationConfigState,
+} from './slices/generationConfig/initialState';
+import {
+ type GenerationTopicState,
+ initialGenerationTopicState,
+} from './slices/generationTopic/initialState';
+
+export type VideoStoreState = VideoGenerationConfigState &
+ GenerationTopicState &
+ GenerationBatchState &
+ CreateVideoState;
+
+export const initialState: VideoStoreState = {
+ ...initialGenerationConfigState,
+ ...initialGenerationTopicState,
+ ...initialGenerationBatchState,
+ ...initialCreateVideoState,
+};
diff --git a/src/store/video/selectors.ts b/src/store/video/selectors.ts
new file mode 100644
index 00000000000..be1f01f497a
--- /dev/null
+++ b/src/store/video/selectors.ts
@@ -0,0 +1,4 @@
+export { createVideoSelectors } from './slices/createVideo/selectors';
+export { generationBatchSelectors } from './slices/generationBatch/selectors';
+export * from './slices/generationConfig/selectors';
+export { generationTopicSelectors as videoGenerationTopicSelectors } from './slices/generationTopic/selectors';
diff --git a/src/store/video/slices/createVideo/action.ts b/src/store/video/slices/createVideo/action.ts
new file mode 100644
index 00000000000..7dd84d79b94
--- /dev/null
+++ b/src/store/video/slices/createVideo/action.ts
@@ -0,0 +1,156 @@
+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
+import { t } from 'i18next';
+import { type StateCreator } from 'zustand';
+
+import { markUserValidAction } from '@/business/client/markUserValidAction';
+import { message } from '@/components/AntdStaticMethods';
+import { videoService } from '@/services/video';
+
+import { type VideoStore } from '../../store';
+import { generationBatchSelectors } from '../generationBatch/selectors';
+import { videoGenerationConfigSelectors } from '../generationConfig/selectors';
+import { generationTopicSelectors } from '../generationTopic';
+
+// ====== action interface ====== //
+
+export interface CreateVideoAction {
+ createVideo: () => Promise<void>;
+ recreateVideo: (generationBatchId: string) => Promise<void>;
+}
+
+// ====== action implementation ====== //
+
+export const createCreateVideoSlice: StateCreator<
+ VideoStore,
+ [['zustand/devtools', never]],
+ [],
+ CreateVideoAction
+> = (set, get) => ({
+ async createVideo() {
+ set({ isCreating: true }, false, 'createVideo/startCreateVideo');
+
+ const store = get();
+ const parameters = videoGenerationConfigSelectors.parameters(store);
+ const provider = videoGenerationConfigSelectors.provider(store);
+ const model = videoGenerationConfigSelectors.model(store);
+ const activeGenerationTopicId = generationTopicSelectors.activeGenerationTopicId(store);
+ const { createGenerationTopic, switchGenerationTopic, setTopicBatchLoaded } = store;
+
+ if (!parameters) {
+ throw new TypeError('parameters is not initialized');
+ }
+
+ if (!parameters.prompt) {
+ throw new TypeError('prompt is empty');
+ }
+
+ // Validate: end frame requires start frame (driven by model schema)
+ const parametersSchema = videoGenerationConfigSelectors.parametersSchema(store);
+ const endImageUrlSchema = parametersSchema?.endImageUrl;
+ if (
+ endImageUrlSchema &&
+ 'requiresImageUrl' in endImageUrlSchema &&
+ endImageUrlSchema.requiresImageUrl &&
+ parameters.endImageUrl &&
+ !parameters.imageUrl
+ ) {
+ message.warning({
+ content: t('generation.validation.endFrameRequiresStartFrame', { ns: 'video' }),
+ duration: 3,
+ });
+ set({ isCreating: false }, false, 'createVideo/endCreateVideo');
+ return;
+ }
+
+ let finalTopicId = activeGenerationTopicId;
+
+ // 1. Create generation topic if not exists
+ const generationTopicId = activeGenerationTopicId;
+ let isNewTopic = false;
+
+ if (!generationTopicId) {
+ isNewTopic = true;
+ const prompts = [parameters.prompt];
+ const newGenerationTopicId = await createGenerationTopic(prompts);
+ finalTopicId = newGenerationTopicId;
+
+ // 2. Initialize empty batch array to avoid skeleton screen
+ setTopicBatchLoaded(newGenerationTopicId);
+
+ // 3. Switch to the new topic (now it has empty data, so no skeleton screen)
+ switchGenerationTopic(newGenerationTopicId);
+ }
+
+ try {
+ // 3. If it's a new topic, set the creating state after topic creation
+ if (isNewTopic) {
+ set({ isCreatingWithNewTopic: true }, false, 'createVideo/startCreateVideoWithNewTopic');
+ }
+
+ if (ENABLE_BUSINESS_FEATURES) {
+ markUserValidAction();
+ }
+
+ // 4. Create video via service
+ await videoService.createVideo({
+ generationTopicId: finalTopicId!,
+ model,
+ params: parameters as any,
+ provider,
+ });
+
+ // 5. Refresh generation batches to show the new batch
+ if (!isNewTopic) {
+ await get().refreshGenerationBatches();
+ }
+
+ // 6. Clear the prompt input after successful video creation
+ set(
+ (state) => ({
+ parameters: { ...state.parameters, prompt: '' },
+ }),
+ false,
+ 'createVideo/clearPrompt',
+ );
+ } finally {
+ // 7. Reset all creating states
+ if (isNewTopic) {
+ set(
+ { isCreating: false, isCreatingWithNewTopic: false },
+ false,
+ 'createVideo/endCreateVideoWithNewTopic',
+ );
+ } else {
+ set({ isCreating: false }, false, 'createVideo/endCreateVideo');
+ }
+ }
+ },
+
+ async recreateVideo(generationBatchId: string) {
+ set({ isCreating: true }, false, 'recreateVideo/start');
+
+ const store = get();
+ const activeGenerationTopicId = generationTopicSelectors.activeGenerationTopicId(store);
+ if (!activeGenerationTopicId) {
+ throw new Error('No active generation topic');
+ }
+
+ const { removeGenerationBatch } = store;
+ const batch = generationBatchSelectors.getGenerationBatchByBatchId(generationBatchId)(store)!;
+
+ try {
+ await removeGenerationBatch(generationBatchId, activeGenerationTopicId);
+
+ await videoService.createVideo({
+ generationTopicId: activeGenerationTopicId,
+ model: batch.model,
+ params: batch.config as any,
+ provider: batch.provider,
+ });
+
+ await store.refreshGenerationBatches();
+ } finally {
+ set({ isCreating: false }, false, 'recreateVideo/end');
+ }
+ },
+});
diff --git a/src/store/video/slices/createVideo/initialState.ts b/src/store/video/slices/createVideo/initialState.ts
new file mode 100644
index 00000000000..cb7067aaf70
--- /dev/null
+++ b/src/store/video/slices/createVideo/initialState.ts
@@ -0,0 +1,9 @@
+export interface CreateVideoState {
+ isCreating: boolean;
+ isCreatingWithNewTopic: boolean;
+}
+
+export const initialCreateVideoState: CreateVideoState = {
+ isCreating: false,
+ isCreatingWithNewTopic: false,
+};
diff --git a/src/store/video/slices/createVideo/selectors.ts b/src/store/video/slices/createVideo/selectors.ts
new file mode 100644
index 00000000000..20dfd9a931e
--- /dev/null
+++ b/src/store/video/slices/createVideo/selectors.ts
@@ -0,0 +1,9 @@
+import { type VideoStore } from '../../store';
+
+const isCreating = (state: VideoStore) => state.isCreating;
+const isCreatingWithNewTopic = (state: VideoStore) => state.isCreatingWithNewTopic;
+
+export const createVideoSelectors = {
+ isCreating,
+ isCreatingWithNewTopic,
+};
diff --git a/src/store/video/slices/generationBatch/action.ts b/src/store/video/slices/generationBatch/action.ts
new file mode 100644
index 00000000000..5bf6041c0a3
--- /dev/null
+++ b/src/store/video/slices/generationBatch/action.ts
@@ -0,0 +1,274 @@
+import { isEqual } from 'es-toolkit/compat';
+import { useRef } from 'react';
+import type { SWRResponse } from 'swr';
+import { type StateCreator } from 'zustand';
+
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';
+import { generationService } from '@/services/generation';
+import { generationBatchService } from '@/services/generationBatch';
+import { AsyncTaskStatus } from '@/types/asyncTask';
+import { type GenerationBatch } from '@/types/generation';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type VideoStore } from '../../store';
+import { generationTopicSelectors } from '../generationTopic/selectors';
+import { type GenerationBatchDispatch, generationBatchReducer } from './reducer';
+
+const n = setNamespace('generationBatch');
+
+// ====== SWR key ====== //
+const SWR_USE_FETCH_GENERATION_BATCHES = 'SWR_USE_FETCH_VIDEO_GENERATION_BATCHES';
+const SWR_USE_CHECK_GENERATION_STATUS = 'SWR_USE_CHECK_VIDEO_GENERATION_STATUS';
+
+// ====== action interface ====== //
+
+export interface GenerationBatchAction {
+ internal_deleteGeneration: (generationId: string) => Promise<void>;
+ internal_deleteGenerationBatch: (batchId: string, topicId: string) => Promise<void>;
+ internal_dispatchGenerationBatch: (
+ topicId: string,
+ payload: GenerationBatchDispatch,
+ action?: string,
+ ) => void;
+ refreshGenerationBatches: () => Promise<void>;
+ removeGeneration: (generationId: string) => Promise<void>;
+ removeGenerationBatch: (batchId: string, topicId: string) => Promise<void>;
+ setTopicBatchLoaded: (topicId: string) => void;
+ useCheckGenerationStatus: (
+ generationId: string,
+ asyncTaskId: string,
+ topicId: string,
+ enable?: boolean,
+ ) => SWRResponse<GetGenerationStatusResult>;
+ useFetchGenerationBatches: (topicId?: string | null) => SWRResponse<GenerationBatch[]>;
+}
+
+// ====== action implementation ====== //
+
+export const createGenerationBatchSlice: StateCreator<
+ VideoStore,
+ [['zustand/devtools', never]],
+ [],
+ GenerationBatchAction
+> = (set, get) => ({
+ internal_deleteGeneration: async (generationId: string) => {
+ const { activeGenerationTopicId, refreshGenerationBatches, internal_dispatchGenerationBatch } =
+ get();
+
+ if (!activeGenerationTopicId) return;
+
+ const currentBatches = get().generationBatchesMap[activeGenerationTopicId] || [];
+ const targetBatch = currentBatches.find((batch) =>
+ batch.generations.some((gen) => gen.id === generationId),
+ );
+
+ if (!targetBatch) return;
+
+ // Optimistic update
+ internal_dispatchGenerationBatch(
+ activeGenerationTopicId,
+ { batchId: targetBatch.id, generationId, type: 'deleteGenerationInBatch' },
+ 'internal_deleteGeneration',
+ );
+
+ await generationService.deleteGeneration(generationId);
+ await refreshGenerationBatches();
+ },
+
+ internal_deleteGenerationBatch: async (batchId: string, topicId: string) => {
+ const { internal_dispatchGenerationBatch, refreshGenerationBatches } = get();
+
+ // Optimistic update
+ internal_dispatchGenerationBatch(
+ topicId,
+ { id: batchId, type: 'deleteBatch' },
+ 'internal_deleteGenerationBatch',
+ );
+
+ await generationBatchService.deleteGenerationBatch(batchId);
+ await refreshGenerationBatches();
+ },
+
+ internal_dispatchGenerationBatch: (topicId, payload, action) => {
+ const currentBatches = get().generationBatchesMap[topicId] || [];
+ const nextBatches = generationBatchReducer(currentBatches, payload);
+
+ const nextMap = {
+ ...get().generationBatchesMap,
+ [topicId]: nextBatches,
+ };
+
+ if (isEqual(nextMap, get().generationBatchesMap)) return;
+
+ set(
+ {
+ generationBatchesMap: nextMap,
+ },
+ false,
+ action ?? n(`dispatchGenerationBatch/${payload.type}`),
+ );
+ },
+
+ refreshGenerationBatches: async () => {
+ const { activeGenerationTopicId } = get();
+ if (activeGenerationTopicId) {
+ await mutate([SWR_USE_FETCH_GENERATION_BATCHES, activeGenerationTopicId]);
+ }
+ },
+
+ removeGeneration: async (generationId: string) => {
+ const { internal_deleteGeneration, activeGenerationTopicId, internal_deleteGenerationBatch } =
+ get();
+
+ await internal_deleteGeneration(generationId);
+
+ // Video batch has only 1 generation, so delete the batch directly
+ if (activeGenerationTopicId) {
+ const updatedBatches = get().generationBatchesMap[activeGenerationTopicId] || [];
+ const emptyBatches = updatedBatches.filter((batch) => batch.generations.length === 0);
+
+ for (const emptyBatch of emptyBatches) {
+ await internal_deleteGenerationBatch(emptyBatch.id, activeGenerationTopicId);
+ }
+ }
+ },
+
+ removeGenerationBatch: async (batchId: string, topicId: string) => {
+ const { internal_deleteGenerationBatch } = get();
+ await internal_deleteGenerationBatch(batchId, topicId);
+ },
+
+ setTopicBatchLoaded: (topicId: string) => {
+ const nextMap = {
+ ...get().generationBatchesMap,
+ [topicId]: [],
+ };
+
+ if (isEqual(nextMap, get().generationBatchesMap)) return;
+
+ set(
+ {
+ generationBatchesMap: nextMap,
+ },
+ false,
+ n('setTopicBatchLoaded'),
+ );
+ },
+
+ useCheckGenerationStatus: (generationId, asyncTaskId, topicId, enable = true) => {
+ const requestCountRef = useRef(0);
+ const isErrorRef = useRef(false);
+
+ return useClientDataSWR<GetGenerationStatusResult>(
+ enable && generationId && !generationId.startsWith('temp-') && asyncTaskId
+ ? [SWR_USE_CHECK_GENERATION_STATUS, generationId, asyncTaskId]
+ : null,
+ async ([, generationId, asyncTaskId]: [string, string, string]) => {
+ requestCountRef.current += 1;
+ return generationService.getGenerationStatus(generationId, asyncTaskId);
+ },
+ {
+ onError: (error) => {
+ isErrorRef.current = true;
+ console.error('Video generation status check error:', error);
+ },
+ onSuccess: async (data: GetGenerationStatusResult) => {
+ if (!data) return;
+
+ isErrorRef.current = false;
+
+ const currentBatches = get().generationBatchesMap[topicId] || [];
+ const targetBatch = currentBatches.find((batch) =>
+ batch.generations.some((gen) => gen.id === generationId),
+ );
+
+ if (
+ (data.status === AsyncTaskStatus.Success || data.status === AsyncTaskStatus.Error) &&
+ targetBatch
+ ) {
+ requestCountRef.current = 0;
+
+ if (data.generation) {
+ get().internal_dispatchGenerationBatch(
+ topicId,
+ {
+ batchId: targetBatch.id,
+ generationId,
+ type: 'updateGenerationInBatch',
+ value: data.generation,
+ },
+ n(
+ `useCheckGenerationStatus/${data.status === AsyncTaskStatus.Success ? 'success' : 'error'}`,
+ ),
+ );
+
+ // Update topic cover if generation succeeds and has a thumbnail
+ if (data.status === AsyncTaskStatus.Success && data.generation.asset?.thumbnailUrl) {
+ const currentTopic =
+ generationTopicSelectors.getGenerationTopicById(topicId)(get());
+
+ if (currentTopic && !currentTopic.coverUrl) {
+ await get().updateGenerationTopicCover(
+ topicId,
+ data.generation.asset.thumbnailUrl,
+ );
+ }
+ }
+ }
+
+ await get().refreshGenerationBatches();
+ }
+ },
+ refreshInterval: (data: GetGenerationStatusResult | undefined) => {
+ if (data?.status === AsyncTaskStatus.Success || data?.status === AsyncTaskStatus.Error) {
+ return 0;
+ }
+
+ const baseInterval = 1000;
+ const maxInterval = 30_000;
+ const currentCount = requestCountRef.current;
+
+ const backoffMultiplier = Math.floor(currentCount / 5);
+ let dynamicInterval = Math.min(
+ baseInterval * Math.pow(2, backoffMultiplier),
+ maxInterval,
+ );
+
+ if (isErrorRef.current) {
+ dynamicInterval = Math.min(dynamicInterval * 2, maxInterval);
+ }
+
+ return dynamicInterval;
+ },
+ refreshWhenHidden: false,
+ },
+ );
+ },
+
+ useFetchGenerationBatches: (topicId) =>
+ useClientDataSWR<GenerationBatch[]>(
+ topicId ? [SWR_USE_FETCH_GENERATION_BATCHES, topicId] : null,
+ async ([, topicId]: [string, string]) => {
+ return generationBatchService.getGenerationBatches(topicId);
+ },
+ {
+ onSuccess: (data) => {
+ const nextMap = {
+ ...get().generationBatchesMap,
+ [topicId!]: data,
+ };
+
+ if (isEqual(nextMap, get().generationBatchesMap)) return;
+
+ set(
+ {
+ generationBatchesMap: nextMap,
+ },
+ false,
+ n('useFetchGenerationBatches(success)', { topicId }),
+ );
+ },
+ },
+ ),
+});
diff --git a/src/store/video/slices/generationBatch/initialState.ts b/src/store/video/slices/generationBatch/initialState.ts
new file mode 100644
index 00000000000..354657fb1c6
--- /dev/null
+++ b/src/store/video/slices/generationBatch/initialState.ts
@@ -0,0 +1,9 @@
+import { type GenerationBatch } from '@/types/generation';
+
+export interface GenerationBatchState {
+ generationBatchesMap: Record<string, GenerationBatch[]>;
+}
+
+export const initialGenerationBatchState: GenerationBatchState = {
+ generationBatchesMap: {},
+};
diff --git a/src/store/video/slices/generationBatch/reducer.ts b/src/store/video/slices/generationBatch/reducer.ts
new file mode 100644
index 00000000000..d1afb5e54b2
--- /dev/null
+++ b/src/store/video/slices/generationBatch/reducer.ts
@@ -0,0 +1,100 @@
+import { produce } from 'immer';
+
+import { type Generation, type GenerationBatch } from '@/types/generation';
+
+interface UpdateGenerationInBatchAction {
+ batchId: string;
+ generationId: string;
+ type: 'updateGenerationInBatch';
+ value: Partial<Generation>;
+}
+
+interface UpdateGenerationBatchAction {
+ id: string;
+ type: 'updateBatch';
+ value: Partial<GenerationBatch>;
+}
+
+interface DeleteGenerationBatchAction {
+ id: string;
+ type: 'deleteBatch';
+}
+
+interface DeleteGenerationInBatchAction {
+ batchId: string;
+ generationId: string;
+ type: 'deleteGenerationInBatch';
+}
+
+interface AddGenerationBatchAction {
+ type: 'addBatch';
+ value: GenerationBatch;
+}
+
+export type GenerationBatchDispatch =
+ | UpdateGenerationInBatchAction
+ | UpdateGenerationBatchAction
+ | DeleteGenerationBatchAction
+ | DeleteGenerationInBatchAction
+ | AddGenerationBatchAction;
+
+export const generationBatchReducer = (
+ state: GenerationBatch[] = [],
+ payload: GenerationBatchDispatch,
+): GenerationBatch[] => {
+ switch (payload.type) {
+ case 'updateGenerationInBatch': {
+ return produce(state, (draftState) => {
+ const batchIndex = draftState.findIndex((batch) => batch.id === payload.batchId);
+ if (batchIndex === -1) return;
+
+ const generationIndex = draftState[batchIndex].generations.findIndex(
+ (gen) => gen.id === payload.generationId,
+ );
+ if (generationIndex === -1) return;
+
+ draftState[batchIndex].generations[generationIndex] = {
+ ...draftState[batchIndex].generations[generationIndex],
+ ...payload.value,
+ };
+ });
+ }
+
+ case 'updateBatch': {
+ return produce(state, (draftState) => {
+ const batchIndex = draftState.findIndex((batch) => batch.id === payload.id);
+ if (batchIndex === -1) return;
+
+ draftState[batchIndex] = {
+ ...draftState[batchIndex],
+ ...payload.value,
+ };
+ });
+ }
+
+ case 'deleteBatch': {
+ return state.filter((batch) => batch.id !== payload.id);
+ }
+
+ case 'deleteGenerationInBatch': {
+ return produce(state, (draftState) => {
+ const batchIndex = draftState.findIndex((batch) => batch.id === payload.batchId);
+ if (batchIndex === -1) return;
+
+ draftState[batchIndex].generations = draftState[batchIndex].generations.filter(
+ (gen) => gen.id !== payload.generationId,
+ );
+ });
+ }
+
+ case 'addBatch': {
+ return produce(state, (draftState) => {
+ draftState.unshift(payload.value);
+ });
+ }
+
+ default: {
+ return state;
+ }
+ }
+};
diff --git a/src/store/video/slices/generationBatch/selectors.ts b/src/store/video/slices/generationBatch/selectors.ts
new file mode 100644
index 00000000000..a01fa52b7a1
--- /dev/null
+++ b/src/store/video/slices/generationBatch/selectors.ts
@@ -0,0 +1,36 @@
+import { type GenerationBatch } from '@/types/generation';
+
+import { type VideoStoreState } from '../../initialState';
+import { generationTopicSelectors } from '../generationTopic/selectors';
+
+// ====== topic batch selectors ====== //
+
+const getGenerationBatchesByTopicId = (topicId: string) => (s: VideoStoreState) => {
+ return s.generationBatchesMap[topicId] || [];
+};
+
+const currentGenerationBatches = (s: VideoStoreState): GenerationBatch[] => {
+ const activeTopicId = generationTopicSelectors.activeGenerationTopicId(s);
+ if (!activeTopicId) return [];
+ return getGenerationBatchesByTopicId(activeTopicId)(s);
+};
+
+const getGenerationBatchByBatchId = (batchId: string) => (s: VideoStoreState) => {
+ const batches = currentGenerationBatches(s);
+ return batches.find((batch) => batch.id === batchId);
+};
+
+const isCurrentGenerationTopicLoaded = (s: VideoStoreState): boolean => {
+ const activeTopicId = generationTopicSelectors.activeGenerationTopicId(s);
+ if (!activeTopicId) return false;
+ return Array.isArray(s.generationBatchesMap[activeTopicId]);
+};
+
+// ====== aggregate selectors ====== //
+
+export const generationBatchSelectors = {
+ currentGenerationBatches,
+ getGenerationBatchByBatchId,
+ getGenerationBatchesByTopicId,
+ isCurrentGenerationTopicLoaded,
+};
diff --git a/src/store/video/slices/generationConfig/action.ts b/src/store/video/slices/generationConfig/action.ts
new file mode 100644
index 00000000000..e896967e963
--- /dev/null
+++ b/src/store/video/slices/generationConfig/action.ts
@@ -0,0 +1,123 @@
+import {
+ type AIVideoModelCard,
+ extractVideoDefaultValues,
+ type RuntimeVideoGenParamsKeys,
+ type RuntimeVideoGenParamsValue,
+ type VideoModelParamsSchema,
+} from 'model-bank';
+import { type StateCreator } from 'zustand/vanilla';
+
+import { aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
+import { useGlobalStore } from '@/store/global';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+import type { VideoStore } from '../../store';
+
+export interface GenerationConfigAction {
+ initializeVideoConfig: (
+ isLogin?: boolean,
+ lastSelectedVideoModel?: string,
+ lastSelectedVideoProvider?: string,
+ ) => void;
+
+ setModelAndProviderOnSelect: (model: string, provider: string) => void;
+
+ setParamOnInput: <K extends RuntimeVideoGenParamsKeys>(
+ paramName: K,
+ value: RuntimeVideoGenParamsValue,
+ ) => void;
+}
+
+export function getVideoModelAndDefaults(model: string, provider: string) {
+ const enabledVideoModelList = aiProviderSelectors.enabledVideoModelList(getAiInfraStoreState());
+
+ const providerItem = enabledVideoModelList.find((providerItem) => providerItem.id === provider);
+ if (!providerItem) {
+ throw new Error(
+ `Provider "${provider}" not found in enabled video provider list. Available providers: ${enabledVideoModelList.map((p) => p.id).join(', ')}`,
+ );
+ }
+
+ const activeModel = providerItem.children.find(
+ (modelItem) => modelItem.id === model,
+ ) as unknown as AIVideoModelCard;
+ if (!activeModel) {
+ throw new Error(
+ `Model "${model}" not found in provider "${provider}". Available models: ${providerItem.children.map((m) => m.id).join(', ')}`,
+ );
+ }
+
+ const parametersSchema = activeModel.parameters as VideoModelParamsSchema;
+ const defaultValues = extractVideoDefaultValues(parametersSchema);
+
+ return { activeModel, defaultValues, parametersSchema };
+}
+
+export const createGenerationConfigSlice: StateCreator<
+ VideoStore,
+ [['zustand/devtools', never]],
+ [],
+ GenerationConfigAction
+> = (set) => ({
+ initializeVideoConfig: (isLogin, lastSelectedVideoModel, lastSelectedVideoProvider) => {
+ if (isLogin && lastSelectedVideoModel && lastSelectedVideoProvider) {
+ try {
+ const { defaultValues, parametersSchema } = getVideoModelAndDefaults(
+ lastSelectedVideoModel,
+ lastSelectedVideoProvider,
+ );
+
+ set(
+ {
+ isInit: true,
+ model: lastSelectedVideoModel,
+ parameters: defaultValues,
+ parametersSchema,
+ provider: lastSelectedVideoProvider,
+ },
+ false,
+ `initializeVideoConfig/${lastSelectedVideoModel}/${lastSelectedVideoProvider}`,
+ );
+ } catch {
+ set({ isInit: true }, false, 'initializeVideoConfig/default');
+ }
+ } else {
+ set({ isInit: true }, false, 'initializeVideoConfig/default');
+ }
+ },
+
+ setModelAndProviderOnSelect: (model, provider) => {
+ const { defaultValues, parametersSchema } = getVideoModelAndDefaults(model, provider);
+
+ set(
+ {
+ model,
+ parameters: defaultValues,
+ parametersSchema,
+ provider,
+ },
+ false,
+ `setModelAndProviderOnSelect/${model}/${provider}`,
+ );
+
+ const isLogin = authSelectors.isLogin(useUserStore.getState());
+ if (isLogin) {
+ useGlobalStore.getState().updateSystemStatus({
+ lastSelectedVideoModel: model,
+ lastSelectedVideoProvider: provider,
+ });
+ }
+ },
+
+ setParamOnInput: (paramName, value) => {
+ set(
+ (state) => {
+ const { parameters } = state;
+ return { parameters: { ...parameters, [paramName]: value } };
+ },
+ false,
+ `setParamOnInput/${paramName}`,
+ );
+ },
+});
diff --git a/src/store/video/slices/generationConfig/hooks.ts b/src/store/video/slices/generationConfig/hooks.ts
new file mode 100644
index 00000000000..094c3f42885
--- /dev/null
+++ b/src/store/video/slices/generationConfig/hooks.ts
@@ -0,0 +1,41 @@
+import { type RuntimeVideoGenParams, type RuntimeVideoGenParamsKeys } from 'model-bank';
+import { useCallback, useMemo } from 'react';
+
+import { useVideoStore } from '../../store';
+import { videoGenerationConfigSelectors } from './selectors';
+
+export function useVideoGenerationConfigParam<
+ N extends RuntimeVideoGenParamsKeys,
+ V extends RuntimeVideoGenParams[N],
+>(paramName: N) {
+ const parameters = useVideoStore(videoGenerationConfigSelectors.parameters);
+ const parametersSchema = useVideoStore(videoGenerationConfigSelectors.parametersSchema);
+
+ const paramValue = parameters?.[paramName] as V;
+ const setParamsValue = useVideoStore((s) => s.setParamOnInput<N>);
+ const setValue = useCallback(
+ (value: V) => {
+ setParamsValue(paramName, value);
+ },
+ [paramName, setParamsValue],
+ );
+
+ const paramConfig = parametersSchema?.[paramName];
+ const paramConstraints = useMemo(() => {
+ if (!paramConfig || typeof paramConfig !== 'object') return {};
+
+ const maxFileSize = 'maxFileSize' in paramConfig ? paramConfig.maxFileSize : undefined;
+ const enumValues = 'enum' in paramConfig ? (paramConfig.enum as string[]) : undefined;
+ const min = 'min' in paramConfig ? (paramConfig.min as number) : undefined;
+ const max = 'max' in paramConfig ? (paramConfig.max as number) : undefined;
+ const step = 'step' in paramConfig ? (paramConfig.step as number) : undefined;
+
+ return { enumValues, max, maxFileSize, min, step };
+ }, [paramConfig]);
+
+ return {
+ setValue,
+ value: paramValue as V,
+ ...paramConstraints,
+ };
+}
diff --git a/src/store/video/slices/generationConfig/initialState.ts b/src/store/video/slices/generationConfig/initialState.ts
new file mode 100644
index 00000000000..d010ca935ef
--- /dev/null
+++ b/src/store/video/slices/generationConfig/initialState.ts
@@ -0,0 +1,35 @@
+/* eslint-disable perfectionist/sort-interfaces */
+import {
+ extractVideoDefaultValues,
+ ModelProvider,
+ type RuntimeVideoGenParams,
+ type VideoModelParamsSchema,
+} from 'model-bank';
+import { seedance15ProParams } from 'model-bank/lobehub';
+
+export const DEFAULT_AI_VIDEO_PROVIDER = ModelProvider.LobeHub;
+export const DEFAULT_AI_VIDEO_MODEL = 'seedance-1-5-pro-251215';
+
+export interface VideoGenerationConfigState {
+ parameters: RuntimeVideoGenParams;
+ parametersSchema: VideoModelParamsSchema;
+
+ provider: string;
+ model: string;
+
+ /**
+ * Marks whether the configuration has been initialized (including restoration from memory)
+ */
+ isInit: boolean;
+}
+
+export const DEFAULT_VIDEO_GENERATION_PARAMETERS: RuntimeVideoGenParams =
+ extractVideoDefaultValues(seedance15ProParams);
+
+export const initialGenerationConfigState: VideoGenerationConfigState = {
+ model: DEFAULT_AI_VIDEO_MODEL,
+ provider: DEFAULT_AI_VIDEO_PROVIDER,
+ parameters: DEFAULT_VIDEO_GENERATION_PARAMETERS,
+ parametersSchema: seedance15ProParams,
+ isInit: false,
+};
diff --git a/src/store/video/slices/generationConfig/selectors.ts b/src/store/video/slices/generationConfig/selectors.ts
new file mode 100644
index 00000000000..30cc311024d
--- /dev/null
+++ b/src/store/video/slices/generationConfig/selectors.ts
@@ -0,0 +1,23 @@
+import { type RuntimeVideoGenParamsKeys } from 'model-bank';
+
+import { type VideoGenerationConfigState } from './initialState';
+
+const model = (s: VideoGenerationConfigState) => s.model;
+const provider = (s: VideoGenerationConfigState) => s.provider;
+
+const parameters = (s: VideoGenerationConfigState) => s.parameters;
+const parametersSchema = (s: VideoGenerationConfigState) => s.parametersSchema;
+const isSupportedParam = (paramName: RuntimeVideoGenParamsKeys) => {
+ return (s: VideoGenerationConfigState) => {
+ const _parametersSchema = parametersSchema(s);
+ return Boolean(paramName in _parametersSchema);
+ };
+};
+
+export const videoGenerationConfigSelectors = {
+ isSupportedParam,
+ model,
+ parameters,
+ parametersSchema,
+ provider,
+};
diff --git a/src/store/video/slices/generationTopic/action.ts b/src/store/video/slices/generationTopic/action.ts
new file mode 100644
index 00000000000..53dce444c04
--- /dev/null
+++ b/src/store/video/slices/generationTopic/action.ts
@@ -0,0 +1,293 @@
+import { chainSummaryGenerationTitle } from '@lobechat/prompts';
+import isEqual from 'fast-deep-equal';
+import type { SWRResponse } from 'swr';
+import { type StateCreator } from 'zustand/vanilla';
+
+import { LOADING_FLAT } from '@/const/message';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
+import { chatService } from '@/services/chat';
+import { generationTopicService } from '@/services/generationTopic';
+import { globalHelpers } from '@/store/global/helpers';
+import { useUserStore } from '@/store/user';
+import { systemAgentSelectors } from '@/store/user/selectors';
+import { type ImageGenerationTopic } from '@/types/generation';
+import { merge } from '@/utils/merge';
+import { setNamespace } from '@/utils/storeDebug';
+
+import type { VideoStore } from '../../store';
+import { type GenerationTopicDispatch, generationTopicReducer } from './reducer';
+import { generationTopicSelectors } from './selectors';
+
+const FETCH_GENERATION_TOPICS_KEY = 'fetchVideoGenerationTopics';
+
+const n = setNamespace('videoGenerationTopic');
+
+export interface GenerationTopicAction {
+ createGenerationTopic: (prompts: string[]) => Promise<string>;
+ internal_createGenerationTopic: () => Promise<string>;
+ internal_dispatchGenerationTopic: (payload: GenerationTopicDispatch, action?: any) => void;
+ internal_removeGenerationTopic: (id: string) => Promise<void>;
+ internal_updateGenerationTopic: (id: string, data: UpdateTopicValue) => Promise<void>;
+ internal_updateGenerationTopicCover: (topicId: string, coverUrl: string) => Promise<void>;
+ internal_updateGenerationTopicLoading: (id: string, loading: boolean) => void;
+ internal_updateGenerationTopicTitleInSummary: (id: string, title: string) => void;
+
+ openNewGenerationTopic: () => void;
+ refreshGenerationTopics: () => Promise<void>;
+ removeGenerationTopic: (id: string) => Promise<void>;
+ summaryGenerationTopicTitle: (topicId: string, prompts: string[]) => Promise<string>;
+ switchGenerationTopic: (topicId: string) => void;
+ updateGenerationTopicCover: (topicId: string, imageUrl: string) => Promise<void>;
+ useFetchGenerationTopics: (enabled: boolean) => SWRResponse<ImageGenerationTopic[]>;
+}
+
+export const createGenerationTopicSlice: StateCreator<
+ VideoStore,
+ [['zustand/devtools', never]],
+ [],
+ GenerationTopicAction
+> = (set, get) => ({
+ createGenerationTopic: async (prompts: string[]) => {
+ if (!prompts || prompts.length === 0) {
+ throw new Error('Prompts cannot be empty when creating a generation topic');
+ }
+
+ const { internal_createGenerationTopic, summaryGenerationTopicTitle } = get();
+
+ const topicId = await internal_createGenerationTopic();
+
+ summaryGenerationTopicTitle(topicId, prompts);
+
+ return topicId;
+ },
+
+ internal_createGenerationTopic: async () => {
+ const tmpId = Date.now().toString();
+
+ get().internal_dispatchGenerationTopic(
+ { type: 'addTopic', value: { id: tmpId, title: '' } },
+ 'internal_createGenerationTopic',
+ );
+
+ get().internal_updateGenerationTopicLoading(tmpId, true);
+
+ const topicId = await generationTopicService.createTopic('video');
+ get().internal_updateGenerationTopicLoading(tmpId, false);
+
+ get().internal_updateGenerationTopicLoading(topicId, true);
+ await get().refreshGenerationTopics();
+ get().internal_updateGenerationTopicLoading(topicId, false);
+
+ return topicId;
+ },
+
+ internal_dispatchGenerationTopic: (payload, action) => {
+ const nextTopics = generationTopicReducer(get().generationTopics, payload);
+
+ if (isEqual(nextTopics, get().generationTopics)) return;
+
+ set(
+ { generationTopics: nextTopics },
+ false,
+ action ?? n(`dispatchGenerationTopic/${payload.type}`),
+ );
+ },
+
+ internal_removeGenerationTopic: async (id: string) => {
+ get().internal_updateGenerationTopicLoading(id, true);
+ try {
+ await generationTopicService.deleteTopic(id);
+ await get().refreshGenerationTopics();
+ } finally {
+ get().internal_updateGenerationTopicLoading(id, false);
+ }
+ },
+
+ internal_updateGenerationTopic: async (id, data) => {
+ get().internal_dispatchGenerationTopic({ id, type: 'updateTopic', value: data });
+
+ get().internal_updateGenerationTopicLoading(id, true);
+
+ await generationTopicService.updateTopic(id, data);
+
+ await get().refreshGenerationTopics();
+ get().internal_updateGenerationTopicLoading(id, false);
+ },
+
+ internal_updateGenerationTopicCover: async (topicId: string, coverUrl: string) => {
+ const {
+ internal_dispatchGenerationTopic,
+ internal_updateGenerationTopicLoading,
+ refreshGenerationTopics,
+ } = get();
+
+ internal_dispatchGenerationTopic(
+ { id: topicId, type: 'updateTopic', value: { coverUrl } },
+ 'internal_updateGenerationTopicCover/optimistic',
+ );
+
+ internal_updateGenerationTopicLoading(topicId, true);
+
+ try {
+ await generationTopicService.updateTopicCover(topicId, coverUrl);
+
+ await refreshGenerationTopics();
+ } finally {
+ internal_updateGenerationTopicLoading(topicId, false);
+ }
+ },
+
+ internal_updateGenerationTopicLoading: (id, loading) => {
+ set(
+ (state) => {
+ if (loading) return { loadingGenerationTopicIds: [...state.loadingGenerationTopicIds, id] };
+
+ return {
+ loadingGenerationTopicIds: state.loadingGenerationTopicIds.filter((i) => i !== id),
+ };
+ },
+ false,
+ n('updateGenerationTopicLoading'),
+ );
+ },
+
+ internal_updateGenerationTopicTitleInSummary: (id, title) => {
+ get().internal_dispatchGenerationTopic(
+ { id, type: 'updateTopic', value: { title } },
+ 'updateGenerationTopicTitleInSummary',
+ );
+ },
+
+ openNewGenerationTopic: () => {
+ set({ activeGenerationTopicId: null }, false, n('openNewGenerationTopic'));
+ },
+
+ refreshGenerationTopics: async () => {
+ await mutate([FETCH_GENERATION_TOPICS_KEY]);
+ },
+
+ removeGenerationTopic: async (id: string) => {
+ const {
+ internal_removeGenerationTopic,
+ generationTopics,
+ activeGenerationTopicId,
+ switchGenerationTopic,
+ openNewGenerationTopic,
+ } = get();
+
+ const isRemovingActiveTopic = activeGenerationTopicId === id;
+ let topicIndexToRemove = -1;
+
+ if (isRemovingActiveTopic) {
+ topicIndexToRemove = generationTopics.findIndex((topic) => topic.id === id);
+ }
+
+ await internal_removeGenerationTopic(id);
+
+ if (isRemovingActiveTopic) {
+ const newTopics = get().generationTopics;
+
+ if (newTopics.length > 0) {
+ const newActiveIndex = Math.min(topicIndexToRemove, newTopics.length - 1);
+ const newActiveTopic = newTopics[newActiveIndex];
+
+ if (newActiveTopic) {
+ switchGenerationTopic(newActiveTopic.id);
+ } else {
+ openNewGenerationTopic();
+ }
+ } else {
+ openNewGenerationTopic();
+ }
+ }
+ },
+
+ summaryGenerationTopicTitle: async (topicId: string, prompts: string[]) => {
+ const topic = generationTopicSelectors.getGenerationTopicById(topicId)(get());
+ if (!topic) throw new Error(`Topic ${topicId} not found`);
+
+ const { internal_updateGenerationTopicTitleInSummary, internal_updateGenerationTopicLoading } =
+ get();
+
+ internal_updateGenerationTopicLoading(topicId, true);
+ internal_updateGenerationTopicTitleInSummary(topicId, LOADING_FLAT);
+
+ let output = '';
+
+ const generateFallbackTitle = () => {
+ const title = prompts[0]
+ .replaceAll(/[^\s\w\u4E00-\u9FFF]/g, '')
+ .trim()
+ .split(/\s+/)
+ .slice(0, 3)
+ .join(' ')
+ .slice(0, 20);
+
+ return title;
+ };
+
+ const generationTopicAgentConfig = systemAgentSelectors.generationTopic(
+ useUserStore.getState(),
+ );
+ await chatService.fetchPresetTaskResult({
+ onError: async () => {
+ const fallbackTitle = generateFallbackTitle();
+ internal_updateGenerationTopicTitleInSummary(topicId, fallbackTitle);
+ await get().internal_updateGenerationTopic(topicId, { title: fallbackTitle });
+ },
+ onFinish: async (text) => {
+ await get().internal_updateGenerationTopic(topicId, { title: text });
+ },
+ onLoadingChange: (loading) => {
+ internal_updateGenerationTopicLoading(topicId, loading);
+ },
+ onMessageHandle: (chunk) => {
+ switch (chunk.type) {
+ case 'text': {
+ output += chunk.text;
+ internal_updateGenerationTopicTitleInSummary(topicId, output);
+ }
+ }
+ },
+ params: merge(
+ generationTopicAgentConfig,
+ chainSummaryGenerationTitle(prompts, 'video', globalHelpers.getCurrentLanguage()),
+ ),
+ });
+
+ return output;
+ },
+
+ switchGenerationTopic: (topicId: string) => {
+ const currentTopics = get().generationTopics;
+ const targetTopic = currentTopics.find((topic) => topic.id === topicId);
+
+ if (!targetTopic) {
+ console.warn(`Generation topic with id ${topicId} not found`);
+ return;
+ }
+
+ if (get().activeGenerationTopicId === topicId) return;
+
+ set({ activeGenerationTopicId: topicId }, false, n('switchGenerationTopic'));
+ },
+
+ updateGenerationTopicCover: async (topicId: string, coverUrl: string) => {
+ const { internal_updateGenerationTopicCover } = get();
+ await internal_updateGenerationTopicCover(topicId, coverUrl);
+ },
+
+ useFetchGenerationTopics: (enabled) =>
+ useClientDataSWR<ImageGenerationTopic[]>(
+ enabled ? [FETCH_GENERATION_TOPICS_KEY] : null,
+ () => generationTopicService.getAllGenerationTopics('video'),
+ {
+ onSuccess: (data) => {
+ if (isEqual(data, get().generationTopics)) return;
+ set({ generationTopics: data }, false, n('useFetchGenerationTopics'));
+ },
+ suspense: true,
+ },
+ ),
+});
diff --git a/src/store/video/slices/generationTopic/index.ts b/src/store/video/slices/generationTopic/index.ts
new file mode 100644
index 00000000000..ffc794fb368
--- /dev/null
+++ b/src/store/video/slices/generationTopic/index.ts
@@ -0,0 +1,2 @@
+export * from './action';
+export * from './selectors';
diff --git a/src/store/video/slices/generationTopic/initialState.ts b/src/store/video/slices/generationTopic/initialState.ts
new file mode 100644
index 00000000000..1d4bf4631a4
--- /dev/null
+++ b/src/store/video/slices/generationTopic/initialState.ts
@@ -0,0 +1,14 @@
+import { type ImageGenerationTopic } from '@/types/generation';
+
+export interface GenerationTopicState {
+ activeGenerationTopicId: string | null;
+ generationTopics: ImageGenerationTopic[];
+ loadingGenerationTopicIds: string[];
+}
+
+export const initialGenerationTopicState: GenerationTopicState = {
+ activeGenerationTopicId:
+ typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('topic') : null,
+ generationTopics: [],
+ loadingGenerationTopicIds: [],
+};
diff --git a/src/store/video/slices/generationTopic/reducer.ts b/src/store/video/slices/generationTopic/reducer.ts
new file mode 100644
index 00000000000..b1e0ca6c695
--- /dev/null
+++ b/src/store/video/slices/generationTopic/reducer.ts
@@ -0,0 +1,66 @@
+import { produce } from 'immer';
+
+import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
+import { type ImageGenerationTopic } from '@/types/generation';
+
+interface AddGenerationTopicAction {
+ type: 'addTopic';
+ value: Partial<ImageGenerationTopic> & { id: string };
+}
+
+interface UpdateGenerationTopicAction {
+ id: string;
+ type: 'updateTopic';
+ value: UpdateTopicValue;
+}
+
+interface DeleteGenerationTopicAction {
+ id: string;
+ type: 'deleteTopic';
+}
+
+export type GenerationTopicDispatch =
+ | AddGenerationTopicAction
+ | UpdateGenerationTopicAction
+ | DeleteGenerationTopicAction;
+
+export const generationTopicReducer = (
+ state: ImageGenerationTopic[] = [],
+ payload: GenerationTopicDispatch,
+): ImageGenerationTopic[] => {
+ switch (payload.type) {
+ case 'addTopic': {
+ return produce(state, (draftState) => {
+ const now = new Date();
+ draftState.unshift({
+ coverUrl: payload.value.coverUrl || null,
+ createdAt: payload.value.createdAt || now,
+ title: payload.value.title || null,
+ updatedAt: payload.value.updatedAt || now,
+ ...payload.value,
+ });
+ });
+ }
+
+ case 'updateTopic': {
+ return produce(state, (draftState) => {
+ const index = draftState.findIndex((topic) => topic.id === payload.id);
+ if (index !== -1) {
+ draftState[index] = {
+ ...draftState[index],
+ ...payload.value,
+ updatedAt: new Date(),
+ };
+ }
+ });
+ }
+
+ case 'deleteTopic': {
+ return state.filter((topic) => topic.id !== payload.id);
+ }
+
+ default: {
+ return state;
+ }
+ }
+};
diff --git a/src/store/video/slices/generationTopic/selectors.ts b/src/store/video/slices/generationTopic/selectors.ts
new file mode 100644
index 00000000000..4229418175a
--- /dev/null
+++ b/src/store/video/slices/generationTopic/selectors.ts
@@ -0,0 +1,15 @@
+import { type VideoStoreState } from '../../initialState';
+
+const activeGenerationTopicId = (s: VideoStoreState) => s.activeGenerationTopicId;
+const generationTopics = (s: VideoStoreState) => s.generationTopics;
+const getGenerationTopicById = (id: string) => (s: VideoStoreState) =>
+ s.generationTopics.find((topic) => topic.id === id);
+const isLoadingGenerationTopic = (id: string) => (s: VideoStoreState) =>
+ s.loadingGenerationTopicIds.includes(id);
+
+export const generationTopicSelectors = {
+ activeGenerationTopicId,
+ generationTopics,
+ getGenerationTopicById,
+ isLoadingGenerationTopic,
+};
diff --git a/src/store/video/store.ts b/src/store/video/store.ts
new file mode 100644
index 00000000000..2a971e37801
--- /dev/null
+++ b/src/store/video/store.ts
@@ -0,0 +1,49 @@
+import { subscribeWithSelector } from 'zustand/middleware';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+import { type StateCreator } from 'zustand/vanilla';
+
+import { createDevtools } from '../middleware/createDevtools';
+import { type VideoStoreState, initialState } from './initialState';
+import { type CreateVideoAction, createCreateVideoSlice } from './slices/createVideo/action';
+import {
+ type GenerationBatchAction,
+ createGenerationBatchSlice,
+} from './slices/generationBatch/action';
+import {
+ type GenerationConfigAction,
+ createGenerationConfigSlice,
+} from './slices/generationConfig/action';
+import {
+ type GenerationTopicAction,
+ createGenerationTopicSlice,
+} from './slices/generationTopic/action';
+
+// =============== aggregate createStoreFn ============ //
+
+export interface VideoStore
+ extends
+ GenerationConfigAction,
+ GenerationTopicAction,
+ GenerationBatchAction,
+ CreateVideoAction,
+ VideoStoreState {}
+
+const createStore: StateCreator<VideoStore, [['zustand/devtools', never]]> = (...parameters) => ({
+ ...initialState,
+ ...createGenerationConfigSlice(...parameters),
+ ...createGenerationTopicSlice(...parameters),
+ ...createGenerationBatchSlice(...parameters),
+ ...createCreateVideoSlice(...parameters),
+});
+
+// =============== implement useStore ============ //
+
+const devtools = createDevtools('video');
+
+export const useVideoStore = createWithEqualityFn<VideoStore>()(
+ subscribeWithSelector(devtools(createStore)),
+ shallow,
+);
+
+export const getVideoStoreState = () => useVideoStore.getState();