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.

🐛 fix(video): surface the real failure when a video error batch is returned (#20493)

Arvin Xuc0d4aa72a49c
diff --git a/apps/server/src/routers/lambda/__tests__/video.test.ts b/apps/server/src/routers/lambda/__tests__/video.test.ts
index 66ad76121dd..54bc36a00ca 100644
--- a/apps/server/src/routers/lambda/__tests__/video.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/video.test.ts
@@ -27,6 +27,9 @@ const {
generationBatches: {
findFirst: vi.fn(),
},
+ generations: {
+ findMany: vi.fn(),
+ },
},
transaction: mockTransaction,
};
@@ -710,6 +713,31 @@ describe('videoRouter', () => {
// Should not proceed to createVideo
expect(mockCreateVideo).not.toHaveBeenCalled();
});
+ it('should link error batch generations to their errored async task', async () => {
+ setupMocks();
+ const { chargeBeforeGenerate } =
+ await import('@/business/server/video-generation/chargeBeforeGenerate');
+ // The billing layer links the generation to its errored async task after
+ // inserting it, so the row it returns carries no asyncTaskId.
+ vi.mocked(chargeBeforeGenerate).mockResolvedValueOnce({
+ errorBatch: {
+ data: {
+ batch: { id: 'batch-err' } as any,
+ generations: [{ asyncTaskId: null, id: 'gen-err' } as any],
+ },
+ success: true,
+ },
+ });
+ mockServerDB.query.generations.findMany.mockResolvedValueOnce([
+ { asyncTaskId: 'async-err', id: 'gen-err' },
+ ]);
+
+ const caller = videoRouter.createCaller(mockCtx);
+ const result = await caller.createVideo(defaultInput);
+
+ expect(result.data?.generations?.[0]).toEqual({ asyncTaskId: 'async-err', id: 'gen-err' });
+ expect(mockCreateVideo).not.toHaveBeenCalled();
+ });
});
describe('createVideo - return value', () => {
diff --git a/apps/server/src/routers/lambda/video/index.ts b/apps/server/src/routers/lambda/video/index.ts
index 2391a5137a1..42b96b81137 100644
--- a/apps/server/src/routers/lambda/video/index.ts
+++ b/apps/server/src/routers/lambda/video/index.ts
@@ -16,7 +16,7 @@ import {
import { isRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, inArray } from 'drizzle-orm';
import { supportsConversationalVideoEdit } from 'model-bank/standardParameters';
import { z } from 'zod';
@@ -38,6 +38,7 @@ import {
type NewGenerationBatch,
} from '@/database/schemas';
import { getServerDB } from '@/database/server';
+import type { LobeChatDatabase } from '@/database/type';
import { appEnv } from '@/envs/app';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -63,6 +64,48 @@ const getVideoGenerationRoute = (value: unknown): VideoGenerationRoute | undefin
};
};
+type ChargeErrorBatch = NonNullable<
+ Awaited<ReturnType<typeof chargeBeforeGenerate>>['errorBatch']
+>;
+
+/**
+ * An error batch (insufficient budget, frozen workspace, …) links each generation to
+ * an errored async task after inserting it, so the returned rows may lack
+ * `asyncTaskId`. Callers such as the generateVideo tool need that id to read the
+ * real failure reason, so fill it in from the persisted rows.
+ */
+const withErrorBatchAsyncTaskIds = async (
+ db: LobeChatDatabase,
+ userId: string,
+ errorBatch: ChargeErrorBatch,
+): Promise<ChargeErrorBatch> => {
+ const items = errorBatch.data?.generations;
+ if (!Array.isArray(items)) return errorBatch;
+
+ const missingIds = items
+ .filter((item) => !item.asyncTaskId && typeof item.id === 'string')
+ .map((item) => item.id as string);
+ if (missingIds.length === 0) return errorBatch;
+
+ const rows = await db.query.generations.findMany({
+ columns: { asyncTaskId: true, id: true },
+ where: and(inArray(generations.id, missingIds), eq(generations.userId, userId)),
+ });
+ const taskIdByGenerationId = new Map(rows.map((row) => [row.id, row.asyncTaskId]));
+
+ return {
+ ...errorBatch,
+ data: {
+ ...errorBatch.data,
+ generations: items.map((item) =>
+ item.asyncTaskId || !item.id
+ ? item
+ : { ...item, asyncTaskId: taskIdByGenerationId.get(item.id) ?? item.asyncTaskId },
+ ),
+ },
+ };
+};
+
const videoProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -293,7 +336,7 @@ export const videoRouter = router({
userId,
workspaceId: wsId,
});
- if (errorBatch) return errorBatch;
+ if (errorBatch) return withErrorBatchAsyncTaskIds(serverDB, userId, errorBatch);
// Generate a one-time token for webhook callback verification
const webhookToken = randomBytes(32).toString('hex');
diff --git a/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.test.ts
index c5c50484d0d..0e3ab93d42c 100644
--- a/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.test.ts
@@ -164,6 +164,51 @@ describe('VideoGenerationExecutionRuntime', () => {
expect(result.content).toContain('Use getVideoGenerationStatus');
});
+ it('reports a rejected pre-charge instead of a started task in no-wait mode', async () => {
+ const service = createService({
+ getGenerationStatus: vi.fn().mockResolvedValue({
+ asyncTaskId: 'task-1',
+ error: {
+ body: { detail: 'Insufficient balance to start this video generation.' },
+ name: 'InsufficientBalance',
+ },
+ generation: null,
+ generationId: 'generation-1',
+ status: AsyncTaskStatus.Error,
+ }),
+ });
+ const runtime = new VideoGenerationExecutionRuntime(service);
+
+ const result = await runtime.generateVideo({
+ prompt: 'A paper airplane gliding over a miniature city',
+ waitUntilComplete: false,
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ type: 'GenerateVideoFailed' });
+ expect(result.content).toContain('Insufficient balance to start this video generation.');
+ expect(result.content).not.toContain('Video generation started');
+ expect(service.getGenerationStatus).toHaveBeenCalledWith({
+ asyncTaskId: 'task-1',
+ generationId: 'generation-1',
+ });
+ });
+
+ it('keeps reporting a started task when the first status read fails', async () => {
+ const service = createService({
+ getGenerationStatus: vi.fn().mockRejectedValue(new Error('status endpoint unavailable')),
+ });
+ const runtime = new VideoGenerationExecutionRuntime(service);
+
+ const result = await runtime.generateVideo({
+ prompt: 'A calm ocean aerial shot',
+ waitUntilComplete: false,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Use getVideoGenerationStatus');
+ });
+
it('falls back to the selected model latency for estimated progress', async () => {
const runtime = new VideoGenerationExecutionRuntime(createService());
diff --git a/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.ts b/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.ts
index 8729ba71b03..d81107e1edd 100644
--- a/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-video-generation/src/ExecutionRuntime/index.ts
@@ -514,6 +514,31 @@ export class VideoGenerationExecutionRuntime {
}
}
+ /**
+ * Read the freshly created task once. Returns the task when it is already in a terminal
+ * error, so no-wait callers do not report a rejected pre-charge as a started generation.
+ * Returns undefined when the task is still running or the status cannot be read — the run
+ * did start, so the caller keeps reporting it as started instead of inventing a failure.
+ */
+ private async readFailedTask(task: GeneratedVideoTask): Promise<GeneratedVideoTask | undefined> {
+ try {
+ const status = await this.service.getGenerationStatus({
+ asyncTaskId: task.asyncTaskId,
+ generationId: task.generationId,
+ });
+ if (status.status !== AsyncTaskStatus.Error) return undefined;
+
+ return {
+ ...task,
+ asset: status.generation?.asset ?? task.asset,
+ error: status.error,
+ status: status.status,
+ };
+ } catch {
+ return undefined;
+ }
+ }
+
async generateVideo(
args: GenerateVideoParams,
context: GenerateVideoRuntimeContext = {},
@@ -594,6 +619,18 @@ export class VideoGenerationExecutionRuntime {
};
if (!waitUntilComplete) {
+ // A pre-charge failure (insufficient budget, frozen workspace, …) still inserts the
+ // generation and links it to an already errored async task, so the batch no longer
+ // tells the two cases apart. Read the task once and report a terminal failure as a
+ // failure instead of announcing a generation that never started.
+ const failedTask = await this.readFailedTask(state.generation);
+ if (failedTask) {
+ const failedState: GenerateVideoState = { ...state, generation: failedTask };
+ return errorOutput('GenerateVideoFailed', formatFailedContent(failedState), {
+ ...failedState,
+ });
+ }
+
return {
content: formatStartedContent(state),
state,