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.

♻️ refactor: improve video generation webhook and type safety

YuTengjing661f1a80b45a
diff --git a/locales/en-US/video.json b/locales/en-US/video.json
index 2e483d1079b..37936398842 100644
--- a/locales/en-US/video.json
+++ b/locales/en-US/video.json
@@ -11,9 +11,13 @@
"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...",
+ "generation.validation.endFrameRequiresStartFrame": "End frame cannot be used without a start frame. Please set a start frame first.",
"topic.createNew": "New Topic",
"topic.deleteConfirm": "Delete Video Topic",
"topic.deleteConfirmDesc": "You are about to delete this video topic. This action cannot be undone.",
diff --git a/locales/zh-CN/video.json b/locales/zh-CN/video.json
index f0c2adebe81..c16d9204266 100644
--- a/locales/zh-CN/video.json
+++ b/locales/zh-CN/video.json
@@ -11,9 +11,13 @@
"config.resolution.label": "分辨率",
"config.seed.label": "种子",
"config.seed.random": "随机",
+ "generation.actions.copyError": "复制错误信息",
+ "generation.actions.errorCopied": "错误信息已复制到剪贴板",
+ "generation.actions.errorCopyFailed": "复制遇到了问题。你可以再试一次",
"generation.actions.generate": "生成",
- "generation.validation.endFrameRequiresStartFrame": "不支持单独设置尾帧,请先设置起始帧",
+ "generation.status.failed": "生成遇到了问题。你可以重试,或调整描述后再试",
"generation.status.generating": "生成中...",
+ "generation.validation.endFrameRequiresStartFrame": "不支持单独设置尾帧,请先设置起始帧",
"topic.createNew": "新建主题",
"topic.deleteConfirm": "删除视频主题",
"topic.deleteConfirmDesc": "确认删除该视频主题吗?删除后无法恢复",
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index c5d96e791eb..0def9c36e20 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -37,8 +37,8 @@ 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({
+ static findByInferenceId = async (db: LobeChatDatabase, inferenceId: string) => {
+ return db.query.asyncTasks.findFirst({
where: eq(asyncTasks.inferenceId, inferenceId),
});
};
diff --git a/packages/database/src/models/generationBatch.ts b/packages/database/src/models/generationBatch.ts
index 02c39a928f7..ac5cb1faa0b 100644
--- a/packages/database/src/models/generationBatch.ts
+++ b/packages/database/src/models/generationBatch.ts
@@ -181,7 +181,7 @@ export class GenerationBatchModel {
): Promise<{ deletedBatch: GenerationBatchItem; filesToDelete: string[] } | undefined> {
log('Deleting generation batch: %s for user: %s', id, this.userId);
- // 1. First, get generations with their assets to collect thumbnail URLs
+ // 1. First, get generations with their assets to collect file URLs for cleanup
const batchWithGenerations = await this.db.query.generationBatches.findFirst({
where: and(eq(generationBatches.id, id), eq(generationBatches.userId, this.userId)),
with: {
diff --git a/packages/database/src/models/generationTopic.ts b/packages/database/src/models/generationTopic.ts
index 37ec1015654..09c8d820059 100644
--- a/packages/database/src/models/generationTopic.ts
+++ b/packages/database/src/models/generationTopic.ts
@@ -6,6 +6,7 @@ import { FileService } from '@/server/services/file';
import type { GenerationTopicItem } from '../schemas/generation';
import { generationTopics } from '../schemas/generation';
import type { LobeChatDatabase } from '../type';
+import type { GenerationTopicType } from '../types/generation';
export class GenerationTopicModel {
private userId: string;
@@ -18,7 +19,7 @@ export class GenerationTopicModel {
this.fileService = new FileService(db, userId);
}
- queryAll = async (type?: string) => {
+ queryAll = async (type?: GenerationTopicType) => {
const conditions = [eq(generationTopics.userId, this.userId)];
if (type) {
conditions.push(eq(generationTopics.type, type));
@@ -43,7 +44,7 @@ export class GenerationTopicModel {
);
};
- create = async (title: string, type?: string) => {
+ create = async (title: string, type?: GenerationTopicType) => {
const [newGenerationTopic] = await this.db
.insert(generationTopics)
.values({
diff --git a/packages/database/src/types/generation.ts b/packages/database/src/types/generation.ts
new file mode 100644
index 00000000000..e3591b96d18
--- /dev/null
+++ b/packages/database/src/types/generation.ts
@@ -0,0 +1 @@
+export type GenerationTopicType = 'image' | 'video';
diff --git a/src/app/(backend)/api/webhooks/video/[provider]/route.ts b/src/app/(backend)/api/webhooks/video/[provider]/route.ts
index c7ff106f284..e3e072fb1f1 100644
--- a/src/app/(backend)/api/webhooks/video/[provider]/route.ts
+++ b/src/app/(backend)/api/webhooks/video/[provider]/route.ts
@@ -57,10 +57,9 @@ export const POST = async (req: Request, { params }: { params: Promise<{ provide
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);
+ const asyncTask = await AsyncTaskModel.findByInferenceId(db, result.inferenceId);
if (!asyncTask) {
log('AsyncTask not found for inferenceId: %s', result.inferenceId);
return NextResponse.json(
@@ -103,6 +102,15 @@ export const POST = async (req: Request, { params }: { params: Promise<{ provide
log('Found generation: %s', generation.id);
+ asyncTaskModel = new AsyncTaskModel(db, asyncTask.userId);
+
+ // Query batch to get model info for both error and success paths
+ const batch = await db.query.generationBatches.findFirst({
+ where: eq(generationBatches.id, generation.generationBatchId!),
+ });
+ const resolvedModel =
+ result.status === 'success' ? (result.model ?? batch?.model ?? '') : (batch?.model ?? '');
+
// Handle error result: refund precharge and mark task as error
if (result.status === 'error') {
log('Video generation failed: %s', result.error);
@@ -117,10 +125,10 @@ export const POST = async (req: Request, { params }: { params: Promise<{ provide
metadata: {
asyncTaskId: asyncTask.id,
generationBatchId: generation.generationBatchId!,
- modelId: '',
- topicId: undefined,
+ modelId: resolvedModel,
+ topicId: batch?.generationTopicId,
},
- model: '',
+ model: resolvedModel,
prechargeResult: (asyncTask.metadata as any)?.precharge,
provider,
userId: asyncTask.userId,
@@ -166,19 +174,15 @@ export const POST = async (req: Request, { params }: { params: Promise<{ provide
// 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 ?? '',
+ modelId: resolvedModel,
topicId: batch?.generationTopicId,
},
- model: result.model ?? batch?.model ?? '',
+ model: resolvedModel,
prechargeResult: (asyncTask.metadata as any)?.precharge,
provider,
usage: result.usage,