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.

⚡️ perf: reuse generation reference images and cap status polling at 5s (#20796)

YuTengjing184dc9cca362
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
index 29c0798f50b..bb54f670454 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
@@ -3,6 +3,7 @@ import type OpenAI from 'openai';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { OpenAIChatMessage } from '../../types';
+import { clearReferenceImageCache } from '../../utils/referenceImageCache';
import { serializeScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { parseDataUri } from '../../utils/uriParser';
import {
@@ -1622,6 +1623,7 @@ describe('convertOpenAIResponseInputs', () => {
describe('convertImageUrlToFile', () => {
beforeEach(() => {
vi.resetAllMocks();
+ clearReferenceImageCache();
});
afterEach(() => {
@@ -1732,9 +1734,25 @@ describe('convertImageUrlToFile', () => {
expect(result).toHaveProperty('type', testCase.contentType || 'image/png');
vi.clearAllMocks();
+ clearReferenceImageCache();
}
});
+ it('should reuse one download for repeated conversions of the same URL', async () => {
+ mockFetch.mockResolvedValue({
+ ok: true,
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
+ headers: new Headers({ 'content-type': 'image/png' }),
+ } satisfies Partial<Response>);
+
+ const first = await convertImageUrlToFile('https://example.com/reference.png');
+ const second = await convertImageUrlToFile('https://example.com/reference.png');
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(first).not.toBe(second);
+ expect(second).toHaveProperty('type', 'image/png');
+ });
+
it('should throw error when HTTP request fails', async () => {
mockFetch.mockResolvedValue({
ok: false,
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.ts
index 54e773db9a3..638b7085c4f 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts
@@ -11,6 +11,7 @@ import type {
UserMessageContentPart,
} from '../../types';
import { isDeepSeekThinkingEligibleModel } from '../../utils/modelParse';
+import { fetchReferenceImageBytes } from '../../utils/referenceImageCache';
import { resolveScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { parseDataUri } from '../../utils/uriParser';
@@ -612,13 +613,17 @@ export const convertImageUrlToFile = async (imageUrl: string) => {
mimeType = mimeTypePart.split(':')[1].split(';')[0];
buffer = Buffer.from(base64Data, 'base64');
} else {
- // a http url
- const response = await fetch(imageUrl);
- if (!response.ok) {
- throw new Error(`Failed to fetch image from ${imageUrl}: ${response.statusText}`);
- }
- buffer = Buffer.from(await response.arrayBuffer());
- mimeType = response.headers.get('content-type') || 'image/png';
+ // a http url; generation retries and batch siblings reuse the same download
+ ({ buffer, mimeType } = await fetchReferenceImageBytes(imageUrl, async (url) => {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch image from ${url}: ${response.statusText}`);
+ }
+ return {
+ buffer: Buffer.from(await response.arrayBuffer()),
+ mimeType: response.headers.get('content-type') || 'image/png',
+ };
+ }));
}
return toFile(buffer, `image.${mimeType.split('/')[1]}`, { type: mimeType });
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts
index 07cbc261f5c..c6a5ab58d6b 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts
@@ -1,4 +1,3 @@
-import { imageUrlToBase64 } from '@lobechat/utils';
import { cleanObject } from '@lobechat/utils/object';
import createDebug from 'debug';
import type { RuntimeImageGenParamsValue } from 'model-bank';
@@ -10,6 +9,7 @@ import type {
CreateImageResponse,
} from '../../types/image';
import { getModelPricing } from '../../utils/getModelPricing';
+import { referenceImageUrlToBase64 } from '../../utils/referenceImageCache';
import { parseDataUri } from '../../utils/uriParser';
import { convertImageUrlToFile } from '../contextBuilders/openai';
import { convertOpenAIImageUsage } from '../usageConverters/openai';
@@ -167,7 +167,7 @@ async function processImageUrlForChat(imageUrl: string): Promise<string> {
return `data:${mimeType || 'image/png'};base64,${base64}`;
} else if (type === 'url') {
// For URL type, convert to base64 first
- const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(imageUrl);
+ const { base64: urlBase64, mimeType: urlMimeType } = await referenceImageUrlToBase64(imageUrl);
return `data:${urlMimeType};base64,${urlBase64}`;
} else {
throw new TypeError(`Currently we don't support image url: ${imageUrl}`);
diff --git a/packages/model-runtime/src/providers/bfl/createImage.test.ts b/packages/model-runtime/src/providers/bfl/createImage.test.ts
index 4b72a51dd49..ffe230ebc7c 100644
--- a/packages/model-runtime/src/providers/bfl/createImage.test.ts
+++ b/packages/model-runtime/src/providers/bfl/createImage.test.ts
@@ -2,6 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CreateImagePayload } from '../../types/image';
+import { clearReferenceImageCache } from '../../utils/referenceImageCache';
import { createBflImage } from './createImage';
import { BflStatusResponse } from './types';
@@ -31,6 +32,7 @@ const mockOptions = {
};
beforeEach(() => {
+ clearReferenceImageCache();
vi.clearAllMocks();
});
diff --git a/packages/model-runtime/src/providers/bfl/createImage.ts b/packages/model-runtime/src/providers/bfl/createImage.ts
index a9d4f5b8ad6..68482315b3c 100644
--- a/packages/model-runtime/src/providers/bfl/createImage.ts
+++ b/packages/model-runtime/src/providers/bfl/createImage.ts
@@ -1,4 +1,3 @@
-import { imageUrlToBase64 } from '@lobechat/utils';
import createDebug from 'debug';
import type { RuntimeImageGenParamsValue } from 'model-bank';
@@ -7,6 +6,7 @@ import type { CreateImagePayload, CreateImageResponse } from '../../types/image'
import type { TaskResult } from '../../utils/asyncifyPolling';
import { asyncifyPolling } from '../../utils/asyncifyPolling';
import { AgentRuntimeError } from '../../utils/createError';
+import { referenceImageUrlToBase64 } from '../../utils/referenceImageCache';
import { parseDataUri } from '../../utils/uriParser';
import type { BflAsyncResponse, BflModelId, BflRequest, BflResultResponse } from './types';
import { BFL_ENDPOINTS, BflStatusResponse } from './types';
@@ -39,7 +39,7 @@ async function convertImageToBase64(imageUrl: string): Promise<string> {
if (type === 'url') {
// Convert URL to base64
- const { base64 } = await imageUrlToBase64(imageUrl);
+ const { base64 } = await referenceImageUrlToBase64(imageUrl);
return base64;
}
diff --git a/packages/model-runtime/src/providers/google/createImage.ts b/packages/model-runtime/src/providers/google/createImage.ts
index fe81610d135..a9570621aab 100644
--- a/packages/model-runtime/src/providers/google/createImage.ts
+++ b/packages/model-runtime/src/providers/google/createImage.ts
@@ -5,7 +5,6 @@ import type {
GoogleGenAI,
Part,
} from '@google/genai';
-import { imageUrlToBase64 } from '@lobechat/utils';
import { convertGoogleAIUsage } from '../../core/usageConverters/google-ai';
import { AgentRuntimeErrorType } from '../../types/error';
@@ -17,6 +16,7 @@ import type {
import { AgentRuntimeError } from '../../utils/createError';
import { getModelPricing } from '../../utils/getModelPricing';
import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';
+import { referenceImageUrlToBase64 } from '../../utils/referenceImageCache';
import { parseDataUri } from '../../utils/uriParser';
// Maximum number of images allowed for processing
@@ -199,7 +199,7 @@ async function processImageForParts(imageUrl: string): Promise<Part> {
},
};
} else if (type === 'url') {
- const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(imageUrl);
+ const { base64: urlBase64, mimeType: urlMimeType } = await referenceImageUrlToBase64(imageUrl);
return {
inlineData: {
diff --git a/packages/model-runtime/src/providers/google/createVideo.ts b/packages/model-runtime/src/providers/google/createVideo.ts
index f491c587bc0..c3c842400ef 100644
--- a/packages/model-runtime/src/providers/google/createVideo.ts
+++ b/packages/model-runtime/src/providers/google/createVideo.ts
@@ -1,7 +1,6 @@
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';
@@ -12,6 +11,7 @@ import type {
} from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';
+import { referenceImageUrlToBase64 } from '../../utils/referenceImageCache';
import { parseDataUri } from '../../utils/uriParser';
const log = debug('lobe-video:google');
@@ -70,7 +70,7 @@ async function imageToGoogleImageFormat(imageUrl: string): Promise<Image> {
};
} else if (type === 'url') {
// Handle both HTTP URLs and file paths (files/...)
- const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(imageUrl);
+ const { base64: urlBase64, mimeType: urlMimeType } = await referenceImageUrlToBase64(imageUrl);
return {
imageBytes: urlBase64,
diff --git a/packages/model-runtime/src/providers/siliconcloud/createImage.ts b/packages/model-runtime/src/providers/siliconcloud/createImage.ts
index 15af0de5ff4..fc212998f06 100644
--- a/packages/model-runtime/src/providers/siliconcloud/createImage.ts
+++ b/packages/model-runtime/src/providers/siliconcloud/createImage.ts
@@ -1,4 +1,3 @@
-import { imageUrlToBase64 } from '@lobechat/utils';
import createDebug from 'debug';
import type { RuntimeImageGenParamsValue } from 'model-bank';
@@ -6,6 +5,7 @@ import type { CreateImageOptions } from '../../core/openaiCompatibleFactory';
import type { CreateImagePayload, CreateImageResponse } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
+import { referenceImageUrlToBase64 } from '../../utils/referenceImageCache';
import { parseDataUri } from '../../utils/uriParser';
const log = createDebug('lobe-image:siliconcloud');
@@ -27,7 +27,7 @@ async function convertToDataURI(imageUrl: string): Promise<string> {
}
if (type === 'url') {
- const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(imageUrl);
+ const { base64: urlBase64, mimeType: urlMimeType } = await referenceImageUrlToBase64(imageUrl);
return `data:${urlMimeType};base64,${urlBase64}`;
}
diff --git a/packages/model-runtime/src/utils/referenceImageCache.test.ts b/packages/model-runtime/src/utils/referenceImageCache.test.ts
new file mode 100644
index 00000000000..6bf29ca1e59
--- /dev/null
+++ b/packages/model-runtime/src/utils/referenceImageCache.test.ts
@@ -0,0 +1,149 @@
+import { imageUrlToBase64 } from '@lobechat/utils';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ clearReferenceImageCache,
+ DownloadCache,
+ fetchReferenceImageBytes,
+ referenceImageUrlToBase64,
+} from './referenceImageCache';
+
+vi.mock('@lobechat/utils', () => ({ imageUrlToBase64: vi.fn() }));
+
+const createCache = (now = () => 0) => {
+ const cache = new DownloadCache({ maxEntryBytes: 10, maxTotalBytes: 12, ttlMs: 1000 }, now);
+ return {
+ get bytes() {
+ return cache.bytes;
+ },
+ get: (key: string, loader: () => Promise<string>) =>
+ cache.get(key, loader, (value) => value.length),
+ get size() {
+ return cache.size;
+ },
+ };
+};
+
+describe('DownloadCache', () => {
+ it('reuses a settled download for the same key', async () => {
+ const cache = createCache();
+ const loader = vi.fn().mockResolvedValue('abc');
+
+ await expect(cache.get('a', loader)).resolves.toBe('abc');
+ await expect(cache.get('a', loader)).resolves.toBe('abc');
+
+ expect(loader).toHaveBeenCalledTimes(1);
+ expect(cache.bytes).toBe(3);
+ });
+
+ it('shares one in-flight download across concurrent callers', async () => {
+ const cache = createCache();
+ let resolve!: (value: string) => void;
+ const loader = vi.fn(() => new Promise<string>((r) => (resolve = r)));
+
+ const first = cache.get('a', loader);
+ const second = cache.get('a', loader);
+ resolve('abc');
+
+ await expect(Promise.all([first, second])).resolves.toEqual(['abc', 'abc']);
+ expect(loader).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not cache failed downloads', async () => {
+ const cache = createCache();
+ const loader = vi.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValue('abc');
+
+ await expect(cache.get('a', loader)).rejects.toThrow('boom');
+ await expect(cache.get('a', loader)).resolves.toBe('abc');
+
+ expect(loader).toHaveBeenCalledTimes(2);
+ });
+
+ it('downloads again after the TTL expires', async () => {
+ let now = 0;
+ const cache = createCache(() => now);
+ const loader = vi.fn().mockResolvedValueOnce('old').mockResolvedValue('new');
+
+ await cache.get('a', loader);
+ now = 1001;
+
+ await expect(cache.get('a', loader)).resolves.toBe('new');
+ expect(cache.bytes).toBe(3);
+ });
+
+ it('returns but does not keep values over the entry limit', async () => {
+ const cache = createCache();
+ const loader = vi.fn().mockResolvedValue('x'.repeat(11));
+
+ await cache.get('a', loader);
+ await cache.get('a', loader);
+
+ expect(loader).toHaveBeenCalledTimes(2);
+ expect(cache.size).toBe(0);
+ });
+
+ it('evicts least recently used entries past the total limit', async () => {
+ const cache = createCache();
+
+ await cache.get('a', async () => 'aaaaa');
+ await cache.get('b', async () => 'bbbbb');
+ // Touch `a` so `b` becomes the least recently used entry.
+ await cache.get('a', async () => 'unused');
+ await cache.get('c', async () => 'ccccc');
+
+ const reload = vi.fn().mockResolvedValue('bbbbb');
+ await cache.get('b', reload);
+
+ expect(reload).toHaveBeenCalledTimes(1);
+ expect(cache.bytes).toBeLessThanOrEqual(12);
+ });
+});
+
+describe('reference image helpers', () => {
+ beforeEach(() => {
+ clearReferenceImageCache();
+ vi.mocked(imageUrlToBase64).mockReset();
+ });
+
+ it('caches base64 conversions of remote URLs', async () => {
+ vi.mocked(imageUrlToBase64).mockResolvedValue({ base64: 'AAAA', mimeType: 'image/png' });
+
+ await referenceImageUrlToBase64('https://cdn.example.com/a.png');
+ await referenceImageUrlToBase64('https://cdn.example.com/a.png');
+
+ expect(imageUrlToBase64).toHaveBeenCalledTimes(1);
+ });
+
+ it('bypasses the cache for data URLs', async () => {
+ vi.mocked(imageUrlToBase64).mockResolvedValue({ base64: 'AAAA', mimeType: 'image/png' });
+
+ await referenceImageUrlToBase64('data:image/png;base64,AAAA');
+ await referenceImageUrlToBase64('data:image/png;base64,AAAA');
+
+ expect(imageUrlToBase64).toHaveBeenCalledTimes(2);
+ });
+
+ it('caches raw downloads of remote URLs', async () => {
+ const fetcher = vi
+ .fn()
+ .mockResolvedValue({ buffer: Buffer.from('img'), mimeType: 'image/png' });
+
+ await fetchReferenceImageBytes('https://cdn.example.com/a.png', fetcher);
+ await fetchReferenceImageBytes('https://cdn.example.com/a.png', fetcher);
+
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps base64 and raw downloads of the same URL apart', async () => {
+ vi.mocked(imageUrlToBase64).mockResolvedValue({ base64: 'AAAA', mimeType: 'image/png' });
+ const bytes = { buffer: Buffer.from('img'), mimeType: 'image/png' };
+
+ await expect(referenceImageUrlToBase64('https://cdn.example.com/a.png')).resolves.toEqual({
+ base64: 'AAAA',
+ mimeType: 'image/png',
+ });
+ await expect(
+ fetchReferenceImageBytes('https://cdn.example.com/a.png', async () => bytes),
+ ).resolves.toBe(bytes);
+ });
+});
diff --git a/packages/model-runtime/src/utils/referenceImageCache.ts b/packages/model-runtime/src/utils/referenceImageCache.ts
new file mode 100644
index 00000000000..5e2acbfdb56
--- /dev/null
+++ b/packages/model-runtime/src/utils/referenceImageCache.ts
@@ -0,0 +1,163 @@
+import { imageUrlToBase64 } from '@lobechat/utils';
+import type { Buffer } from 'buffer.js';
+
+/**
+ * Short-lived in-process cache for downloaded image/video generation reference
+ * images.
+ *
+ * Providers that cannot take a URL download each reference image and re-encode
+ * it (base64 or multipart File). Without a cache, the same image is downloaded
+ * again for every RouterRuntime fallback attempt within one request. Batch
+ * siblings each run as a separate async HTTP request, so they share downloads
+ * only when they land on the same server instance; serverless deployments may
+ * spread them across instances. Those repeats happen within seconds, so a
+ * one-minute TTL covers them while limiting staleness for arbitrary URLs whose
+ * content may change (for example, an external URL passed by an agent tool).
+ *
+ * Only successful downloads of `http(s)` URLs are cached; concurrent requests
+ * for the same URL share one in-flight download.
+ */
+interface CacheEntry {
+ expiresAt: number;
+ promise: Promise<unknown>;
+ /** Byte size once the download settles; 0 while in flight. */
+ size: number;
+}
+
+export interface DownloadCacheOptions {
+ /** Values larger than this are returned but not kept. */
+ maxEntryBytes: number;
+ /** Total bytes kept across settled entries; least recently used entries are evicted first. */
+ maxTotalBytes: number;
+ ttlMs: number;
+}
+
+/**
+ * URL-keyed download cache sharing one byte budget across value kinds. Callers
+ * must namespace keys per value kind so one key always maps to one value type.
+ */
+export class DownloadCache {
+ private readonly entries = new Map<string, CacheEntry>();
+ private totalBytes = 0;
+
+ constructor(
+ private readonly options: DownloadCacheOptions,
+ private readonly now: () => number = Date.now,
+ ) {}
+
+ get size() {
+ return this.entries.size;
+ }
+
+ get bytes() {
+ return this.totalBytes;
+ }
+
+ clear() {
+ this.entries.clear();
+ this.totalBytes = 0;
+ }
+
+ async get<T>(key: string, loader: () => Promise<T>, sizeOf: (value: T) => number): Promise<T> {
+ const existing = this.entries.get(key);
+ if (existing) {
+ if (existing.expiresAt > this.now()) {
+ // Refresh LRU order: Map iteration follows insertion order.
+ this.entries.delete(key);
+ this.entries.set(key, existing);
+ return existing.promise as Promise<T>;
+ }
+ this.remove(key, existing);
+ }
+
+ const promise = loader();
+ const entry: CacheEntry = {
+ expiresAt: this.now() + this.options.ttlMs,
+ promise,
+ size: 0,
+ };
+ this.entries.set(key, entry);
+
+ try {
+ const value = await promise;
+ // The entry may have been cleared or replaced while the download was in flight.
+ if (this.entries.get(key) !== entry) return value;
+
+ const size = sizeOf(value);
+ if (size > this.options.maxEntryBytes) {
+ this.entries.delete(key);
+ return value;
+ }
+
+ entry.size = size;
+ this.totalBytes += size;
+ this.evictOverflow();
+ return value;
+ } catch (error) {
+ if (this.entries.get(key) === entry) this.entries.delete(key);
+ throw error;
+ }
+ }
+
+ private remove(key: string, entry: CacheEntry) {
+ this.entries.delete(key);
+ this.totalBytes -= entry.size;
+ }
+
+ private evictOverflow() {
+ for (const [key, entry] of this.entries) {
+ if (this.totalBytes <= this.options.maxTotalBytes) return;
+ // In-flight entries have no size yet and are kept so their waiters still dedupe.
+ if (entry.size > 0) this.remove(key, entry);
+ }
+ }
+}
+
+const MB = 1024 * 1024;
+
+const isRemoteUrl = (url: string) => /^https?:\/\//i.test(url);
+
+const referenceImageCache = new DownloadCache({
+ maxEntryBytes: 20 * MB,
+ maxTotalBytes: 64 * MB,
+ ttlMs: 60 * 1000,
+});
+
+export interface ReferenceImageBytes {
+ buffer: Buffer;
+ mimeType: string;
+}
+
+/**
+ * Cached `imageUrlToBase64` for generation reference images. Data URLs and other
+ * non-HTTP inputs bypass the cache.
+ */
+export const referenceImageUrlToBase64 = (imageUrl: string) =>
+ isRemoteUrl(imageUrl)
+ ? referenceImageCache.get(
+ `base64:${imageUrl}`,
+ () => imageUrlToBase64(imageUrl),
+ (value) => value.base64.length,
+ )
+ : imageUrlToBase64(imageUrl);
+
+/**
+ * Cached raw download of a remote generation reference image. Callers must not
+ * mutate the returned buffer because it is shared with later cache hits.
+ */
+export const fetchReferenceImageBytes = (
+ imageUrl: string,
+ fetcher: (url: string) => Promise<ReferenceImageBytes>,
+) =>
+ isRemoteUrl(imageUrl)
+ ? referenceImageCache.get(
+ `bytes:${imageUrl}`,
+ () => fetcher(imageUrl),
+ (value) => value.buffer.byteLength,
+ )
+ : fetcher(imageUrl);
+
+/** Test helper: drop every cached reference image. */
+export const clearReferenceImageCache = () => {
+ referenceImageCache.clear();
+};
diff --git a/src/business/client/handleGenerationPromptModerationError.ts b/src/business/client/handleGenerationPromptModerationError.ts
deleted file mode 100644
index bb0d90f181b..00000000000
--- a/src/business/client/handleGenerationPromptModerationError.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const handleGenerationPromptModerationError = (_error: unknown) => {};
diff --git a/src/business/client/isGenerationPromptModerationError.ts b/src/business/client/isGenerationPromptModerationError.ts
new file mode 100644
index 00000000000..5bd12a9a15f
--- /dev/null
+++ b/src/business/client/isGenerationPromptModerationError.ts
@@ -0,0 +1,6 @@
+/**
+ * Whether a generation submit failed because the prompt itself was rejected by
+ * content moderation. Callers show this next to the prompt input instead of as a
+ * generic request error.
+ */
+export const isGenerationPromptModerationError = (_error: unknown): boolean => false;
diff --git a/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptBlockedNotice.tsx b/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptBlockedNotice.tsx
new file mode 100644
index 00000000000..43f2fcb4c01
--- /dev/null
+++ b/src/routes/(main)/(create)/features/GenerationInput/GenerationPromptBlockedNotice.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Alert } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ padding-block-start: 8px;
+ padding-inline: 8px;
+ `,
+}));
+
+interface GenerationPromptBlockedNoticeProps {
+ onClose: () => void;
+}
+
+/**
+ * Shown on top of the prompt input when content moderation rejected the
+ * submitted prompt, so the reason sits next to the text the user has to revise.
+ */
+const GenerationPromptBlockedNotice = memo<GenerationPromptBlockedNoticeProps>(({ onClose }) => {
+ const { t } = useTranslation('common');
+
+ return (
+ <div className={styles.container}>
+ <Alert
+ closable={{ onClose }}
+ title={t('generation.promptModeration.blocked')}
+ type={'error'}
+ variant={'soft'}
+ />
+ </div>
+ );
+});
+
+GenerationPromptBlockedNotice.displayName = 'GenerationPromptBlockedNotice';
+
+export default GenerationPromptBlockedNotice;
diff --git a/src/routes/(main)/(create)/features/GenerationInput/index.ts b/src/routes/(main)/(create)/features/GenerationInput/index.ts
index b02ac6eb5ff..446da881be3 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/index.ts
+++ b/src/routes/(main)/(create)/features/GenerationInput/index.ts
@@ -6,6 +6,7 @@ export {
useImageGenerationModelNotice,
useVideoGenerationModelNotice,
} from './GenerationModelNotice/useGenerationModelNotice';
+export { default as GenerationPromptBlockedNotice } from './GenerationPromptBlockedNotice';
export { default as GenerationPromptInput } from './GenerationPromptInput';
export { default as GenerationVisibilitySelector } from './GenerationVisibilitySelector';
export { default as ImagePreviewHeader } from './ImagePreviewHeader';
diff --git a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
index 169b59a78b1..e76a549e13e 100644
--- a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx
@@ -19,6 +19,7 @@ import {
ConfigAction,
GenerationMediaModeSegment,
GenerationModelNotice,
+ GenerationPromptBlockedNotice,
GenerationPromptInput,
GenerationVisibilitySelector,
InlineImageReference,
@@ -150,6 +151,10 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
} = useImageReferenceUpload();
const isCreating = useImageStore(createImageSelectors.isCreating);
const createImage = useImageStore((s) => s.createImage);
+ const blockedPrompt = useImageStore(createImageSelectors.blockedPrompt);
+ const dismissBlockedPrompt = useImageStore((s) => s.dismissBlockedPrompt);
+ // Editing the prompt dismisses the notice: it only describes the submitted text.
+ const isPromptBlocked = blockedPrompt !== undefined && blockedPrompt === value;
const setModelAndProviderOnSelect = useImageStore((s) => s.setModelAndProviderOnSelect);
const activeGenerationTopicId = useImageStore(generationTopicSelectors.activeGenerationTopicId);
const activeGenerationTopic = useImageStore((s) =>
@@ -288,6 +293,11 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
isCreating={isCreating}
isDarkMode={isDarkMode}
value={value}
+ header={
+ isPromptBlocked ? (
+ <GenerationPromptBlockedNotice onClose={dismissBlockedPrompt} />
+ ) : undefined
+ }
inlineContent={
showInlineRef ? (
<InlineImageReference
diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
index 585b71338a9..35813d3e83c 100644
--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx
@@ -29,6 +29,7 @@ import {
ConfigAction,
GenerationMediaModeSegment,
GenerationModelNotice,
+ GenerationPromptBlockedNotice,
GenerationPromptInput,
GenerationVisibilitySelector,
InlineVideoFrames,
@@ -324,6 +325,10 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
const isCreating = useVideoStore(createVideoSelectors.isCreating);
const createVideo = useVideoStore((s) => s.createVideo);
const cancelEditingVideo = useVideoStore((s) => s.cancelEditingVideo);
+ const blockedPrompt = useVideoStore(createVideoSelectors.blockedPrompt);
+ const dismissBlockedPrompt = useVideoStore((s) => s.dismissBlockedPrompt);
+ // Editing the prompt dismisses the notice: it only describes the submitted text.
+ const isPromptBlocked = blockedPrompt !== undefined && blockedPrompt === value;
const editingGenerationId = useVideoStore(createVideoSelectors.editingGenerationId);
const currentGenerationBatches = useVideoStore(generationBatchSelectors.currentGenerationBatches);
const editingBatch = useMemo(() => {
@@ -594,14 +599,21 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {
: 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)}
- />
+ editingGenerationId || isPromptBlocked ? (
+ <>
+ {editingGenerationId && (
+ <EditingVideoHeader
+ coverUrl={editingAsset?.coverUrl || editingAsset?.thumbnailUrl}
+ prompt={editingBatch?.prompt}
+ version={versionMap.get(editingGenerationId)?.version ?? 1}
+ onCancel={cancelEditingVideo}
+ onLocate={() => revealVideoGeneration(editingGenerationId)}
+ />
+ )}
+ {isPromptBlocked && (
+ <GenerationPromptBlockedNotice onClose={dismissBlockedPrompt} />
+ )}
+ </>
) : undefined
}
inlineContent={
diff --git a/src/store/image/slices/createImage/action.test.ts b/src/store/image/slices/createImage/action.test.ts
index 492c775c1f0..974ca25fdc2 100644
--- a/src/store/image/slices/createImage/action.test.ts
+++ b/src/store/image/slices/createImage/action.test.ts
@@ -4,13 +4,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { imageService } from '@/services/image';
import { useImageStore } from '@/store/image';
-const { handleGenerationPromptModerationErrorMock } = vi.hoisted(() => ({
- handleGenerationPromptModerationErrorMock: vi.fn(),
+const { isGenerationPromptModerationErrorMock, toastErrorMock } = vi.hoisted(() => ({
+ isGenerationPromptModerationErrorMock: vi.fn(),
+ toastErrorMock: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ toast: { error: toastErrorMock },
}));
// Mock external dependencies
-vi.mock('@/business/client/handleGenerationPromptModerationError', () => ({
- handleGenerationPromptModerationError: handleGenerationPromptModerationErrorMock,
+vi.mock('@/business/client/isGenerationPromptModerationError', () => ({
+ isGenerationPromptModerationError: isGenerationPromptModerationErrorMock,
}));
vi.mock('@/services/image', () => ({
@@ -48,6 +54,7 @@ describe('CreateImageAction', () => {
const initialState = useImageStore.getState();
useImageStore.setState({
...initialState,
+ blockedPrompt: undefined,
isCreating: false,
isCreatingWithNewTopic: false,
activeGenerationTopicId: 'active-topic-id',
@@ -210,7 +217,7 @@ describe('CreateImageAction', () => {
// The service should have been called before the error
expect(mockImageService.createImage).toHaveBeenCalled();
- expect(handleGenerationPromptModerationErrorMock).toHaveBeenCalledWith(error);
+ expect(isGenerationPromptModerationErrorMock).toHaveBeenCalledWith(error);
// Verify prompt is NOT cleared when error occurs
expect(result.current.parameters?.prompt).toBe('test prompt');
@@ -248,12 +255,65 @@ describe('CreateImageAction', () => {
// Verify topic was created before the error
expect(mockCreateGenerationTopic).toHaveBeenCalled();
expect(mockSwitchGenerationTopic).toHaveBeenCalled();
- expect(handleGenerationPromptModerationErrorMock).toHaveBeenCalledWith(error);
+ expect(isGenerationPromptModerationErrorMock).toHaveBeenCalledWith(error);
// Verify prompt is NOT cleared when error occurs
expect(result.current.parameters?.prompt).toBe('test prompt');
});
+ it('should keep a moderation-rejected prompt for the inline notice', async () => {
+ const error = new Error('blocked');
+ mockImageService.createImage.mockRejectedValueOnce(error);
+ isGenerationPromptModerationErrorMock.mockReturnValueOnce(true);
+
+ const { result } = renderHook(() => useImageStore());
+
+ await expect(
+ act(async () => {
+ await result.current.createImage();
+ }),
+ ).rejects.toThrow('blocked');
+
+ // A rejected act does not re-render the hook, so read the store directly.
+ expect(useImageStore.getState().blockedPrompt).toBe('test prompt');
+ expect(useImageStore.getState().parameters?.prompt).toBe('test prompt');
+ expect(toastErrorMock).not.toHaveBeenCalled();
+
+ act(() => {
+ useImageStore.getState().dismissBlockedPrompt();
+ });
+ expect(useImageStore.getState().blockedPrompt).toBeUndefined();
+ });
+
+ it('should clear a previous moderation rejection when submitting again', async () => {
+ act(() => {
+ useImageStore.setState({
+ blockedPrompt: 'test prompt',
+ refreshGenerationBatches: vi.fn().mockResolvedValue(undefined),
+ });
+ });
+ const { result } = renderHook(() => useImageStore());
+
+ await act(async () => {
+ await result.current.createImage();
+ });
+
+ expect(useImageStore.getState().blockedPrompt).toBeUndefined();
+ });
+
+ it('should not mark the prompt as blocked for other errors', async () => {
+ mockImageService.createImage.mockRejectedValueOnce(new Error('Service error'));
+ const { result } = renderHook(() => useImageStore());
+
+ await expect(
+ act(async () => {
+ await result.current.createImage();
+ }),
+ ).rejects.toThrow('Service error');
+
+ expect(useImageStore.getState().blockedPrompt).toBeUndefined();
+ });
+
it('should clear prompt input after successful image creation', async () => {
const mockRefreshGenerationBatches = vi.fn().mockResolvedValue(undefined);
const { result } = renderHook(() => useImageStore());
@@ -368,7 +428,29 @@ describe('CreateImageAction', () => {
// Verify batch was removed before the error
expect(mockRemoveGenerationBatch).toHaveBeenCalledWith('batch-id', 'active-topic-id');
- expect(handleGenerationPromptModerationErrorMock).toHaveBeenCalledWith(error);
+ expect(isGenerationPromptModerationErrorMock).toHaveBeenCalledWith(error);
+ });
+
+ it('should toast a moderation rejection instead of marking the input', async () => {
+ mockImageService.createImage.mockRejectedValueOnce(new Error('blocked'));
+ isGenerationPromptModerationErrorMock.mockReturnValueOnce(true);
+ const { result } = renderHook(() => useImageStore());
+
+ act(() => {
+ useImageStore.setState({ removeGenerationBatch: vi.fn().mockResolvedValue(undefined) });
+ });
+
+ let caught: unknown;
+ await act(async () => {
+ try {
+ await result.current.recreateImage('batch-id');
+ } catch (e) {
+ caught = e;
+ }
+ });
+ expect((caught as Error)?.message).toBe('blocked');
+ expect(toastErrorMock).toHaveBeenCalledTimes(1);
+ expect(useImageStore.getState().blockedPrompt).toBeUndefined();
});
it('should handle batch removal error', async () => {
diff --git a/src/store/image/slices/createImage/action.ts b/src/store/image/slices/createImage/action.ts
index 558fe46409f..f398ee2f778 100644
--- a/src/store/image/slices/createImage/action.ts
+++ b/src/store/image/slices/createImage/action.ts
@@ -1,5 +1,8 @@
-import { handleGenerationPromptModerationError } from '@/business/client/handleGenerationPromptModerationError';
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
import { handleLobeHubModelDeprecatedError } from '@/business/client/handleLobeHubModelDeprecatedError';
+import { isGenerationPromptModerationError } from '@/business/client/isGenerationPromptModerationError';
import { imageService } from '@/services/image';
import { type StoreSetter } from '@/store/types';
@@ -24,7 +27,11 @@ export class CreateImageActionImpl {
}
async createImage() {
- this.#set({ isCreating: true }, false, 'createImage/startCreateImage');
+ this.#set(
+ { blockedPrompt: undefined, isCreating: true },
+ false,
+ 'createImage/startCreateImage',
+ );
const store = this.#get();
const imageNum = imageGenerationConfigSelectors.imageNum(store);
@@ -95,7 +102,10 @@ export class CreateImageActionImpl {
'createImage/clearPrompt',
);
} catch (error) {
- handleGenerationPromptModerationError(error);
+ // A rejected prompt is shown on the prompt input, where the user fixes it.
+ if (isGenerationPromptModerationError(error)) {
+ this.#set({ blockedPrompt: parameters.prompt }, false, 'createImage/promptBlocked');
+ }
handleLobeHubModelDeprecatedError(error);
throw error;
} finally {
@@ -112,6 +122,10 @@ export class CreateImageActionImpl {
}
}
+ dismissBlockedPrompt() {
+ this.#set({ blockedPrompt: undefined }, false, 'dismissBlockedPrompt');
+ }
+
async recreateImage(generationBatchId: string) {
this.#set({ isCreating: true }, false, 'recreateImage/startCreateImage');
@@ -143,7 +157,11 @@ export class CreateImageActionImpl {
// 3. Refresh generation batches to show the real data
await store.refreshGenerationBatches();
} catch (error) {
- handleGenerationPromptModerationError(error);
+ // Regenerating reuses the batch's prompt, not the input's, so there is no
+ // input to annotate; fall back to a toast.
+ if (isGenerationPromptModerationError(error)) {
+ toast.error(t('generation.promptModeration.blocked', { ns: 'common' }));
+ }
handleLobeHubModelDeprecatedError(error);
throw error;
} finally {
diff --git a/src/store/image/slices/createImage/initialState.ts b/src/store/image/slices/createImage/initialState.ts
index 60d7d321b42..3480e967e76 100644
--- a/src/store/image/slices/createImage/initialState.ts
+++ b/src/store/image/slices/createImage/initialState.ts
@@ -1,9 +1,16 @@
export interface CreateImageState {
+ /**
+ * Prompt the last submit was rejected for by content moderation. The prompt
+ * input shows an inline notice while its value still equals this prompt, so
+ * editing the prompt dismisses it.
+ */
+ blockedPrompt?: string;
isCreating: boolean;
isCreatingWithNewTopic: boolean;
}
export const initialCreateImageState: CreateImageState = {
+ blockedPrompt: undefined,
isCreating: false,
isCreatingWithNewTopic: false,
};
diff --git a/src/store/image/slices/createImage/selectors.ts b/src/store/image/slices/createImage/selectors.ts
index 6f4abc36633..c0a8aa2b5a1 100644
--- a/src/store/image/slices/createImage/selectors.ts
+++ b/src/store/image/slices/createImage/selectors.ts
@@ -1,9 +1,11 @@
import { type ImageStore } from '../../store';
+const blockedPrompt = (state: ImageStore) => state.blockedPrompt;
const isCreating = (state: ImageStore) => state.isCreating;
const isCreatingWithNewTopic = (state: ImageStore) => state.isCreatingWithNewTopic;
export const createImageSelectors = {
+ blockedPrompt,
isCreating,
isCreatingWithNewTopic,
};
diff --git a/src/store/image/slices/generationBatch/action.ts b/src/store/image/slices/generationBatch/action.ts
index b24c4d5d6a3..dfc58d12f64 100644
--- a/src/store/image/slices/generationBatch/action.ts
+++ b/src/store/image/slices/generationBatch/action.ts
@@ -9,6 +9,7 @@ import { type GetGenerationStatusResult } from '@/server/routers/lambda/generati
import { generationService } from '@/services/generation';
import { generationBatchService } from '@/services/generationBatch';
import { type StoreSetter } from '@/store/types';
+import { getGenerationStatusPollingInterval } from '@/store/utils/generationStatusPolling';
import { AsyncTaskStatus } from '@/types/asyncTask';
import { type GenerationBatch } from '@/types/generation';
import { setNamespace } from '@/utils/storeDebug';
@@ -195,32 +196,12 @@ export class GenerationBatchActionImpl {
},
{
refreshWhenHidden: false,
- refreshInterval: (data: GetGenerationStatusResult | undefined) => {
- // If status is success or error, stop polling
- if (data?.status === AsyncTaskStatus.Success || data?.status === AsyncTaskStatus.Error) {
- return 0; // Stop polling
- }
-
- // Dynamically adjust interval based on request count: use exponential backoff algorithm
- // Base interval 1 second, max interval 30 seconds
- const baseInterval = 1000;
- const maxInterval = 30_000;
- const currentCount = requestCountRef.current;
-
- // Exponential backoff: double the interval every 5 requests
- const backoffMultiplier = Math.floor(currentCount / 5);
- let dynamicInterval = Math.min(
- baseInterval * Math.pow(2, backoffMultiplier),
- maxInterval,
- );
-
- // If there was a previous error, use a longer interval (multiply by 2)
- if (isErrorRef.current) {
- dynamicInterval = Math.min(dynamicInterval * 2, maxInterval);
- }
-
- return dynamicInterval;
- },
+ refreshInterval: (data: GetGenerationStatusResult | undefined) =>
+ getGenerationStatusPollingInterval({
+ hasError: isErrorRef.current,
+ requestCount: requestCountRef.current,
+ status: data?.status,
+ }),
onError: (error) => {
// Set error state when an error occurs
isErrorRef.current = true;
diff --git a/src/store/utils/generationStatusPolling.test.ts b/src/store/utils/generationStatusPolling.test.ts
new file mode 100644
index 00000000000..e99fb543f64
--- /dev/null
+++ b/src/store/utils/generationStatusPolling.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { AsyncTaskStatus } from '@/types/asyncTask';
+
+import { getGenerationStatusPollingInterval } from './generationStatusPolling';
+
+describe('getGenerationStatusPollingInterval', () => {
+ it.each([AsyncTaskStatus.Success, AsyncTaskStatus.Error])(
+ 'stops polling once the task is %s',
+ (status) => {
+ expect(getGenerationStatusPollingInterval({ hasError: false, requestCount: 3, status })).toBe(
+ 0,
+ );
+ },
+ );
+
+ it.each([
+ [0, 1000],
+ [4, 1000],
+ [5, 2000],
+ [10, 4000],
+ [15, 5000],
+ [100, 5000],
+ ])('after %i requests polls every %ims', (requestCount, expected) => {
+ expect(
+ getGenerationStatusPollingInterval({
+ hasError: false,
+ requestCount,
+ status: AsyncTaskStatus.Processing,
+ }),
+ ).toBe(expected);
+ });
+
+ it('keeps long-running tasks within 5s of completion instead of 30s', () => {
+ expect(getGenerationStatusPollingInterval({ hasError: false, requestCount: 40 })).toBe(5000);
+ });
+
+ it('backs off further after a failed status request', () => {
+ expect(getGenerationStatusPollingInterval({ hasError: true, requestCount: 0 })).toBe(2000);
+ expect(getGenerationStatusPollingInterval({ hasError: true, requestCount: 100 })).toBe(10_000);
+ });
+});
diff --git a/src/store/utils/generationStatusPolling.ts b/src/store/utils/generationStatusPolling.ts
new file mode 100644
index 00000000000..342f5496776
--- /dev/null
+++ b/src/store/utils/generationStatusPolling.ts
@@ -0,0 +1,39 @@
+import { AsyncTaskStatus } from '@/types/asyncTask';
+
+const BASE_INTERVAL_MS = 1000;
+/**
+ * Cap for the normal polling interval. A long cap delays showing a finished
+ * generation: with the former 30s cap, a multi-minute video stayed on screen as
+ * "generating" for ~15s on average after it completed (LOBE-8250). The status
+ * query is a cheap primary-key read, so a short cap is affordable.
+ */
+const MAX_INTERVAL_MS = 5000;
+/** Cap once the last status request failed, so outages back off further. */
+const MAX_ERROR_INTERVAL_MS = 10_000;
+const REQUESTS_PER_BACKOFF_STEP = 5;
+
+interface GenerationStatusPollingState {
+ /** Whether the latest status request failed. */
+ hasError: boolean;
+ /** Number of status requests sent so far. */
+ requestCount: number;
+ /** Latest known task status. */
+ status?: AsyncTaskStatus;
+}
+
+/**
+ * SWR `refreshInterval` for image/video generation status polling: stop once the
+ * task is terminal, otherwise double from 1s every 5 requests up to the cap.
+ */
+export const getGenerationStatusPollingInterval = ({
+ hasError,
+ requestCount,
+ status,
+}: GenerationStatusPollingState): number => {
+ if (status === AsyncTaskStatus.Success || status === AsyncTaskStatus.Error) return 0;
+
+ const backoffStep = Math.floor(requestCount / REQUESTS_PER_BACKOFF_STEP);
+ const interval = Math.min(BASE_INTERVAL_MS * 2 ** backoffStep, MAX_INTERVAL_MS);
+
+ return hasError ? Math.min(interval * 2, MAX_ERROR_INTERVAL_MS) : interval;
+};
diff --git a/src/store/video/slices/createVideo/action.test.ts b/src/store/video/slices/createVideo/action.test.ts
index 8e72f3b2a6a..ffaeb608106 100644
--- a/src/store/video/slices/createVideo/action.test.ts
+++ b/src/store/video/slices/createVideo/action.test.ts
@@ -19,8 +19,12 @@ const omniModel: AIVideoModelCard = {
type: 'video',
};
-vi.mock('@/business/client/handleGenerationPromptModerationError', () => ({
- handleGenerationPromptModerationError: vi.fn(),
+const { isGenerationPromptModerationErrorMock } = vi.hoisted(() => ({
+ isGenerationPromptModerationErrorMock: vi.fn(),
+}));
+
+vi.mock('@/business/client/isGenerationPromptModerationError', () => ({
+ isGenerationPromptModerationError: isGenerationPromptModerationErrorMock,
}));
vi.mock('@/business/client/handleLobeHubModelDeprecatedError', () => ({
handleLobeHubModelDeprecatedError: vi.fn(),
@@ -50,6 +54,7 @@ describe('CreateVideoAction', () => {
useVideoStore.setState({
activeGenerationTopicId: 'topic-1',
+ blockedPrompt: undefined,
editingDraftSnapshot: undefined,
editingGenerationId: undefined,
isCreating: false,
@@ -163,6 +168,25 @@ describe('CreateVideoAction', () => {
expect(result.current.parameters.prompt).toBe('Keep the subject still');
});
+ it('should keep a moderation-rejected prompt for the inline notice and clear it on resubmit', async () => {
+ vi.mocked(videoService.createVideo).mockRejectedValueOnce(new Error('blocked'));
+ isGenerationPromptModerationErrorMock.mockReturnValueOnce(true);
+
+ await expect(useVideoStore.getState().createVideo()).rejects.toThrow('blocked');
+ expect(useVideoStore.getState().blockedPrompt).toBe('An unrelated draft');
+ expect(useVideoStore.getState().parameters?.prompt).toBe('An unrelated draft');
+
+ await useVideoStore.getState().createVideo();
+ expect(useVideoStore.getState().blockedPrompt).toBeUndefined();
+ });
+
+ it('should not mark the prompt as blocked for other errors', async () => {
+ vi.mocked(videoService.createVideo).mockRejectedValueOnce(new Error('Service error'));
+
+ await expect(useVideoStore.getState().createVideo()).rejects.toThrow('Service error');
+ expect(useVideoStore.getState().blockedPrompt).toBeUndefined();
+ });
+
it('should restore the original draft when editing is cancelled', () => {
const { result } = renderHook(() => useVideoStore());
diff --git a/src/store/video/slices/createVideo/action.ts b/src/store/video/slices/createVideo/action.ts
index 01193e10163..46e6c74f6ea 100644
--- a/src/store/video/slices/createVideo/action.ts
+++ b/src/store/video/slices/createVideo/action.ts
@@ -2,8 +2,8 @@ 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 { isGenerationPromptModerationError } from '@/business/client/isGenerationPromptModerationError';
import { videoService } from '@/services/video';
import { type StoreSetter } from '@/store/types';
import { preserveSupportedParams } from '@/store/utils/preserveSupportedParams';
@@ -80,7 +80,11 @@ export class CreateVideoActionImpl {
}
createVideo = async (): Promise<void> => {
- this.#set({ isCreating: true }, false, 'createVideo/startCreateVideo');
+ this.#set(
+ { blockedPrompt: undefined, isCreating: true },
+ false,
+ 'createVideo/startCreateVideo',
+ );
const store = this.#get();
const parameters = videoGenerationConfigSelectors.parameters(store);
@@ -169,7 +173,10 @@ export class CreateVideoActionImpl {
'createVideo/clearPrompt',
);
} catch (error) {
- handleGenerationPromptModerationError(error);
+ // A rejected prompt is shown on the prompt input, where the user fixes it.
+ if (isGenerationPromptModerationError(error)) {
+ this.#set({ blockedPrompt: parameters.prompt }, false, 'createVideo/promptBlocked');
+ }
handleLobeHubModelDeprecatedError(error);
throw error;
} finally {
@@ -186,6 +193,10 @@ export class CreateVideoActionImpl {
}
};
+ dismissBlockedPrompt = (): void => {
+ this.#set({ blockedPrompt: undefined }, false, 'dismissBlockedPrompt');
+ };
+
cancelEditingVideo = (): void => {
this.#set((state) => restoreEditingDraft(state), false, 'cancelEditingVideo');
};
@@ -214,7 +225,11 @@ export class CreateVideoActionImpl {
await store.refreshGenerationBatches();
} catch (error) {
- handleGenerationPromptModerationError(error);
+ // Regenerating reuses the batch's prompt, not the input's, so there is no
+ // input to annotate; fall back to a toast.
+ if (isGenerationPromptModerationError(error)) {
+ toast.error(t('generation.promptModeration.blocked', { ns: 'common' }));
+ }
handleLobeHubModelDeprecatedError(error);
throw error;
} finally {
diff --git a/src/store/video/slices/createVideo/initialState.ts b/src/store/video/slices/createVideo/initialState.ts
index f1c03f94883..4d6e0d7258c 100644
--- a/src/store/video/slices/createVideo/initialState.ts
+++ b/src/store/video/slices/createVideo/initialState.ts
@@ -13,6 +13,12 @@ export interface VideoEditingDraftSnapshot {
}
export interface CreateVideoState {
+ /**
+ * Prompt the last submit was rejected for by content moderation. The prompt
+ * input shows an inline notice while its value still equals this prompt, so
+ * editing the prompt dismisses it.
+ */
+ blockedPrompt?: string;
editingDraftSnapshot?: VideoEditingDraftSnapshot;
editingGenerationId?: string;
isCreating: boolean;
@@ -20,6 +26,7 @@ export interface CreateVideoState {
}
export const initialCreateVideoState: CreateVideoState = {
+ blockedPrompt: undefined,
editingDraftSnapshot: undefined,
editingGenerationId: undefined,
isCreating: false,
diff --git a/src/store/video/slices/createVideo/selectors.ts b/src/store/video/slices/createVideo/selectors.ts
index 0b39e709290..729517678f8 100644
--- a/src/store/video/slices/createVideo/selectors.ts
+++ b/src/store/video/slices/createVideo/selectors.ts
@@ -1,10 +1,12 @@
import { type VideoStore } from '../../store';
+const blockedPrompt = (state: VideoStore) => state.blockedPrompt;
const editingGenerationId = (state: VideoStore) => state.editingGenerationId;
const isCreating = (state: VideoStore) => state.isCreating;
const isCreatingWithNewTopic = (state: VideoStore) => state.isCreatingWithNewTopic;
export const createVideoSelectors = {
+ blockedPrompt,
editingGenerationId,
isCreating,
isCreatingWithNewTopic,
diff --git a/src/store/video/slices/generationBatch/action.ts b/src/store/video/slices/generationBatch/action.ts
index dbf0d9cc2ed..8c7e798ed3c 100644
--- a/src/store/video/slices/generationBatch/action.ts
+++ b/src/store/video/slices/generationBatch/action.ts
@@ -9,6 +9,7 @@ import { type GetGenerationStatusResult } from '@/server/routers/lambda/generati
import { generationService } from '@/services/generation';
import { generationBatchService } from '@/services/generationBatch';
import { type StoreSetter } from '@/store/types';
+import { getGenerationStatusPollingInterval } from '@/store/utils/generationStatusPolling';
import { AsyncTaskStatus } from '@/types/asyncTask';
import { type GenerationBatch } from '@/types/generation';
import { setNamespace } from '@/utils/storeDebug';
@@ -240,27 +241,12 @@ export class GenerationBatchActionImpl {
await this.#get().refreshGenerationBatches();
}
},
- refreshInterval: (data: GetGenerationStatusResult | undefined) => {
- if (data?.status === AsyncTaskStatus.Success || data?.status === AsyncTaskStatus.Error) {
- return 0;
- }
-
- const baseInterval = 1000;
- const maxInterval = 30_000;
- const currentCount = requestCountRef.current;
-
- const backoffMultiplier = Math.floor(currentCount / 5);
- let dynamicInterval = Math.min(
- baseInterval * Math.pow(2, backoffMultiplier),
- maxInterval,
- );
-
- if (isErrorRef.current) {
- dynamicInterval = Math.min(dynamicInterval * 2, maxInterval);
- }
-
- return dynamicInterval;
- },
+ refreshInterval: (data: GetGenerationStatusResult | undefined) =>
+ getGenerationStatusPollingInterval({
+ hasError: isErrorRef.current,
+ requestCount: requestCountRef.current,
+ status: data?.status,
+ }),
refreshWhenHidden: false,
},
);