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: support Gemini Omni video generation and editing (#17572)

YuTengjingf5931b12b537
diff --git a/apps/server/src/router-hono/webhooks/handlers/video.ts b/apps/server/src/router-hono/webhooks/handlers/video.ts
index 85324949cf2..8099407c171 100644
--- a/apps/server/src/router-hono/webhooks/handlers/video.ts
+++ b/apps/server/src/router-hono/webhooks/handlers/video.ts
@@ -4,7 +4,7 @@ import {
buildMappedBusinessModelFields,
resolveBusinessModelMapping,
} from '@lobechat/business-model-runtime';
-import { ModelRuntime } from '@lobechat/model-runtime';
+import { ModelRuntime, type VideoGenerationUsage } from '@lobechat/model-runtime';
import {
AsyncTaskError,
AsyncTaskErrorType,
@@ -25,6 +25,7 @@ import { AsyncTaskModel } from '@/database/models/asyncTask';
import { GenerationModel } from '@/database/models/generation';
import { generationBatches } from '@/database/schemas';
import { getServerDB } from '@/database/server';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { VideoGenerationService } from '@/server/services/generation/video';
import { sanitizeFileName } from '@/utils/sanitizeFileName';
@@ -45,8 +46,10 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>
const provider = c.req.param('provider');
let body: any;
+ let rawBody: string;
try {
- body = await c.req.json();
+ rawBody = await c.req.text();
+ body = JSON.parse(rawBody);
} catch {
return c.json({ error: 'Invalid JSON body' }, 400);
}
@@ -63,31 +66,40 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>
const runtime = ModelRuntime.initializeWithProvider(provider, {
apiKey: 'webhook-placeholder',
});
- const result = await runtime.handleCreateVideoWebhook({ body });
+ const url = new URL(c.req.url);
+ const webhookResult = await runtime.handleCreateVideoWebhook({
+ body,
+ headers: Object.fromEntries(c.req.raw.headers.entries()),
+ model: url.searchParams.get('model') ?? undefined,
+ rawBody,
+ url: c.req.url,
+ });
- if (!result) {
+ if (!webhookResult) {
return c.json({ error: `Provider ${provider} does not support video webhook` }, 400);
}
// Skip intermediate statuses (e.g. queued, running)
- if (result.status === 'pending') {
+ if (webhookResult.status === 'pending') {
log('Skipping intermediate status for provider: %s', provider);
return c.json({ success: true });
}
- log('Webhook parse result: %O', result);
+ log('Webhook parse result: %O', webhookResult);
const db = await getServerDB();
// Find asyncTask by inferenceId
- const asyncTask = await AsyncTaskModel.findByInferenceId(db, result.inferenceId);
+ const asyncTask = await AsyncTaskModel.findByInferenceId(db, webhookResult.inferenceId);
if (!asyncTask) {
- log('AsyncTask not found for inferenceId: %s', result.inferenceId);
- return c.json({ error: `AsyncTask not found for inferenceId: ${result.inferenceId}` }, 404);
+ log('AsyncTask not found for inferenceId: %s', webhookResult.inferenceId);
+ return c.json(
+ { error: `AsyncTask not found for inferenceId: ${webhookResult.inferenceId}` },
+ 404,
+ );
}
// Verify webhook token to prevent forged callbacks
- const url = new URL(c.req.url);
const token = url.searchParams.get('token');
const metadata = asyncTask.metadata as VideoGenerationTaskMetadata | undefined;
const expectedToken = metadata?.webhookToken;
@@ -153,6 +165,76 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>
resolvedModelId,
});
+ let result:
+ | {
+ error: string;
+ inferenceId: string;
+ status: 'error';
+ }
+ | {
+ headers?: Record<string, string>;
+ inferenceId: string;
+ status: 'success';
+ usage?: VideoGenerationUsage;
+ videoUrl: string;
+ };
+
+ if (webhookResult.status === 'completed') {
+ const userRuntime = await initModelRuntimeFromDB(
+ db,
+ asyncTask.userId,
+ provider,
+ asyncTask.workspaceId ?? undefined,
+ );
+ const pollResult = await userRuntime.handlePollVideoStatus(
+ webhookResult.inferenceId,
+ // Match the model id the route was pinned for at creation, not the user-facing alias.
+ resolvedModelId,
+ metadata?.route,
+ );
+
+ if (!pollResult) {
+ throw new Error(`Provider ${provider} does not support video polling`);
+ }
+
+ if (pollResult.status === 'pending') {
+ log(
+ 'Interaction completed but generated video file is still processing: %s',
+ webhookResult.inferenceId,
+ );
+ return c.json({ error: 'Generated video file is still processing' }, 503);
+ }
+
+ const pollHeaders = 'headers' in pollResult ? pollResult.headers : undefined;
+
+ result =
+ pollResult.status === 'failed'
+ ? {
+ error: pollResult.error,
+ inferenceId: webhookResult.inferenceId,
+ status: 'error',
+ }
+ : {
+ headers: pollHeaders,
+ inferenceId: webhookResult.inferenceId,
+ status: 'success',
+ usage: pollResult.usage,
+ videoUrl: pollResult.videoUrl,
+ };
+ } else {
+ result = webhookResult;
+ }
+
+ const claimed = await AsyncTaskModel.claimVideoCompletion(
+ db,
+ asyncTask.id,
+ c.req.header('webhook-id') ?? undefined,
+ );
+ if (!claimed) {
+ log('AsyncTask %s completion already claimed, skipping duplicate webhook', asyncTask.id);
+ return c.json({ success: true });
+ }
+
// Handle error result: refund precharge and mark task as error
if (result.status === 'error') {
log('Video generation failed: %s', result.error);
@@ -190,13 +272,17 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>
asyncTask.userId,
asyncTask.workspaceId ?? undefined,
);
- const processResult = await videoService.processVideoForGeneration(result.videoUrl);
+ const processResult = await videoService.processVideoForGeneration(result.videoUrl, {
+ headers: result.headers,
+ });
const asset: VideoGenerationAsset = {
coverUrl: processResult.coverKey,
duration: processResult.duration,
height: processResult.height,
- originalUrl: result.videoUrl,
+ interactionId: result.inferenceId,
+ originalUrl: result.videoUrl.startsWith('data:') ? undefined : result.videoUrl,
+ previousGenerationId: metadata?.previousGenerationId,
thumbnailUrl: processResult.thumbnailKey,
type: 'video',
url: processResult.videoKey,
diff --git a/apps/server/src/routers/async/video.ts b/apps/server/src/routers/async/video.ts
index 9ede16a7cc4..0be5e57aac5 100644
--- a/apps/server/src/routers/async/video.ts
+++ b/apps/server/src/routers/async/video.ts
@@ -65,10 +65,11 @@ const checkAbortSignal = (signal: AbortSignal) => {
async function pollUntilCompletion(
modelRuntime: any,
inferenceId: string,
+ model: string,
signal: AbortSignal,
): Promise<{ headers?: Record<string, string>; videoUrl: string } | null> {
- const maxRetries = 120;
const pollingInterval = 5000;
+ const maxRetries = Math.ceil(ASYNC_TASK_TIMEOUT / pollingInterval);
for (let attempt = 0; attempt < maxRetries; attempt++) {
checkAbortSignal(signal);
@@ -76,7 +77,7 @@ async function pollUntilCompletion(
try {
log('Polling attempt %d/%d for inferenceId: %s', attempt + 1, maxRetries, inferenceId);
- const result = await modelRuntime.handlePollVideoStatus(inferenceId);
+ const result = await modelRuntime.handlePollVideoStatus(inferenceId, model);
if (result.status === 'success') {
log('Video generation succeeded for inferenceId: %s', inferenceId);
@@ -172,7 +173,7 @@ export const videoRouter = router({
checkAbortSignal(signal);
- const pollResult = await pollUntilCompletion(modelRuntime, inferenceId, signal);
+ const pollResult = await pollUntilCompletion(modelRuntime, inferenceId, model, signal);
if (!pollResult) {
log('Polling completed but no video URL returned for inferenceId: %s', inferenceId);
diff --git a/apps/server/src/routers/lambda/__tests__/video.test.ts b/apps/server/src/routers/lambda/__tests__/video.test.ts
index bc960e16194..c49fc02a5ca 100644
--- a/apps/server/src/routers/lambda/__tests__/video.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/video.test.ts
@@ -8,6 +8,7 @@ import { AsyncTaskStatus } from '@/types/asyncTask';
const {
mockCreateVideo,
+ mockFindPreviousGeneration,
mockFindUserById,
mockGenerationTopicFindById,
mockGetVideoAvgLatencies,
@@ -15,15 +16,29 @@ const {
mockProcessBackgroundVideoPolling,
mockResolveBusinessModelMapping,
mockAfter,
+ mockAppEnv,
mockServerDB,
mockTransaction,
} = vi.hoisted(() => {
const mockTransaction = vi.fn();
- const mockServerDB = { transaction: mockTransaction };
+ const mockServerDB = {
+ query: {
+ generationBatches: {
+ findFirst: vi.fn(),
+ },
+ },
+ transaction: mockTransaction,
+ };
const mockCreateVideo = vi.fn();
const mockAfter = vi.fn(function (cb: () => void) {
return cb();
});
+ const mockAppEnv = {
+ APP_URL: 'https://app.example.com',
+ VIDEO_GENERATION_PREFER_WEBHOOK: false,
+ WEBHOOK_PROXY_URL: undefined as string | undefined,
+ };
+ const mockFindPreviousGeneration = vi.fn();
const mockFindUserById = vi.fn();
const mockGenerationTopicFindById = vi.fn();
const mockGetVideoAvgLatencies = vi.fn();
@@ -32,6 +47,7 @@ const {
const mockResolveBusinessModelMapping = vi.fn();
return {
mockCreateVideo,
+ mockFindPreviousGeneration,
mockFindUserById,
mockGenerationTopicFindById,
mockGetVideoAvgLatencies,
@@ -39,6 +55,7 @@ const {
mockProcessBackgroundVideoPolling,
mockResolveBusinessModelMapping,
mockAfter,
+ mockAppEnv,
mockServerDB,
mockTransaction,
};
@@ -47,6 +64,11 @@ const {
// ---- module-level mocks ----
vi.mock('@/database/models/asyncTask');
+vi.mock('@/database/models/generation', () => ({
+ GenerationModel: vi.fn(function () {
+ return { findById: mockFindPreviousGeneration };
+ }),
+}));
vi.mock('@/database/models/generationTopic', () => ({
GenerationTopicModel: vi.fn(function () {
return {
@@ -105,7 +127,7 @@ vi.mock('@/server/services/generation/latency', () => ({
`${provider}\0${model}`,
}));
vi.mock('@/envs/app', () => ({
- appEnv: { APP_URL: 'https://app.example.com' },
+ appEnv: mockAppEnv,
}));
vi.mock('debug', () => ({
default: vi.fn(function () {
@@ -152,14 +174,16 @@ const mockDbUpdate = vi.fn().mockReturnValue({
function setupMocks() {
const mockUpdate = vi.fn().mockResolvedValue(undefined);
+ const mockGetFullFileUrl = vi.fn().mockResolvedValue(null);
+ const mockGetKeyFromFullUrl = vi.fn().mockResolvedValue(null);
vi.mocked(AsyncTaskModel).mockImplementation(function () {
return { update: mockUpdate } as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
- getFullFileUrl: vi.fn().mockResolvedValue(null),
- getKeyFromFullUrl: vi.fn().mockResolvedValue(null),
+ getFullFileUrl: mockGetFullFileUrl,
+ getKeyFromFullUrl: mockGetKeyFromFullUrl,
} as any;
});
@@ -168,7 +192,7 @@ function setupMocks() {
cb({ insert: mockInsert, update: mockDbUpdate }),
);
- return { mockUpdate };
+ return { mockGetFullFileUrl, mockGetKeyFromFullUrl, mockInsert, mockUpdate };
}
// ---- import router AFTER mocks are set up ----
@@ -188,35 +212,287 @@ describe('videoRouter', () => {
}),
);
mockFindUserById.mockResolvedValue({ email: '[email protected]' });
+ mockFindPreviousGeneration.mockResolvedValue(undefined);
mockGenerationTopicFindById.mockResolvedValue({ id: 'topic-1' });
mockGetVideoAvgLatencies.mockResolvedValue(new Map());
mockIsLobeHubModelAvailable.mockResolvedValue(true);
+ mockServerDB.query.generationBatches.findFirst.mockResolvedValue(undefined);
+ mockAppEnv.VIDEO_GENERATION_PREFER_WEBHOOK = false;
+ mockAppEnv.WEBHOOK_PROXY_URL = undefined;
});
describe('createVideo - async strategy routing', () => {
- it('should use webhook path when response contains useWebhook: true', async () => {
+ it('should use the webhook path when selected by the runtime', async () => {
const { mockUpdate } = setupMocks();
- mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-1', useWebhook: true });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'inf-1',
+ });
const caller = videoRouter.createCaller(mockCtx);
const result = await caller.createVideo(defaultInput);
expect(result.success).toBe(true);
+ expect(mockCreateVideo).toHaveBeenCalledWith(
+ expect.objectContaining({
+ callbackUrl: expect.stringMatching(/^https:\/\/app\.example\.com\/api\/webhooks\/video/),
+ }),
+ expect.objectContaining({ preferredCompletionMode: 'polling' }),
+ );
expect(mockUpdate).toHaveBeenCalledWith('async-1', {
inferenceId: 'inf-1',
+ metadata: {
+ completionMode: 'webhook',
+ webhookToken: expect.any(String),
+ },
status: AsyncTaskStatus.Processing,
});
// Webhook: should NOT trigger background polling
expect(mockAfter).not.toHaveBeenCalled();
});
+ it('should pass the webhook preference and typed proxy callback URL to the runtime', async () => {
+ setupMocks();
+ mockAppEnv.VIDEO_GENERATION_PREFER_WEBHOOK = true;
+ mockAppEnv.WEBHOOK_PROXY_URL = 'https://local-tunnel.example.com';
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'inf-proxy',
+ });
+
+ const caller = videoRouter.createCaller(mockCtx);
+ await caller.createVideo(defaultInput);
+
+ expect(mockCreateVideo).toHaveBeenCalledWith(
+ expect.objectContaining({
+ callbackUrl: expect.stringMatching(
+ /^https:\/\/local-tunnel\.example\.com\/api\/webhooks\/video/,
+ ),
+ }),
+ expect.objectContaining({ preferredCompletionMode: 'webhook' }),
+ );
+ });
+
+ it('should keep a path prefix from the configured callback base URL', async () => {
+ setupMocks();
+ mockAppEnv.WEBHOOK_PROXY_URL = 'https://proxy.example.com/lobehub/';
+
+ const caller = videoRouter.createCaller(mockCtx);
+ await caller.createVideo(defaultInput);
+
+ expect(mockCreateVideo).toHaveBeenCalledWith(
+ expect.objectContaining({
+ callbackUrl: expect.stringMatching(
+ /^https:\/\/proxy\.example\.com\/lobehub\/api\/webhooks\/video\/[^?]+\?/,
+ ),
+ }),
+ expect.any(Object),
+ );
+ });
+
+ it('should preserve route metadata without polling for a webhook-based interaction', async () => {
+ const { mockUpdate } = setupMocks();
+ mockCreateVideo.mockImplementation(async (_payload, options) => {
+ options.metadata.routeAttempt = {
+ apiType: 'google',
+ channelId: 'google-channel-2',
+ routerId: 'google-router',
+ };
+
+ return {
+ completionMode: 'webhook',
+ inferenceId: 'interactions/omni-1',
+ };
+ });
+
+ const caller = videoRouter.createCaller(mockCtx);
+ await caller.createVideo(defaultInput);
+
+ expect(mockAfter).not.toHaveBeenCalled();
+ expect(mockProcessBackgroundVideoPolling).not.toHaveBeenCalled();
+ expect(mockUpdate).toHaveBeenCalledWith(
+ 'async-1',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ route: {
+ apiType: 'google',
+ channelId: 'google-channel-2',
+ routerId: 'google-router',
+ },
+ }),
+ }),
+ );
+ });
+
+ it('should preserve reference image URLs that are not storage files', async () => {
+ const { mockGetKeyFromFullUrl, mockInsert } = setupMocks();
+ const imageUrls = [
+ 'https://images.example.com/reference.png',
+ 'data:image/png;base64,reference',
+ ];
+ mockGetKeyFromFullUrl.mockResolvedValue(null);
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'inf-reference',
+ });
+
+ const caller = videoRouter.createCaller(mockCtx);
+ await caller.createVideo({
+ ...defaultInput,
+ params: { ...defaultInput.params, imageUrls },
+ });
+
+ const values = mockInsert.mock.results[0].value.values;
+ expect(values).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ config: expect.objectContaining({ imageUrls }),
+ }),
+ );
+ });
+
+ it('should pass the previous interaction when editing a compatible video', async () => {
+ const { mockInsert } = setupMocks();
+ mockFindPreviousGeneration.mockResolvedValue({
+ asset: { interactionId: 'interactions/source-1', type: 'video' },
+ generationBatchId: 'source-batch',
+ id: 'source-generation',
+ });
+ mockServerDB.query.generationBatches.findFirst.mockResolvedValue({
+ generationTopicId: 'topic-1',
+ id: 'source-batch',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'interactions/edit-1',
+ });
+
+ const caller = videoRouter.createCaller(mockCtx);
+ await caller.createVideo({
+ ...defaultInput,
+ model: 'gemini-omni-1.1-flash',
+ previousGenerationId: 'source-generation',
+ provider: 'google',
+ });
+
+ expect(mockCreateVideo).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({ task: 'edit' }),
+ previousInteractionId: 'interactions/source-1',
+ }),
+ expect.any(Object),
+ );
+
+ const values = mockInsert.mock.results[0].value.values;
+ expect(values.mock.calls[0][0].config).not.toHaveProperty('previousGenerationId');
+ expect(values).toHaveBeenNthCalledWith(
+ 3,
+ expect.objectContaining({
+ metadata: expect.objectContaining({ previousGenerationId: 'source-generation' }),
+ }),
+ );
+ });
+
+ it('should pin the edit to the route that created the source video', async () => {
+ const { mockUpdate } = setupMocks();
+ const sourceRoute = { apiType: 'google', channelId: 'google-channel-2', routerId: 'r-1' };
+ const mockFindTask = vi.fn().mockResolvedValue({ metadata: { route: sourceRoute } });
+ vi.mocked(AsyncTaskModel).mockImplementation(function () {
+ return { findById: mockFindTask, update: mockUpdate } as any;
+ });
+ mockFindPreviousGeneration.mockResolvedValue({
+ asset: { interactionId: 'interactions/source-1', type: 'video' },
+ asyncTaskId: 'source-task',
+ generationBatchId: 'source-batch',
+ id: 'source-generation',
+ });
+ mockServerDB.query.generationBatches.findFirst.mockResolvedValue({
+ generationTopicId: 'topic-1',
+ id: 'source-batch',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'interactions/edit-1',
+ });
+
+ const caller = videoRouter.createCaller(mockCtx);
+ await caller.createVideo({
+ ...defaultInput,
+ model: 'gemini-omni-1.1-flash',
+ previousGenerationId: 'source-generation',
+ provider: 'google',
+ });
+
+ expect(mockFindTask).toHaveBeenCalledWith('source-task');
+ expect(mockCreateVideo).toHaveBeenCalledWith(
+ expect.objectContaining({ previousInteractionId: 'interactions/source-1' }),
+ expect.objectContaining({ route: sourceRoute }),
+ );
+ });
+
+ it('should reject editing with a model that has no conversational video support', async () => {
+ setupMocks();
+
+ const caller = videoRouter.createCaller(mockCtx);
+
+ await expect(
+ caller.createVideo({
+ ...defaultInput,
+ previousGenerationId: 'source-generation',
+ }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'The selected model does not support conversational video editing',
+ });
+ expect(mockFindPreviousGeneration).not.toHaveBeenCalled();
+ expect(mockTransaction).not.toHaveBeenCalled();
+ });
+
+ it('should reject editing across models', async () => {
+ setupMocks();
+ mockFindPreviousGeneration.mockResolvedValue({
+ asset: { interactionId: 'interactions/source-1', type: 'video' },
+ generationBatchId: 'source-batch',
+ id: 'source-generation',
+ });
+ mockServerDB.query.generationBatches.findFirst.mockResolvedValue({
+ generationTopicId: 'topic-1',
+ id: 'source-batch',
+ model: 'different-model',
+ provider: 'volcengine',
+ });
+
+ const caller = videoRouter.createCaller(mockCtx);
+
+ await expect(
+ caller.createVideo({
+ ...defaultInput,
+ model: 'gemini-omni-1.1-flash',
+ previousGenerationId: 'source-generation',
+ provider: 'google',
+ }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Previous video generation cannot be edited with the selected model',
+ });
+ expect(mockTransaction).not.toHaveBeenCalled();
+ expect(mockCreateVideo).not.toHaveBeenCalled();
+ });
+
it('should validate mapped model id before rejecting deprecated lobehub video models', async () => {
setupMocks();
mockResolveBusinessModelMapping.mockResolvedValue({
requestedModelId: 'onboarding-video',
resolvedModelId: 'dreamina-seedance-2-0-260128',
});
- mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-mapped', useWebhook: true });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'inf-mapped',
+ });
const caller = videoRouter.createCaller(mockCtx);
const result = await caller.createVideo({
@@ -237,7 +513,10 @@ describe('videoRouter', () => {
await expect(availabilityOptions!.getUserEmail!()).resolves.toBe('[email protected]');
expect(mockFindUserById).toHaveBeenCalledWith(mockServerDB, mockCtx.userId);
expect(mockCreateVideo).toHaveBeenCalledWith(
- expect.objectContaining({ model: 'dreamina-seedance-2-0-260128' }),
+ expect.objectContaining({
+ callbackUrl: expect.stringContaining('model=dreamina-seedance-2-0-260128'),
+ model: 'dreamina-seedance-2-0-260128',
+ }),
expect.any(Object),
);
});
@@ -278,9 +557,12 @@ describe('videoRouter', () => {
expect(mockCreateVideo).not.toHaveBeenCalled();
});
- it('should use polling path when response contains only inferenceId', async () => {
+ it('should use the polling path when selected by the runtime', async () => {
const { mockUpdate } = setupMocks();
- mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-2' });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'polling',
+ inferenceId: 'inf-2',
+ });
const caller = videoRouter.createCaller(mockCtx);
const result = await caller.createVideo(defaultInput);
@@ -288,6 +570,10 @@ describe('videoRouter', () => {
expect(result.success).toBe(true);
expect(mockUpdate).toHaveBeenCalledWith('async-1', {
inferenceId: 'inf-2',
+ metadata: {
+ completionMode: 'polling',
+ webhookToken: expect.any(String),
+ },
status: AsyncTaskStatus.Processing,
});
// Polling: should trigger background polling after the response.
@@ -298,6 +584,7 @@ describe('videoRouter', () => {
it('should use polling path when response contains videoUrl (no special handling)', async () => {
const { mockUpdate } = setupMocks();
mockCreateVideo.mockResolvedValue({
+ completionMode: 'polling',
inferenceId: 'inf-3',
videoUrl: 'https://cdn.example.com/video.mp4',
});
@@ -308,6 +595,10 @@ describe('videoRouter', () => {
expect(result.success).toBe(true);
expect(mockUpdate).toHaveBeenCalledWith('async-1', {
inferenceId: 'inf-3',
+ metadata: {
+ completionMode: 'polling',
+ webhookToken: expect.any(String),
+ },
status: AsyncTaskStatus.Processing,
});
// No special videoUrl branch — falls through to polling
@@ -315,16 +606,18 @@ describe('videoRouter', () => {
expect(mockProcessBackgroundVideoPolling).toHaveBeenCalled();
});
- it('should fall through to polling when useWebhook is false', async () => {
+ it('should not start polling for a webhook task', async () => {
setupMocks();
- mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-4', useWebhook: false });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'inf-4',
+ });
const caller = videoRouter.createCaller(mockCtx);
await caller.createVideo(defaultInput);
- // useWebhook=false means not webhook, should fall to polling
- expect(mockAfter).toHaveBeenCalled();
- expect(mockProcessBackgroundVideoPolling).toHaveBeenCalled();
+ expect(mockAfter).not.toHaveBeenCalled();
+ expect(mockProcessBackgroundVideoPolling).not.toHaveBeenCalled();
});
});
@@ -386,7 +679,10 @@ describe('videoRouter', () => {
describe('createVideo - return value', () => {
it('should return batch and generation data', async () => {
setupMocks();
- mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-5', useWebhook: true });
+ mockCreateVideo.mockResolvedValue({
+ completionMode: 'webhook',
+ inferenceId: 'inf-5',
+ });
const caller = videoRouter.createCaller(mockCtx);
const result = await caller.createVideo(defaultInput);
diff --git a/apps/server/src/routers/lambda/video/index.ts b/apps/server/src/routers/lambda/video/index.ts
index 499c8cb8e8a..b44286e6b6d 100644
--- a/apps/server/src/routers/lambda/video/index.ts
+++ b/apps/server/src/routers/lambda/video/index.ts
@@ -6,10 +6,18 @@ import {
buildMappedBusinessModelFields,
resolveBusinessModelMapping,
} from '@lobechat/business-model-runtime';
-import { ChatErrorType, RequestTrigger } from '@lobechat/types';
+import {
+ ChatErrorType,
+ RequestTrigger,
+ type VideoGenerationAsset,
+ type VideoGenerationRoute,
+ type VideoGenerationTaskMetadata,
+} from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { and, eq } from 'drizzle-orm';
+import { supportsConversationalVideoEdit } from 'model-bank/standardParameters';
import { z } from 'zod';
import { getProviderContentPolicyErrorMessage } from '@/business/server/getProviderContentPolicyErrorMessage';
@@ -19,6 +27,7 @@ import { chargeAfterGenerate } from '@/business/server/video-generation/chargeAf
import { chargeBeforeGenerate } from '@/business/server/video-generation/chargeBeforeGenerate';
import { getVideoFreeQuota } from '@/business/server/video-generation/getVideoFreeQuota';
import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { GenerationModel } from '@/database/models/generation';
import { GenerationTopicModel } from '@/database/models/generationTopic';
import { UserModel } from '@/database/models/user';
import {
@@ -43,6 +52,16 @@ import { createVideoTaskSubmitError } from './error';
const log = debug('lobe-video:lambda');
+const getVideoGenerationRoute = (value: unknown): VideoGenerationRoute | undefined => {
+ if (!isRecord(value) || typeof value.apiType !== 'string') return;
+
+ return {
+ apiType: value.apiType,
+ ...(typeof value.channelId === 'string' ? { channelId: value.channelId } : {}),
+ ...(typeof value.routerId === 'string' ? { routerId: value.routerId } : {}),
+ };
+};
+
const videoProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -74,6 +93,7 @@ const createVideoInputSchema = z.object({
seed: z.number().nullish(),
})
.passthrough(),
+ previousGenerationId: z.string().optional(),
provider: z.string(),
});
export type CreateVideoServicePayload = z.infer<typeof createVideoInputSchema>;
@@ -84,7 +104,7 @@ export const videoRouter = router({
.mutation(async ({ input, ctx }) => {
const { userId, serverDB, asyncTaskModel, fileService, generationTopicModel } = ctx;
const wsId = ctx.workspaceId ?? undefined;
- const { generationTopicId, provider, model, params } = input;
+ const { generationTopicId, previousGenerationId, provider, model, params } = input;
const { resolvedModelId } = await resolveBusinessModelMapping(provider, model);
@@ -108,6 +128,28 @@ export const videoRouter = router({
// Normalize image URLs to S3 keys for database storage
let configForDatabase = { ...params };
+ const referenceImageUrls = Array.isArray(params.imageUrls)
+ ? params.imageUrls.filter((url): url is string => typeof url === 'string')
+ : [];
+
+ // Process multiple reference images
+ if (referenceImageUrls.length > 0) {
+ try {
+ const imageKeys = (
+ await Promise.all(
+ referenceImageUrls.map(async (url) => {
+ const key = await fileService.getKeyFromFullUrl(url);
+ if (key) log('Converted image URL to key: %s -> %s', url, key);
+ return key ?? url;
+ }),
+ )
+ ).filter(Boolean);
+
+ configForDatabase = { ...configForDatabase, imageUrls: imageKeys };
+ } catch (error) {
+ console.error('Error converting imageUrls to keys: %O', error);
+ }
+ }
// Process first-frame imageUrl
if (typeof params.imageUrl === 'string' && params.imageUrl) {
@@ -160,6 +202,18 @@ export const videoRouter = router({
}
}
+ if (referenceImageUrls.length > 0) {
+ const s3Urls = await Promise.all(
+ ((configForDatabase.imageUrls as string[] | undefined) ?? []).map(
+ async (value, index) =>
+ value === referenceImageUrls[index]
+ ? value
+ : (await fileService.getFullFileUrl(value)) || referenceImageUrls[index],
+ ),
+ );
+ updates.imageUrls = s3Urls;
+ }
+
if (Object.keys(updates).length > 0) {
generationParams = { ...params, ...updates };
}
@@ -171,6 +225,57 @@ export const videoRouter = router({
throw new TRPCError({ code: 'FORBIDDEN', message: 'Invalid generation topic' });
}
+ let previousInteractionId: string | undefined;
+ let previousRoute: VideoGenerationRoute | undefined;
+ if (previousGenerationId) {
+ if (!supportsConversationalVideoEdit(resolvedModelId)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'The selected model does not support conversational video editing',
+ });
+ }
+
+ const previousGeneration = await new GenerationModel(serverDB, userId, wsId).findById(
+ previousGenerationId,
+ );
+ if (!previousGeneration) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Previous video generation not found',
+ });
+ }
+
+ const previousBatch = await serverDB.query.generationBatches.findFirst({
+ where: and(
+ eq(generationBatches.id, previousGeneration.generationBatchId),
+ eq(generationBatches.userId, userId),
+ ),
+ });
+ const previousAsset = previousGeneration.asset as VideoGenerationAsset | null;
+
+ if (
+ !previousBatch ||
+ previousBatch.generationTopicId !== generationTopicId ||
+ previousBatch.provider !== provider ||
+ previousBatch.model !== model ||
+ !previousAsset?.interactionId
+ ) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Previous video generation cannot be edited with the selected model',
+ });
+ }
+
+ previousInteractionId = previousAsset.interactionId;
+ const previousTask = previousGeneration.asyncTaskId
+ ? await asyncTaskModel.findById(previousGeneration.asyncTaskId)
+ : undefined;
+ previousRoute = getVideoGenerationRoute(
+ (previousTask?.metadata as VideoGenerationTaskMetadata | null)?.route,
+ );
+ generationParams = { ...generationParams, task: 'edit' };
+ }
+
const { errorBatch, prechargeResult } = await chargeBeforeGenerate({
generationTopicId,
model,
@@ -196,7 +301,9 @@ export const videoRouter = router({
// 1. Create generationBatch
const newBatch: NewGenerationBatch = {
- config: configForDatabase,
+ config: {
+ ...configForDatabase,
+ },
generationTopicId,
model,
prompt: params.prompt,
@@ -224,6 +331,7 @@ export const videoRouter = router({
.values({
metadata: {
...(prechargeResult ? { precharge: prechargeResult } : {}),
+ ...(previousGenerationId ? { previousGenerationId } : {}),
// The completion charge runs in a webhook/polling context that no
// longer sees this request; carry the origin so the spend stays
// attributed to it.
@@ -258,43 +366,48 @@ export const videoRouter = router({
try {
const modelRuntime = await initModelRuntimeFromDB(serverDB, userId, provider, wsId);
- const callbackBaseUrl = process.env.WEBHOOK_PROXY_URL || appEnv.APP_URL;
- const callbackUrl = `${callbackBaseUrl}/api/webhooks/video/${provider}?token=${webhookToken}`;
+ const callbackBaseUrl = appEnv.WEBHOOK_PROXY_URL || appEnv.APP_URL;
+ // Append to the base instead of resolving a root-relative path, which would drop a
+ // reverse-proxy prefix such as `https://host/lobehub`.
+ const callbackUrl = new URL(
+ `${callbackBaseUrl.replace(/\/+$/, '')}/api/webhooks/video/${provider}`,
+ );
+ callbackUrl.searchParams.set('model', resolvedModelId);
+ callbackUrl.searchParams.set('token', webhookToken);
log('Using callback URL: %s', callbackUrl);
+ const requestMetadata: Record<string, unknown> = { trigger: RequestTrigger.Video };
const response = await modelRuntime.createVideo(
{
- callbackUrl,
+ callbackUrl: callbackUrl.toString(),
model: resolvedModelId,
params: generationParams,
+ previousInteractionId,
+ },
+ {
+ metadata: requestMetadata,
+ preferredCompletionMode: appEnv.VIDEO_GENERATION_PREFER_WEBHOOK ? 'webhook' : 'polling',
+ route: previousRoute,
},
- { metadata: { trigger: RequestTrigger.Video } },
);
- log('Video task submitted successfully, inferenceId: %s', response?.inferenceId);
+ if (!response) throw new Error('Video generation is not supported by this runtime');
- // Determine async strategy based on response:
- // - useWebhook: provider registered a callback URL, wait for webhook
- // - otherwise: use background polling to check status
- const useWebhook = response && 'useWebhook' in response && response.useWebhook;
+ log('Video task submitted successfully, inferenceId: %s', response.inferenceId);
- if (useWebhook) {
- // Webhook-based provider (e.g. Volcengine): wait for callback
- log('Webhook-based provider detected, waiting for callback');
-
- await asyncTaskModel.update(asyncTaskId, {
- inferenceId: response?.inferenceId,
- status: AsyncTaskStatus.Processing,
- });
- } else if (response) {
- // Polling-based provider (e.g. OpenAI Sora): use background polling
- log('Polling-based provider detected (inferenceId only), scheduling background polling');
-
- await asyncTaskModel.update(asyncTaskId, {
- inferenceId: response.inferenceId,
- status: AsyncTaskStatus.Processing,
- });
+ const route = getVideoGenerationRoute(requestMetadata.routeAttempt);
+ const taskMetadata: VideoGenerationTaskMetadata = {
+ completionMode: response.completionMode,
+ ...(prechargeResult ? { precharge: prechargeResult } : {}),
+ ...(previousGenerationId ? { previousGenerationId } : {}),
+ ...(route ? { route } : {}),
+ // This object replaces the metadata written at insert time, so keep the
+ // spend origin the completion charge relies on.
+ ...(ctx.spendOrigin ? { spendOrigin: ctx.spendOrigin } : {}),
+ webhookToken,
+ };
+ const schedulePolling = (inferenceId: string) => {
after(async () => {
log('Background video polling scheduled for task: %s', asyncTaskId);
@@ -307,10 +420,13 @@ export const videoRouter = router({
generationBatchId: createdBatch.id,
generationId: createdGeneration.id,
generationTopicId,
- inferenceId: response.inferenceId,
+ inferenceId,
model,
prechargeResult,
+ previousGenerationId,
provider,
+ route,
+ spendOrigin: ctx.spendOrigin,
userId,
workspaceId: wsId,
});
@@ -320,6 +436,28 @@ export const videoRouter = router({
console.error('[video] Background polling failed:', error);
}
});
+ };
+
+ if (response.completionMode === 'webhook') {
+ // Webhook-based provider (e.g. Volcengine): wait for callback
+ log('Webhook-based provider detected, waiting for callback');
+
+ await asyncTaskModel.update(asyncTaskId, {
+ inferenceId: response.inferenceId,
+ metadata: taskMetadata,
+ status: AsyncTaskStatus.Processing,
+ });
+ } else {
+ // Polling-based provider (e.g. OpenAI Sora): use background polling
+ log('Polling-based provider detected (inferenceId only), scheduling background polling');
+
+ await asyncTaskModel.update(asyncTaskId, {
+ inferenceId: response.inferenceId,
+ metadata: taskMetadata,
+ status: AsyncTaskStatus.Processing,
+ });
+
+ schedulePolling(response.inferenceId);
log('After() hook registered for background video polling: %s', asyncTaskId);
}
diff --git a/apps/server/src/services/generation/video.ts b/apps/server/src/services/generation/video.ts
index 909fce2a7d2..4e7b0d56780 100644
--- a/apps/server/src/services/generation/video.ts
+++ b/apps/server/src/services/generation/video.ts
@@ -8,6 +8,7 @@ import { pipeline } from 'node:stream/promises';
import { promisify } from 'node:util';
import { type LobeChatDatabase } from '@lobechat/database';
+import { parseDataUri } from '@lobechat/model-runtime';
import debug from 'debug';
import { nanoid } from 'nanoid';
import sharp from 'sharp';
@@ -61,7 +62,10 @@ export class VideoGenerationService {
headers?: Record<string, string>;
},
): Promise<VideoProcessResult> {
- log('Processing video from URL: %s', videoUrl);
+ log(
+ 'Processing video from source: %s',
+ videoUrl.startsWith('data:') ? 'inline data' : videoUrl,
+ );
let tempVideoPath: string | null = null;
let tempCoverPath: string | null = null;
@@ -79,10 +83,7 @@ export class VideoGenerationService {
const fileHash = createHash('sha256').update(videoBuffer).digest('hex');
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';
+ const { ext: videoExt, mimeType } = this.resolveVideoFormat(videoUrl);
// Generate S3 keys
const uuid = nanoid();
@@ -173,10 +174,25 @@ export class VideoGenerationService {
headers?: Record<string, string>;
},
): Promise<string> {
- const ext = path.extname(new URL(url).pathname).toLowerCase() || '.mp4';
+ const { ext } = this.resolveVideoFormat(url);
const tempVideoPath = path.join(os.tmpdir(), `lobe-video-${nanoid()}${ext}`);
log('Downloading video to: %s', tempVideoPath);
+ if (url.startsWith('data:')) {
+ const { base64, mimeType } = parseDataUri(url);
+ if (!base64 || !mimeType?.startsWith('video/')) throw new Error('Invalid video data URI');
+
+ const videoBuffer = Buffer.from(base64, 'base64');
+ if (videoBuffer.length > VideoGenerationService.MAX_VIDEO_SIZE) {
+ throw new Error(
+ `Video file too large: ${videoBuffer.length} bytes (max ${VideoGenerationService.MAX_VIDEO_SIZE} bytes)`,
+ );
+ }
+
+ await fs.writeFile(tempVideoPath, videoBuffer);
+ return tempVideoPath;
+ }
+
const response = await fetch(url, {
headers: options?.headers,
signal: AbortSignal.timeout(VideoGenerationService.DOWNLOAD_TIMEOUT_MS),
@@ -220,6 +236,22 @@ export class VideoGenerationService {
return tempVideoPath;
}
+ private resolveVideoFormat(url: string): { ext: string; mimeType: string } {
+ if (url.startsWith('data:')) {
+ const mimeType = parseDataUri(url).mimeType?.toLowerCase();
+ return {
+ ext: mimeType === 'video/webm' ? '.webm' : '.mp4',
+ mimeType: mimeType || 'video/mp4',
+ };
+ }
+
+ const ext = path.extname(new URL(url).pathname).toLowerCase();
+ return {
+ ext: ext || '.mp4',
+ mimeType: ext === '.webm' ? 'video/webm' : 'video/mp4',
+ };
+ }
+
private async getVideoMetadata(videoPath: string): Promise<VideoMetadata> {
const ffmpegPath = getFfmpegPath();
diff --git a/apps/server/src/services/generation/videoBackgroundPolling.test.ts b/apps/server/src/services/generation/videoBackgroundPolling.test.ts
index 0f5ffe2102f..c35a0666c47 100644
--- a/apps/server/src/services/generation/videoBackgroundPolling.test.ts
+++ b/apps/server/src/services/generation/videoBackgroundPolling.test.ts
@@ -1,5 +1,8 @@
+import { resolveBusinessModelMapping } from '@lobechat/business-model-runtime';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { chargeAfterGenerate } from '@/business/server/video-generation/chargeAfterGenerate';
+import { notifyVideoCompleted } from '@/business/server/video-generation/notifyVideoCompleted';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { GenerationModel } from '@/database/models/generation';
import type { LobeChatDatabase } from '@/database/type';
@@ -12,6 +15,19 @@ import { FileSource } from '@/types/files';
vi.mock('@/database/models/asyncTask');
vi.mock('@/database/models/generation');
vi.mock('@/server/services/generation/video');
+vi.mock('@/business/server/video-generation/chargeAfterGenerate', () => ({
+ chargeAfterGenerate: vi.fn(),
+}));
+vi.mock('@/business/server/video-generation/notifyVideoCompleted', () => ({
+ notifyVideoCompleted: vi.fn(),
+}));
+vi.mock('@lobechat/business-model-runtime', async (importOriginal) => ({
+ ...((await importOriginal()) as any),
+ buildMappedBusinessModelFields: vi.fn(() => ({})),
+ resolveBusinessModelMapping: vi.fn(async (_provider: string, model: string) => ({
+ resolvedModelId: model,
+ })),
+}));
vi.mock('@/utils/sanitizeFileName', () => ({
sanitizeFileName: vi.fn(function (...args) {
return args.join('-');
@@ -47,6 +63,7 @@ describe('videoBackgroundPolling', () => {
query: {
generationBatches: {
findFirst: vi.fn().mockResolvedValue({
+ config: {},
id: 'batch-123',
prompt: 'test-prompt',
}),
@@ -63,6 +80,7 @@ describe('videoBackgroundPolling', () => {
inferenceId: 'inference-abc',
model: 'test-model',
prechargeResult: { credits: 10 },
+ previousGenerationId: 'gen-source',
provider: 'test-provider',
userId: 'user-xyz',
};
@@ -81,6 +99,7 @@ describe('videoBackgroundPolling', () => {
return mockVideoService as any;
});
vi.mocked(initModelRuntimeFromDB).mockResolvedValue(mockModelRuntime as any);
+ vi.mocked(AsyncTaskModel.claimVideoCompletion).mockResolvedValue(true);
});
afterEach(() => {
@@ -93,6 +112,7 @@ describe('videoBackgroundPolling', () => {
status: 'success',
videoUrl: 'https://example.com/video.mp4',
headers: { 'Content-Type': 'video/mp4' },
+ usage: { completionTokens: 28_960, totalTokens: 29_120 },
});
mockVideoService.processVideoForGeneration.mockResolvedValue({
@@ -109,7 +129,11 @@ describe('videoBackgroundPolling', () => {
await processBackgroundVideoPolling(mockDb, mockParams);
- expect(mockModelRuntime.handlePollVideoStatus).toHaveBeenCalledWith('inference-abc');
+ expect(mockModelRuntime.handlePollVideoStatus).toHaveBeenCalledWith(
+ 'inference-abc',
+ 'test-model',
+ undefined,
+ );
expect(mockVideoService.processVideoForGeneration).toHaveBeenCalledWith(
'https://example.com/video.mp4',
@@ -122,7 +146,9 @@ describe('videoBackgroundPolling', () => {
coverUrl: 'cover-key-123',
duration: 10,
height: 1080,
+ interactionId: 'inference-abc',
originalUrl: 'https://example.com/video.mp4',
+ previousGenerationId: 'gen-source',
thumbnailUrl: 'thumb-key-456',
type: 'video',
url: 'video-key-789',
@@ -151,6 +177,122 @@ describe('videoBackgroundPolling', () => {
duration: expect.any(Number),
status: AsyncTaskStatus.Success,
});
+ expect(notifyVideoCompleted).toHaveBeenCalledWith(
+ expect.objectContaining({
+ generationBatchId: 'batch-123',
+ topicId: 'topic-789',
+ }),
+ );
+ expect(chargeAfterGenerate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ model: 'test-model',
+ prechargeResult: { credits: 10 },
+ usage: { completionTokens: 28_960, totalTokens: 29_120 },
+ }),
+ );
+ });
+
+ it('should poll the pinned route with the mapped model id instead of the alias', async () => {
+ vi.mocked(resolveBusinessModelMapping).mockResolvedValueOnce({
+ resolvedModelId: 'mapped-model',
+ } as any);
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
+ status: 'failed',
+ error: 'Model API error',
+ });
+ const route = { apiType: 'google', channelId: 'channel-1', routerId: 'router-1' };
+
+ await processBackgroundVideoPolling(mockDb, { ...mockParams, route });
+
+ expect(mockModelRuntime.handlePollVideoStatus).toHaveBeenCalledWith(
+ 'inference-abc',
+ 'mapped-model',
+ route,
+ );
+ });
+
+ it('should keep spend origin and workspace context on completion', async () => {
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
+ status: 'success',
+ videoUrl: 'https://example.com/video.mp4',
+ });
+ const spendOrigin = { trigger: 'agent-share' };
+
+ await processBackgroundVideoPolling(mockDb, {
+ ...mockParams,
+ spendOrigin,
+ workspaceId: 'ws-1',
+ });
+
+ expect(notifyVideoCompleted).toHaveBeenCalledWith(
+ expect.objectContaining({ workspaceId: 'ws-1' }),
+ );
+ expect(chargeAfterGenerate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ asyncTaskId: 'task-123', trigger: 'agent-share' }),
+ workspaceId: 'ws-1',
+ }),
+ );
+ });
+
+ it('should keep spend origin on the failure refund', async () => {
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
+ status: 'failed',
+ error: 'Model API error',
+ });
+
+ await processBackgroundVideoPolling(mockDb, {
+ ...mockParams,
+ spendOrigin: { trigger: 'agent-share' },
+ });
+
+ expect(chargeAfterGenerate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ isError: true,
+ metadata: expect.objectContaining({ trigger: 'agent-share' }),
+ }),
+ );
+ });
+
+ it('should skip a polling result already claimed by a webhook', async () => {
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
+ status: 'success',
+ videoUrl: 'https://example.com/video.mp4',
+ });
+ vi.mocked(AsyncTaskModel.claimVideoCompletion).mockResolvedValueOnce(false);
+
+ await processBackgroundVideoPolling(mockDb, mockParams);
+
+ expect(mockVideoService.processVideoForGeneration).not.toHaveBeenCalled();
+ expect(mockGenerationModel.createAssetAndFile).not.toHaveBeenCalled();
+ expect(mockAsyncTaskModel.update).not.toHaveBeenCalled();
+ });
+
+ it('should not persist inline video data as the original URL', async () => {
+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({
+ status: 'success',
+ videoUrl: 'data:video/mp4;base64,inline-video',
+ });
+ mockVideoService.processVideoForGeneration.mockResolvedValue({
+ coverKey: 'cover-key',
+ duration: 10,
+ fileHash: 'hash',
+ fileSize: 1024,
+ height: 1080,
+ mimeType: 'video/mp4',
+ thumbnailKey: 'thumb-key',
+ videoKey: 'video-key',
+ width: 1920,
+ });
+
+ await processBackgroundVideoPolling(mockDb, mockParams);
+
+ expect(mockGenerationModel.createAssetAndFile).toHaveBeenCalledWith(
+ 'gen-456',
+ expect.objectContaining({ originalUrl: undefined }),
+ expect.any(Object),
+ FileSource.VideoGeneration,
+ );
});
});
diff --git a/apps/server/src/services/generation/videoBackgroundPolling.ts b/apps/server/src/services/generation/videoBackgroundPolling.ts
index 5cf5464dafb..5b05800ae7d 100644
--- a/apps/server/src/services/generation/videoBackgroundPolling.ts
+++ b/apps/server/src/services/generation/videoBackgroundPolling.ts
@@ -1,8 +1,17 @@
-import { RequestTrigger } from '@lobechat/types';
+import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';
+import {
+ buildMappedBusinessModelFields,
+ resolveBusinessModelMapping,
+} from '@lobechat/business-model-runtime';
+import type { VideoGenerationUsage } from '@lobechat/model-runtime';
+import { RequestTrigger, type SpendOrigin, type VideoGenerationRoute } from '@lobechat/types';
import debug from 'debug';
+import type { RuntimeVideoGenParams } from 'model-bank';
import { getProviderContentPolicyErrorMessage } from '@/business/server/getProviderContentPolicyErrorMessage';
import { trackProviderContentPolicyViolation } from '@/business/server/trackProviderContentPolicyViolation';
+import { chargeAfterGenerate } from '@/business/server/video-generation/chargeAfterGenerate';
+import { notifyVideoCompleted } from '@/business/server/video-generation/notifyVideoCompleted';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { GenerationModel } from '@/database/models/generation';
import type { LobeChatDatabase } from '@/database/type';
@@ -24,7 +33,11 @@ interface BackgroundPollingParams {
inferenceId: string;
model: string;
prechargeResult?: any;
+ previousGenerationId?: string;
provider: string;
+ route?: VideoGenerationRoute;
+ /** Keeps the completion charge attributed like the webhook path, which reads it from the task row. */
+ spendOrigin?: SpendOrigin;
userId: string;
workspaceId?: string;
}
@@ -38,9 +51,14 @@ export async function processBackgroundVideoPolling(
asyncTaskId,
generationBatchId,
generationId,
+ generationTopicId,
inferenceId,
model,
+ prechargeResult,
+ previousGenerationId,
provider,
+ route,
+ spendOrigin,
userId,
workspaceId,
} = params;
@@ -52,39 +70,52 @@ export async function processBackgroundVideoPolling(
inferenceId,
);
+ let claimedByThisWorker = false;
+
try {
const asyncTaskModel = new AsyncTaskModel(db, userId, workspaceId);
const videoService = new VideoGenerationService(db, userId, workspaceId);
const generationModel = new GenerationModel(db, userId, workspaceId);
const modelRuntime = await initModelRuntimeFromDB(db, userId, provider, workspaceId);
- const pollResult = await pollUntilCompletion(modelRuntime, inferenceId);
+ // `route` was pinned for the mapped model id at creation, so poll with that id too;
+ // the user-facing alias may resolve to a router list that no longer holds the route.
+ const { resolvedModelId: pollModelId } = await resolveBusinessModelMapping(provider, model);
+ const pollResult = await pollUntilCompletion(modelRuntime, inferenceId, pollModelId, route);
if (!pollResult) {
throw new Error('Polling completed but no video URL returned');
}
+ claimedByThisWorker = await AsyncTaskModel.claimVideoCompletion(db, asyncTaskId);
+ if (!claimedByThisWorker) {
+ log('Video task already claimed or finalized, skipping polling result: %s', asyncTaskId);
+ return;
+ }
+
log('Video polling succeeded for task: %s, processing video...', asyncTaskId);
const processResult = await videoService.processVideoForGeneration(pollResult.videoUrl, {
headers: pollResult.headers,
});
+ const batch = await db.query.generationBatches.findFirst({
+ where: (batches, { eq }) => eq(batches.id, generationBatchId),
+ });
+
const asset: VideoGenerationAsset = {
coverUrl: processResult.coverKey,
duration: processResult.duration,
height: processResult.height,
- originalUrl: pollResult.videoUrl,
+ interactionId: inferenceId,
+ originalUrl: pollResult.videoUrl.startsWith('data:') ? undefined : pollResult.videoUrl,
+ previousGenerationId,
thumbnailUrl: processResult.thumbnailKey,
type: 'video',
url: processResult.videoKey,
width: processResult.width,
};
- const batch = await db.query.generationBatches.findFirst({
- where: (batches, { eq }) => eq(batches.id, generationBatchId),
- });
-
await generationModel.createAssetAndFile(
generationId,
asset,
@@ -103,11 +134,62 @@ export async function processBackgroundVideoPolling(
status: AsyncTaskStatus.Success,
});
+ try {
+ await notifyVideoCompleted({
+ generationBatchId,
+ model,
+ prompt: batch?.prompt ?? '',
+ topicId: generationTopicId,
+ userId,
+ workspaceId,
+ });
+ } catch (error) {
+ console.error('[video-background-polling] Video completion notification failed:', error);
+ }
+
+ try {
+ const { resolvedModelId } = await resolveBusinessModelMapping(provider, model);
+ await chargeAfterGenerate({
+ computePriceParams: {
+ generateAudio: (batch?.config as RuntimeVideoGenParams | undefined)?.generateAudio,
+ resolution: (batch?.config as RuntimeVideoGenParams | undefined)?.resolution,
+ },
+ latency: duration,
+ metadata: {
+ ...spendOrigin,
+ asyncTaskId,
+ generationBatchId,
+ topicId: generationTopicId,
+ ...buildMappedBusinessModelFields({
+ provider,
+ requestedModelId: resolvedModelId === model ? undefined : model,
+ resolvedModelId,
+ }),
+ },
+ model: resolvedModelId,
+ prechargeResult,
+ provider,
+ usage: pollResult.usage,
+ userId,
+ workspaceId,
+ });
+ } catch (error) {
+ console.error('[video-background-polling] Video completion charge failed:', error);
+ }
+
log('Video processing completed successfully for task: %s', asyncTaskId);
} catch (error) {
log('Background video polling error for task: %s', asyncTaskId, error);
const asyncTaskModel = new AsyncTaskModel(db, userId, workspaceId);
+ if (!claimedByThisWorker) {
+ claimedByThisWorker = await AsyncTaskModel.claimVideoCompletion(db, asyncTaskId);
+ if (!claimedByThisWorker) {
+ log('Video task failure already handled by another worker: %s', asyncTaskId);
+ return;
+ }
+ }
+
const providerContentPolicyMessage = await getProviderContentPolicyErrorMessage({
error,
provider,
@@ -138,25 +220,56 @@ export async function processBackgroundVideoPolling(
),
status: AsyncTaskStatus.Error,
});
+
+ try {
+ const { resolvedModelId } = await resolveBusinessModelMapping(provider, model);
+ await chargeAfterGenerate({
+ isError: true,
+ metadata: {
+ ...spendOrigin,
+ asyncTaskId,
+ generationBatchId,
+ topicId: generationTopicId,
+ ...buildMappedBusinessModelFields({
+ provider,
+ requestedModelId: resolvedModelId === model ? undefined : model,
+ resolvedModelId,
+ }),
+ },
+ model: resolvedModelId,
+ prechargeResult,
+ provider,
+ userId,
+ workspaceId,
+ });
+ } catch (refundError) {
+ console.error('[video-background-polling] Video generation refund failed:', refundError);
+ }
}
}
async function pollUntilCompletion(
modelRuntime: any,
inferenceId: string,
-): Promise<{ headers?: Record<string, string>; videoUrl: string } | null> {
- const maxRetries = 120;
+ model: string,
+ route?: VideoGenerationRoute,
+): Promise<{
+ headers?: Record<string, string>;
+ usage?: VideoGenerationUsage;
+ videoUrl: string;
+} | null> {
const pollingInterval = 5000;
+ const maxRetries = Math.ceil(ASYNC_TASK_TIMEOUT / pollingInterval);
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
log('Polling attempt %d/%d for task: %s', attempt + 1, maxRetries, inferenceId);
- const result = await modelRuntime.handlePollVideoStatus(inferenceId);
+ const result = await modelRuntime.handlePollVideoStatus(inferenceId, model, route);
if (result.status === 'success') {
log('Video generation succeeded for task: %s', inferenceId);
- return { headers: result.headers, videoUrl: result.videoUrl };
+ return { headers: result.headers, usage: result.usage, videoUrl: result.videoUrl };
}
if (result.status === 'failed') {
diff --git a/locales/en-US/models.json b/locales/en-US/models.json
index 0319aeaa3e9..3816c19d47c 100644
--- a/locales/en-US/models.json
+++ b/locales/en-US/models.json
@@ -530,6 +530,7 @@
"gemini-3.8-flash.description": "Gemini 3.8 Flash is Google's most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows.",
"gemini-flash-latest.description": "Points to gemini-3.8-flash",
"gemini-flash-lite-latest.description": "Points to gemini-3.5-flash-lite",
+ "gemini-omni-1.1-flash.description": "Gemini Omni Flash is a natively multimodal model for text-to-video, image-to-video, reference-to-video, and conversational video editing.",
"gemini-pro-latest.description": "Points to gemini-3.1-pro-preview",
"gemma-4-31B-it.description": "Gemma 4 31B IT is Google's latest multimodal model supporting text, image, and video understanding. Preview model for evaluation purposes only.",
"gemma-4-31b.description": "This model excels at multimodal reasoning across screenshots, documents, diagrams, and design assets. Ideal for visual agentic workflows, image-aware copilots, and teams migrating from closed multimodal APIs to an open model.",
diff --git a/locales/en-US/video.json b/locales/en-US/video.json
index 80b845f033e..3f799ea6c8f 100644
--- a/locales/en-US/video.json
+++ b/locales/en-US/video.json
@@ -7,6 +7,7 @@
"config.header.title": "Video",
"config.imageUpload.maxCountReached": "You can add up to {{count}} reference images",
"config.imageUrl.label": "Start Frame",
+ "config.prompt.editPlaceholder": "Describe what you want to change in this video",
"config.prompt.placeholder": "Describe the video you want to generate",
"config.prompt.placeholderWithRef": "Describe the scene you want to generate with the image",
"config.promptExtend.label": "Prompt Extend",
@@ -15,17 +16,31 @@
"config.seed.label": "Seed",
"config.seed.random": "Random",
"config.size.label": "Size",
+ "config.title": "Configuration",
"config.watermark.label": "Watermark",
"config.webSearch.label": "Web Search",
+ "generation.actions.cancelEdit": "Cancel Edit",
"generation.actions.copyError": "Copy Error Message",
+ "generation.actions.edit": "Edit Video",
"generation.actions.errorCopied": "Error Message Copied to Clipboard",
"generation.actions.errorCopyFailed": "Failed to Copy Error Message",
"generation.actions.generate": "Generate",
+ "generation.actions.generateEdit": "Generate Edit",
+ "generation.editing.badge": "Editing",
+ "generation.editing.cancelHint": "Cancel editing (Esc)",
+ "generation.editing.hint": "Describe what to change; everything else stays the same",
+ "generation.editing.modelLocked": "Edits keep the original video's model",
+ "generation.editing.title": "Editing V{{version}}",
"generation.freeQuota.exhausted": "🎁 Free quota used up, credits will be consumed",
"generation.freeQuota.remaining": "🎁 {{remaining}} free videos today",
+ "generation.status.editing": "Generating Edit...",
"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.",
+ "generation.version.editedFrom": "Edited from V{{version}}",
+ "generation.version.label": "V{{version}}",
+ "generation.version.locateSource": "Show the source video",
+ "generation.version.sourceDeleted": "Edited from a deleted video",
"notice.modelRemoved": "The current model is no longer available from {{name}}. Please switch to an available model.",
"notice.providerDisabled": "The provider {{name}} for the current model is disabled. Please enable it or switch to an available model.",
"topic.createNew": "Create New Topic",
diff --git a/locales/zh-CN/models.json b/locales/zh-CN/models.json
index c62bf07b59f..15b9d397771 100644
--- a/locales/zh-CN/models.json
+++ b/locales/zh-CN/models.json
@@ -530,6 +530,7 @@
"gemini-3.8-flash.description": "Gemini 3.8 Flash 是 Google 最聪明的 Flash 模型,专为长程软件工程、自主智能体和复杂企业工作流打造。",
"gemini-flash-latest.description": "指向 gemini-3.8-flash",
"gemini-flash-lite-latest.description": "指向 gemini-3.5-flash-lite",
+ "gemini-omni-1.1-flash.description": "Gemini Omni Flash 是一个原生多模态模型,支持从文本到视频、图像到视频、参考到视频以及对话式视频编辑。",
"gemini-pro-latest.description": "指向 gemini-3.1-pro-preview",
"gemma-4-31B-it.description": "Gemma 4 31B IT是谷歌最新的多模态模型,支持文本、图像和视频理解。仅供评估使用的预览模型。",
"gemma-4-31b.description": "此模型在跨截图、文档、图表和设计资源的多模态推理方面表现卓越。适用于视觉代理工作流、图像感知助手以及从封闭多模态 API 迁移到开放模型的团队。",
diff --git a/locales/zh-CN/video.json b/locales/zh-CN/video.json
index 4617bcdd0fb..cc4af3b10ca 100644
--- a/locales/zh-CN/video.json
+++ b/locales/zh-CN/video.json
@@ -7,6 +7,7 @@
"config.header.title": "视频",
"config.imageUpload.maxCountReached": "最多可添加 {{count}} 张参考图",
"config.imageUrl.label": "起始画面",
+ "config.prompt.editPlaceholder": "描述你希望如何修改这个视频",
"config.prompt.placeholder": "描述你想生成的视频内容",
"config.prompt.placeholderWithRef": "结合图片,描述你想生成的画面",
"config.promptExtend.label": "提示词扩展",
@@ -15,17 +16,31 @@
"config.seed.label": "种子",
"config.seed.random": "随机",
"config.size.label": "尺寸",
+ "config.title": "配置",
"config.watermark.label": "水印",
"config.webSearch.label": "联网搜索",
+ "generation.actions.cancelEdit": "取消编辑",
"generation.actions.copyError": "复制错误信息",
+ "generation.actions.edit": "编辑视频",
"generation.actions.errorCopied": "错误信息已复制到剪贴板",
"generation.actions.errorCopyFailed": "复制错误信息失败",
"generation.actions.generate": "生成",
+ "generation.actions.generateEdit": "生成编辑版本",
+ "generation.editing.badge": "编辑中",
+ "generation.editing.cancelHint": "取消编辑(Esc)",
+ "generation.editing.hint": "描述要修改的地方,其余内容保持不变",
+ "generation.editing.modelLocked": "编辑时沿用原视频的模型",
+ "generation.editing.title": "编辑 V{{version}}",
"generation.freeQuota.exhausted": "🎁 免费额度已用完,将开始消耗积分",
"generation.freeQuota.remaining": "🎁 今日剩余 {{remaining}} 个免费视频",
+ "generation.status.editing": "正在生成编辑版本...",
"generation.status.failed": "生成失败",
"generation.status.generating": "生成中...",
"generation.validation.endFrameRequiresStartFrame": "使用结束画面前需先设置起始画面。请先设置起始画面。",
+ "generation.version.editedFrom": "基于 V{{version}} 编辑",
+ "generation.version.label": "V{{version}}",
+ "generation.version.locateSource": "定位到原视频",
+ "generation.version.sourceDeleted": "原视频已删除",
"notice.modelRemoved": "当前模型已不在 {{name}} 的模型列表中,请先切换可用模型",
"notice.providerDisabled": "当前模型所属的服务商 {{name}} 未启用,请先启用或切换可用模型",
"topic.createNew": "创作新主题",
diff --git a/package.json b/package.json
index 36ba0c9b98f..b83eb68d6bd 100644
--- a/package.json
+++ b/package.json
@@ -219,7 +219,7 @@
"@fal-ai/client": "^1.10.1",
"@floating-ui/react": "^0.27.20",
"@formkit/auto-animate": "^0.9.0",
- "@google/genai": "~1.50.1",
+ "@google/genai": "^2.13.0",
"@henrygd/queue": "^1.2.0",
"@huggingface/inference": "^4.13.25",
"@icons-pack/react-simple-icons": "^13.13.0",
diff --git a/packages/database/src/models/__tests__/asyncTask.test.ts b/packages/database/src/models/__tests__/asyncTask.test.ts
index 49442086094..f9905ece9b4 100644
--- a/packages/database/src/models/__tests__/asyncTask.test.ts
+++ b/packages/database/src/models/__tests__/asyncTask.test.ts
@@ -900,3 +900,55 @@ describe('AsyncTaskModel.findByInferenceId', () => {
expect(result).toBeUndefined();
});
});
+
+describe('AsyncTaskModel.claimVideoCompletion', () => {
+ it('should atomically claim an active video task once and preserve metadata', async () => {
+ const [task] = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: { webhookToken: 'secret-token' },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.VideoGeneration,
+ userId,
+ })
+ .returning();
+
+ const firstClaim = await AsyncTaskModel.claimVideoCompletion(
+ serverDB,
+ task.id,
+ 'webhook-event-1',
+ );
+ const duplicateClaim = await AsyncTaskModel.claimVideoCompletion(
+ serverDB,
+ task.id,
+ 'webhook-event-2',
+ );
+
+ const claimedTask = await serverDB.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, task.id),
+ });
+
+ expect(firstClaim).toBe(true);
+ expect(duplicateClaim).toBe(false);
+ expect(claimedTask?.metadata).toMatchObject({
+ completionEventId: 'webhook-event-1',
+ webhookToken: 'secret-token',
+ });
+ expect(
+ (claimedTask?.metadata as { completionClaimedAt?: string } | undefined)?.completionClaimedAt,
+ ).toBeTypeOf('string');
+ });
+
+ it('should not claim a terminal video task', async () => {
+ const [task] = await serverDB
+ .insert(asyncTasks)
+ .values({
+ status: AsyncTaskStatus.Success,
+ type: AsyncTaskType.VideoGeneration,
+ userId,
+ })
+ .returning();
+
+ await expect(AsyncTaskModel.claimVideoCompletion(serverDB, task.id)).resolves.toBe(false);
+ });
+});
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index 3cc3b829210..e01daf373c2 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -63,6 +63,57 @@ export class AsyncTaskModel {
});
};
+ /**
+ * Atomically claims the right to finalize a video task (store the asset, charge, notify).
+ *
+ * Webhook retries (the handler answers 503 while the provider file is still processing) and the
+ * background polling fallback can both reach completion for the same task. The claim is a single
+ * compare-and-set UPDATE — still active AND no `completionClaimedAt` yet — so exactly one caller
+ * wins; do not split it into a read followed by a write, or completion may run twice.
+ * @returns `true` when this caller owns the completion, `false` when it was already claimed or finalized
+ */
+ static claimVideoCompletion = async (
+ db: LobeChatDatabase,
+ taskId: string,
+ completionEventId?: string,
+ ) => {
+ const claimedAt = new Date().toISOString();
+ const metadataWithClaim = sql`
+ jsonb_set(
+ COALESCE(${asyncTasks.metadata}, '{}'::jsonb),
+ '{completionClaimedAt}',
+ to_jsonb(${claimedAt}::text),
+ true
+ )
+ `;
+
+ const [claimed] = await db
+ .update(asyncTasks)
+ .set({
+ metadata: completionEventId
+ ? sql`
+ jsonb_set(
+ ${metadataWithClaim},
+ '{completionEventId}',
+ to_jsonb(${completionEventId}::text),
+ true
+ )
+ `
+ : metadataWithClaim,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(asyncTasks.id, taskId),
+ inArray(asyncTasks.status, [AsyncTaskStatus.Pending, AsyncTaskStatus.Processing]),
+ sql`NOT (COALESCE(${asyncTasks.metadata}, '{}'::jsonb) ? 'completionClaimedAt')`,
+ ),
+ )
+ .returning({ id: asyncTasks.id });
+
+ return Boolean(claimed);
+ };
+
update(taskId: string, value: Partial<AsyncTaskSelectItem>) {
return this.db
.update(asyncTasks)
diff --git a/packages/database/src/models/generation.ts b/packages/database/src/models/generation.ts
index ceffed8b614..f3eb489ba87 100644
--- a/packages/database/src/models/generation.ts
+++ b/packages/database/src/models/generation.ts
@@ -5,6 +5,7 @@ import type {
GenerationAsset,
ImageGenerationAsset,
VideoGenerationAsset,
+ VideoGenerationTaskMetadata,
} from '@lobechat/types';
import { FileSource } from '@lobechat/types';
import debug from 'debug';
@@ -249,12 +250,17 @@ export class GenerationModel {
}
}
+ const previousGenerationId = (
+ generation.asyncTask?.metadata as VideoGenerationTaskMetadata | null | undefined
+ )?.previousGenerationId;
+
// Build the Generation object following the same structure as in generationBatch.ts
const result: Generation = {
asset,
asyncTaskId: generation.asyncTaskId || null,
createdAt: generation.createdAt,
id: generation.id,
+ ...(previousGenerationId ? { previousGenerationId } : {}),
seed: generation.seed,
task: {
error: generation.asyncTask?.error
diff --git a/packages/env/src/__tests__/app.test.ts b/packages/env/src/__tests__/app.test.ts
index d92577ad272..c6d19fe5da1 100644
--- a/packages/env/src/__tests__/app.test.ts
+++ b/packages/env/src/__tests__/app.test.ts
@@ -93,6 +93,7 @@ describe('APP_URL fallback', () => {
delete process.env.VERCEL_URL;
delete process.env.VERCEL_BRANCH_URL;
delete process.env.VERCEL_PROJECT_PRODUCTION_URL;
+ delete process.env.PORT;
});
it('should use APP_URL when explicitly set', async () => {
@@ -157,3 +158,33 @@ describe('APP_URL fallback', () => {
});
});
});
+
+describe('video generation completion settings', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ delete process.env.VIDEO_GENERATION_PREFER_WEBHOOK;
+ delete process.env.WEBHOOK_PROXY_URL;
+ });
+
+ it('should default to polling', async () => {
+ const { getAppConfig } = await import('../app');
+
+ expect(getAppConfig().VIDEO_GENERATION_PREFER_WEBHOOK).toBe(false);
+ });
+
+ it('should enable the webhook preference with an explicit flag', async () => {
+ process.env.VIDEO_GENERATION_PREFER_WEBHOOK = '1';
+
+ const { getAppConfig } = await import('../app');
+
+ expect(getAppConfig().VIDEO_GENERATION_PREFER_WEBHOOK).toBe(true);
+ });
+
+ it('should expose the typed webhook proxy URL', async () => {
+ process.env.WEBHOOK_PROXY_URL = 'https://video-webhook.example.com';
+
+ const { getAppConfig } = await import('../app');
+
+ expect(getAppConfig().WEBHOOK_PROXY_URL).toBe('https://video-webhook.example.com');
+ });
+});
diff --git a/packages/env/src/app.ts b/packages/env/src/app.ts
index 7f4c9388831..2d23b7671c5 100644
--- a/packages/env/src/app.ts
+++ b/packages/env/src/app.ts
@@ -17,13 +17,13 @@ const getVercelUrl = () => {
return `https://${process.env.VERCEL_BRANCH_URL}`;
};
-const APP_URL = process.env.APP_URL
- ? process.env.APP_URL
- : isInVercel
+const APP_URL =
+ process.env.APP_URL ||
+ (isInVercel
? getVercelUrl()
: process.env.NODE_ENV === 'development'
? `http://localhost:${process.env.PORT || 3010}`
- : `http://localhost:${process.env.PORT || 3210}`;
+ : `http://localhost:${process.env.PORT || 3210}`);
// INTERNAL_APP_URL is used for server-to-server calls to bypass CDN/proxy
// Falls back to APP_URL if not set
@@ -50,6 +50,8 @@ export const getAppConfig = () => {
APP_URL: z.string(),
INTERNAL_APP_URL: z.string().optional(),
+ VIDEO_GENERATION_PREFER_WEBHOOK: z.boolean().optional(),
+ WEBHOOK_PROXY_URL: z.string().url().optional(),
VERCEL_EDGE_CONFIG: z.string().optional(),
MIDDLEWARE_REWRITE_THROUGH_LOCAL: z.boolean().optional(),
@@ -113,6 +115,8 @@ export const getAppConfig = () => {
APP_URL,
INTERNAL_APP_URL,
+ VIDEO_GENERATION_PREFER_WEBHOOK: process.env.VIDEO_GENERATION_PREFER_WEBHOOK === '1',
+ WEBHOOK_PROXY_URL: process.env.WEBHOOK_PROXY_URL,
MIDDLEWARE_REWRITE_THROUGH_LOCAL: process.env.MIDDLEWARE_REWRITE_THROUGH_LOCAL === '1',
CUSTOM_FONT_FAMILY: process.env.CUSTOM_FONT_FAMILY,
diff --git a/packages/locales/src/default/video.ts b/packages/locales/src/default/video.ts
index 570bd02d8f7..02e17c69bb6 100644
--- a/packages/locales/src/default/video.ts
+++ b/packages/locales/src/default/video.ts
@@ -7,6 +7,7 @@ export default {
'config.header.title': 'Video',
'config.imageUpload.maxCountReached': 'You can add up to {{count}} reference images',
'config.imageUrl.label': 'Start Frame',
+ 'config.prompt.editPlaceholder': 'Describe what you want to change in this video',
'config.promptExtend.label': 'Prompt Extend',
'config.prompt.placeholder': 'Describe the video you want to generate',
'config.prompt.placeholderWithRef': 'Describe the scene you want to generate with the image',
@@ -15,18 +16,32 @@ export default {
'config.seed.label': 'Seed',
'config.seed.random': 'Random',
'config.size.label': 'Size',
+ 'config.title': 'Configuration',
'config.watermark.label': 'Watermark',
'config.webSearch.label': 'Web Search',
+ 'generation.actions.cancelEdit': 'Cancel Edit',
'generation.actions.copyError': 'Copy Error Message',
'generation.actions.errorCopied': 'Error Message Copied to Clipboard',
'generation.actions.errorCopyFailed': 'Failed to Copy Error Message',
+ 'generation.actions.edit': 'Edit Video',
'generation.actions.generate': 'Generate',
+ 'generation.actions.generateEdit': 'Generate Edit',
+ 'generation.editing.badge': 'Editing',
+ 'generation.editing.cancelHint': 'Cancel editing (Esc)',
+ 'generation.editing.hint': 'Describe what to change; everything else stays the same',
+ 'generation.editing.modelLocked': "Edits keep the original video's model",
+ 'generation.editing.title': 'Editing V{{version}}',
'generation.freeQuota.exhausted': '🎁 Free quota used up, credits will be consumed',
'generation.freeQuota.remaining': '🎁 {{remaining}} free videos today',
- 'generation.validation.endFrameRequiresStartFrame':
- 'End frame cannot be used without a start frame. Please set a start frame first.',
+ 'generation.status.editing': 'Generating Edit...',
'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.',
+ 'generation.version.editedFrom': 'Edited from V{{version}}',
+ 'generation.version.label': 'V{{version}}',
+ 'generation.version.locateSource': 'Show the source video',
+ 'generation.version.sourceDeleted': 'Edited from a deleted video',
'notice.modelRemoved':
'The current model is no longer available from {{name}}. Please switch to an available model.',
'notice.providerDisabled':
diff --git a/packages/locales/src/modelDescriptionOverrides.ts b/packages/locales/src/modelDescriptionOverrides.ts
index f8da397d398..0851627f7ce 100644
--- a/packages/locales/src/modelDescriptionOverrides.ts
+++ b/packages/locales/src/modelDescriptionOverrides.ts
@@ -7,6 +7,8 @@ export const modelDescriptionOverrides = {
'Seedance 2.0 Fast by ByteDance offers the same capabilities as Seedance 2.0 with faster generation speeds at a more competitive price.',
'fal-ai/bytedance/seedream/v4.5.description':
'Seedream 4.5, built by ByteDance Seed team, supports multi-image editing and composition. Features enhanced subject consistency, precise instruction following, spatial logic understanding, aesthetic expression, poster layout and logo design with high-precision text-image rendering.',
+ 'gemini-omni-1.1-flash.description':
+ 'Gemini Omni Flash is a natively multimodal model for text-to-video, image-to-video, reference-to-video, and conversational video editing.',
'grok-4.20-beta-0309-non-reasoning.description': 'A non-reasoning variant for simple use cases',
'grok-4.20-beta-0309-reasoning.description':
'Intelligent, blazing-fast model that reasons before responding',
diff --git a/packages/model-bank/src/standard-parameters/video.test.ts b/packages/model-bank/src/standard-parameters/video.test.ts
index 169093bb924..0fce55c2e5d 100644
--- a/packages/model-bank/src/standard-parameters/video.test.ts
+++ b/packages/model-bank/src/standard-parameters/video.test.ts
@@ -27,6 +27,10 @@ describe('video standard-parameters', () => {
prompt: { default: '' },
resolution: { default: '720p', enum: ['480p', '720p', '1080p'] },
seed: { default: null },
+ task: {
+ default: 'text_to_video',
+ enum: ['text_to_video', 'image_to_video', 'reference_to_video', 'edit'],
+ },
};
expect(() => VideoModelParamsMetaSchema.parse(fullSchema)).not.toThrow();
@@ -62,6 +66,7 @@ describe('video standard-parameters', () => {
expect(result.seed?.default).toBeNull();
expect(result.seed?.max).toBe(MAX_VIDEO_SEED);
expect(result.seed?.min).toBe(-1);
+ expect(result.task).toBeUndefined();
});
it('should reject invalid types', () => {
@@ -104,6 +109,10 @@ describe('video standard-parameters', () => {
prompt: { default: 'test prompt' },
resolution: { default: '1080p', enum: ['720p', '1080p'] },
seed: { default: 42 },
+ task: {
+ default: 'edit',
+ enum: ['text_to_video', 'image_to_video', 'reference_to_video', 'edit'],
+ },
};
const result = extractVideoDefaultValues(schema);
@@ -118,6 +127,7 @@ describe('video standard-parameters', () => {
expect(result.webSearch).toBe(false);
expect(result.resolution).toBe('1080p');
expect(result.seed).toBe(42);
+ expect(result.task).toBe('edit');
});
it('should extract defaults from minimal schema', () => {
diff --git a/packages/model-bank/src/standard-parameters/video.ts b/packages/model-bank/src/standard-parameters/video.ts
index 708a1d3d978..4e3fa55797e 100644
--- a/packages/model-bank/src/standard-parameters/video.ts
+++ b/packages/model-bank/src/standard-parameters/video.ts
@@ -21,6 +21,24 @@ export const PRESET_VIDEO_ASPECT_RATIOS = [
export const PRESET_VIDEO_RESOLUTIONS = ['480p', '720p', '1080p'];
+export const VIDEO_GENERATION_TASKS = [
+ 'text_to_video',
+ 'image_to_video',
+ 'reference_to_video',
+ 'edit',
+] as const;
+
+export const GEMINI_OMNI_VIDEO_MODEL_ID = 'gemini-omni-1.1-flash';
+
+/**
+ * Video models that can edit a finished generation by continuing its provider interaction.
+ * Every stored video carries an interaction id, so model support is the capability signal.
+ */
+export const CONVERSATIONAL_VIDEO_EDIT_MODELS: readonly string[] = [GEMINI_OMNI_VIDEO_MODEL_ID];
+
+export const supportsConversationalVideoEdit = (modelId: string) =>
+ CONVERSATIONAL_VIDEO_EDIT_MODELS.includes(modelId);
+
export const VideoModelParamsMetaSchema = z.object({
prompt: z.object({
default: z.string().optional().default(''),
@@ -158,6 +176,15 @@ export const VideoModelParamsMetaSchema = z.object({
type: z.tuple([z.literal('number'), z.literal('null')]).optional(),
})
.optional(),
+
+ task: z
+ .object({
+ default: z.enum(VIDEO_GENERATION_TASKS),
+ description: z.string().optional(),
+ enum: z.array(z.enum(VIDEO_GENERATION_TASKS)),
+ type: z.literal('string').optional(),
+ })
+ .optional(),
});
export type VideoModelParamsSchema = z.input<typeof VideoModelParamsMetaSchema>;
diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.json
index c8c59be0519..d7166ef1dd5 100644
--- a/packages/model-runtime/package.json
+++ b/packages/model-runtime/package.json
@@ -31,7 +31,7 @@
"@azure-rest/ai-inference": "1.0.0-beta.5",
"@azure/core-auth": "^1.10.1",
"@fal-ai/client": "^1.10.1",
- "@google/genai": "^1.52.0",
+ "@google/genai": "^2.13.0",
"@huggingface/inference": "^4.13.21",
"@lobechat/business-model-bank": "workspace:*",
"@lobechat/business-model-runtime": "workspace:*",
diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.ts
index 5865fbd0338..204a46dfe86 100644
--- a/packages/model-runtime/src/core/BaseAI.ts
+++ b/packages/model-runtime/src/core/BaseAI.ts
@@ -12,7 +12,7 @@ import type {
CreateImageResponse,
CreateVideoMethodOptions,
CreateVideoPayload,
- CreateVideoResponse,
+ CreateVideoResult,
Embeddings,
EmbeddingsOptions,
EmbeddingsPayload,
@@ -21,9 +21,12 @@ import type {
HandleCreateVideoWebhookPayload,
HandleCreateVideoWebhookResult,
ModelRequestOptions,
+ PollVideoStatusResult,
PullModelParams,
TextToSpeechOptions,
TextToSpeechPayload,
+ VideoGenerationCapabilities,
+ VideoPollingRoute,
} from '../types';
export interface LobeRuntimeAI {
@@ -37,7 +40,7 @@ export interface LobeRuntimeAI {
createVideo?: (
payload: CreateVideoPayload,
options?: CreateVideoMethodOptions,
- ) => Promise<CreateVideoResponse>;
+ ) => Promise<CreateVideoResult>;
embeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<Embeddings[]>;
@@ -46,20 +49,25 @@ export interface LobeRuntimeAI {
options?: GenerateObjectOptions,
) => Promise<any>;
+ getVideoGenerationCapabilities?: (model: string) => VideoGenerationCapabilities;
+
handleCreateVideoWebhook?: (
payload: HandleCreateVideoWebhookPayload,
) => Promise<HandleCreateVideoWebhookResult>;
handlePollVideoStatus?: (
inferenceId: string,
- ) => Promise<
- | { status: 'success'; videoUrl: string }
- | { status: 'failed'; error: string }
- | { status: 'pending' }
- >;
+ model?: string,
+ route?: VideoPollingRoute,
+ ) => Promise<PollVideoStatusResult>;
models?: () => Promise<any>;
+ /**
+ * Composite runtimes set this when they resolve completion mode inside their selected route.
+ */
+ orchestratesVideoGenerationCompletion?: boolean;
+
// Model management related interface
pullModel?: (params: PullModelParams, options?: ModelRequestOptions) => Promise<Response>;
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index 5d5ac50b5d8..affaa06f43a 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -309,17 +309,39 @@ describe('ModelRuntime', () => {
model: 'sora-1',
params: { prompt: 'a cat' } as any,
};
- const mockResponse = { inferenceId: 'job-1' };
- const createVideo = vi.fn().mockResolvedValue(mockResponse);
+ const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'job-1' });
// @ts-ignore - injecting a minimal runtime for this case
- mockModelRuntime['_runtime'] = { createVideo };
+ mockModelRuntime['_runtime'] = {
+ createVideo,
+ getVideoGenerationCapabilities: () => ({ completionModes: ['polling'] }),
+ };
- const options = { metadata: { trigger: 'video' } };
+ const options = {
+ metadata: { trigger: 'video' },
+ preferredCompletionMode: 'webhook' as const,
+ };
const result = await mockModelRuntime.createVideo(payload, options);
expect(createVideo).toHaveBeenCalledWith(payload, options);
- expect(result).toBe(mockResponse);
+ expect(result).toEqual({ completionMode: 'polling', inferenceId: 'job-1' });
+ });
+
+ it('should preserve completion mode from an orchestrating runtime', async () => {
+ const payload: CreateVideoPayload = {
+ model: 'sora-1',
+ params: { prompt: 'a cat' } as any,
+ };
+ const response = { completionMode: 'webhook' as const, inferenceId: 'job-2' };
+ const createVideo = vi.fn().mockResolvedValue(response);
+
+ // @ts-ignore - injecting a minimal composite runtime for this case
+ mockModelRuntime['_runtime'] = {
+ createVideo,
+ orchestratesVideoGenerationCompletion: true,
+ };
+
+ await expect(mockModelRuntime.createVideo(payload)).resolves.toBe(response);
});
it('should handle undefined createVideo method gracefully', async () => {
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index dee393ee973..593496e5f10 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -30,9 +30,12 @@ import type {
import type {
CreateVideoMethodOptions,
CreateVideoPayload,
+ CreateVideoResponse,
HandleCreateVideoWebhookPayload,
+ VideoPollingRoute,
} from '../types/video';
import { AgentRuntimeError } from '../utils/createError';
+import { createVideoWithCompletionMode } from '../utils/videoCompletionMode';
import type { LobeRuntimeAI } from './BaseAI';
const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');
@@ -444,19 +447,24 @@ export class ModelRuntime {
return this._runtime.createImage?.(payload, finalOptions);
}
- async createVideo(payload: CreateVideoPayload, options?: CreateVideoMethodOptions) {
+ async createVideo(
+ payload: CreateVideoPayload,
+ options?: CreateVideoMethodOptions,
+ ): Promise<CreateVideoResponse | undefined> {
const finalOptions = this._hooks?.beforeCreateVideo && !options ? {} : options;
await this._hooks?.beforeCreateVideo?.(payload, finalOptions);
- return this._runtime.createVideo?.(payload, finalOptions);
+ if (!this._runtime.createVideo) return;
+
+ return createVideoWithCompletionMode(this._runtime, payload, finalOptions);
}
async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
return this._runtime.handleCreateVideoWebhook?.(payload);
}
- async handlePollVideoStatus(inferenceId: string) {
- return this._runtime.handlePollVideoStatus?.(inferenceId);
+ async handlePollVideoStatus(inferenceId: string, model?: string, route?: VideoPollingRoute) {
+ return this._runtime.handlePollVideoStatus?.(inferenceId, model, route);
}
async models() {
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 9239121da4d..36efb8a616a 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -647,6 +647,7 @@ describe('createRouterRuntime', () => {
createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-id' });
embeddings = vi.fn().mockResolvedValue([]);
generateObject = vi.fn().mockResolvedValue({});
+ getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
textToSpeech = vi.fn().mockResolvedValue('speech-response');
}
@@ -2389,6 +2390,7 @@ describe('createRouterRuntime', () => {
class MockRuntime implements LobeRuntimeAI {
createVideo = mockCreateVideo;
+ getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
}
const Runtime = createRouterRuntime({
@@ -2407,7 +2409,7 @@ describe('createRouterRuntime', () => {
const payload = { model: 'sora-1', params: { prompt: 'a cat' } } as any;
const result = await runtime.createVideo(payload);
- expect(result).toEqual({ inferenceId: 'job-1' });
+ expect(result).toEqual({ completionMode: 'polling', inferenceId: 'job-1' });
expect(mockCreateVideo).toHaveBeenCalledWith(payload, undefined);
});
@@ -2417,6 +2419,7 @@ describe('createRouterRuntime', () => {
class MockRuntime implements LobeRuntimeAI {
createVideo = mockCreateVideo;
+ getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
}
const Runtime = createRouterRuntime({
@@ -2446,6 +2449,7 @@ describe('createRouterRuntime', () => {
class MockRuntime implements LobeRuntimeAI {
createVideo = mockCreateVideo;
+ getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
}
const Runtime = createRouterRuntime({
@@ -2466,6 +2470,7 @@ describe('createRouterRuntime', () => {
const metadata = { trigger: 'video' };
const options = {
metadata,
+ preferredCompletionMode: 'webhook',
pricingContext: { plan: 'premium', scope: 'personal' },
} as const;
@@ -2506,6 +2511,186 @@ describe('createRouterRuntime', () => {
});
expect(mockHandlePollVideoStatus).toHaveBeenCalledWith('job-1');
});
+
+ it('should resolve the video router from the polling model', async () => {
+ class MockRuntime implements LobeRuntimeAI {
+ handlePollVideoStatus = vi.fn().mockResolvedValue({
+ status: 'success',
+ videoUrl: 'https://example.com/video.mp4',
+ });
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: async (_, { model }) => {
+ if (model !== 'gemini-omni-1.1-flash') {
+ throw new Error('unexpected model');
+ }
+
+ return [
+ {
+ apiType: 'google',
+ models: [model],
+ options: {},
+ runtime: MockRuntime as any,
+ },
+ ];
+ },
+ });
+
+ const runtime = new Runtime();
+
+ await expect(
+ runtime.handlePollVideoStatus('interaction-1', 'gemini-omni-1.1-flash'),
+ ).resolves.toMatchObject({ status: 'success' });
+ });
+
+ it('should poll with the same channel that created the video', async () => {
+ class MockRuntime implements LobeRuntimeAI {
+ private apiKey: string;
+
+ constructor(options: { apiKey: string }) {
+ this.apiKey = options.apiKey;
+ }
+
+ createVideo = vi.fn().mockImplementation(async () => {
+ if (this.apiKey === 'key-1') throw new Error('channel unavailable');
+ return { inferenceId: 'interaction-1' };
+ });
+
+ getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
+
+ handlePollVideoStatus = vi.fn().mockImplementation(async () => ({
+ status: 'success',
+ videoUrl: `https://example.com/${this.apiKey}.mp4`,
+ }));
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ routers: [
+ {
+ apiType: 'google',
+ id: 'google-router',
+ models: ['gemini-omni-1.1-flash'],
+ options: [
+ { apiKey: 'key-1', id: 'google-channel-1' },
+ { apiKey: 'key-2', id: 'google-channel-2' },
+ ],
+ runtime: MockRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime({ userId: 'user-1' });
+ const metadata: Record<string, unknown> = { trigger: RequestTrigger.Video };
+
+ await runtime.createVideo(
+ { model: 'gemini-omni-1.1-flash', params: { prompt: 'a cat' } } as any,
+ { metadata },
+ );
+
+ await expect(
+ runtime.handlePollVideoStatus(
+ 'interaction-1',
+ 'gemini-omni-1.1-flash',
+ metadata.routeAttempt as any,
+ ),
+ ).resolves.toEqual({
+ status: 'success',
+ videoUrl: 'https://example.com/key-2.mp4',
+ });
+ });
+
+ it('should create a continuation only through the pinned video channel', async () => {
+ const usedKeys: string[] = [];
+
+ class MockRuntime implements LobeRuntimeAI {
+ private apiKey: string;
+
+ constructor(options: { apiKey: string }) {
+ this.apiKey = options.apiKey;
+ }
+
+ createVideo = vi.fn().mockImplementation(async () => {
+ usedKeys.push(this.apiKey);
+ if (this.apiKey === 'key-2') throw new Error('interaction not found');
+ return { inferenceId: 'interaction-2' };
+ });
+
+ getVideoGenerationCapabilities = () => ({ completionModes: ['polling'] as const });
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ routers: [
+ {
+ apiType: 'google',
+ id: 'google-router',
+ models: ['gemini-omni-1.1-flash'],
+ options: [
+ { apiKey: 'key-1', id: 'google-channel-1' },
+ { apiKey: 'key-2', id: 'google-channel-2' },
+ ],
+ runtime: MockRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime({ userId: 'user-1' });
+ const payload = {
+ model: 'gemini-omni-1.1-flash',
+ params: { prompt: 'slower' },
+ previousInteractionId: 'interaction-1',
+ } as any;
+ const route = { apiType: 'google', channelId: 'google-channel-2', routerId: 'google-router' };
+
+ await expect(runtime.createVideo(payload, { route })).rejects.toThrow(
+ 'interaction not found',
+ );
+ expect(usedKeys).toEqual(['key-2']);
+
+ await expect(
+ runtime.createVideo(payload, { route: { ...route, channelId: 'google-channel-9' } }),
+ ).rejects.toThrow('The video generation channel is no longer available');
+ expect(usedKeys).toEqual(['key-2']);
+ });
+
+ it('should resolve the video webhook router from the payload model', async () => {
+ class MockRuntime implements LobeRuntimeAI {
+ handleCreateVideoWebhook = vi.fn().mockResolvedValue({
+ inferenceId: 'interaction-1',
+ status: 'completed',
+ });
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: async (_, { model }) => {
+ if (model !== 'gemini-omni-1.1-flash') {
+ throw new Error('unexpected model');
+ }
+
+ return [
+ {
+ apiType: 'google',
+ models: [model],
+ options: {},
+ runtime: MockRuntime as any,
+ },
+ ];
+ },
+ });
+
+ const runtime = new Runtime();
+
+ await expect(
+ runtime.handleCreateVideoWebhook({
+ body: { type: 'interaction.completed' },
+ model: 'gemini-omni-1.1-flash',
+ }),
+ ).resolves.toMatchObject({ status: 'completed' });
+ });
});
describe('generateObject method', () => {
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 6b5d82fd10d..3eb490cfc73 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -29,7 +29,7 @@ import type {
CreateImageResponse,
CreateVideoMethodOptions,
CreateVideoPayload,
- CreateVideoResponse,
+ CreateVideoResult,
EmbeddingsOptions,
EmbeddingsPayload,
GenerateObjectOptions,
@@ -38,6 +38,7 @@ import type {
HandleCreateVideoWebhookResult,
ILobeAgentRuntimeErrorType,
TextToSpeechPayload,
+ VideoPollingRoute,
} from '../../types';
import { AgentRuntimeError } from '../../utils/createError';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
@@ -45,6 +46,7 @@ import { postProcessModelList } from '../../utils/postProcessModelList';
import { isImageDecodingRequestError, shouldStopFallbackForError } from '../../utils/routeFallback';
import { safeParseJSON } from '../../utils/safeParseJSON';
import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';
+import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import type { LobeRuntimeAI } from '../BaseAI';
import type {
CreateImageOptions,
@@ -129,6 +131,8 @@ interface RouteAttemptContext {
allowedApiTypes?: ReadonlySet<ApiType>;
metadata?: Record<string, unknown>;
method: RouterRuntimeMethod;
+ /** Skip routing and fallback: only the route's router/channel may serve the request. */
+ pinnedRoute?: VideoPollingRoute;
pricingContext?: ModelPricingContext;
toolsCount?: number;
user?: string;
@@ -213,7 +217,7 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
createVideo?: (
payload: CreateVideoPayload,
options: CreateVideoOptions,
- ) => Promise<CreateVideoResponse>;
+ ) => Promise<CreateVideoResult>;
customClient?: CustomClientOptions<T>;
debug?: {
chatCompletion: () => boolean;
@@ -274,6 +278,7 @@ export const createRouterRuntime = ({
}: CreateRouterRuntimeOptions) => {
return class UniformRuntime implements LobeRuntimeAI {
public _options: LobeClientOptions & Record<string, any>;
+ orchestratesVideoGenerationCompletion = true;
private _routers: Routers;
private _params: any;
private _id: string;
@@ -852,8 +857,11 @@ export const createRouterRuntime = ({
): Promise<T> {
const totalStartedAt = Date.now();
const requestId = nanoid();
- const { allowedApiTypes, metadata, pricingContext, toolsCount, user } = routeContext;
- const matchedRouter = await this.resolveMatchedRouter(model, pricingContext);
+ const { allowedApiTypes, metadata, pinnedRoute, pricingContext, toolsCount, user } =
+ routeContext;
+ const pinned = await this.resolvePinnedRoute(model, pinnedRoute);
+ const matchedRouter =
+ pinned?.router ?? (await this.resolveMatchedRouter(model, pricingContext));
const eligibleRouterOptions = this.normalizeRouterOptions(matchedRouter).filter(
(option) =>
!allowedApiTypes || allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),
@@ -861,12 +869,14 @@ export const createRouterRuntime = ({
if (eligibleRouterOptions.length === 0) {
throw new TypeError(`No provider route supports raw audio input for model ${model}`);
}
- const routerOptions = await this.applySortRouterOptions(
- matchedRouter,
- model,
- eligibleRouterOptions,
- routeContext,
- );
+ const routerOptions = pinned
+ ? [pinned.option]
+ : await this.applySortRouterOptions(
+ matchedRouter,
+ model,
+ eligibleRouterOptions,
+ routeContext,
+ );
const totalOptions = routerOptions.length;
const firstChannelId = routerOptions[0]?.id;
const weighted = routerOptions.some((option) => option.weight !== undefined);
@@ -1237,23 +1247,78 @@ export const createRouterRuntime = ({
async createVideo(payload: CreateVideoPayload, options?: CreateVideoMethodOptions) {
return this.runWithFallback(
payload.model,
- (runtime) => runtime.createVideo!(payload, options),
+ (runtime) => createVideoWithCompletionMode(runtime, payload, options),
{
metadata: options?.metadata,
method: 'createVideo',
+ pinnedRoute: options?.route,
pricingContext: options?.pricingContext,
},
);
}
- async handlePollVideoStatus(inferenceId: string) {
- const resolvedRouters = await this.resolveRouters();
- const matchedRouter = this._options.baseURL
- ? (resolvedRouters.find((router) => router.baseURLPattern?.test(this._options.baseURL!)) ??
- resolvedRouters.at(-1)!)
- : resolvedRouters.at(-1)!;
- const routerOptions = this.normalizeRouterOptions(matchedRouter);
- const { runtime } = await this.createRuntimeFromOption(matchedRouter, routerOptions[0]);
+ /**
+ * Resolve the exact router/channel that created a video instead of re-running normal
+ * routing: stateful providers such as Gemini Omni scope the interaction to the creating
+ * API key, so another channel's key can neither read nor continue it. Fail loudly when
+ * that route disappears rather than silently switching keys.
+ */
+ private async resolvePinnedRoute(model: string | undefined, route?: VideoPollingRoute) {
+ if (!route?.routerId && !route?.channelId) return;
+
+ const resolvedRouters = await this.resolveRouters({ model });
+ const router = route.routerId
+ ? resolvedRouters.find((item) => item.id === route.routerId)
+ : resolvedRouters.find((item) =>
+ this.normalizeRouterOptions(item).some((option) => option.id === route.channelId),
+ );
+
+ if (!router) {
+ throw new Error('The video generation route is no longer available');
+ }
+
+ const routerOptions = this.normalizeRouterOptions(router);
+ const option = route.channelId
+ ? routerOptions.find((item) => item.id === route.channelId)
+ : routerOptions[0];
+
+ if (!option) {
+ throw new Error('The video generation channel is no longer available');
+ }
+
+ return { option, router };
+ }
+
+ async handlePollVideoStatus(inferenceId: string, model?: string, route?: VideoPollingRoute) {
+ const pinned = await this.resolvePinnedRoute(model, route);
+ let matchedRouter = pinned?.router;
+
+ if (!matchedRouter && model) {
+ matchedRouter = await this.resolveMatchedRouter(model);
+ }
+
+ if (!matchedRouter) {
+ const resolvedRouters = await this.resolveRouters({ model });
+ const { baseURL } = this._options;
+ matchedRouter =
+ (baseURL
+ ? resolvedRouters.find((router) => router.baseURLPattern?.test(baseURL))
+ : undefined) ?? resolvedRouters.at(-1)!;
+ }
+
+ const selectedOption = pinned?.option ?? this.normalizeRouterOptions(matchedRouter)[0];
+ if (!selectedOption) {
+ throw new Error('The video generation channel is no longer available');
+ }
+
+ const { id: apiType, runtime } = await this.createRuntimeFromOption(
+ matchedRouter,
+ selectedOption,
+ );
+
+ if (route?.apiType && apiType !== route.apiType) {
+ throw new Error('The video generation provider route has changed');
+ }
if (!runtime.handlePollVideoStatus) {
throw new Error('Video polling is not supported by the matched runtime');
@@ -1263,7 +1328,7 @@ export const createRouterRuntime = ({
}
async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
- const model = (payload.body as any)?.model;
+ const model = payload.model ?? (payload.body as { model?: string } | undefined)?.model;
const resolvedRouters = await this.resolveRouters({ model });
const routerOptions = this.normalizeRouterOptions(resolvedRouters[0]);
const { runtime } = await this.createRuntimeFromOption(resolvedRouters[0], routerOptions[0]);
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts
index 7e5d5593f4d..d87451708f5 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts
@@ -3,7 +3,7 @@ import { ModelProvider } from 'model-bank';
import type {
CreateVideoPayload,
- CreateVideoResponse,
+ CreateVideoResult,
PollVideoStatusResult,
} from '../../types/video';
import { resolveMappedModelId } from '../../utils/modelIdMapping';
@@ -126,7 +126,7 @@ export async function pollOpenAICompatibleVideoStatus(
export async function createOpenAICompatibleVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const requestModel = resolveMappedModelId(model, options);
const { prompt, imageUrl, size, duration } = params;
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 7be887da164..d003b2bba53 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -15,6 +15,7 @@ import {
createSignatureScope,
serializeScopedSignature,
} from '../../utils/signatureScope';
+import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import * as openaiHelpers from '../contextBuilders/openai';
import { createOpenAICompatibleRuntime } from './index';
@@ -4218,6 +4219,83 @@ describe('LobeOpenAICompatibleFactory', () => {
});
});
+ describe('createVideo completion mode', () => {
+ it('should default to polling and strip callback URLs', async () => {
+ const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-1' });
+ const Runtime = createOpenAICompatibleRuntime({
+ createVideo,
+ provider: 'video-provider',
+ });
+ const runtime = new Runtime({ apiKey: 'test' });
+
+ await expect(
+ createVideoWithCompletionMode(
+ runtime,
+ {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'video-model',
+ params: { prompt: 'A cat' },
+ },
+ { preferredCompletionMode: 'webhook' },
+ ),
+ ).resolves.toEqual({
+ completionMode: 'polling',
+ inferenceId: 'video-1',
+ });
+ expect(createVideo).toHaveBeenCalledWith(
+ {
+ model: 'video-model',
+ params: { prompt: 'A cat' },
+ },
+ expect.any(Object),
+ );
+ });
+
+ it('should use webhook mode for a webhook-only runtime', async () => {
+ const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-2' });
+ const Runtime = createOpenAICompatibleRuntime({
+ createVideo,
+ provider: 'webhook-video-provider',
+ videoGenerationCapabilities: { completionModes: ['webhook'] },
+ });
+ const runtime = new Runtime({ apiKey: 'test' });
+ const payload = {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'video-model',
+ params: { prompt: 'A cat' },
+ };
+
+ await expect(createVideoWithCompletionMode(runtime, payload)).resolves.toEqual({
+ completionMode: 'webhook',
+ inferenceId: 'video-2',
+ });
+ expect(createVideo).toHaveBeenCalledWith(payload, expect.any(Object));
+ });
+
+ it('should resolve model capabilities using the mapped upstream model', async () => {
+ const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-3' });
+ const resolveCapabilities = vi
+ .fn()
+ .mockReturnValue({ completionModes: ['polling'] as const });
+ const Runtime = createOpenAICompatibleRuntime({
+ createVideo,
+ provider: 'mapped-video-provider',
+ videoGenerationCapabilities: resolveCapabilities,
+ });
+ const runtime = new Runtime({
+ apiKey: 'test',
+ modelIdMapping: { 'logical-video-model': 'upstream-video-model' },
+ });
+
+ await createVideoWithCompletionMode(runtime, {
+ model: 'logical-video-model',
+ params: { prompt: 'A cat' },
+ });
+
+ expect(resolveCapabilities).toHaveBeenCalledWith('upstream-video-model');
+ });
+ });
+
describe('transcribe', () => {
it('should transcribe audio and return the text', async () => {
const transcribeMock = vi
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index f7464ad3b36..a0f21d24e86 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -40,10 +40,11 @@ import type {
} from '../../types/image';
import type {
CreateVideoPayload,
- CreateVideoResponse,
+ CreateVideoResult,
HandleCreateVideoWebhookPayload,
HandleCreateVideoWebhookResult,
PollVideoStatusResult,
+ VideoGenerationCapabilities,
} from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
import { debugPayload, debugResponse, debugStream } from '../../utils/debugStream';
@@ -262,7 +263,7 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
createVideo?: (
payload: CreateVideoPayload,
options: CreateVideoOptions,
- ) => Promise<CreateVideoResponse>;
+ ) => Promise<CreateVideoResult>;
customClient?: CustomClientOptions<T>;
debug?: {
chatCompletion: () => boolean;
@@ -331,6 +332,8 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
payload: ResponseCreateParamsWithPromptCacheKey;
};
};
+ videoGenerationCapabilities?:
+ VideoGenerationCapabilities | ((model: string) => VideoGenerationCapabilities);
}
export const createOpenAICompatibleRuntime = <T extends Record<string, any> = any>({
@@ -347,6 +350,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
promptCacheKeyModels,
createImage: customCreateImage,
createVideo: customCreateVideo,
+ videoGenerationCapabilities,
handleCreateVideoWebhook: customHandleCreateVideoWebhook,
handlePollVideoStatus: customHandlePollVideoStatus,
generateObject: generateObjectConfig,
@@ -367,6 +371,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
baseURL!: string;
protected _options: ConstructorOptions<T>;
+ getVideoGenerationCapabilities(model: string): VideoGenerationCapabilities {
+ const requestModel = resolveMappedModelId(model, this.modelIdMappingOptions);
+
+ return typeof videoGenerationCapabilities === 'function'
+ ? videoGenerationCapabilities(requestModel)
+ : (videoGenerationCapabilities ?? { completionModes: ['polling'] });
+ }
+
constructor(options: LobeClientOptions & Record<string, any> = {}) {
const { modelIdMapping, ...inputOptions } = options as LobeClientOptions &
Record<string, any> &
@@ -940,7 +952,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
});
}
- async createVideo(payload: CreateVideoPayload) {
+ async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResult> {
const log = debug(`${this.logPrefix}:createVideo`);
if (customCreateVideo) {
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
index 76d791a8c41..d527ab7bb19 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
@@ -715,6 +715,41 @@ describe('computeChatPricing', () => {
expect(totalCredits).toBe(232);
});
+ it('bills Gemini Omni video output separately from input and text output', () => {
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'imageInput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoInput', rate: 1.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 9, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'videoGeneration', rate: 17.5, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ // A real conversational edit: the source video is billed as input.
+ const usage: ModelTokensUsage = {
+ inputTextTokens: 43,
+ inputVideoTokens: 58_511,
+ outputReasoningTokens: 383,
+ outputTextTokens: 1025,
+ outputVideoTokens: 57_920,
+ totalInputTokens: 58_554,
+ totalOutputTokens: 59_328,
+ totalTokens: 117_882,
+ };
+
+ const result = computeChatCost(pricing, usage);
+
+ expect(result?.issues).toHaveLength(0);
+ const breakdown = result!.breakdown;
+ expect(breakdown.find((item) => item.unit.name === 'textInput')?.quantity).toBe(43);
+ expect(breakdown.find((item) => item.unit.name === 'videoInput')?.quantity).toBe(58_511);
+ expect(breakdown.find((item) => item.unit.name === 'textOutput')?.quantity).toBe(1408);
+ expect(breakdown.find((item) => item.unit.name === 'videoGeneration')?.quantity).toBe(57_920);
+ expect(breakdown.find((item) => item.unit.name === 'imageInput')).toBeUndefined();
+ expect(result?.totalCost).toBe(1.114104);
+ });
+
it('splits cache reads by modality when dedicated modality cache units exist', () => {
const pricing: Pricing = {
units: [
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
index cac2bfc21a4..eb4371380d1 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
@@ -233,6 +233,7 @@ const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResol
imageOutput: (usage) => usage.outputImageTokens,
videoInput: resolveInputVideoTokens,
+ videoGeneration: (usage) => usage.outputVideoTokens,
imageGeneration: () => undefined,
diff --git a/packages/model-runtime/src/providers/google/createVideo.test.ts b/packages/model-runtime/src/providers/google/createVideo.test.ts
index 2233018baad..3522fd12317 100644
--- a/packages/model-runtime/src/providers/google/createVideo.test.ts
+++ b/packages/model-runtime/src/providers/google/createVideo.test.ts
@@ -29,7 +29,7 @@ vi.mock('../../utils/uriParser', () => ({
}));
vi.mock('@lobechat/utils', () => ({
- imageUrlToBase64: vi.fn(async (url) => ({
+ imageUrlToBase64: vi.fn(async (_url) => ({
base64: 'mock-base64-data',
mimeType: 'image/jpeg',
})),
@@ -43,6 +43,9 @@ vi.mock('@google/genai', () => ({
describe('createGoogleVideo', () => {
const mockClient = {
+ interactions: {
+ create: vi.fn(),
+ },
models: {
generateVideos: vi.fn(),
},
@@ -53,6 +56,172 @@ describe('createGoogleVideo', () => {
});
describe('successful creation', () => {
+ it('should create a background Gemini Omni interaction with a dynamic webhook', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/omni-123' });
+
+ const payload: CreateVideoPayload = {
+ callbackUrl: 'https://app.example.com/api/webhooks/video/google?token=secret',
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ aspectRatio: '9:16',
+ prompt: 'A cat playing guitar',
+ },
+ };
+
+ const result = await createGoogleVideo(mockClient as any, 'google', payload);
+
+ expect(mockClient.interactions.create).toHaveBeenCalledWith({
+ api_version: 'v1beta',
+ background: true,
+ generation_config: { video_config: { task: 'text_to_video' } },
+ input: 'A cat playing guitar',
+ model: 'gemini-omni-1.1-flash',
+ response_format: {
+ aspect_ratio: '9:16',
+ delivery: 'uri',
+ type: 'video',
+ },
+ store: true,
+ webhook_config: {
+ uris: ['https://app.example.com/api/webhooks/video/google?token=secret'],
+ },
+ });
+ expect(result).toEqual({ inferenceId: 'interactions/omni-123' });
+ });
+
+ it('should continue a Gemini Omni interaction with only the new edit instruction', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/edit-456' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ imageUrl: 'https://example.com/stale-start-frame.jpg',
+ imageUrls: ['https://example.com/stale-reference.jpg'],
+ prompt: 'Make the camera move more slowly',
+ },
+ previousInteractionId: 'interactions/source-123',
+ });
+
+ const request = mockClient.interactions.create.mock.calls[0][0];
+ expect(request).toMatchObject({
+ input: 'Make the camera move more slowly',
+ previous_interaction_id: 'interactions/source-123',
+ });
+ expect(request).not.toHaveProperty('generation_config');
+ });
+
+ it('should infer image-to-video when a stale text task is sent with media', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/image-456' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ imageUrls: ['https://example.com/reference.jpg'],
+ prompt: 'Animate this image',
+ task: 'text_to_video',
+ },
+ });
+
+ expect(mockClient.interactions.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ generation_config: { video_config: { task: 'image_to_video' } },
+ }),
+ );
+ });
+
+ it('should preserve all frame inputs and select reference-to-video', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/reference-789' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ endImageUrl: 'https://example.com/end.jpg',
+ imageUrl: 'https://example.com/start.jpg',
+ imageUrls: ['https://example.com/one.jpg', 'https://example.com/two.jpg'],
+ prompt: 'Put both characters in the same scene',
+ },
+ });
+
+ expect(mockClient.interactions.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ generation_config: { video_config: { task: 'reference_to_video' } },
+ input: [
+ { data: 'mock-base64-data', mime_type: 'image/jpeg', type: 'image' },
+ { data: 'mock-base64-data', mime_type: 'image/jpeg', type: 'image' },
+ { data: 'mock-base64-data', mime_type: 'image/jpeg', type: 'image' },
+ { data: 'mock-base64-data', mime_type: 'image/jpeg', type: 'image' },
+ { text: 'Put both characters in the same scene', type: 'text' },
+ ],
+ }),
+ );
+ });
+
+ it('should let Gemini infer first and last frame interpolation', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/frames-123' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ endImageUrl: 'https://example.com/end.jpg',
+ imageUrl: 'https://example.com/start.jpg',
+ prompt: 'Transition from sunrise to night',
+ },
+ });
+
+ const request = mockClient.interactions.create.mock.calls[0][0];
+ expect(request).not.toHaveProperty('generation_config');
+ expect(request.input).toHaveLength(3);
+ });
+
+ it('should treat a single reference image plus an end image as frame interpolation', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/frames-456' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ endImageUrl: 'https://example.com/end.jpg',
+ imageUrls: ['https://example.com/start.jpg'],
+ prompt: 'Transition from sunrise to night',
+ },
+ });
+
+ const request = mockClient.interactions.create.mock.calls[0][0];
+ expect(request).not.toHaveProperty('generation_config');
+ expect(request.input).toHaveLength(3);
+ });
+
+ it('should keep reference mode when several references accompany an end image', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/refs-789' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ endImageUrl: 'https://example.com/end.jpg',
+ imageUrls: ['https://example.com/a.jpg', 'https://example.com/b.jpg'],
+ prompt: 'Combine these subjects',
+ },
+ });
+
+ expect(mockClient.interactions.create.mock.calls[0][0].generation_config).toEqual({
+ video_config: { task: 'reference_to_video' },
+ });
+ });
+
+ it('should send the requested Gemini Omni output resolution', async () => {
+ mockClient.interactions.create.mockResolvedValueOnce({ id: 'interactions/res-123' });
+
+ await createGoogleVideo(mockClient as any, 'google', {
+ model: 'gemini-omni-1.1-flash',
+ params: { prompt: 'A drone shot of mountains', resolution: '1080p' },
+ });
+
+ expect(mockClient.interactions.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ response_format: { delivery: 'uri', resolution: '1080p', type: 'video' },
+ }),
+ );
+ });
+
it('should create video with basic prompt', async () => {
const mockOperation = { name: 'operations/test-op-123' };
mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);
@@ -478,6 +647,12 @@ describe('createGoogleVideo', () => {
describe('pollGoogleVideoOperation', () => {
const mockClient = {
+ files: {
+ get: vi.fn(),
+ },
+ interactions: {
+ get: vi.fn(),
+ },
operations: {
getVideosOperation: vi.fn(),
},
@@ -488,6 +663,85 @@ describe('pollGoogleVideoOperation', () => {
});
describe('successful completion', () => {
+ it('should return inline Gemini Omni video data', async () => {
+ mockClient.interactions.get.mockResolvedValueOnce({
+ id: 'v1_omni-inline',
+ output_video: {
+ data: 'base64-video',
+ mime_type: 'video/mp4',
+ },
+ status: 'completed',
+ usage: {
+ input_tokens_by_modality: [
+ { modality: 'video', tokens: 58_511 },
+ { modality: 'text', tokens: 43 },
+ ],
+ output_tokens_by_modality: [{ modality: 'video', tokens: 57_920 }],
+ total_input_tokens: 58_554,
+ total_output_tokens: 58_945,
+ total_thought_tokens: 383,
+ total_tokens: 117_882,
+ },
+ });
+
+ const result = await pollGoogleVideoOperation(
+ mockClient as any,
+ 'v1_omni-inline',
+ 'google',
+ 'test-api-key',
+ );
+
+ expect(mockClient.interactions.get).toHaveBeenCalledWith('v1_omni-inline', {
+ api_version: 'v1beta',
+ });
+
+ expect(result).toEqual({
+ status: 'success',
+ usage: {
+ completionTokens: 58_945,
+ modelUsage: {
+ inputImageTokens: undefined,
+ inputTextTokens: 43,
+ inputVideoTokens: 58_511,
+ outputReasoningTokens: 383,
+ outputTextTokens: 1025,
+ outputVideoTokens: 57_920,
+ totalInputTokens: 58_554,
+ totalOutputTokens: 59_328,
+ totalTokens: 117_882,
+ },
+ totalTokens: 117_882,
+ },
+ videoUrl: 'data:video/mp4;base64,base64-video',
+ });
+ });
+
+ it('should wait for a Gemini file and return its authenticated download URI', async () => {
+ mockClient.interactions.get.mockResolvedValueOnce({
+ id: 'interactions/omni-uri',
+ output_video: { type: 'video', uri: 'files/generated-video' },
+ status: 'completed',
+ });
+ mockClient.files.get.mockResolvedValueOnce({
+ downloadUri: 'https://generativelanguage.googleapis.com/download/video',
+ state: 'ACTIVE',
+ });
+
+ const result = await pollGoogleVideoOperation(
+ mockClient as any,
+ 'interactions/omni-uri',
+ 'google',
+ 'test-api-key',
+ );
+
+ expect(mockClient.files.get).toHaveBeenCalledWith({ name: 'files/generated-video' });
+ expect(result).toEqual({
+ headers: { 'x-goog-api-key': 'test-api-key' },
+ status: 'success',
+ videoUrl: 'https://generativelanguage.googleapis.com/download/video',
+ });
+ });
+
it('should return success when operation is done', async () => {
const mockOperation = {
done: true,
@@ -742,6 +996,41 @@ describe('pollGoogleVideoOperation', () => {
});
describe('pending state', () => {
+ it('should poll a qualified Veo operation resource', async () => {
+ const qualifiedOperation =
+ 'projects/test/locations/us-central1/publishers/google/models/veo/operations/test-123';
+ mockClient.operations.getVideosOperation.mockResolvedValueOnce({ done: false });
+
+ const result = await pollGoogleVideoOperation(
+ mockClient as any,
+ qualifiedOperation,
+ 'google',
+ 'test-api-key',
+ );
+
+ expect(result).toEqual({ status: 'pending' });
+ expect(mockClient.operations.getVideosOperation).toHaveBeenCalledWith({
+ operation: expect.objectContaining({ name: qualifiedOperation }),
+ });
+ expect(mockClient.interactions.get).not.toHaveBeenCalled();
+ });
+
+ it('should return pending while a Gemini Omni interaction is in progress', async () => {
+ mockClient.interactions.get.mockResolvedValueOnce({
+ id: 'interactions/omni-pending',
+ status: 'in_progress',
+ });
+
+ const result = await pollGoogleVideoOperation(
+ mockClient as any,
+ 'interactions/omni-pending',
+ 'google',
+ 'test-api-key',
+ );
+
+ expect(result).toEqual({ status: 'pending' });
+ });
+
it('should return pending when operation not done', async () => {
const mockOperation = { done: false };
mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);
diff --git a/packages/model-runtime/src/providers/google/createVideo.ts b/packages/model-runtime/src/providers/google/createVideo.ts
index be9acefb100..f491c587bc0 100644
--- a/packages/model-runtime/src/providers/google/createVideo.ts
+++ b/packages/model-runtime/src/providers/google/createVideo.ts
@@ -1,14 +1,56 @@
import type { GenerateVideosConfig, GoogleGenAI, Image } from '@google/genai';
import { GenerateVideosOperation } from '@google/genai';
+import type { ModelTokensUsage } from '@lobechat/types';
import { imageUrlToBase64 } from '@lobechat/utils';
import debug from 'debug';
+import { GEMINI_OMNI_VIDEO_MODEL_ID } from 'model-bank/standardParameters';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type {
+ CreateVideoPayload,
+ CreateVideoResult,
+ VideoGenerationUsage,
+} from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';
import { parseDataUri } from '../../utils/uriParser';
const log = debug('lobe-video:google');
+const GOOGLE_FILE_DOWNLOAD_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta';
+
+interface OmniVideoContent {
+ data?: string;
+ mime_type?: string;
+ type?: 'video';
+ uri?: string;
+}
+
+interface OmniInteraction {
+ id: string;
+ output_video?: OmniVideoContent;
+ status: string;
+ steps?: Array<{
+ content?: Array<Record<string, unknown>>;
+ error?: { message?: string };
+ type?: string;
+ }>;
+ usage?: OmniUsage;
+}
+
+interface OmniModalityTokens {
+ modality?: string;
+ tokens?: number;
+}
+
+interface OmniUsage {
+ input_tokens_by_modality?: OmniModalityTokens[];
+ output_tokens_by_modality?: OmniModalityTokens[];
+ total_input_tokens?: number;
+ total_output_tokens?: number;
+ total_thought_tokens?: number;
+ total_tokens?: number;
+}
+
+export const isGeminiOmniVideoModel = (model: string) => model === GEMINI_OMNI_VIDEO_MODEL_ID;
/**
* Convert image URL to Google Image format
@@ -39,13 +81,159 @@ async function imageToGoogleImageFormat(imageUrl: string): Promise<Image> {
}
}
+async function imageToOmniContent(imageUrl: string) {
+ const image = await imageToGoogleImageFormat(imageUrl);
+
+ return {
+ data: image.imageBytes,
+ mime_type: image.mimeType || 'image/png',
+ type: 'image' as const,
+ };
+}
+
+function extractOmniVideo(interaction: OmniInteraction): OmniVideoContent | undefined {
+ if (interaction.output_video) return interaction.output_video;
+
+ for (const step of interaction.steps ?? []) {
+ if (step.type !== 'model_output') continue;
+
+ const video = step.content?.find((content) => content.type === 'video');
+ if (video) return video as unknown as OmniVideoContent;
+ }
+
+ return undefined;
+}
+
+function extractOmniError(interaction: OmniInteraction): string {
+ for (const step of interaction.steps ?? []) {
+ if (step.error?.message) return step.error.message;
+ }
+
+ return `Gemini interaction ${interaction.status}`;
+}
+
+const sumModalityTokens = (items: OmniModalityTokens[] | undefined, modality: string) => {
+ const matched = items?.filter((item) => item.modality === modality);
+ if (!matched?.length) return undefined;
+
+ return matched.reduce((sum, item) => sum + (item.tokens ?? 0), 0);
+};
+
+/**
+ * Gemini Omni bills input, text/thinking output and video output at different rates, so keep the
+ * per-modality breakdown for token pricing. `total_output_tokens` holds the generated text and
+ * video tokens; thinking tokens are reported separately in `total_thought_tokens`.
+ * @see https://ai.google.dev/gemini-api/docs/pricing#gemini-omni-flash
+ */
+const convertOmniUsage = (usage: OmniUsage | undefined): VideoGenerationUsage | undefined => {
+ const totalOutputTokens = usage?.total_output_tokens;
+ if (!usage || !totalOutputTokens || totalOutputTokens <= 0) return undefined;
+
+ const outputVideoTokens = sumModalityTokens(usage.output_tokens_by_modality, 'video') ?? 0;
+ const outputReasoningTokens = usage.total_thought_tokens ?? 0;
+ const modelUsage: ModelTokensUsage = {
+ inputImageTokens: sumModalityTokens(usage.input_tokens_by_modality, 'image'),
+ // Default to 0 so pricing never falls back to billing all input tokens at the text rate.
+ inputTextTokens: sumModalityTokens(usage.input_tokens_by_modality, 'text') ?? 0,
+ inputVideoTokens: sumModalityTokens(usage.input_tokens_by_modality, 'video'),
+ outputReasoningTokens,
+ outputTextTokens: Math.max(0, totalOutputTokens - outputVideoTokens),
+ outputVideoTokens,
+ totalInputTokens: usage.total_input_tokens ?? 0,
+ totalOutputTokens: totalOutputTokens + outputReasoningTokens,
+ totalTokens: usage.total_tokens,
+ };
+
+ return {
+ completionTokens: totalOutputTokens,
+ modelUsage,
+ totalTokens: usage.total_tokens ?? totalOutputTokens,
+ };
+};
+
+async function createGoogleOmniVideo(
+ client: GoogleGenAI,
+ payload: CreateVideoPayload,
+): Promise<CreateVideoResult> {
+ const { callbackUrl, model, params, previousInteractionId } = payload;
+ const { aspectRatio, endImageUrl, imageUrl, imageUrls, prompt, resolution } = params;
+ const images = [imageUrl, ...(imageUrls ?? []), endImageUrl].filter((url): url is string =>
+ Boolean(url),
+ );
+
+ /**
+ * Infer the task from the actual request media. Persisted generation parameters and older
+ * clients can retain a stale `text_to_video` value after images are added, which Gemini rejects.
+ * First/last frame interpolation has no task value: Gemini infers it from the ordered frames, and
+ * forcing `reference_to_video` would treat them as subject references instead. The start frame
+ * may arrive as `imageUrl` or, following the Seedance convention used by the video page, as the
+ * single `imageUrls` entry.
+ */
+ const isFrameInterpolation = Boolean(endImageUrl) && images.length <= 2;
+ const resolvedTask = previousInteractionId
+ ? 'edit'
+ : isFrameInterpolation
+ ? undefined
+ : images.length > 1
+ ? 'reference_to_video'
+ : images.length === 1
+ ? 'image_to_video'
+ : 'text_to_video';
+ /**
+ * Stateful continuation already restores the source media from `previous_interaction_id`.
+ * Re-sending persisted frame inputs can make Gemini reject the edit as conflicting media.
+ */
+ const input = previousInteractionId
+ ? prompt
+ : images.length === 0
+ ? prompt
+ : [
+ ...(await Promise.all(images.map((url) => imageToOmniContent(url)))),
+ { text: prompt, type: 'text' as const },
+ ];
+
+ const interaction = (await client.interactions.create({
+ api_version: 'v1beta',
+ background: true,
+ ...(previousInteractionId || !resolvedTask
+ ? {}
+ : { generation_config: { video_config: { task: resolvedTask } } }),
+ input,
+ model,
+ ...(previousInteractionId ? { previous_interaction_id: previousInteractionId } : {}),
+ response_format: {
+ ...(aspectRatio ? { aspect_ratio: aspectRatio as '16:9' | '9:16' } : {}),
+ delivery: 'uri',
+ ...(resolution ? { resolution } : {}),
+ type: 'video',
+ },
+ store: true,
+ ...(callbackUrl
+ ? {
+ webhook_config: {
+ uris: [callbackUrl],
+ },
+ }
+ : {}),
+ })) as OmniInteraction;
+
+ if (!interaction.id) throw new Error('Gemini interaction response is missing an id');
+
+ return { inferenceId: interaction.id };
+}
+
export async function createGoogleVideo(
client: GoogleGenAI,
provider: string,
payload: CreateVideoPayload,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
try {
const { model, params } = payload;
+
+ if (isGeminiOmniVideoModel(model)) {
+ return await createGoogleOmniVideo(client, payload);
+ }
+
const {
prompt,
imageUrl,
@@ -113,13 +301,89 @@ export async function createGoogleVideo(
}
}
+async function pollGoogleOmniInteraction(client: GoogleGenAI, inferenceId: string, apiKey: string) {
+ const interaction = (await client.interactions.get(inferenceId, {
+ api_version: 'v1beta',
+ })) as OmniInteraction;
+ const usage = convertOmniUsage(interaction.usage);
+
+ if (interaction.status === 'queued' || interaction.status === 'in_progress') {
+ return { status: 'pending' as const };
+ }
+
+ if (interaction.status !== 'completed') {
+ return {
+ error: extractOmniError(interaction),
+ status: 'failed' as const,
+ };
+ }
+
+ const video = extractOmniVideo(interaction);
+ if (!video) {
+ return {
+ error: 'Gemini interaction completed without video output',
+ status: 'failed' as const,
+ };
+ }
+
+ if (video.data) {
+ return {
+ status: 'success' as const,
+ ...(usage ? { usage } : {}),
+ videoUrl: `data:${video.mime_type || 'video/mp4'};base64,${video.data}`,
+ };
+ }
+
+ if (!video.uri) {
+ return {
+ error: 'Gemini interaction video output is missing data and URI',
+ status: 'failed' as const,
+ };
+ }
+
+ const fileMatch = video.uri.match(/(?:^|\/)(files\/[^/:?#]+)/);
+ if (!fileMatch) {
+ return {
+ headers: { 'x-goog-api-key': apiKey },
+ status: 'success' as const,
+ ...(usage ? { usage } : {}),
+ videoUrl: video.uri,
+ };
+ }
+
+ const file = await client.files.get({ name: fileMatch[1] });
+ const fileState = String(file.state ?? '').toUpperCase();
+
+ if (fileState === 'FAILED') {
+ return {
+ error: file.error?.message || 'Gemini generated video file processing failed',
+ status: 'failed' as const,
+ };
+ }
+
+ if (fileState !== 'ACTIVE') return { status: 'pending' as const };
+
+ return {
+ headers: { 'x-goog-api-key': apiKey },
+ status: 'success' as const,
+ ...(usage ? { usage } : {}),
+ videoUrl:
+ file.downloadUri || `${GOOGLE_FILE_DOWNLOAD_BASE_URL}/${fileMatch[1]}:download?alt=media`,
+ };
+}
+
export async function pollGoogleVideoOperation(
client: GoogleGenAI,
inferenceId: string,
provider: string,
apiKey: string,
): Promise<
- | { headers?: Record<string, string>; status: 'success'; videoUrl: string }
+ | {
+ headers?: Record<string, string>;
+ status: 'success';
+ usage?: VideoGenerationUsage;
+ videoUrl: string;
+ }
| { status: 'failed'; error: string }
| { status: 'pending' }
> {
@@ -130,6 +394,10 @@ export async function pollGoogleVideoOperation(
return { error: 'Invalid operation name', status: 'failed' };
}
+ if (!inferenceId.startsWith('operations/') && !inferenceId.includes('/operations/')) {
+ return await pollGoogleOmniInteraction(client, inferenceId, apiKey);
+ }
+
// Create a proper GenerateVideosOperation instance from the operation name
const operation = new GenerateVideosOperation();
operation.name = inferenceId;
diff --git a/packages/model-runtime/src/providers/google/handleCreateVideoWebhook.test.ts b/packages/model-runtime/src/providers/google/handleCreateVideoWebhook.test.ts
new file mode 100644
index 00000000000..c4c10de0314
--- /dev/null
+++ b/packages/model-runtime/src/providers/google/handleCreateVideoWebhook.test.ts
@@ -0,0 +1,203 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { handleGoogleVideoWebhook } from './handleCreateVideoWebhook';
+
+const signingKeys = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
+const publicJwk = await crypto.subtle.exportKey('jwk', signingKeys.publicKey);
+
+const toBase64 = (bytes: ArrayBuffer) => btoa(String.fromCharCode(...new Uint8Array(bytes)));
+
+const sign = async (content: string, key: CryptoKey = signingKeys.privateKey) =>
+ toBase64(await crypto.subtle.sign({ name: 'Ed25519' }, key, new TextEncoder().encode(content)));
+
+/** Builds a delivery signed the way Gemini signs dynamic webhooks (Standard Webhooks `v1a`). */
+const createPayload = async (
+ body: unknown,
+ {
+ signingKey,
+ timestamp = Math.floor(Date.now() / 1000).toString(),
+ }: { signingKey?: CryptoKey; timestamp?: string } = {},
+) => {
+ const rawBody = JSON.stringify(body);
+ const webhookId = 'msg_test';
+
+ return {
+ body,
+ headers: {
+ 'webhook-id': webhookId,
+ 'webhook-signature': `v1a,${await sign(`${webhookId}.${timestamp}.${rawBody}`, signingKey)}`,
+ 'webhook-timestamp': timestamp,
+ },
+ rawBody,
+ url: 'https://app.example.com/api/webhooks/video/google?token=secret',
+ };
+};
+
+describe('handleGoogleVideoWebhook', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ keys: [{ ...publicJwk, alg: 'EdDSA', use: 'sig' }] })),
+ );
+ });
+
+ it('should verify and normalize an interaction completion event', async () => {
+ const result = await handleGoogleVideoWebhook(
+ await createPayload({
+ data: { id: 'interactions/omni-123' },
+ type: 'interaction.completed',
+ }),
+ );
+
+ expect(result).toEqual({
+ inferenceId: 'interactions/omni-123',
+ status: 'completed',
+ });
+ });
+
+ it('should normalize a video generated event as completed', async () => {
+ const result = await handleGoogleVideoWebhook(
+ await createPayload({
+ data: {
+ id: 'interactions/omni-video-123',
+ output_file_uri: 'https://example.com/video.mp4',
+ },
+ type: 'video.generated',
+ }),
+ );
+
+ expect(result).toEqual({
+ inferenceId: 'interactions/omni-video-123',
+ status: 'completed',
+ });
+ });
+
+ it('should normalize an interaction failure event', async () => {
+ const result = await handleGoogleVideoWebhook(
+ await createPayload({
+ data: {
+ error_code: 'SAFETY',
+ error_message: 'Video generation was blocked',
+ id: 'interactions/omni-failed',
+ },
+ type: 'interaction.failed',
+ }),
+ );
+
+ expect(result).toEqual({
+ error: 'Video generation was blocked',
+ inferenceId: 'interactions/omni-failed',
+ status: 'error',
+ });
+ });
+
+ it('should reject stale webhook deliveries', async () => {
+ await expect(
+ handleGoogleVideoWebhook(
+ await createPayload(
+ { data: { id: 'interactions/omni-123' }, type: 'interaction.completed' },
+ { timestamp: '1' },
+ ),
+ ),
+ ).rejects.toThrow('outside the allowed replay window');
+ });
+
+ it('should reject unsigned webhook deliveries', async () => {
+ await expect(
+ handleGoogleVideoWebhook({
+ body: { data: { id: 'interactions/omni-123' }, type: 'interaction.completed' },
+ headers: { 'webhook-timestamp': Math.floor(Date.now() / 1000).toString() },
+ }),
+ ).rejects.toThrow('Missing Google webhook signature');
+ });
+ it('should reject a delivery signed with an unknown key', async () => {
+ const otherKeys = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [
+ 'sign',
+ 'verify',
+ ]);
+
+ await expect(
+ handleGoogleVideoWebhook(
+ await createPayload(
+ { data: { id: 'interactions/omni-123' }, type: 'interaction.completed' },
+ { signingKey: otherKeys.privateKey },
+ ),
+ ),
+ ).rejects.toThrow('Invalid Google webhook signature');
+ });
+
+ it('should reject a delivery whose body was changed after signing', async () => {
+ const payload = await createPayload({
+ data: { id: 'interactions/omni-123' },
+ type: 'interaction.completed',
+ });
+
+ await expect(
+ handleGoogleVideoWebhook({
+ ...payload,
+ rawBody: payload.rawBody.replace('omni-123', 'omni-456'),
+ }),
+ ).rejects.toThrow('Invalid Google webhook signature');
+ });
+
+ describe('key refresh', () => {
+ const jwksResponse = (jwk: JsonWebKey) =>
+ new Response(JSON.stringify({ keys: [{ ...jwk, alg: 'EdDSA', use: 'sig' }] }));
+
+ /** Loads a fresh module instance so the module-level JWKS cache starts empty. */
+ const loadHandler = async () => {
+ vi.resetModules();
+ return (await import('./handleCreateVideoWebhook')).handleGoogleVideoWebhook;
+ };
+
+ const completedBody = { data: { id: 'interactions/omni-123' }, type: 'interaction.completed' };
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ return () => vi.useRealTimers();
+ });
+
+ it('should not refetch keys for every forged signature', async () => {
+ const handle = await loadHandler();
+ const forgedKeys = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [
+ 'sign',
+ 'verify',
+ ]);
+
+ await handle(await createPayload(completedBody));
+ for (let i = 0; i < 3; i++) {
+ await expect(
+ handle(await createPayload(completedBody, { signingKey: forgedKeys.privateKey })),
+ ).rejects.toThrow('Invalid Google webhook signature');
+ }
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ });
+
+ it('should refresh keys once the cooldown has passed to pick up rotated keys', async () => {
+ const handle = await loadHandler();
+ const oldKeys = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [
+ 'sign',
+ 'verify',
+ ]);
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(
+ jwksResponse(await crypto.subtle.exportKey('jwk', oldKeys.publicKey)),
+ )
+ .mockResolvedValueOnce(jwksResponse(publicJwk));
+
+ await handle(await createPayload(completedBody, { signingKey: oldKeys.privateKey }));
+ vi.setSystemTime(Date.now() + 61 * 1000);
+
+ await expect(handle(await createPayload(completedBody))).resolves.toMatchObject({
+ status: 'completed',
+ });
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/google/handleCreateVideoWebhook.ts b/packages/model-runtime/src/providers/google/handleCreateVideoWebhook.ts
new file mode 100644
index 00000000000..2f83a26553f
--- /dev/null
+++ b/packages/model-runtime/src/providers/google/handleCreateVideoWebhook.ts
@@ -0,0 +1,169 @@
+import type {
+ HandleCreateVideoWebhookPayload,
+ HandleCreateVideoWebhookResult,
+} from '../../types/video';
+
+const GOOGLE_WEBHOOK_JWKS_URL = 'https://generativelanguage.googleapis.com/.well-known/jwks.json';
+const MAX_WEBHOOK_AGE_MS = 5 * 60 * 1000;
+const JWKS_CACHE_TTL_MS = 10 * 60 * 1000;
+const JWKS_FETCH_TIMEOUT_MS = 10 * 1000;
+/**
+ * The webhook route is public, so a forged signature must not be able to force a JWKS refetch on
+ * every request. Rotation-triggered refreshes are limited to one per window.
+ */
+const JWKS_FORCE_REFRESH_COOLDOWN_MS = 60 * 1000;
+
+interface GoogleWebhookJwk extends JsonWebKey {
+ alg?: string;
+ crv?: string;
+}
+
+let jwksCache: { expiresAt: number; fetchedAt: number; keys: CryptoKey[] } | undefined;
+
+const importEd25519Keys = async (keys: GoogleWebhookJwk[]) => {
+ const imported: CryptoKey[] = [];
+
+ for (const jwk of keys) {
+ if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') continue;
+
+ imported.push(
+ await crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify']),
+ );
+ }
+
+ return imported;
+};
+
+const getGoogleWebhookKeys = async (forceRefresh = false) => {
+ const now = Date.now();
+ if (jwksCache) {
+ const fresh = jwksCache.expiresAt > now;
+ const inCooldown = now - jwksCache.fetchedAt < JWKS_FORCE_REFRESH_COOLDOWN_MS;
+ if (forceRefresh ? inCooldown : fresh) return jwksCache.keys;
+ }
+
+ const res = await fetch(GOOGLE_WEBHOOK_JWKS_URL, {
+ signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`Failed to fetch Google webhook keys: ${res.status}`);
+
+ const { keys = [] } = (await res.json()) as { keys?: GoogleWebhookJwk[] };
+ const imported = await importEd25519Keys(keys);
+ const fetchedAt = Date.now();
+ jwksCache = { expiresAt: fetchedAt + JWKS_CACHE_TTL_MS, fetchedAt, keys: imported };
+
+ return imported;
+};
+
+const decodeBase64 = (value: string) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
+
+const verifyWithKeys = async (
+ keys: CryptoKey[],
+ signatures: Uint8Array<ArrayBuffer>[],
+ content: Uint8Array<ArrayBuffer>,
+) => {
+ for (const signature of signatures) {
+ for (const key of keys) {
+ if (await crypto.subtle.verify({ name: 'Ed25519' }, key, signature, content)) return true;
+ }
+ }
+
+ return false;
+};
+
+interface GoogleWebhookBody {
+ data?: {
+ error_code?: string;
+ error_message?: string;
+ id?: string;
+ };
+ type?: string;
+}
+
+const getHeader = (headers: Record<string, string> | undefined, name: string) => {
+ if (!headers) return undefined;
+
+ const target = name.toLowerCase();
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === target);
+ return entry?.[1];
+};
+
+/**
+ * Verifies a dynamic (per-request `webhook_config`) delivery.
+ *
+ * Although the Gemini docs describe the header as an RS256 JWT, real deliveries follow the
+ * Standard Webhooks asymmetric scheme: `webhook-signature: v1a,<base64 Ed25519 signature>`
+ * over `${webhook-id}.${webhook-timestamp}.${rawBody}`, verified against the Ed25519 keys
+ * published at the JWKS endpoint (which carry no `kid`). Observed on 2026-09-25.
+ * @see https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md
+ */
+async function verifyDynamicWebhook(payload: HandleCreateVideoWebhookPayload) {
+ const signatureHeader = getHeader(payload.headers, 'webhook-signature');
+ if (!signatureHeader) throw new Error('Missing Google webhook signature');
+
+ const webhookId = getHeader(payload.headers, 'webhook-id');
+ if (!webhookId) throw new Error('Missing Google webhook id');
+
+ if (payload.rawBody === undefined) throw new Error('Missing raw body for Google webhook');
+
+ const timestamp = getHeader(payload.headers, 'webhook-timestamp');
+ if (!timestamp) throw new Error('Missing Google webhook timestamp');
+
+ const timestampMs = Number(timestamp) * 1000;
+ if (!Number.isFinite(timestampMs) || Math.abs(Date.now() - timestampMs) > MAX_WEBHOOK_AGE_MS) {
+ throw new Error('Google webhook timestamp is outside the allowed replay window');
+ }
+
+ // The header may carry several space-separated `<version>,<signature>` entries during key rotation.
+ const signatures = signatureHeader
+ .split(' ')
+ .map((entry) => entry.split(','))
+ .filter(([version, value]) => version === 'v1a' && value)
+ .map(([, value]) => decodeBase64(value));
+ if (signatures.length === 0) throw new Error('Unsupported Google webhook signature format');
+
+ const content = new TextEncoder().encode(`${webhookId}.${timestamp}.${payload.rawBody}`);
+
+ const cachedKeys = await getGoogleWebhookKeys();
+ if (await verifyWithKeys(cachedKeys, signatures, content)) return;
+ // Retry once with fresh keys in case Google rotated them after we cached the set.
+ const refreshedKeys = await getGoogleWebhookKeys(true);
+ if (refreshedKeys !== cachedKeys && (await verifyWithKeys(refreshedKeys, signatures, content)))
+ return;
+
+ throw new Error('Invalid Google webhook signature');
+}
+
+export async function handleGoogleVideoWebhook(
+ payload: HandleCreateVideoWebhookPayload,
+): Promise<HandleCreateVideoWebhookResult> {
+ await verifyDynamicWebhook(payload);
+
+ const body = payload.body as GoogleWebhookBody;
+ const inferenceId = body.data?.id;
+
+ if (!inferenceId) throw new Error('Missing interaction id in Google webhook body');
+
+ switch (body.type) {
+ case 'interaction.completed':
+ case 'video.generated': {
+ return { inferenceId, status: 'completed' };
+ }
+
+ case 'interaction.failed':
+ case 'interaction.cancelled': {
+ return {
+ error:
+ body.data?.error_message ||
+ body.data?.error_code ||
+ `Gemini interaction ${body.type.split('.')[1]}`,
+ inferenceId,
+ status: 'error',
+ };
+ }
+
+ default: {
+ return { inferenceId, status: 'pending' };
+ }
+ }
+}
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index dffa7d3b170..d3f976b9469 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -12,6 +12,7 @@ import {
createSignatureScope,
serializeScopedSignature,
} from '../../utils/signatureScope';
+import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import { LobeGoogleAI } from './index';
const provider = 'google';
@@ -77,6 +78,94 @@ describe('LobeGoogleAI', () => {
});
});
+ describe('createVideo', () => {
+ it('should reject Gemini Omni Flash on Vertex AI', async () => {
+ const vertexInstance = new LobeGoogleAI({ apiKey: 'test', isVertexAi: true });
+
+ await expect(
+ vertexInstance.createVideo({
+ model: 'gemini-omni-1.1-flash',
+ params: { prompt: 'A cinematic sunrise' },
+ }),
+ ).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: 'vertexai',
+ });
+ });
+
+ it('should default Gemini Omni Flash to polling and omit its webhook config', async () => {
+ const createInteraction = vi
+ .spyOn(instance['client'].interactions, 'create')
+ .mockResolvedValue({ id: 'interactions/omni-polling' } as any);
+
+ await expect(
+ createVideoWithCompletionMode(instance, {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'gemini-omni-1.1-flash',
+ params: { prompt: 'A cinematic sunrise' },
+ }),
+ ).resolves.toEqual({
+ completionMode: 'polling',
+ inferenceId: 'interactions/omni-polling',
+ });
+ expect(createInteraction).toHaveBeenCalledWith(
+ expect.not.objectContaining({ webhook_config: expect.anything() }),
+ );
+ });
+
+ it('should use a dynamic webhook for Gemini Omni Flash when webhook mode is preferred', async () => {
+ const createInteraction = vi
+ .spyOn(instance['client'].interactions, 'create')
+ .mockResolvedValue({ id: 'interactions/omni-webhook' } as any);
+
+ await expect(
+ createVideoWithCompletionMode(
+ instance,
+ {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'gemini-omni-1.1-flash',
+ params: { prompt: 'A cinematic sunrise' },
+ },
+ { preferredCompletionMode: 'webhook' },
+ ),
+ ).resolves.toEqual({
+ completionMode: 'webhook',
+ inferenceId: 'interactions/omni-webhook',
+ });
+ expect(createInteraction).toHaveBeenCalledWith(
+ expect.objectContaining({
+ webhook_config: {
+ uris: ['https://example.com/webhook'],
+ },
+ }),
+ );
+ });
+
+ it('should keep Veo on polling when webhook mode is preferred', async () => {
+ const generateVideos = vi
+ .spyOn(instance['client'].models, 'generateVideos')
+ .mockResolvedValue({ name: 'operations/veo-1' } as any);
+
+ await expect(
+ createVideoWithCompletionMode(
+ instance,
+ {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'veo-3.1-generate-preview',
+ params: { prompt: 'A cinematic sunrise' },
+ },
+ { preferredCompletionMode: 'webhook' },
+ ),
+ ).resolves.toEqual({
+ completionMode: 'polling',
+ inferenceId: 'operations/veo-1',
+ });
+ expect(generateVideos).toHaveBeenCalledWith(
+ expect.not.objectContaining({ callbackUrl: expect.anything() }),
+ );
+ });
+ });
+
describe('chat', () => {
it('should return a StreamingTextResponse on successful API call', async () => {
const result = await instance.chat({
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 2dc5e4b2891..4ff4a5aba47 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -31,13 +31,17 @@ import type {
import { AgentRuntimeErrorType } from '../../types/error';
import type { CreateImagePayload, CreateImageResponse } from '../../types/image';
import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type {
+ CreateVideoPayload,
+ CreateVideoResult,
+ VideoGenerationCapabilities,
+} from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
import { getModelPricing } from '../../utils/getModelPricing';
import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
-import { withMappedModelId } from '../../utils/modelIdMapping';
+import { resolveMappedModelId, withMappedModelId } from '../../utils/modelIdMapping';
import { StreamingResponse } from '../../utils/response';
import {
createSignatureChannelId,
@@ -45,8 +49,9 @@ import {
getRuntimeSignatureScopeSource,
} from '../../utils/signatureScope';
import { createGoogleImage } from './createImage';
-import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';
+import { createGoogleVideo, isGeminiOmniVideoModel, pollGoogleVideoOperation } from './createVideo';
import { createGoogleGenerateObject, createGoogleGenerateObjectWithTools } from './generateObject';
+import { handleGoogleVideoWebhook } from './handleCreateVideoWebhook';
import {
isGemini3OrAbove,
isGoogleImageResponseModel,
@@ -343,12 +348,32 @@ export class LobeGoogleAI implements LobeRuntimeAI {
});
}
- async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResponse> {
- return createGoogleVideo(
- this.client,
- this.provider,
- withMappedModelId(payload, this.modelIdMappingOptions),
- );
+ async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResult> {
+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);
+
+ if (this.isVertexAi && isGeminiOmniVideoModel(requestPayload.model)) {
+ throw AgentRuntimeError.createVideo({
+ error: {
+ message: 'Gemini Omni Flash is only supported by the Gemini Developer API',
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: this.provider,
+ });
+ }
+
+ return createGoogleVideo(this.client, this.provider, requestPayload);
+ }
+
+ getVideoGenerationCapabilities(model: string): VideoGenerationCapabilities {
+ const requestModel = resolveMappedModelId(model, this.modelIdMappingOptions);
+
+ if (isGeminiOmniVideoModel(requestModel)) {
+ return { completionModes: ['polling', 'webhook'] };
+ }
+
+ return {
+ completionModes: ['polling'],
+ };
}
/**
@@ -385,6 +410,10 @@ export class LobeGoogleAI implements LobeRuntimeAI {
return pollGoogleVideoOperation(this.client, inferenceId, this.provider, this.apiKey!);
}
+ async handleCreateVideoWebhook(payload: Parameters<typeof handleGoogleVideoWebhook>[0]) {
+ return handleGoogleVideoWebhook(payload);
+ }
+
/**
* Generate structured output using Google Gemini API
* @see https://ai.google.dev/gemini-api/docs/structured-output
diff --git a/packages/model-runtime/src/providers/hunyuan/createVideo.ts b/packages/model-runtime/src/providers/hunyuan/createVideo.ts
index 884b1e0c6aa..f68f0a0d640 100644
--- a/packages/model-runtime/src/providers/hunyuan/createVideo.ts
+++ b/packages/model-runtime/src/providers/hunyuan/createVideo.ts
@@ -3,7 +3,7 @@ import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
import type {
CreateVideoPayload,
- CreateVideoResponse,
+ CreateVideoResult,
PollVideoStatusResult,
} from '../../types/video';
@@ -55,7 +55,7 @@ const parseInferenceId = (inferenceId: string) => {
export async function createHunyuanVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { apiKey } = options;
const { model, params } = payload;
const { prompt, imageUrl, resolution, watermark } = params;
diff --git a/packages/model-runtime/src/providers/minimax/createVideo.ts b/packages/model-runtime/src/providers/minimax/createVideo.ts
index 2e0e5389179..dfb7d103df0 100644
--- a/packages/model-runtime/src/providers/minimax/createVideo.ts
+++ b/packages/model-runtime/src/providers/minimax/createVideo.ts
@@ -1,7 +1,7 @@
import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type { CreateVideoPayload, CreateVideoResult } from '../../types/video';
import { resolveMappedModelId } from '../../utils/modelIdMapping';
const log = createDebug('lobe-video:minimax');
@@ -224,7 +224,7 @@ export async function pollMiniMaxVideoStatus(
export async function createMiniMaxVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const requestModel = resolveMappedModelId(model, options);
const { prompt, imageUrl, imageUrls, endImageUrl, aspectRatio, duration, resolution } = params;
diff --git a/packages/model-runtime/src/providers/qwen/createVideo.ts b/packages/model-runtime/src/providers/qwen/createVideo.ts
index 491e54f2b17..069f0c538cf 100644
--- a/packages/model-runtime/src/providers/qwen/createVideo.ts
+++ b/packages/model-runtime/src/providers/qwen/createVideo.ts
@@ -1,7 +1,7 @@
import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type { CreateVideoPayload, CreateVideoResult } from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
const log = createDebug('lobe-video:qwen');
@@ -368,7 +368,7 @@ async function createVideoTask(
export async function createQwenVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { apiKey, baseURL, provider } = options;
const { model, params } = payload;
diff --git a/packages/model-runtime/src/providers/siliconcloud/createVideo.ts b/packages/model-runtime/src/providers/siliconcloud/createVideo.ts
index 0257fb0b1a8..88f2ab48b68 100644
--- a/packages/model-runtime/src/providers/siliconcloud/createVideo.ts
+++ b/packages/model-runtime/src/providers/siliconcloud/createVideo.ts
@@ -1,7 +1,7 @@
import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type { CreateVideoPayload, CreateVideoResult } from '../../types/video';
const log = createDebug('lobe-video:siliconcloud');
@@ -95,7 +95,7 @@ export async function pollSiliconCloudVideoStatus(
export async function createSiliconCloudVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const { prompt, imageUrl, size, seed } = params;
diff --git a/packages/model-runtime/src/providers/volcengine/index.ts b/packages/model-runtime/src/providers/volcengine/index.ts
index 99daade7fc3..87f1224affe 100644
--- a/packages/model-runtime/src/providers/volcengine/index.ts
+++ b/packages/model-runtime/src/providers/volcengine/index.ts
@@ -130,4 +130,5 @@ export const LobeVolcengineAI = createOpenAICompatibleRuntime({
} as any;
},
},
+ videoGenerationCapabilities: { completionModes: ['webhook'] },
});
diff --git a/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts b/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts
index 59bb9ef9b09..ad15e729aa7 100644
--- a/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts
+++ b/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts
@@ -40,18 +40,7 @@ describe('createVolcengineVideo', () => {
const result = await createVolcengineVideo(payload, options);
- expect(result).toEqual({ inferenceId: 'task-abc-123', useWebhook: true });
- });
-
- it('should return useWebhook: true to indicate webhook-based async flow', async () => {
- mockFetch.mockResolvedValue({
- json: () => Promise.resolve({ id: 'task-webhook' }),
- ok: true,
- });
-
- const result = await createVolcengineVideo(payload, options);
-
- expect((result as any).useWebhook).toBe(true);
+ expect(result).toEqual({ inferenceId: 'task-abc-123' });
});
it('should send minimal body with only prompt', async () => {
diff --git a/packages/model-runtime/src/providers/volcengine/video/createVideo.ts b/packages/model-runtime/src/providers/volcengine/video/createVideo.ts
index 338a6788b6b..1404f02e484 100644
--- a/packages/model-runtime/src/providers/volcengine/video/createVideo.ts
+++ b/packages/model-runtime/src/providers/volcengine/video/createVideo.ts
@@ -1,7 +1,7 @@
import createDebug from 'debug';
import type { CreateVideoOptions } from '../../../core/openaiCompatibleFactory';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../../types/video';
+import type { CreateVideoPayload, CreateVideoResult } from '../../../types/video';
const log = createDebug('lobe-video:volcengine');
@@ -12,7 +12,7 @@ const log = createDebug('lobe-video:volcengine');
export async function createVolcengineVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const {
prompt,
@@ -95,5 +95,5 @@ export async function createVolcengineVideo(
throw new Error('Invalid response: missing task id');
}
- return { inferenceId: data.id, useWebhook: true };
+ return { inferenceId: data.id };
}
diff --git a/packages/model-runtime/src/providers/wenxin/createVideo.ts b/packages/model-runtime/src/providers/wenxin/createVideo.ts
index cc5e23f7d51..00b57333e91 100644
--- a/packages/model-runtime/src/providers/wenxin/createVideo.ts
+++ b/packages/model-runtime/src/providers/wenxin/createVideo.ts
@@ -1,7 +1,7 @@
import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type { CreateVideoPayload, CreateVideoResult } from '../../types/video';
const log = createDebug('lobe-video:wenxin');
@@ -89,7 +89,7 @@ export async function pollWenxinVideoStatus(
export async function createWenxinVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const { prompt, imageUrl, aspectRatio, duration, generateAudio, promptExtend, watermark } =
params;
diff --git a/packages/model-runtime/src/providers/xai/createVideo.ts b/packages/model-runtime/src/providers/xai/createVideo.ts
index 9c7f99782c4..f0c64042f51 100644
--- a/packages/model-runtime/src/providers/xai/createVideo.ts
+++ b/packages/model-runtime/src/providers/xai/createVideo.ts
@@ -1,7 +1,7 @@
import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
-import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
+import type { CreateVideoPayload, CreateVideoResult } from '../../types/video';
const log = createDebug('lobe-video:xai');
@@ -86,7 +86,7 @@ export async function pollXAIVideoStatus(
export async function createXAIVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const { prompt, imageUrl, aspectRatio, duration, resolution, size } = params;
diff --git a/packages/model-runtime/src/providers/zhipu/createVideo.ts b/packages/model-runtime/src/providers/zhipu/createVideo.ts
index 9a43a0eae3f..5f86544986c 100644
--- a/packages/model-runtime/src/providers/zhipu/createVideo.ts
+++ b/packages/model-runtime/src/providers/zhipu/createVideo.ts
@@ -3,7 +3,7 @@ import createDebug from 'debug';
import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';
import type {
CreateVideoPayload,
- CreateVideoResponse,
+ CreateVideoResult,
PollVideoStatusResult,
} from '../../types/video';
import { resolveMappedModelId } from '../../utils/modelIdMapping';
@@ -89,7 +89,7 @@ export async function pollZhipuVideoStatus(
export async function createZhipuVideo(
payload: CreateVideoPayload,
options: CreateVideoOptions,
-): Promise<CreateVideoResponse> {
+): Promise<CreateVideoResult> {
const { model, params } = payload;
const requestModel = resolveMappedModelId(model, options);
const {
diff --git a/packages/model-runtime/src/types/video.ts b/packages/model-runtime/src/types/video.ts
index e5b97cf2182..251a0aa6018 100644
--- a/packages/model-runtime/src/types/video.ts
+++ b/packages/model-runtime/src/types/video.ts
@@ -1,3 +1,8 @@
+import type {
+ ModelTokensUsage,
+ VideoGenerationCompletionMode,
+ VideoGenerationRoute,
+} from '@lobechat/types';
import type { RuntimeVideoGenParams } from 'model-bank';
import type { ModelPricingContext } from './pricing';
@@ -12,30 +17,52 @@ export type CreateVideoPayload = {
callbackUrl?: string;
model: string;
params: RuntimeVideoGenParams;
+ previousInteractionId?: string;
};
export interface CreateVideoMethodOptions {
/** Metadata passed to hooks (billing, tracing, etc.) */
metadata?: Record<string, unknown>;
+ /** Deployment preference; the selected runtime resolves it against model capabilities. */
+ preferredCompletionMode?: VideoGenerationCompletionMode;
/** Request-scoped pricing context for model-bank pricing lookups. */
pricingContext?: ModelPricingContext;
+ /**
+ * Route that created the source video of a continuation. Stateful providers such as
+ * Gemini Omni scope interactions to the creating API key, so the edit must reuse it.
+ */
+ route?: VideoPollingRoute;
}
-export type CreateVideoResponse =
- | {
- inferenceId: string;
- /** Provider uses webhook callback instead of polling */
- useWebhook?: boolean;
- }
- | {
- inferenceId: string;
- videoUrl: string;
- };
+export interface CreateVideoResult {
+ inferenceId: string;
+ videoUrl?: string;
+}
+
+export interface CreateVideoResponse extends CreateVideoResult {
+ completionMode: VideoGenerationCompletionMode;
+}
+
+export interface VideoGenerationCapabilities {
+ completionModes: readonly VideoGenerationCompletionMode[];
+}
+
+export interface VideoGenerationUsage {
+ completionTokens: number;
+ /**
+ * Per-modality token breakdown for models billed by input and output modality (e.g. Gemini
+ * Omni). When present, billing prices it with the model's token units instead of pricing
+ * `completionTokens` at a single video rate.
+ */
+ modelUsage?: ModelTokensUsage;
+ totalTokens: number;
+}
export type PollVideoStatusResult =
| {
headers?: Record<string, string>;
status: 'success';
+ usage?: VideoGenerationUsage;
videoUrl: string;
}
| {
@@ -46,19 +73,26 @@ export type PollVideoStatusResult =
status: 'pending';
};
+export type VideoPollingRoute = VideoGenerationRoute;
+
export type HandleCreateVideoWebhookPayload = {
body: unknown;
headers?: Record<string, string>;
+ model?: string;
+ rawBody?: string;
+ url?: string;
};
export type HandleCreateVideoWebhookResult =
- | { status: 'pending' }
+ | { inferenceId?: string; status: 'pending' }
+ | { inferenceId: string; status: 'completed' }
| {
generateAudio?: boolean;
+ headers?: Record<string, string>;
inferenceId: string;
model?: string;
status: 'success';
- usage?: { completionTokens: number; totalTokens: number };
+ usage?: VideoGenerationUsage;
videoUrl: string;
}
| { error: string; inferenceId: string; status: 'error' };
diff --git a/packages/model-runtime/src/utils/videoCompletionMode.test.ts b/packages/model-runtime/src/utils/videoCompletionMode.test.ts
new file mode 100644
index 00000000000..c5e1889f086
--- /dev/null
+++ b/packages/model-runtime/src/utils/videoCompletionMode.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createVideoWithCompletionMode,
+ prepareVideoPayload,
+ resolveVideoCompletionMode,
+} from './videoCompletionMode';
+
+describe('resolveVideoCompletionMode', () => {
+ it('should default dual-mode models to polling', () => {
+ expect(
+ resolveVideoCompletionMode({
+ callbackUrl: 'https://example.com/webhook',
+ capabilities: { completionModes: ['polling', 'webhook'] },
+ }),
+ ).toBe('polling');
+ });
+
+ it('should honor the webhook preference when a callback URL is available', () => {
+ expect(
+ resolveVideoCompletionMode({
+ callbackUrl: 'https://example.com/webhook',
+ capabilities: { completionModes: ['polling', 'webhook'] },
+ preferredCompletionMode: 'webhook',
+ }),
+ ).toBe('webhook');
+ });
+
+ it('should use the only supported mode when it differs from the preference', () => {
+ expect(
+ resolveVideoCompletionMode({
+ callbackUrl: 'https://example.com/webhook',
+ capabilities: { completionModes: ['webhook'] },
+ preferredCompletionMode: 'polling',
+ }),
+ ).toBe('webhook');
+ });
+
+ it('should fall back to polling when webhook has no callback URL', () => {
+ expect(
+ resolveVideoCompletionMode({
+ capabilities: { completionModes: ['polling', 'webhook'] },
+ preferredCompletionMode: 'webhook',
+ }),
+ ).toBe('polling');
+ });
+
+ it('should reject webhook-only runtimes without a callback URL', () => {
+ expect(() =>
+ resolveVideoCompletionMode({
+ capabilities: { completionModes: ['webhook'] },
+ }),
+ ).toThrow('Video generation requires a webhook callback URL');
+ });
+});
+
+describe('prepareVideoPayload', () => {
+ const payload = {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'video-model',
+ params: { prompt: 'A cat' },
+ };
+
+ it('should remove the callback URL from polling requests', () => {
+ expect(prepareVideoPayload(payload, 'polling')).toEqual({
+ model: 'video-model',
+ params: { prompt: 'A cat' },
+ });
+ });
+
+ it('should preserve the callback URL for webhook requests', () => {
+ expect(prepareVideoPayload(payload, 'webhook')).toBe(payload);
+ });
+});
+
+describe('createVideoWithCompletionMode', () => {
+ it('should resolve and execute a single completion mode for a provider runtime', async () => {
+ const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-1' });
+ const runtime = {
+ createVideo,
+ getVideoGenerationCapabilities: () => ({
+ completionModes: ['polling', 'webhook'] as const,
+ }),
+ };
+
+ await expect(
+ createVideoWithCompletionMode(
+ runtime,
+ {
+ callbackUrl: 'https://example.com/webhook',
+ model: 'video-model',
+ params: { prompt: 'A cat' },
+ },
+ { preferredCompletionMode: 'webhook' },
+ ),
+ ).resolves.toEqual({
+ completionMode: 'webhook',
+ inferenceId: 'video-1',
+ });
+ expect(createVideo).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/model-runtime/src/utils/videoCompletionMode.ts b/packages/model-runtime/src/utils/videoCompletionMode.ts
new file mode 100644
index 00000000000..51397bc923d
--- /dev/null
+++ b/packages/model-runtime/src/utils/videoCompletionMode.ts
@@ -0,0 +1,75 @@
+import type { VideoGenerationCompletionMode } from '@lobechat/types';
+
+import type { LobeRuntimeAI } from '../core/BaseAI';
+import type {
+ CreateVideoMethodOptions,
+ CreateVideoPayload,
+ CreateVideoResponse,
+ VideoGenerationCapabilities,
+} from '../types/video';
+
+interface ResolveVideoCompletionModeOptions {
+ callbackUrl?: string;
+ capabilities: VideoGenerationCapabilities;
+ preferredCompletionMode?: VideoGenerationCompletionMode;
+}
+
+/**
+ * Resolve exactly one completion mode before the provider request is submitted.
+ *
+ * The deployment preference is best-effort: runtimes may fall back to their only supported
+ * mode, while webhook mode additionally requires a callback URL for the current request.
+ */
+export const resolveVideoCompletionMode = ({
+ capabilities,
+ callbackUrl,
+ preferredCompletionMode = 'polling',
+}: ResolveVideoCompletionModeOptions): VideoGenerationCompletionMode => {
+ const supportsPolling = capabilities.completionModes.includes('polling');
+ const supportsWebhook = capabilities.completionModes.includes('webhook');
+
+ if (preferredCompletionMode === 'webhook' && supportsWebhook && callbackUrl) return 'webhook';
+ if (preferredCompletionMode === 'polling' && supportsPolling) return 'polling';
+
+ if (supportsPolling) return 'polling';
+ if (supportsWebhook && callbackUrl) return 'webhook';
+
+ throw new Error(
+ supportsWebhook
+ ? 'Video generation requires a webhook callback URL'
+ : 'Video generation runtime does not declare a supported completion mode',
+ );
+};
+
+export const prepareVideoPayload = (
+ payload: CreateVideoPayload,
+ completionMode: VideoGenerationCompletionMode,
+): CreateVideoPayload => {
+ if (completionMode === 'webhook') return payload;
+
+ const { callbackUrl: _, ...pollingPayload } = payload;
+ return pollingPayload;
+};
+
+export const createVideoWithCompletionMode = async (
+ runtime: LobeRuntimeAI,
+ payload: CreateVideoPayload,
+ options?: CreateVideoMethodOptions,
+): Promise<CreateVideoResponse> => {
+ if (!runtime.createVideo) throw new Error('Video generation is not supported by this runtime');
+ if (runtime.orchestratesVideoGenerationCompletion) {
+ return runtime.createVideo(payload, options) as Promise<CreateVideoResponse>;
+ }
+ if (!runtime.getVideoGenerationCapabilities) {
+ throw new Error('Video generation runtime does not declare completion capabilities');
+ }
+
+ const completionMode = resolveVideoCompletionMode({
+ callbackUrl: payload.callbackUrl,
+ capabilities: runtime.getVideoGenerationCapabilities(payload.model),
+ preferredCompletionMode: options?.preferredCompletionMode,
+ });
+ const result = await runtime.createVideo(prepareVideoPayload(payload, completionMode), options);
+
+ return { ...result, completionMode };
+};
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index 90e6dbae706..7122b11fb88 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -201,8 +201,15 @@ export interface HourlyUserMemoryExtractionMetadata {
startedAt: string;
}
+export type VideoGenerationCompletionMode = 'polling' | 'webhook';
+
export interface VideoGenerationTaskMetadata {
- precharge?: Record<string, unknown>;
+ completionClaimedAt?: string;
+ completionEventId?: string;
+ completionMode?: VideoGenerationCompletionMode;
+ precharge?: unknown;
+ previousGenerationId?: string;
+ route?: VideoGenerationRoute;
/**
* Origin of the submitting request, carried across the async boundary so the
* completion charge (webhook / polling) can keep the spend attributed.
@@ -214,3 +221,9 @@ export interface VideoGenerationTaskMetadata {
spendOrigin?: SpendOrigin;
webhookToken?: string;
}
+
+export interface VideoGenerationRoute {
+ apiType: string;
+ channelId?: string;
+ routerId?: string;
+}
diff --git a/packages/types/src/generation/index.ts b/packages/types/src/generation/index.ts
index 69fac8aca64..3f4dd8c2c68 100644
--- a/packages/types/src/generation/index.ts
+++ b/packages/types/src/generation/index.ts
@@ -48,7 +48,11 @@ export interface VideoGenerationAsset extends BaseGenerationAsset {
coverUrl?: string;
duration?: number;
height?: number;
+ /** Provider interaction id used to continue stateful video editing. */
+ interactionId?: string;
originalUrl?: string;
+ /** Previous generated version used as the editing source. */
+ previousGenerationId?: string;
thumbnailUrl?: string;
url?: string;
width?: number;
@@ -63,6 +67,7 @@ export interface GenerationConfig {
height?: number;
imageUrl?: string | null;
imageUrls?: string[];
+ previousGenerationId?: string;
prompt: string;
resolution?: string;
size?: string;
@@ -84,6 +89,11 @@ export interface Generation {
asyncTaskId: string | null;
createdAt: Date;
id: string;
+ /**
+ * Source generation this one edits, read from the async task metadata so the
+ * version link is available while the edit is still generating.
+ */
+ previousGenerationId?: string;
seed?: number | null;
task: GenerationAsyncTask;
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 5428f908df1..ebabf2761f2 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -97,6 +97,10 @@ export interface ModelTokensUsage {
// Output tokens breakdown
outputTextTokens?: number;
+ /**
+ * Generated video tokens, billed through the `videoGeneration` pricing unit.
+ */
+ outputVideoTokens?: number;
rejectedPredictionTokens?: number;
// Total tokens
@@ -127,6 +131,7 @@ export const ModelUsageSchema = z.object({
outputImageTokens: z.number().optional(),
outputAudioTokens: z.number().optional(),
outputReasoningTokens: z.number().optional(),
+ outputVideoTokens: z.number().optional(),
// Prediction tokens
acceptedPredictionTokens: z.number().optional(),
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx
index fc7f1817912..a87e1d60a97 100644
--- a/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx
@@ -1,11 +1,12 @@
'use client';
import { ActionIconGroup, Block, Flexbox, Markdown } from '@lobehub/ui';
-import { Tag, Text, toast } from '@lobehub/ui/base-ui';
+import { Button, Tag, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
import dayjs from 'dayjs';
-import { CopyIcon, RotateCcwSquareIcon, Trash2 } from 'lucide-react';
+import { CopyIcon, RotateCcwSquareIcon, SquarePenIcon, Trash2, XIcon } from 'lucide-react';
import { type RuntimeVideoGenParamsKeys, type RuntimeVideoGenParamsValue } from 'model-bank';
+import { supportsConversationalVideoEdit } from 'model-bank/standardParameters';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,14 +16,17 @@ import { ModelIcon } from '@/components/LobeIcons';
import { GenerationInvalidAPIKey } from '@/routes/(main)/(create)/features/GenerationInput';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useVideoStore } from '@/store/video';
+import { createVideoSelectors } from '@/store/video/selectors';
import { AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';
-import type { GenerationBatch } from '@/types/generation';
+import type { GenerationBatch, VideoGenerationAsset } from '@/types/generation';
import { downloadFile } from '@/utils/client/downloadFile';
+import EditSourceLink from './EditSourceLink';
import VideoErrorItem from './VideoErrorItem';
import VideoLoadingItem from './VideoLoadingItem';
import VideoReferenceFrames from './VideoReferenceFrames';
import VideoSuccessItem from './VideoSuccessItem';
+import { type VideoVersionNode } from './videoVersion';
const styles = createStaticStyles(({ css, cssVar, cx }) => ({
batchActions: cx(
@@ -43,266 +47,342 @@ const styles = createStaticStyles(({ css, cssVar, cx }) => ({
interface VideoGenerationBatchItemProps {
batch: GenerationBatch;
+ /** Topic-wide version index, built once by the feed rather than per row. */
+ versionMap: Map<string, VideoVersionNode>;
}
-export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(({ batch }) => {
- const { t } = useTranslation(['video', 'image']);
- const useCheckGenerationStatus = useVideoStore((s) => s.useCheckGenerationStatus);
- const removeGeneration = useVideoStore((s) => s.removeGeneration);
- const removeGenerationBatch = useVideoStore((s) => s.removeGenerationBatch);
- const setModelAndProviderOnSelect = useVideoStore((s) => s.setModelAndProviderOnSelect);
- const setParamOnInput = useVideoStore((s) => s.setParamOnInput);
- const activeTopicId = useVideoStore((s) => s.activeGenerationTopicId);
- const activeWorkspaceId = useActiveWorkspaceId();
- const { shouldRenderBusinessBatchItem, businessBatchItem } =
- useRenderBusinessVideoBatchItem(batch);
-
- const enabledVideoModelList = useAiInfraStore(aiProviderSelectors.enabledVideoModelList);
- // Resolve the model's display name from the enabled model catalog, falling back
- // to the raw model id when the model is not found (e.g. removed/renamed models).
- const modelDisplayName = useMemo(() => {
- const provider = enabledVideoModelList.find((p) => p.id === batch.provider);
- const model = provider?.children.find((m) => m.id === batch.model);
- return model?.displayName || batch.model;
- }, [enabledVideoModelList, batch.provider, batch.model]);
-
- const creator = batch.creator;
- const showCreator = Boolean(activeWorkspaceId && creator?.id);
- const creatorName = creator?.fullName || creator?.username || '';
-
- 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?.id) return;
-
- try {
- await removeGeneration(generation.id);
- } catch (error) {
- console.error('Failed to delete generation:', error);
- }
- }, [removeGeneration, generation?.id]);
-
- const handleCopyPrompt = useCallback(async () => {
- try {
- await navigator.clipboard.writeText(batch.prompt);
- toast.success(t('generation.actions.promptCopied', { ns: 'image' }));
- } catch (error) {
- console.error('Failed to copy prompt:', error);
- toast.error(t('generation.actions.promptCopyFailed', { ns: 'image' }));
- }
- }, [batch.prompt, t]);
+export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(
+ ({ batch, versionMap }) => {
+ const { t } = useTranslation(['video', 'image']);
+ const useCheckGenerationStatus = useVideoStore((s) => s.useCheckGenerationStatus);
+ const removeGeneration = useVideoStore((s) => s.removeGeneration);
+ const removeGenerationBatch = useVideoStore((s) => s.removeGenerationBatch);
+ const setModelAndProviderOnSelect = useVideoStore((s) => s.setModelAndProviderOnSelect);
+ const setParamOnInput = useVideoStore((s) => s.setParamOnInput);
+ const startEditingVideo = useVideoStore((s) => s.startEditingVideo);
+ const cancelEditingVideo = useVideoStore((s) => s.cancelEditingVideo);
+ const editingGenerationId = useVideoStore(createVideoSelectors.editingGenerationId);
+ const activeTopicId = useVideoStore((s) => s.activeGenerationTopicId);
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const { shouldRenderBusinessBatchItem, businessBatchItem } =
+ useRenderBusinessVideoBatchItem(batch);
+
+ const enabledVideoModelList = useAiInfraStore(aiProviderSelectors.enabledVideoModelList);
+ // Resolve the model's display name from the enabled model catalog, falling back
+ // to the raw model id when the model is not found (e.g. removed/renamed models).
+ const modelDisplayName = useMemo(() => {
+ const provider = enabledVideoModelList.find((p) => p.id === batch.provider);
+ const model = provider?.children.find((m) => m.id === batch.model);
+ return model?.displayName || batch.model;
+ }, [enabledVideoModelList, batch.provider, batch.model]);
+
+ const creator = batch.creator;
+ const showCreator = Boolean(activeWorkspaceId && creator?.id);
+ const creatorName = creator?.fullName || creator?.username || '';
+
+ const time = useMemo(() => {
+ return dayjs(batch.createdAt).format('YYYY-MM-DD HH:mm:ss');
+ }, [batch.createdAt]);
+
+ const generation = batch.generations[0];
+
+ const versionNode = generation ? versionMap.get(generation.id) : undefined;
+ const editSource = versionNode?.previousGenerationId
+ ? versionMap.get(versionNode.previousGenerationId)
+ : undefined;
+ // Only label versions once a video is part of an edit chain, so plain generations stay clean.
+ const showVersion = Boolean(versionNode && (versionNode.version > 1 || versionNode.hasEdits));
+
+ const isEditingSource = Boolean(generation && editingGenerationId === generation.id);
+ const canEdit =
+ supportsConversationalVideoEdit(batch.model) &&
+ generation?.task.status === AsyncTaskStatus.Success &&
+ Boolean((generation.asset as VideoGenerationAsset | null | undefined)?.interactionId);
+
+ const isFinalized =
+ generation?.task.status === AsyncTaskStatus.Success ||
+ generation?.task.status === AsyncTaskStatus.Error;
+
+ useCheckGenerationStatus(
+ generation?.id ?? '',
+ generation?.task.id ?? '',
+ activeTopicId!,
+ !isFinalized,
+ );
- const handleReuseSettings = useCallback(() => {
- setModelAndProviderOnSelect(batch.model, batch.provider);
+ const handleDelete = useCallback(async () => {
+ if (!generation?.id) return;
- if (!batch.config) return;
+ try {
+ await removeGeneration(generation.id);
+ } catch (error) {
+ console.error('Failed to delete generation:', error);
+ }
+ }, [removeGeneration, generation?.id]);
+
+ const handleCopyPrompt = useCallback(async () => {
+ try {
+ await navigator.clipboard.writeText(batch.prompt);
+ toast.success(t('generation.actions.promptCopied', { ns: 'image' }));
+ } catch (error) {
+ console.error('Failed to copy prompt:', error);
+ toast.error(t('generation.actions.promptCopyFailed', { ns: 'image' }));
+ }
+ }, [batch.prompt, t]);
- for (const [paramName, value] of Object.entries(batch.config)) {
- if (value === undefined) continue;
+ const handleReuseSettings = useCallback(() => {
+ setModelAndProviderOnSelect(batch.model, batch.provider);
- setParamOnInput(paramName as RuntimeVideoGenParamsKeys, value as RuntimeVideoGenParamsValue);
- }
- }, [batch.config, batch.model, batch.provider, setModelAndProviderOnSelect, setParamOnInput]);
+ if (!batch.config) return;
- const handleDeleteBatch = useCallback(async () => {
- if (!activeTopicId) return;
+ for (const [paramName, value] of Object.entries(batch.config)) {
+ if (value === undefined) continue;
- try {
- await removeGenerationBatch(batch.id, activeTopicId);
- } catch (error) {
- console.error('Failed to delete batch:', error);
- }
- }, [activeTopicId, batch.id, removeGenerationBatch]);
+ setParamOnInput(
+ paramName as RuntimeVideoGenParamsKeys,
+ value as RuntimeVideoGenParamsValue,
+ );
+ }
+ }, [batch.config, batch.model, batch.provider, setModelAndProviderOnSelect, setParamOnInput]);
- const handleDownload = useCallback(async () => {
- if (!generation?.asset?.url) return;
+ const handleEdit = useCallback(() => {
+ if (!generation?.asset || !('interactionId' in generation.asset)) return;
+ if (!generation.asset.interactionId) 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`;
+ if (editingGenerationId === generation.id) {
+ cancelEditingVideo();
+ return;
+ }
- 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);
- toast.success(t('generation.actions.errorCopied'));
- } catch (error) {
- console.error('Failed to copy error message:', error);
- toast.error(t('generation.actions.errorCopyFailed'));
- }
- }, [generation?.task.error, 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]);
+ startEditingVideo({
+ generationId: generation.id,
+ model: batch.model,
+ provider: batch.provider,
+ sourceParameters: batch.config,
+ });
+ }, [
+ batch.config,
+ batch.model,
+ batch.provider,
+ cancelEditingVideo,
+ editingGenerationId,
+ generation,
+ startEditingVideo,
+ ]);
+
+ const handleDeleteBatch = useCallback(async () => {
+ if (!activeTopicId) return;
+
+ try {
+ await removeGenerationBatch(batch.id, activeTopicId);
+ } catch (error) {
+ console.error('Failed to delete batch:', error);
+ }
+ }, [activeTopicId, batch.id, removeGenerationBatch]);
- if (!generation) {
- return null;
- }
+ const handleDownload = useCallback(async () => {
+ if (!generation?.asset?.url) return;
- if (shouldRenderBusinessBatchItem) {
- return businessBatchItem;
- }
+ 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);
+ toast.success(t('generation.actions.errorCopied'));
+ } catch (error) {
+ console.error('Failed to copy error message:', error);
+ toast.error(t('generation.actions.errorCopyFailed'));
+ }
+ }, [generation?.task.error, 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]);
- const isInvalidApiKey = generation.task.error?.name === AsyncTaskErrorType.InvalidProviderAPIKey;
+ if (!generation) {
+ return null;
+ }
- if (isInvalidApiKey) {
- return (
- <GenerationInvalidAPIKey
- provider={batch.provider}
- onNavigate={() => {
- if (!activeTopicId) return;
- removeGenerationBatch(batch.id, activeTopicId);
- }}
- />
- );
- }
+ if (shouldRenderBusinessBatchItem) {
+ return businessBatchItem;
+ }
+
+ const isInvalidApiKey =
+ generation.task.error?.name === AsyncTaskErrorType.InvalidProviderAPIKey;
- const renderContent = () => {
- if (generation.task.status === AsyncTaskStatus.Success && generation.asset?.url) {
+ if (isInvalidApiKey) {
return (
- <VideoSuccessItem
- generation={generation}
- onDelete={handleDelete}
- onDownload={handleDownload}
+ <GenerationInvalidAPIKey
+ provider={batch.provider}
+ onNavigate={() => {
+ if (!activeTopicId) return;
+ removeGenerationBatch(batch.id, activeTopicId);
+ }}
/>
);
}
- if (generation.task.status === AsyncTaskStatus.Error) {
+ const renderContent = () => {
+ if (generation.task.status === AsyncTaskStatus.Success && generation.asset?.url) {
+ return (
+ <VideoSuccessItem
+ generation={generation}
+ isEditing={isEditingSource}
+ onDelete={handleDelete}
+ onDownload={handleDownload}
+ />
+ );
+ }
+
+ if (generation.task.status === AsyncTaskStatus.Error) {
+ return (
+ <VideoErrorItem
+ aspectRatio={displayAspectRatio}
+ generation={generation}
+ onCopyError={handleCopyError}
+ onDelete={handleDelete}
+ />
+ );
+ }
+
return (
- <VideoErrorItem
+ <VideoLoadingItem
aspectRatio={displayAspectRatio}
+ avgLatencyMs={batch.avgLatencyMs}
generation={generation}
- onCopyError={handleCopyError}
- onDelete={handleDelete}
/>
);
- }
+ };
+
+ const hasReferenceFrames =
+ batch.config?.imageUrl ||
+ (batch.config?.imageUrls && batch.config.imageUrls.length > 0) ||
+ batch.config?.endImageUrl;
return (
- <VideoLoadingItem
- aspectRatio={displayAspectRatio}
- avgLatencyMs={batch.avgLatencyMs}
- generation={generation}
- />
- );
- };
-
- const hasReferenceFrames =
- batch.config?.imageUrl ||
- (batch.config?.imageUrls && batch.config.imageUrls.length > 0) ||
- batch.config?.endImageUrl;
-
- return (
- <Block className={styles.container} gap={8} variant={'borderless'}>
- <Flexbox horizontal align={'flex-start'} gap={16}>
- {hasReferenceFrames && (
- <VideoReferenceFrames
- endImageUrl={batch.config?.endImageUrl}
- imageUrl={batch.config?.imageUrl}
- imageUrls={batch.config?.imageUrls}
+ <Block
+ className={styles.container}
+ data-video-generation-id={generation.id}
+ gap={8}
+ variant={'borderless'}
+ >
+ {versionNode?.previousGenerationId && (
+ <EditSourceLink
+ source={editSource}
+ sourceVersion={Math.max(versionNode.version - 1, 1)}
/>
)}
- <Markdown variant={'chat'}>{batch.prompt}</Markdown>
- </Flexbox>
- {renderContent()}
- <Flexbox
- horizontal
- align={'center'}
- gap={4}
- justify={'space-between'}
- style={{ opacity: 0.66 }}
- >
- <Flexbox horizontal align={'center'} gap={4}>
- <Tag icon={<ModelIcon model={batch.model} />} variant={'borderless'}>
- {modelDisplayName}
- </Tag>
- {batch.config?.resolution && <Tag variant={'borderless'}>{batch.config.resolution}</Tag>}
- </Flexbox>
- <Flexbox horizontal align={'center'} gap={6}>
- {showCreator && (
- <>
- <Text fontSize={12} type={'secondary'}>
- {t('generation.metadata.by', { name: creatorName, ns: 'image' })}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- ·
- </Text>
- </>
+ <Flexbox horizontal align={'flex-start'} gap={16}>
+ {hasReferenceFrames && (
+ <VideoReferenceFrames
+ endImageUrl={batch.config?.endImageUrl}
+ imageUrl={batch.config?.imageUrl}
+ imageUrls={batch.config?.imageUrls}
+ />
)}
- <Text as={'time'} fontSize={12} type={'secondary'}>
- {t('generation.metadata.createdAt', { ns: 'image', time })}
- </Text>
+ <Markdown variant={'chat'}>{batch.prompt}</Markdown>
</Flexbox>
- </Flexbox>
- <Flexbox horizontal align={'center'} className={styles.batchActions}>
- <ActionIconGroup
- items={[
- {
- icon: RotateCcwSquareIcon,
- key: 'reuseSettings',
- label: t('generation.actions.reuseSettings', { ns: 'image' }),
- onClick: handleReuseSettings,
- },
- {
- icon: CopyIcon,
- key: 'copyPrompt',
- label: t('generation.actions.copyPrompt', { ns: 'image' }),
- onClick: handleCopyPrompt,
- },
- {
- danger: true,
- icon: Trash2,
- key: 'deleteBatch',
- label: t('generation.actions.deleteBatch', { ns: 'image' }),
- onClick: handleDeleteBatch,
- },
- ]}
- />
- </Flexbox>
- </Block>
- );
-});
+ {renderContent()}
+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Flexbox horizontal align={'center'} gap={4} style={{ opacity: 0.66 }}>
+ <Tag icon={<ModelIcon model={batch.model} />} variant={'borderless'}>
+ {modelDisplayName}
+ </Tag>
+ {showVersion && versionNode && (
+ <Tag variant={'borderless'}>
+ {t('generation.version.label', { version: String(versionNode.version) })}
+ </Tag>
+ )}
+ {batch.config?.resolution && (
+ <Tag variant={'borderless'}>{batch.config.resolution}</Tag>
+ )}
+ </Flexbox>
+ {canEdit && (
+ <Button
+ icon={isEditingSource ? XIcon : SquarePenIcon}
+ size={'small'}
+ type={isEditingSource ? 'primary' : 'default'}
+ onClick={handleEdit}
+ >
+ {isEditingSource
+ ? t('generation.actions.cancelEdit')
+ : t('generation.actions.edit')}
+ </Button>
+ )}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={6} style={{ opacity: 0.66 }}>
+ {showCreator && (
+ <>
+ <Text fontSize={12} type={'secondary'}>
+ {t('generation.metadata.by', { name: creatorName, ns: 'image' })}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ ·
+ </Text>
+ </>
+ )}
+ <Text as={'time'} fontSize={12} type={'secondary'}>
+ {t('generation.metadata.createdAt', { ns: 'image', time })}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} className={styles.batchActions}>
+ <ActionIconGroup
+ items={[
+ {
+ icon: RotateCcwSquareIcon,
+ key: 'reuseSettings',
+ label: t('generation.actions.reuseSettings', { ns: 'image' }),
+ onClick: handleReuseSettings,
+ },
+ {
+ icon: CopyIcon,
+ key: 'copyPrompt',
+ label: t('generation.actions.copyPrompt', { ns: 'image' }),
+ onClick: handleCopyPrompt,
+ },
+ {
+ danger: true,
+ icon: Trash2,
+ key: 'deleteBatch',
+ label: t('generation.actions.deleteBatch', { ns: 'image' }),
+ onClick: handleDeleteBatch,
+ },
+ ]}
+ />
+ </Flexbox>
+ </Block>
+ );
+ },
+);
VideoGenerationBatchItem.displayName = 'VideoGenerationBatchItem';
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/EditSourceLink.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/EditSourceLink.tsx
new file mode 100644
index 00000000000..8985d379158
--- /dev/null
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/EditSourceLink.tsx
@@ -0,0 +1,112 @@
+'use client';
+
+import { Flexbox, Image } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { CornerDownRightIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { VideoGenerationAsset } from '@/types/generation';
+
+import { revealVideoGeneration, type VideoVersionNode } from './videoVersion';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ link: css`
+ cursor: pointer;
+
+ width: fit-content;
+ max-width: 100%;
+ padding-block: 2px;
+ padding-inline: 6px 10px;
+ border-radius: 999px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillQuaternary};
+
+ transition: background 0.15s ${cssVar.motionEaseInOut};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ thumb: css`
+ overflow: hidden;
+ flex: none;
+
+ width: 32px;
+ height: 20px;
+ border-radius: 4px;
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+}));
+
+interface EditSourceLinkProps {
+ source?: VideoVersionNode;
+ /** Version number of the source; used when the source card is no longer loaded. */
+ sourceVersion: number;
+}
+
+/**
+ * Shows which version an edit was made from; clicking it jumps back to that card.
+ */
+const EditSourceLink = memo<EditSourceLinkProps>(({ source, sourceVersion }) => {
+ const { t } = useTranslation('video');
+
+ if (!source) {
+ return (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <CornerDownRightIcon size={14} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('generation.version.sourceDeleted')}
+ </Text>
+ </Flexbox>
+ );
+ }
+
+ const asset = source.generation.asset as VideoGenerationAsset | null | undefined;
+ const cover = asset?.coverUrl || asset?.thumbnailUrl;
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.link}
+ gap={6}
+ role={'button'}
+ // `role="button"` alone leaves it unreachable: it has to take focus and
+ // answer Enter / Space the way a real button does.
+ tabIndex={0}
+ title={t('generation.version.locateSource')}
+ onClick={() => revealVideoGeneration(source.generation.id)}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ revealVideoGeneration(source.generation.id);
+ }}
+ >
+ <CornerDownRightIcon size={14} style={{ flex: 'none' }} />
+ {cover && (
+ <div className={styles.thumb}>
+ <Image
+ alt=""
+ preview={false}
+ src={cover}
+ style={{ height: '100%', objectFit: 'cover', width: '100%' }}
+ />
+ </div>
+ )}
+ <Text ellipsis fontSize={12} style={{ color: 'inherit' }}>
+ {t('generation.version.editedFrom', { version: String(sourceVersion) })}
+ {source.batch.prompt ? ` · ${source.batch.prompt}` : ''}
+ </Text>
+ </Flexbox>
+ );
+});
+
+EditSourceLink.displayName = 'EditSourceLink';
+
+export default EditSourceLink;
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx
index bd352a424f9..71677347c5a 100644
--- a/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx
@@ -1,35 +1,81 @@
'use client';
import { Block } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { SquarePenIcon } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { ActionButtons } from '@/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ActionButtons';
import { styles } from '@/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/styles';
import type { Generation, VideoGenerationAsset } from '@/types/generation';
+const editingStyles = createStaticStyles(({ css, cssVar }) => ({
+ badge: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 10;
+ inset-block-start: 8px;
+ inset-inline-start: 8px;
+
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 8px;
+ border-radius: 999px;
+
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorBgContainer};
+
+ background: ${cssVar.colorText};
+ `,
+ editing: css`
+ box-shadow: 0 0 0 2px ${cssVar.colorPrimary};
+ `,
+}));
+
interface VideoSuccessItemProps {
generation: Generation;
+ /** Marks the video currently loaded into the prompt input as the edit source. */
+ isEditing?: boolean;
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 showDownload onDelete={onDelete} onDownload={onDownload} />
- </Block>
- );
-});
+const VideoSuccessItem = memo<VideoSuccessItemProps>(
+ ({ generation, isEditing, onDelete, onDownload }) => {
+ const { t } = useTranslation('video');
+ const asset = generation.asset as VideoGenerationAsset;
+
+ return (
+ <Block
+ className={cx(styles.imageContainer, isEditing && editingStyles.editing)}
+ 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%' }}
+ />
+ {isEditing && (
+ <div className={editingStyles.badge}>
+ <SquarePenIcon size={12} />
+ {t('generation.editing.badge')}
+ </div>
+ )}
+ <ActionButtons showDownload onDelete={onDelete} onDownload={onDownload} />
+ </Block>
+ );
+ },
+);
VideoSuccessItem.displayName = 'VideoSuccessItem';
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/index.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/index.tsx
index c26529d532d..03d8f2291a2 100644
--- a/src/routes/(main)/(create)/video/features/GenerationFeed/index.tsx
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/index.tsx
@@ -7,14 +7,18 @@ import { useVideoStore } from '@/store/video';
import { generationBatchSelectors } from '@/store/video/selectors';
import { VideoGenerationBatchItem } from './BatchItem';
+import { useVideoVersionMap } from './videoVersion';
const VideoGenerationFeed = memo(() => {
const currentGenerationBatches = useVideoStore(generationBatchSelectors.currentGenerationBatches);
+ const versionMap = useVideoVersionMap();
return (
<GenerationFeed
batches={currentGenerationBatches ?? []}
- renderBatchItem={(batch) => <VideoGenerationBatchItem batch={batch} key={batch.id} />}
+ renderBatchItem={(batch) => (
+ <VideoGenerationBatchItem batch={batch} key={batch.id} versionMap={versionMap} />
+ )}
/>
);
});
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/videoVersion.test.ts b/src/routes/(main)/(create)/video/features/GenerationFeed/videoVersion.test.ts
new file mode 100644
index 00000000000..0f9aed1a11b
--- /dev/null
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/videoVersion.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Generation, GenerationBatch } from '@/types/generation';
+
+import { buildVideoVersionMap } from './videoVersion';
+
+const makeBatch = (
+ id: string,
+ generation: Partial<Generation> & { id: string },
+): GenerationBatch => ({
+ createdAt: new Date(),
+ generations: [
+ {
+ asyncTaskId: null,
+ createdAt: new Date(),
+ task: { id: '', status: 'success' as any },
+ ...generation,
+ },
+ ],
+ id,
+ model: 'gemini-omni-1.1-flash',
+ prompt: id,
+ provider: 'google',
+});
+
+describe('buildVideoVersionMap', () => {
+ it('numbers an edit chain from the original generation', () => {
+ const map = buildVideoVersionMap([
+ makeBatch('b1', { id: 'g1' }),
+ makeBatch('b2', { id: 'g2', previousGenerationId: 'g1' }),
+ makeBatch('b3', {
+ asset: { previousGenerationId: 'g2', type: 'video' },
+ id: 'g3',
+ }),
+ ]);
+
+ expect(map.get('g1')).toMatchObject({ previousGenerationId: undefined, version: 1 });
+ expect(map.get('g2')).toMatchObject({ previousGenerationId: 'g1', version: 2 });
+ expect(map.get('g3')).toMatchObject({ previousGenerationId: 'g2', version: 3 });
+ expect(map.get('g1')?.hasEdits).toBe(true);
+ expect(map.get('g2')?.hasEdits).toBe(true);
+ expect(map.get('g3')?.hasEdits).toBe(false);
+ });
+
+ it('keeps counting when the source generation is no longer loaded', () => {
+ const map = buildVideoVersionMap([
+ makeBatch('b2', { id: 'g2', previousGenerationId: 'deleted' }),
+ ]);
+
+ expect(map.get('g2')).toMatchObject({ previousGenerationId: 'deleted', version: 2 });
+ });
+
+ it('stops on a malformed cycle', () => {
+ const map = buildVideoVersionMap([
+ makeBatch('b1', { id: 'g1', previousGenerationId: 'g2' }),
+ makeBatch('b2', { id: 'g2', previousGenerationId: 'g1' }),
+ ]);
+
+ expect(map.get('g1')?.version).toBeLessThanOrEqual(50);
+ });
+});
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/videoVersion.ts b/src/routes/(main)/(create)/video/features/GenerationFeed/videoVersion.ts
new file mode 100644
index 00000000000..8c9427588fa
--- /dev/null
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/videoVersion.ts
@@ -0,0 +1,87 @@
+import { cssVar } from 'antd-style';
+import { useMemo } from 'react';
+
+import { useVideoStore } from '@/store/video';
+import { generationBatchSelectors } from '@/store/video/selectors';
+import type { Generation, GenerationBatch, VideoGenerationAsset } from '@/types/generation';
+
+/** Guards against malformed cycles when walking the edit chain. */
+const MAX_VERSION_DEPTH = 50;
+
+export interface VideoVersionNode {
+ batch: GenerationBatch;
+ generation: Generation;
+ /** Whether another generation in the topic was edited from this one. */
+ hasEdits: boolean;
+ /** Source generation id; set only when this generation is an edit. */
+ previousGenerationId?: string;
+ /** 1 for an original generation, +1 for every edit on top of it. */
+ version: number;
+}
+
+export const getPreviousGenerationId = (generation: Generation): string | undefined =>
+ generation.previousGenerationId ??
+ (generation.asset as VideoGenerationAsset | null | undefined)?.previousGenerationId;
+
+/**
+ * Indexes the topic's video generations and numbers each edit chain (V1, V2, …).
+ * When a source was deleted, the edit keeps counting from the last known version.
+ */
+export const buildVideoVersionMap = (batches: GenerationBatch[]) => {
+ const byId = new Map<string, { batch: GenerationBatch; generation: Generation }>();
+
+ for (const batch of batches) {
+ for (const generation of batch.generations) byId.set(generation.id, { batch, generation });
+ }
+
+ const versions = new Map<string, VideoVersionNode>();
+
+ for (const [id, entry] of byId) {
+ let version = 1;
+ let cursor = getPreviousGenerationId(entry.generation);
+
+ while (cursor && version < MAX_VERSION_DEPTH) {
+ version += 1;
+ const source = byId.get(cursor);
+ cursor = source ? getPreviousGenerationId(source.generation) : undefined;
+ }
+
+ versions.set(id, {
+ ...entry,
+ hasEdits: false,
+ previousGenerationId: getPreviousGenerationId(entry.generation),
+ version,
+ });
+ }
+
+ for (const node of versions.values()) {
+ const source = node.previousGenerationId ? versions.get(node.previousGenerationId) : undefined;
+ if (source) source.hasEdits = true;
+ }
+
+ return versions;
+};
+
+export const useVideoVersionMap = () => {
+ const batches = useVideoStore(generationBatchSelectors.currentGenerationBatches);
+
+ return useMemo(() => buildVideoVersionMap(batches ?? []), [batches]);
+};
+
+const generationSelector = (generationId: string) =>
+ `[data-video-generation-id="${CSS.escape(generationId)}"]`;
+
+/**
+ * Brings a generation card into view and briefly outlines it, so users can find
+ * the version an edit came from in a long feed.
+ */
+export const revealVideoGeneration = (generationId: string) => {
+ const element = document.querySelector<HTMLElement>(generationSelector(generationId));
+ if (!element) return;
+
+ element.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ element.animate(
+ [{ boxShadow: `0 0 0 2px ${cssVar.colorPrimary}` }, { boxShadow: '0 0 0 2px transparent' }],
+ { delay: 300, duration: 1600, easing: 'ease-out' },
+ );
+};
diff --git a/src/routes/(main)/(create)/video/features/PromptInput/EditingVideoHeader.tsx b/src/routes/(main)/(create)/video/features/PromptInput/EditingVideoHeader.tsx
new file mode 100644
index 00000000000..04c3763db08
--- /dev/null
+++ b/src/routes/(main)/(create)/video/features/PromptInput/EditingVideoHeader.tsx
@@ -0,0 +1,125 @@
+'use client';
+
+import { Flexbox, Image } from '@lobehub/ui';
+import { ActionIcon, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { LocateFixedIcon, SquarePenIcon, VideoIcon, XIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ margin-block-end: 4px;
+ padding-block: 8px;
+ padding-inline: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ locate: css`
+ position: absolute;
+ inset: 0;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ color: ${cssVar.colorTextLightSolid};
+
+ opacity: 0;
+ background: ${cssVar.colorBgMask};
+
+ transition: opacity 0.15s ${cssVar.motionEaseInOut};
+ `,
+ preview: css`
+ cursor: pointer;
+
+ position: relative;
+
+ overflow: hidden;
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 72px;
+ height: 44px;
+ border-radius: 6px;
+
+ background: ${cssVar.colorFillSecondary};
+ box-shadow: 0 0 0 2px ${cssVar.colorPrimary};
+
+ &:hover > span {
+ opacity: 1;
+ }
+ `,
+ title: css`
+ color: ${cssVar.colorPrimary};
+ `,
+}));
+
+interface EditingVideoHeaderProps {
+ coverUrl?: string;
+ onCancel: () => void;
+ onLocate: () => void;
+ prompt?: string;
+ version: number;
+}
+
+const EditingVideoHeader = memo<EditingVideoHeaderProps>(
+ ({ coverUrl, prompt, version, onCancel, onLocate }) => {
+ const { t } = useTranslation('video');
+
+ return (
+ <Flexbox horizontal align={'center'} className={styles.container} gap={12}>
+ <div
+ className={styles.preview}
+ role={'button'}
+ // `role="button"` alone leaves it unreachable: it has to take focus and
+ // answer Enter / Space the way a real button does.
+ tabIndex={0}
+ title={t('generation.version.locateSource')}
+ onClick={onLocate}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ onLocate();
+ }}
+ >
+ {coverUrl ? (
+ <Image
+ alt=""
+ preview={false}
+ src={coverUrl}
+ style={{ height: '100%', objectFit: 'cover', width: '100%' }}
+ />
+ ) : (
+ <VideoIcon size={18} />
+ )}
+ <span className={styles.locate}>
+ <LocateFixedIcon size={16} />
+ </span>
+ </div>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} className={styles.title} gap={6}>
+ <SquarePenIcon size={14} />
+ <Text fontSize={13} style={{ color: 'inherit' }} weight={500}>
+ {t('generation.editing.title', { version: String(version) })}
+ </Text>
+ </Flexbox>
+ <Text ellipsis fontSize={12} title={prompt} type={'secondary'}>
+ {prompt || t('generation.editing.hint')}
+ </Text>
+ </Flexbox>
+ <ActionIcon
+ icon={XIcon}
+ size={'small'}
+ title={t('generation.editing.cancelHint')}
+ onClick={onCancel}
+ />
+ </Flexbox>
+ );
+ },
+);
+
+EditingVideoHeader.displayName = 'EditingVideoHeader';
+
+export default EditingVideoHeader;
diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
index 4ac861b8b0c..34aff81fd7a 100644
--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
@@ -4,7 +4,7 @@ import { Flexbox, InputNumber } from '@lobehub/ui';
import { ActionIcon, SliderWithInput, Switch, Tabs, Text } from '@lobehub/ui/base-ui';
import { Divider } from 'antd';
import { Clock3, Dices } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { type KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import VideoFreeQuotaInfo from '@/business/client/features/VideoFreeQuotaInfo';
@@ -35,12 +35,16 @@ import { authSelectors } from '@/store/user/slices/auth/selectors';
import { useVideoStore } from '@/store/video';
import {
createVideoSelectors,
+ generationBatchSelectors,
videoGenerationConfigSelectors,
videoGenerationTopicSelectors,
} from '@/store/video/selectors';
import { useVideoGenerationConfigParam } from '@/store/video/slices/generationConfig/hooks';
+import type { VideoGenerationAsset } from '@/types/generation';
import { generateUniqueSeeds } from '@/utils/number';
+import { revealVideoGeneration, useVideoVersionMap } from '../GenerationFeed/videoVersion';
+import EditingVideoHeader from './EditingVideoHeader';
import PromptTitle from './Title';
import { useVideoReferenceUpload } from './useVideoReferenceUpload';
@@ -305,6 +309,16 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
useVideoGenerationConfigParam('endImageUrl');
const isCreating = useVideoStore(createVideoSelectors.isCreating);
const createVideo = useVideoStore((s) => s.createVideo);
+ const cancelEditingVideo = useVideoStore((s) => s.cancelEditingVideo);
+ const editingGenerationId = useVideoStore(createVideoSelectors.editingGenerationId);
+ const currentGenerationBatches = useVideoStore(generationBatchSelectors.currentGenerationBatches);
+ const editingBatch = useMemo(() => {
+ if (!editingGenerationId) return undefined;
+
+ return currentGenerationBatches.find((batch) =>
+ batch.generations.some((generation) => generation.id === editingGenerationId),
+ );
+ }, [currentGenerationBatches, editingGenerationId]);
const setModelAndProviderOnSelect = useVideoStore((s) => s.setModelAndProviderOnSelect);
const activeGenerationTopicId = useVideoStore(
videoGenerationTopicSelectors.activeGenerationTopicId,
@@ -342,8 +356,29 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const isLogin = useUserStore(authSelectors.isLogin);
const { value: duration } = useVideoGenerationConfigParam('duration');
const { handleUploadFiles, uploadingPreviews } = useVideoReferenceUpload();
+ const versionMap = useVideoVersionMap();
+ const inputWrapperRef = useRef<HTMLDivElement>(null);
useFetchAiVideoConfig();
+ // Entering edit mode starts from the feed card, so move focus to the input to
+ // let users type the change right away.
+ useEffect(() => {
+ if (!editingGenerationId) return;
+
+ inputWrapperRef.current?.querySelector('textarea')?.focus();
+ }, [editingGenerationId]);
+
+ const handleEditingKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLDivElement>) => {
+ if (!editingGenerationId || e.key !== 'Escape' || e.nativeEvent.isComposing) return;
+ if (!(e.target instanceof HTMLTextAreaElement)) return;
+
+ e.preventDefault();
+ cancelEditingVideo();
+ },
+ [cancelEditingVideo, editingGenerationId],
+ );
+
// Read query parameters
const [promptParam, setPromptParam] = useQueryState('prompt');
const [modelParam, setModelParam] = useQueryState('model');
@@ -437,6 +472,10 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
[imageUrl, imageUrls],
);
const hasRefImages = framePreviewUrls.length > 0 || Boolean(endImageUrl);
+ const editingGeneration = editingBatch?.generations.find(
+ (generation) => generation.id === editingGenerationId,
+ );
+ const editingAsset = editingGeneration?.asset as VideoGenerationAsset | null | undefined;
const displayVisibility = activeGenerationTopic
? activeGenerationTopic.visibility === 'private'
? 'private'
@@ -513,160 +552,200 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
{showTitle && <PromptTitle />}
<GenerationModelNotice notice={modelNotice} ns={'video'} />
<Flexbox gap={8}>
- <GenerationPromptInput
- disableGenerate={!isInit || isModelUnavailable}
- disabled={!canCreate}
- generateLabel={t('generation.actions.generate')}
- generatingLabel={t('generation.status.generating')}
- isCreating={isCreating}
- isDarkMode={isDarkMode}
- value={value}
- inlineContent={
- showInlineFrames ? (
- <InlineVideoFrames
- endImageUrl={endImageUrl}
- imageUrl={imageUrl}
- imageUrls={imageUrls}
- isSupportEndImage={isSupportEndImageUrl}
- maxCount={maxCount}
- maxFileSize={imageUrlsMaxFileSize ?? imageUrlMaxFileSize}
- uploadingPreviews={uploadingPreviews}
- onEndImageChange={handleEndImageChange}
- onImageUrlsChange={handleAddImage}
- onRemoveImageUrl={handleRemoveImage}
- onUploadFiles={handleUploadFiles}
- onImageChange={(data) => {
- if (data === null) {
- handleRemoveImage(imageUrl || '');
- return;
- }
- handleAddImage(data);
- }}
- />
- ) : undefined
- }
- leftActions={
- <Flexbox
- horizontal
- align={'center'}
- gap={4}
- style={canCreate ? undefined : { opacity: 0.5, pointerEvents: 'none' }}
- >
- <GenerationMediaModeSegment mode={'video'} />
- <ModelSwitchPanel
- ModelItemComponent={VideoModelItem}
- enabledList={enabledVideoModelList}
- model={currentModel ?? undefined}
- openOnHover={false}
- placement="topLeft"
- pricingMode="video"
- provider={currentProvider ?? undefined}
- onModelChange={async ({ model, provider }) => {
- if (!canCreate) return;
-
- setModelAndProviderOnSelect(model, provider);
- }}
- >
- <ActionIcon
- icon={<ModelIcon model={currentModel ?? ''} size={22} />}
- size={{
- blockSize: 36,
- size: 20,
+ <div ref={inputWrapperRef} onKeyDownCapture={handleEditingKeyDown}>
+ <GenerationPromptInput
+ disableGenerate={!isInit || isModelUnavailable}
+ disabled={!canCreate}
+ isCreating={isCreating}
+ isDarkMode={isDarkMode}
+ value={value}
+ generateLabel={
+ editingGenerationId
+ ? t('generation.actions.generateEdit')
+ : t('generation.actions.generate')
+ }
+ generatingLabel={
+ editingGenerationId
+ ? t('generation.status.editing')
+ : t('generation.status.generating')
+ }
+ header={
+ editingGenerationId ? (
+ <EditingVideoHeader
+ coverUrl={editingAsset?.coverUrl || editingAsset?.thumbnailUrl}
+ prompt={editingBatch?.prompt}
+ version={versionMap.get(editingGenerationId)?.version ?? 1}
+ onCancel={cancelEditingVideo}
+ onLocate={() => revealVideoGeneration(editingGenerationId)}
+ />
+ ) : undefined
+ }
+ inlineContent={
+ !editingGenerationId && showInlineFrames ? (
+ <InlineVideoFrames
+ endImageUrl={endImageUrl}
+ imageUrl={imageUrl}
+ imageUrls={imageUrls}
+ isSupportEndImage={isSupportEndImageUrl}
+ maxCount={maxCount}
+ maxFileSize={imageUrlsMaxFileSize ?? imageUrlMaxFileSize}
+ uploadingPreviews={uploadingPreviews}
+ onEndImageChange={handleEndImageChange}
+ onImageUrlsChange={handleAddImage}
+ onRemoveImageUrl={handleRemoveImage}
+ onUploadFiles={handleUploadFiles}
+ onImageChange={(data) => {
+ if (data === null) {
+ handleRemoveImage(imageUrl || '');
+ return;
+ }
+ handleAddImage(data);
}}
/>
- </ModelSwitchPanel>
- <ConfigAction
- title={t('config.title', { defaultValue: 'Config' })}
- content={
- <Flexbox gap={12}>
- {isSupportAspectRatio && (
- <Flexbox gap={6}>
- <Text fontSize={12}>{t('config.aspectRatio.label')}</Text>
- <AspectRatioItem />
- </Flexbox>
- )}
- {isSupportResolution && (
- <Flexbox gap={6}>
- <Text fontSize={12}>{t('config.resolution.label')}</Text>
- <ResolutionItem />
- </Flexbox>
- )}
- {isSupportSize && (
- <Flexbox gap={6}>
- <Text fontSize={12}>{t('config.size.label')}</Text>
- <SizeItem />
- </Flexbox>
- )}
- {isSupportSeed && (
- <Flexbox gap={6}>
- <Text fontSize={12}>{t('config.seed.label')}</Text>
- <SeedItem />
- </Flexbox>
- )}
- {(isSupportGenerateAudio ||
- isSupportCameraFixed ||
- isSupportWatermark ||
- isSupportPromptExtend ||
- isSupportWebSearch) && <Divider style={{ marginBlock: 4 }} />}
- {isSupportGenerateAudio && (
- <SwitchItem
- label={t('config.generateAudio.label')}
- paramName={'generateAudio'}
- />
- )}
- {isSupportCameraFixed && (
- <SwitchItem label={t('config.cameraFixed.label')} paramName={'cameraFixed'} />
- )}
- {isSupportWatermark && (
- <SwitchItem label={t('config.watermark.label')} paramName={'watermark'} />
- )}
- {isSupportPromptExtend && <PromptExtendItem />}
- {isSupportWebSearch && (
- <SwitchItem label={t('config.webSearch.label')} paramName={'webSearch'} />
- )}
- </Flexbox>
- }
- />
- {isSupportDuration && (
- <Action
- icon={Clock3}
- trigger={'click'}
- popover={{
- content: <DurationItem />,
- minWidth: 220,
- title: t('config.duration.label'),
+ ) : undefined
+ }
+ leftActions={
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={canCreate ? undefined : { opacity: 0.5, pointerEvents: 'none' }}
+ >
+ <GenerationMediaModeSegment mode={'video'} />
+ {editingGenerationId ? (
+ <ActionIcon
+ disabled
+ icon={<ModelIcon model={currentModel ?? ''} size={22} />}
+ title={t('generation.editing.modelLocked')}
+ size={{
+ blockSize: 36,
+ size: 20,
+ }}
+ />
+ ) : (
+ <ModelSwitchPanel
+ ModelItemComponent={VideoModelItem}
+ enabledList={enabledVideoModelList}
+ model={currentModel ?? undefined}
+ openOnHover={false}
+ placement="topLeft"
+ pricingMode="video"
+ provider={currentProvider ?? undefined}
+ onModelChange={async ({ model, provider }) => {
+ if (!canCreate) return;
+
+ setModelAndProviderOnSelect(model, provider);
+ }}
+ >
+ <ActionIcon
+ icon={<ModelIcon model={currentModel ?? ''} size={22} />}
+ size={{
+ blockSize: 36,
+ size: 20,
+ }}
+ />
+ </ModelSwitchPanel>
+ )}
+ <ConfigAction
+ title={t('config.title', { defaultValue: 'Config' })}
+ content={
+ <Flexbox gap={12}>
+ {isSupportAspectRatio && (
+ <Flexbox gap={6}>
+ <Text fontSize={12}>{t('config.aspectRatio.label')}</Text>
+ <AspectRatioItem />
+ </Flexbox>
+ )}
+ {isSupportResolution && (
+ <Flexbox gap={6}>
+ <Text fontSize={12}>{t('config.resolution.label')}</Text>
+ <ResolutionItem />
+ </Flexbox>
+ )}
+ {isSupportSize && (
+ <Flexbox gap={6}>
+ <Text fontSize={12}>{t('config.size.label')}</Text>
+ <SizeItem />
+ </Flexbox>
+ )}
+ {isSupportSeed && (
+ <Flexbox gap={6}>
+ <Text fontSize={12}>{t('config.seed.label')}</Text>
+ <SeedItem />
+ </Flexbox>
+ )}
+ {(isSupportGenerateAudio ||
+ isSupportCameraFixed ||
+ isSupportWatermark ||
+ isSupportPromptExtend ||
+ isSupportWebSearch) && <Divider style={{ marginBlock: 4 }} />}
+ {isSupportGenerateAudio && (
+ <SwitchItem
+ label={t('config.generateAudio.label')}
+ paramName={'generateAudio'}
+ />
+ )}
+ {isSupportCameraFixed && (
+ <SwitchItem
+ label={t('config.cameraFixed.label')}
+ paramName={'cameraFixed'}
+ />
+ )}
+ {isSupportWatermark && (
+ <SwitchItem label={t('config.watermark.label')} paramName={'watermark'} />
+ )}
+ {isSupportPromptExtend && <PromptExtendItem />}
+ {isSupportWebSearch && (
+ <SwitchItem label={t('config.webSearch.label')} paramName={'webSearch'} />
+ )}
+ </Flexbox>
+ }
+ />
+ {isSupportDuration && (
+ <Action
+ icon={Clock3}
+ trigger={'click'}
+ popover={{
+ content: <DurationItem />,
+ minWidth: 220,
+ title: t('config.duration.label'),
+ }}
+ title={[t('config.duration.label'), duration ? `${duration}s` : '']
+ .filter(Boolean)
+ .join(' ')}
+ />
+ )}
+ </Flexbox>
+ }
+ placeholder={
+ editingGenerationId
+ ? t('config.prompt.editPlaceholder')
+ : hasRefImages
+ ? t('config.prompt.placeholderWithRef')
+ : t('config.prompt.placeholder')
+ }
+ rightActions={
+ <>
+ <PromptTransformAction
+ mode={'video'}
+ prompt={value}
+ onPromptChange={(next) => {
+ if (!canCreate) return;
+
+ setValue(next as any);
}}
- title={[t('config.duration.label'), duration ? `${duration}s` : '']
- .filter(Boolean)
- .join(' ')}
/>
- )}
- </Flexbox>
- }
- placeholder={
- hasRefImages ? t('config.prompt.placeholderWithRef') : t('config.prompt.placeholder')
- }
- rightActions={
- <>
- <PromptTransformAction
- mode={'video'}
- prompt={value}
- onPromptChange={(next) => {
- if (!canCreate) return;
-
- setValue(next as any);
- }}
- />
- <GenerationVisibilitySelector
- disabledReason={visibilityLockedReason}
- visibility={displayVisibility}
- onChange={setNewGenerationTopicVisibility}
- />
- </>
- }
- onGenerate={handleGenerate}
- onValueChange={setValue}
- />
+ <GenerationVisibilitySelector
+ disabledReason={visibilityLockedReason}
+ visibility={displayVisibility}
+ onChange={setNewGenerationTopicVisibility}
+ />
+ </>
+ }
+ onGenerate={handleGenerate}
+ onValueChange={setValue}
+ />
+ </div>
<VideoFreeQuotaInfo />
</Flexbox>
</Flexbox>
diff --git a/src/store/video/slices/createVideo/action.test.ts b/src/store/video/slices/createVideo/action.test.ts
new file mode 100644
index 00000000000..8e72f3b2a6a
--- /dev/null
+++ b/src/store/video/slices/createVideo/action.test.ts
@@ -0,0 +1,259 @@
+import { act, renderHook } from '@testing-library/react';
+import type { AIVideoModelCard, RuntimeVideoGenParams, VideoModelParamsSchema } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { videoService } from '@/services/video';
+import { useVideoStore } from '@/store/video';
+
+const omniSchema: VideoModelParamsSchema = {
+ aspectRatio: { default: '16:9', enum: ['16:9', '9:16'] },
+ duration: { default: 10, max: 10, min: 10 },
+ prompt: { default: '' },
+};
+
+const omniModel: AIVideoModelCard = {
+ displayName: 'Gemini Omni Flash',
+ id: 'gemini-omni-1.1-flash',
+ parameters: omniSchema,
+ releasedAt: '2026-06-01',
+ type: 'video',
+};
+
+vi.mock('@/business/client/handleGenerationPromptModerationError', () => ({
+ handleGenerationPromptModerationError: vi.fn(),
+}));
+vi.mock('@/business/client/handleLobeHubModelDeprecatedError', () => ({
+ handleLobeHubModelDeprecatedError: vi.fn(),
+}));
+vi.mock('@/services/video', () => ({
+ videoService: {
+ createVideo: vi.fn(),
+ },
+}));
+vi.mock('@/store/aiInfra', () => ({
+ aiProviderSelectors: {
+ enabledVideoModelList: vi.fn(() => [
+ {
+ children: [omniModel],
+ id: 'google',
+ name: 'Google',
+ },
+ ]),
+ },
+ getAiInfraStoreState: vi.fn(() => ({})),
+}));
+
+describe('CreateVideoAction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(videoService.createVideo).mockResolvedValue({ success: true } as any);
+
+ useVideoStore.setState({
+ activeGenerationTopicId: 'topic-1',
+ editingDraftSnapshot: undefined,
+ editingGenerationId: undefined,
+ isCreating: false,
+ isCreatingWithNewTopic: false,
+ model: 'draft-model',
+ parameters: {
+ imageUrls: ['draft-reference.png'],
+ prompt: 'An unrelated draft',
+ } as RuntimeVideoGenParams,
+ parametersSchema: { prompt: { default: '' } },
+ provider: 'draft-provider',
+ refreshGenerationBatches: vi.fn().mockResolvedValue(undefined),
+ uploadingImagePreviews: ['blob:draft'],
+ });
+ });
+
+ it('should start editing with a blank instruction and without source media', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-source',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ sourceParameters: {
+ aspectRatio: '9:16',
+ imageUrls: ['source-reference.png'],
+ prompt: 'Original generation prompt',
+ },
+ });
+ });
+
+ expect(result.current.editingGenerationId).toBe('generation-source');
+ expect(result.current.model).toBe('gemini-omni-1.1-flash');
+ expect(result.current.provider).toBe('google');
+ expect(result.current.parameters).toEqual({
+ aspectRatio: '9:16',
+ duration: 10,
+ prompt: '',
+ });
+ expect(result.current.uploadingImagePreviews).toEqual([]);
+ expect(result.current.editingDraftSnapshot).toMatchObject({
+ model: 'draft-model',
+ parameters: {
+ imageUrls: ['draft-reference.png'],
+ prompt: 'An unrelated draft',
+ },
+ provider: 'draft-provider',
+ uploadingImagePreviews: ['blob:draft'],
+ });
+ });
+
+ it('should submit the source generation and restore the original draft after success', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-source',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ sourceParameters: { aspectRatio: '9:16', prompt: 'Original generation prompt' },
+ });
+ result.current.setParamOnInput('prompt', 'Make the camera move more slowly');
+ });
+
+ await act(async () => {
+ await result.current.createVideo();
+ });
+
+ expect(videoService.createVideo).toHaveBeenCalledWith({
+ generationTopicId: 'topic-1',
+ model: 'gemini-omni-1.1-flash',
+ params: {
+ aspectRatio: '9:16',
+ duration: 10,
+ prompt: 'Make the camera move more slowly',
+ },
+ previousGenerationId: 'generation-source',
+ provider: 'google',
+ });
+ expect(result.current.editingGenerationId).toBeUndefined();
+ expect(result.current.editingDraftSnapshot).toBeUndefined();
+ expect(result.current.model).toBe('draft-model');
+ expect(result.current.parameters).toEqual({
+ imageUrls: ['draft-reference.png'],
+ prompt: 'An unrelated draft',
+ });
+ expect(result.current.uploadingImagePreviews).toEqual(['blob:draft']);
+ });
+
+ it('should preserve the edit instruction and edit state when creation fails', async () => {
+ vi.mocked(videoService.createVideo).mockRejectedValueOnce(new Error('API failed'));
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-source',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ result.current.setParamOnInput('prompt', 'Keep the subject still');
+ });
+
+ await expect(
+ act(async () => {
+ await result.current.createVideo();
+ }),
+ ).rejects.toThrow('API failed');
+
+ expect(result.current.editingGenerationId).toBe('generation-source');
+ expect(result.current.parameters.prompt).toBe('Keep the subject still');
+ });
+
+ it('should restore the original draft when editing is cancelled', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-source',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ result.current.setParamOnInput('prompt', 'Temporary edit instruction');
+ result.current.cancelEditingVideo();
+ });
+
+ expect(result.current.editingGenerationId).toBeUndefined();
+ expect(result.current.editingDraftSnapshot).toBeUndefined();
+ expect(result.current.model).toBe('draft-model');
+ expect(result.current.provider).toBe('draft-provider');
+ expect(result.current.parameters).toEqual({
+ imageUrls: ['draft-reference.png'],
+ prompt: 'An unrelated draft',
+ });
+ });
+
+ it('should keep the typed instruction when switching to another edit source', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-a',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ result.current.setParamOnInput('prompt', 'Make the camera move more slowly');
+ result.current.startEditingVideo({
+ generationId: 'generation-b',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ });
+
+ expect(result.current.editingGenerationId).toBe('generation-b');
+ expect(result.current.parameters.prompt).toBe('Make the camera move more slowly');
+ expect(result.current.editingDraftSnapshot?.parameters.prompt).toBe('An unrelated draft');
+ });
+
+ it('should leave edit mode and restore the draft when the edit source is deleted', async () => {
+ useVideoStore.setState({
+ generationBatchesMap: {},
+ internal_deleteGeneration: vi.fn().mockResolvedValue(undefined),
+ });
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-source',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ });
+
+ await act(async () => {
+ await result.current.removeGeneration('generation-source');
+ });
+
+ expect(result.current.editingGenerationId).toBeUndefined();
+ expect(result.current.model).toBe('draft-model');
+ expect(result.current.parameters.prompt).toBe('An unrelated draft');
+ });
+
+ it('should leave edit mode when the batch holding the edit source is deleted', async () => {
+ useVideoStore.setState({
+ generationBatchesMap: {
+ 'topic-1': [{ generations: [{ id: 'generation-source' }], id: 'batch-source' } as any],
+ },
+ internal_deleteGenerationBatch: vi.fn().mockResolvedValue(undefined),
+ });
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.startEditingVideo({
+ generationId: 'generation-source',
+ model: 'gemini-omni-1.1-flash',
+ provider: 'google',
+ });
+ });
+
+ await act(async () => {
+ await result.current.removeGenerationBatch('batch-source', 'topic-1');
+ });
+
+ expect(result.current.editingGenerationId).toBeUndefined();
+ expect(result.current.model).toBe('draft-model');
+ });
+});
diff --git a/src/store/video/slices/createVideo/action.ts b/src/store/video/slices/createVideo/action.ts
index 4872fc276fc..505a5c155fe 100644
--- a/src/store/video/slices/createVideo/action.ts
+++ b/src/store/video/slices/createVideo/action.ts
@@ -1,18 +1,67 @@
import { toast } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
+import { type RuntimeVideoGenParams, type RuntimeVideoGenParamsKeys } from 'model-bank';
import { handleGenerationPromptModerationError } from '@/business/client/handleGenerationPromptModerationError';
import { handleLobeHubModelDeprecatedError } from '@/business/client/handleLobeHubModelDeprecatedError';
import { videoService } from '@/services/video';
import { type StoreSetter } from '@/store/types';
+import { preserveSupportedParams } from '@/store/utils/preserveSupportedParams';
+import { type GenerationConfig } from '@/types/generation';
import { type VideoStore } from '../../store';
import { generationBatchSelectors } from '../generationBatch/selectors';
+import { getVideoModelAndDefaults } from '../generationConfig/action';
import { videoGenerationConfigSelectors } from '../generationConfig/selectors';
import { generationTopicSelectors } from '../generationTopic';
+import type { VideoEditingDraftSnapshot } from './initialState';
type Setter = StoreSetter<VideoStore>;
+interface StartEditingVideoParams {
+ generationId: string;
+ model: string;
+ provider: string;
+ sourceParameters?: GenerationConfig;
+}
+
+const EDIT_INPUT_PARAMETER_KEYS = new Set([
+ 'endImageUrl',
+ 'imageUrl',
+ 'imageUrls',
+ 'prompt',
+ 'task',
+]);
+
+const cloneEditingDraft = (store: VideoStore): VideoEditingDraftSnapshot => ({
+ model: store.model,
+ parameters: {
+ ...store.parameters,
+ ...(store.parameters.imageUrls ? { imageUrls: [...store.parameters.imageUrls] } : {}),
+ },
+ parametersSchema: store.parametersSchema,
+ provider: store.provider,
+ uploadingImagePreviews: [...store.uploadingImagePreviews],
+});
+
+const restoreEditingDraft = (state: VideoStore) => {
+ const snapshot = state.editingDraftSnapshot;
+
+ if (!snapshot) {
+ return { editingDraftSnapshot: undefined, editingGenerationId: undefined };
+ }
+
+ return {
+ editingDraftSnapshot: undefined,
+ editingGenerationId: undefined,
+ model: snapshot.model,
+ parameters: snapshot.parameters,
+ parametersSchema: snapshot.parametersSchema,
+ provider: snapshot.provider,
+ uploadingImagePreviews: snapshot.uploadingImagePreviews,
+ };
+};
+
export const createCreateVideoSlice = (set: Setter, get: () => VideoStore, _api?: unknown) =>
new CreateVideoActionImpl(set, get, _api);
@@ -97,6 +146,7 @@ export class CreateVideoActionImpl {
generationTopicId: finalTopicId!,
model,
params: parameters as any,
+ previousGenerationId: store.editingGenerationId,
provider,
});
@@ -105,11 +155,12 @@ export class CreateVideoActionImpl {
await this.#get().refreshGenerationBatches();
}
- // 6. Clear the prompt input after successful video creation
+ // 6. Restore the original draft after an edit, or clear a regular generation prompt
this.#set(
- (state) => ({
- parameters: { ...state.parameters, prompt: '' },
- }),
+ (state) =>
+ state.editingGenerationId
+ ? restoreEditingDraft(state)
+ : { parameters: { ...state.parameters, prompt: '' } },
false,
'createVideo/clearPrompt',
);
@@ -131,6 +182,10 @@ export class CreateVideoActionImpl {
}
};
+ cancelEditingVideo = (): void => {
+ this.#set((state) => restoreEditingDraft(state), false, 'cancelEditingVideo');
+ };
+
recreateVideo = async (generationBatchId: string): Promise<void> => {
this.#set({ isCreating: true }, false, 'recreateVideo/start');
@@ -162,6 +217,47 @@ export class CreateVideoActionImpl {
this.#set({ isCreating: false }, false, 'recreateVideo/end');
}
};
+
+ startEditingVideo = ({
+ generationId,
+ model,
+ provider,
+ sourceParameters,
+ }: StartEditingVideoParams): void => {
+ const store = this.#get();
+ const { defaultValues, parametersSchema } = getVideoModelAndDefaults(model, provider);
+ // Carry the source video's settings over, but not its prompt or input media.
+ const carriedKeys = Object.keys(parametersSchema).filter(
+ (key) => !EDIT_INPUT_PARAMETER_KEYS.has(key),
+ ) as RuntimeVideoGenParamsKeys[];
+ const parameters = preserveSupportedParams(
+ (sourceParameters ?? {}) as RuntimeVideoGenParams,
+ defaultValues,
+ parametersSchema,
+ carriedKeys,
+ );
+
+ this.#set(
+ {
+ editingDraftSnapshot: store.editingDraftSnapshot ?? cloneEditingDraft(store),
+ editingGenerationId: generationId,
+ model,
+ /**
+ * Switching from one edit source to another keeps the typed instruction: it is
+ * usually still what the user wants, and clearing it would silently lose input.
+ */
+ parameters: {
+ ...parameters,
+ prompt: store.editingGenerationId ? store.parameters.prompt : '',
+ },
+ parametersSchema,
+ provider,
+ uploadingImagePreviews: [],
+ },
+ false,
+ `startEditingVideo/${generationId}`,
+ );
+ };
}
export type CreateVideoAction = Pick<CreateVideoActionImpl, keyof CreateVideoActionImpl>;
diff --git a/src/store/video/slices/createVideo/initialState.ts b/src/store/video/slices/createVideo/initialState.ts
index cb7067aaf70..12d2fcdb49e 100644
--- a/src/store/video/slices/createVideo/initialState.ts
+++ b/src/store/video/slices/createVideo/initialState.ts
@@ -1,9 +1,23 @@
+import type { RuntimeVideoGenParams, VideoModelParamsSchema } from 'model-bank';
+
+export interface VideoEditingDraftSnapshot {
+ model: string;
+ parameters: RuntimeVideoGenParams;
+ parametersSchema: VideoModelParamsSchema;
+ provider: string;
+ uploadingImagePreviews: string[];
+}
+
export interface CreateVideoState {
+ editingDraftSnapshot?: VideoEditingDraftSnapshot;
+ editingGenerationId?: string;
isCreating: boolean;
isCreatingWithNewTopic: boolean;
}
export const initialCreateVideoState: CreateVideoState = {
+ editingDraftSnapshot: undefined,
+ editingGenerationId: undefined,
isCreating: false,
isCreatingWithNewTopic: false,
};
diff --git a/src/store/video/slices/createVideo/selectors.ts b/src/store/video/slices/createVideo/selectors.ts
index 20dfd9a931e..0b39e709290 100644
--- a/src/store/video/slices/createVideo/selectors.ts
+++ b/src/store/video/slices/createVideo/selectors.ts
@@ -1,9 +1,11 @@
import { type VideoStore } from '../../store';
+const editingGenerationId = (state: VideoStore) => state.editingGenerationId;
const isCreating = (state: VideoStore) => state.isCreating;
const isCreatingWithNewTopic = (state: VideoStore) => state.isCreatingWithNewTopic;
export const createVideoSelectors = {
+ editingGenerationId,
isCreating,
isCreatingWithNewTopic,
};
diff --git a/src/store/video/slices/generationBatch/action.ts b/src/store/video/slices/generationBatch/action.ts
index 6618195772d..aaabb35c4e8 100644
--- a/src/store/video/slices/generationBatch/action.ts
+++ b/src/store/video/slices/generationBatch/action.ts
@@ -110,6 +110,8 @@ export class GenerationBatchActionImpl {
await internal_deleteGeneration(generationId);
+ if (this.#get().editingGenerationId === generationId) this.#get().cancelEditingVideo();
+
// Video batch has only 1 generation, so delete the batch directly
if (activeGenerationTopicId) {
const updatedBatches = this.#get().generationBatchesMap[activeGenerationTopicId] || [];
@@ -122,8 +124,17 @@ export class GenerationBatchActionImpl {
};
removeGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {
- const { internal_deleteGenerationBatch } = this.#get();
+ const { editingGenerationId, generationBatchesMap, internal_deleteGenerationBatch } =
+ this.#get();
+ const containsEditingSource =
+ !!editingGenerationId &&
+ !!generationBatchesMap[topicId]
+ ?.find((batch) => batch.id === batchId)
+ ?.generations.some((generation) => generation.id === editingGenerationId);
+
await internal_deleteGenerationBatch(batchId, topicId);
+
+ if (containsEditingSource) this.#get().cancelEditingVideo();
};
setTopicBatchLoaded = (topicId: string): void => {
diff --git a/src/store/video/slices/generationConfig/action.test.ts b/src/store/video/slices/generationConfig/action.test.ts
index c4c61aa7f45..47d44017516 100644
--- a/src/store/video/slices/generationConfig/action.test.ts
+++ b/src/store/video/slices/generationConfig/action.test.ts
@@ -93,6 +93,7 @@ beforeEach(() => {
vi.clearAllMocks();
useVideoStore.setState({
+ editingGenerationId: 'generation-source',
isInit: true,
model: 'video-model-a',
provider: 'provider-a',
@@ -132,6 +133,7 @@ describe('video generationConfig actions', () => {
endImageUrl: 'end-custom.png',
});
expect(result.current.parameters?.duration).toBe(modelBDefaultValues.duration);
+ expect(result.current.editingGenerationId).toBeUndefined();
});
it('should clamp preserved reference images to the next model limit', () => {
diff --git a/src/store/video/slices/generationConfig/action.ts b/src/store/video/slices/generationConfig/action.ts
index 587d17ea97a..6cc57cda917 100644
--- a/src/store/video/slices/generationConfig/action.ts
+++ b/src/store/video/slices/generationConfig/action.ts
@@ -123,6 +123,8 @@ export class GenerationConfigActionImpl {
this.#set(
{
+ editingDraftSnapshot: undefined,
+ editingGenerationId: undefined,
model,
parameters,
parametersSchema,
diff --git a/src/store/video/slices/generationTopic/action.test.ts b/src/store/video/slices/generationTopic/action.test.ts
index 52378f01090..0dcafef94e8 100644
--- a/src/store/video/slices/generationTopic/action.test.ts
+++ b/src/store/video/slices/generationTopic/action.test.ts
@@ -76,6 +76,38 @@ describe('VideoGenerationTopicAction', () => {
});
});
+ describe('topic navigation', () => {
+ it('should clear the editing generation when switching topics', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ useVideoStore.setState({
+ activeGenerationTopicId: 'topic-1',
+ editingGenerationId: 'generation-1',
+ });
+ result.current.switchGenerationTopic('topic-2');
+ });
+
+ expect(result.current.activeGenerationTopicId).toBe('topic-2');
+ expect(result.current.editingGenerationId).toBeUndefined();
+ });
+
+ it('should clear the editing generation when opening a new topic', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ useVideoStore.setState({
+ activeGenerationTopicId: 'topic-1',
+ editingGenerationId: 'generation-1',
+ });
+ result.current.openNewGenerationTopic();
+ });
+
+ expect(result.current.activeGenerationTopicId).toBeNull();
+ expect(result.current.editingGenerationId).toBeUndefined();
+ });
+ });
+
describe('internal_createGenerationTopic', () => {
it('should create video topic with private visibility by default', async () => {
const { result } = renderHook(() => useVideoStore());
diff --git a/src/store/video/slices/generationTopic/action.ts b/src/store/video/slices/generationTopic/action.ts
index 85e449685fa..b1441522ade 100644
--- a/src/store/video/slices/generationTopic/action.ts
+++ b/src/store/video/slices/generationTopic/action.ts
@@ -164,7 +164,15 @@ export class GenerationTopicActionImpl {
};
openNewGenerationTopic = (): void => {
- this.#set({ activeGenerationTopicId: null }, false, n('openNewGenerationTopic'));
+ this.#set(
+ {
+ activeGenerationTopicId: null,
+ editingDraftSnapshot: undefined,
+ editingGenerationId: undefined,
+ },
+ false,
+ n('openNewGenerationTopic'),
+ );
};
refreshGenerationTopics = async (): Promise<void> => {
@@ -270,7 +278,15 @@ export class GenerationTopicActionImpl {
switchGenerationTopic = (topicId: string): void => {
if (this.#get().activeGenerationTopicId === topicId) return;
- this.#set({ activeGenerationTopicId: topicId }, false, n('switchGenerationTopic'));
+ this.#set(
+ {
+ activeGenerationTopicId: topicId,
+ editingDraftSnapshot: undefined,
+ editingGenerationId: undefined,
+ },
+ false,
+ n('switchGenerationTopic'),
+ );
};
updateGenerationTopicCover = async (topicId: string, coverUrl: string): Promise<void> => {