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(image-generation): immersive "develop from blur" canvas for generateImage (#19931)

Arvin Xu6ee6848ac1ff
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 95e59cef6af..8991f3f698b 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -314,6 +314,8 @@
"builtins.lobe-group-management.inspector.speak.title": "Designated Agent speaks:",
"builtins.lobe-group-management.title": "Group Coordinator",
"builtins.lobe-image-generation.apiName.generateImage": "Generate image",
+ "builtins.lobe-image-generation.apiName.generateImage.completed": "Created image",
+ "builtins.lobe-image-generation.apiName.generateImage.loading": "Creating image",
"builtins.lobe-image-generation.apiName.getImageGenerationStatus": "Check image status",
"builtins.lobe-image-generation.apiName.getImageModelParameters": "Inspect model parameters",
"builtins.lobe-image-generation.apiName.listImageModels": "List image models",
@@ -333,6 +335,7 @@
"builtins.lobe-image-generation.render.parameterList.parameters_one": "{{count}} parameter",
"builtins.lobe-image-generation.render.parameterList.parameters_other": "{{count}} parameters",
"builtins.lobe-image-generation.render.retry": "Retry",
+ "builtins.lobe-image-generation.render.status.elapsed": "{{status}} · {{seconds}}s",
"builtins.lobe-image-generation.render.status.error": "Failed",
"builtins.lobe-image-generation.render.status.pending": "Pending",
"builtins.lobe-image-generation.render.status.processing": "Generating",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index ce5c4e74432..9bead01ba70 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -314,6 +314,8 @@
"builtins.lobe-group-management.inspector.speak.title": "指定 Agent 发言:",
"builtins.lobe-group-management.title": "群组协调",
"builtins.lobe-image-generation.apiName.generateImage": "生成图片",
+ "builtins.lobe-image-generation.apiName.generateImage.completed": "已创建图片",
+ "builtins.lobe-image-generation.apiName.generateImage.loading": "正在创建图片",
"builtins.lobe-image-generation.apiName.getImageGenerationStatus": "检查图片状态",
"builtins.lobe-image-generation.apiName.getImageModelParameters": "查看模型参数",
"builtins.lobe-image-generation.apiName.listImageModels": "查看生图模型",
@@ -333,6 +335,7 @@
"builtins.lobe-image-generation.render.parameterList.parameters_one": "{{count}} 个参数",
"builtins.lobe-image-generation.render.parameterList.parameters_other": "{{count}} 个参数",
"builtins.lobe-image-generation.render.retry": "重试",
+ "builtins.lobe-image-generation.render.status.elapsed": "{{status}} · {{seconds}} 秒",
"builtins.lobe-image-generation.render.status.error": "失败",
"builtins.lobe-image-generation.render.status.pending": "等待中",
"builtins.lobe-image-generation.render.status.processing": "生成中",
diff --git a/packages/builtin-tool-image-generation/src/client/Inspector/generateImageLabel.test.ts b/packages/builtin-tool-image-generation/src/client/Inspector/generateImageLabel.test.ts
new file mode 100644
index 00000000000..8d36fe990e6
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/Inspector/generateImageLabel.test.ts
@@ -0,0 +1,49 @@
+import { AsyncTaskStatus } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { GeneratedImageTask } from '../../types';
+import { getGenerateImageLabelTense } from './generateImageLabel';
+
+const task = (status: GeneratedImageTask['status']): GeneratedImageTask => ({
+ asyncTaskId: 'task',
+ generationId: 'gen',
+ status,
+});
+
+describe('getGenerateImageLabelTense', () => {
+ it('uses the progressive tense while arguments stream or the tool runs', () => {
+ expect(getGenerateImageLabelTense(true)).toBe('loading');
+ expect(getGenerateImageLabelTense(true, { generations: [task(AsyncTaskStatus.Success)] })).toBe(
+ 'loading',
+ );
+ });
+
+ it('claims completion only when every image succeeded', () => {
+ expect(
+ getGenerateImageLabelTense(false, {
+ generations: [task(AsyncTaskStatus.Success), task(AsyncTaskStatus.Success)],
+ }),
+ ).toBe('completed');
+ });
+
+ it('does not claim completion while images are still in flight', () => {
+ expect(
+ getGenerateImageLabelTense(false, {
+ generations: [task(AsyncTaskStatus.Success), task(AsyncTaskStatus.Processing)],
+ }),
+ ).toBe('neutral');
+ expect(
+ getGenerateImageLabelTense(false, { generations: [task(AsyncTaskStatus.Pending)] }),
+ ).toBe('neutral');
+ });
+
+ it('does not claim completion when an image failed or nothing was returned', () => {
+ expect(
+ getGenerateImageLabelTense(false, {
+ generations: [task(AsyncTaskStatus.Success), task(AsyncTaskStatus.Error)],
+ }),
+ ).toBe('neutral');
+ expect(getGenerateImageLabelTense(false, { generations: [] })).toBe('neutral');
+ expect(getGenerateImageLabelTense(false)).toBe('neutral');
+ });
+});
diff --git a/packages/builtin-tool-image-generation/src/client/Inspector/generateImageLabel.ts b/packages/builtin-tool-image-generation/src/client/Inspector/generateImageLabel.ts
new file mode 100644
index 00000000000..6eae60ef215
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/Inspector/generateImageLabel.ts
@@ -0,0 +1,25 @@
+import { AsyncTaskStatus } from '@lobechat/types';
+
+import type { GenerateImageState } from '../../types';
+
+export type GenerateImageLabelTense = 'completed' | 'loading' | 'neutral';
+
+/**
+ * The row stays in the chat history, so its tense must match what the canvas
+ * below shows. A returned call is only "created" once every image succeeded —
+ * a call that returned with images still in flight, or with a failed image,
+ * falls back to the neutral action name instead of claiming completion.
+ */
+export const getGenerateImageLabelTense = (
+ isRunning: boolean | undefined,
+ pluginState?: Partial<GenerateImageState> | null,
+): GenerateImageLabelTense => {
+ if (isRunning) return 'loading';
+
+ const generations = pluginState?.generations;
+ if (!generations?.length) return 'neutral';
+
+ return generations.every((task) => task.status === AsyncTaskStatus.Success)
+ ? 'completed'
+ : 'neutral';
+};
diff --git a/packages/builtin-tool-image-generation/src/client/Inspector/index.tsx b/packages/builtin-tool-image-generation/src/client/Inspector/index.tsx
index 1ae7727be1e..56ecc849bd4 100644
--- a/packages/builtin-tool-image-generation/src/client/Inspector/index.tsx
+++ b/packages/builtin-tool-image-generation/src/client/Inspector/index.tsx
@@ -8,7 +8,9 @@ import { useTranslation } from 'react-i18next';
import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+import type { GenerateImageState } from '../../types';
import { ImageGenerationApiName } from '../../types';
+import { getGenerateImageLabelTense } from './generateImageLabel';
const styles = createStaticStyles(({ css, cssVar }) => ({
chip: css`
@@ -59,7 +61,6 @@ const compactId = (id: string) => (id.length > 14 ? `${id.slice(0, 7)}…${id.sl
interface ImageGenerationInspectorArgs {
generationId?: unknown;
- imageNum?: unknown;
model?: unknown;
prompt?: unknown;
provider?: unknown;
@@ -84,52 +85,45 @@ const apiMeta = {
},
};
-const ImageGenerationInspector = memo<BuiltinInspectorProps<ImageGenerationInspectorArgs, unknown>>(
- ({ apiName, args, partialArgs, isArgumentsStreaming, isLoading }) => {
- const { t } = useTranslation('plugin');
- const currentArgs = { ...partialArgs, ...args };
- const provider = stringValue(currentArgs.provider);
- const model = stringValue(currentArgs.model);
- const prompt = stringValue(currentArgs.prompt);
- const generationId = stringValue(currentArgs.generationId);
- const meta = apiMeta[apiName as ImageGenerationApiName] ?? apiMeta.generateImage;
- const imageNum = typeof currentArgs.imageNum === 'number' ? currentArgs.imageNum : undefined;
- const label = t(`builtins.lobe-image-generation.apiName.${apiName}`, {
- defaultValue: meta.defaultLabel,
- });
- const Icon = meta.Icon;
-
- return (
- <div className={cx(inspectorTextStyles.root, styles.root)}>
- <Icon className={styles.icon} size={14} />
- <span
- className={cx(
- styles.label,
- (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
- )}
- >
- {label}
- </span>
- {apiName === ImageGenerationApiName.generateImage && prompt && (
- <span className={cx(highlightTextStyles.primary, styles.prompt)}>{prompt}</span>
- )}
- {apiName === ImageGenerationApiName.generateImage && imageNum && imageNum > 1 && (
- <span className={styles.chip}>
- {t('builtins.lobe-image-generation.render.generatedCount', {
- count: imageNum,
- defaultValue: '{{count}} images',
- })}
- </span>
- )}
- {provider && <span className={styles.chip}>{provider}</span>}
- {model && <span className={styles.chip}>{model}</span>}
- {apiName === ImageGenerationApiName.getImageGenerationStatus && generationId && (
- <span className={styles.chip}>{compactId(generationId)}</span>
- )}
- </div>
- );
- },
-);
+const ImageGenerationInspector = memo<
+ BuiltinInspectorProps<ImageGenerationInspectorArgs, Partial<GenerateImageState>>
+>(({ apiName, args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+ const currentArgs = { ...partialArgs, ...args };
+ const provider = stringValue(currentArgs.provider);
+ const model = stringValue(currentArgs.model);
+ const prompt = stringValue(currentArgs.prompt);
+ const generationId = stringValue(currentArgs.generationId);
+ const meta = apiMeta[apiName as ImageGenerationApiName] ?? apiMeta.generateImage;
+ const isGenerateImage = apiName === ImageGenerationApiName.generateImage;
+ const isRunning = isArgumentsStreaming || isLoading;
+ // The canvas below carries model / count / status, so this row only names the
+ // action — and switches tense so old history doesn't read as still running.
+ const tense = getGenerateImageLabelTense(isRunning, pluginState);
+ const label = isGenerateImage
+ ? tense === 'neutral'
+ ? t('builtins.lobe-image-generation.apiName.generateImage')
+ : t(`builtins.lobe-image-generation.apiName.generateImage.${tense}`)
+ : t(`builtins.lobe-image-generation.apiName.${apiName}`, {
+ defaultValue: meta.defaultLabel,
+ });
+ const Icon = meta.Icon;
+
+ return (
+ <div className={cx(inspectorTextStyles.root, styles.root)}>
+ <Icon className={styles.icon} size={14} />
+ <span className={cx(styles.label, isRunning && shinyTextStyles.shinyText)}>{label}</span>
+ {isGenerateImage && prompt && (
+ <span className={cx(highlightTextStyles.primary, styles.prompt)}>{prompt}</span>
+ )}
+ {!isGenerateImage && provider && <span className={styles.chip}>{provider}</span>}
+ {!isGenerateImage && model && <span className={styles.chip}>{model}</span>}
+ {apiName === ImageGenerationApiName.getImageGenerationStatus && generationId && (
+ <span className={styles.chip}>{compactId(generationId)}</span>
+ )}
+ </div>
+ );
+});
ImageGenerationInspector.displayName = 'ImageGenerationInspector';
diff --git a/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx b/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx
index 1ad0d1dccb5..437b8c7e29e 100644
--- a/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx
+++ b/packages/builtin-tool-image-generation/src/client/Render/GenerateImage.tsx
@@ -1,183 +1,57 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block } from '@lobehub/ui';
+import { PreviewGroup } from '@lobehub/ui';
import { Alert, Button, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { memo, useCallback, useEffect, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useClientDataSWR } from '@/libs/swr';
-import { imageKeys } from '@/libs/swr/keys';
+import { downloadPreviewImage } from '@/features/Conversation/Messages/components/downloadPreviewImage';
import { normalizeAsyncError } from '@/libs/swr/normalizeError';
-import { generationService } from '@/services/generation';
-import type {
- GeneratedImageTask,
- GenerateImageParams,
- GenerateImageState,
- GetImageGenerationStatusParams,
- GetImageGenerationStatusState,
-} from '../../types';
-
-const POLLING_INTERVAL = 3000;
+import type { GeneratedImageTask, GenerateImageParams, GenerateImageState } from '../../types';
+import { resolveAspectRatio } from '../components/aspectRatio';
+import { peekGenerationClock } from '../components/generationClock';
+import ImageCanvas from '../components/ImageCanvas';
+import ImageCanvasGrid from '../components/ImageCanvasGrid';
+import {
+ getStateAssetUrl,
+ getStateErrorDetail,
+ getTaskAssetUrl,
+ getTaskErrorDetail,
+ isTerminalStatus,
+ useGenerationStatus,
+} from '../components/useGenerationStatus';
const styles = createStaticStyles(({ css, cssVar }) => ({
- error: css`
- color: ${cssVar.colorError};
- `,
- grid: css`
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(132px, 1fr));
- gap: 10px;
- padding: 12px;
- `,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
- justify-content: space-between;
-
- min-width: 0;
- padding-block: 8px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- image: css`
- width: 100%;
- height: 100%;
- object-fit: cover;
- `,
- meta: css`
- overflow: hidden;
- display: flex;
- flex: 1;
- flex-direction: column;
- gap: 2px;
-
- min-width: 0;
- `,
- model: css`
+ caption: css`
overflow: hidden;
font-family: ${cssVar.fontFamilyCode};
font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- prompt: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
+ color: ${cssVar.colorTextQuaternary};
text-overflow: ellipsis;
white-space: nowrap;
`,
- status: css`
- flex-shrink: 0;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 999px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- tile: css`
- overflow: hidden;
-
- aspect-ratio: 1;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 8px;
-
- background: ${cssVar.colorFillTertiary};
- `,
- tileBody: css`
+ root: css`
display: flex;
flex-direction: column;
gap: 8px;
- align-items: center;
- justify-content: center;
-
- width: 100%;
- height: 100%;
- padding: 12px;
-
- text-align: center;
`,
}));
-const isTerminalStatus = (status?: string) => status === 'success' || status === 'error';
-
-const getAssetUrl = (state?: GetImageGenerationStatusState) => {
- const asset = state?.generation?.asset;
- return asset?.url || asset?.thumbnailUrl || asset?.originalUrl;
-};
-
-const getTaskAssetUrl = (task: GeneratedImageTask) =>
- task.asset?.url || task.asset?.thumbnailUrl || task.asset?.originalUrl;
-
-const getErrorDetail = (state?: GetImageGenerationStatusState) => {
- const error = state?.error;
- if (!error) return;
- const body = error.body;
- if (typeof body === 'string') return body;
- return body.detail;
-};
-
-const getTaskErrorDetail = (task: GeneratedImageTask) => {
- const error = task.error;
- if (!error) return;
- const body = error.body;
- if (typeof body === 'string') return body;
- return body.detail;
-};
-
-const useGenerationStatus = (params: GetImageGenerationStatusParams, enabled: boolean) => {
- const [pollingStopped, setPollingStopped] = useState(false);
-
- useEffect(() => {
- setPollingStopped(false);
- }, [params.asyncTaskId, params.generationId]);
-
- const result = useClientDataSWR<GetImageGenerationStatusState>(
- enabled && params.asyncTaskId
- ? imageKeys.generationStatus(params.generationId, params.asyncTaskId)
- : null,
- async () => {
- const result = await generationService.getGenerationStatus(
- params.generationId,
- params.asyncTaskId,
- );
- return {
- ...result,
- asyncTaskId: params.asyncTaskId,
- generationId: params.generationId,
- };
- },
- {
- onError: () => setPollingStopped(true),
- onSuccess: () => setPollingStopped(false),
- refreshInterval: (data?: GetImageGenerationStatusState) =>
- pollingStopped || isTerminalStatus(data?.status) ? 0 : POLLING_INTERVAL,
- shouldRetryOnError: false,
- },
- );
-
- const { mutate } = result;
- const retry = useCallback(() => {
- setPollingStopped(false);
- void mutate();
- }, [mutate]);
-
- return { ...result, retry };
-};
-
-const GenerationTile = memo<{ index: number; task: GeneratedImageTask }>(({ index, task }) => {
+const GenerationTile = memo<{
+ index: number;
+ parameters?: Record<string, unknown>;
+ /**
+ * Shared footprint for multi-image grids. Omitted for a lone image, which
+ * takes the real ratio of its own asset once it lands.
+ */
+ ratio?: number;
+ startedAt?: number;
+ task: GeneratedImageTask;
+}>(({ index, parameters, ratio: sharedRatio, startedAt, task }) => {
const { t } = useTranslation('plugin');
const shouldFetchStatus = !isTerminalStatus(task.status);
const { data, error, isLoading, isValidating, retry } = useGenerationStatus(
@@ -193,39 +67,36 @@ const GenerationTile = memo<{ index: number; task: GeneratedImageTask }>(({ inde
data?.status ||
task.status ||
(isLoading ? 'processing' : 'pending');
- const url = getTaskAssetUrl(task) || getAssetUrl(data);
+ const url = getTaskAssetUrl(task) || getStateAssetUrl(data);
const errorDetail =
- error instanceof Error ? error.message : getTaskErrorDetail(task) || getErrorDetail(data);
+ error instanceof Error ? error.message : getTaskErrorDetail(task) || getStateErrorDetail(data);
const canRetry = Boolean(error) && normalizeAsyncError(error).retryable;
+ const ratio =
+ sharedRatio ?? resolveAspectRatio(parameters, task.asset ?? data?.generation?.asset);
return (
- <div className={styles.tile}>
- {url ? (
- <img
- alt={t('builtins.lobe-image-generation.render.imageAlt', { index: index + 1 })}
- className={styles.image}
- src={url}
- />
- ) : (
- <div className={styles.tileBody}>
- <Text
- as={'span'}
- className={status === 'error' ? styles.error : undefined}
- color={status === 'error' ? cssVar.colorError : cssVar.colorTextSecondary}
- fontSize={12}
- >
- {status === 'error'
- ? errorDetail || t('builtins.lobe-image-generation.render.status.error')
- : t(`builtins.lobe-image-generation.render.status.${status}`)}
+ <ImageCanvas
+ alt={t('builtins.lobe-image-generation.render.imageAlt', { index: index + 1 })}
+ badge={t(`builtins.lobe-image-generation.render.status.${status}`)}
+ ratio={ratio}
+ seed={index}
+ startedAt={startedAt}
+ url={url}
+ onDownload={downloadPreviewImage}
+ >
+ {status === 'error' && !url && (
+ <>
+ <Text as={'span'} color={cssVar.colorError} fontSize={12}>
+ {errorDetail || t('builtins.lobe-image-generation.render.status.error')}
</Text>
{canRetry && (
<Button loading={isValidating} size={'small'} onClick={retry}>
{t('builtins.lobe-image-generation.render.retry')}
</Button>
)}
- </div>
+ </>
)}
- </div>
+ </ImageCanvas>
);
});
@@ -233,7 +104,7 @@ GenerationTile.displayName = 'GenerationTile';
export const GenerateImageRender = memo<
BuiltinRenderProps<GenerateImageParams, GenerateImageState>
->(({ args, pluginError, pluginState }) => {
+>(({ args, pluginError, pluginState, toolCallId }) => {
const { t } = useTranslation('plugin');
const generations = pluginState?.generations ?? [];
@@ -252,31 +123,30 @@ export const GenerateImageRender = memo<
const provider = pluginState?.provider || args?.provider;
const model = pluginState?.model || args?.model;
- const prompt = pluginState?.prompt || args?.prompt;
+ const parameters = args?.parameters;
+ // Canvases in a grid share one footprint so a finished image never resizes
+ // its cell out of line with the ones still generating.
+ const gridRatio = resolveAspectRatio(parameters, generations[0]?.asset);
+ const isGrid = generations.length > 1;
return (
- <Block variant={'outlined'} width={'100%'}>
- <div className={styles.header}>
- <div className={styles.meta}>
- <div className={styles.prompt}>{prompt}</div>
- <div className={styles.model}>{[provider, model].filter(Boolean).join('/')}</div>
- </div>
- <span className={styles.status}>
- {t('builtins.lobe-image-generation.render.generatedCount', {
- count: generations.length,
- })}
- </span>
- </div>
- <div className={styles.grid}>
- {generations.map((task, index) => (
- <GenerationTile
- index={index}
- key={`${task.generationId}-${task.asyncTaskId}`}
- task={task}
- />
- ))}
- </div>
- </Block>
+ <div className={styles.root}>
+ <PreviewGroup preview={{ onDownload: downloadPreviewImage }}>
+ <ImageCanvasGrid count={generations.length} ratio={gridRatio}>
+ {generations.map((task, index) => (
+ <GenerationTile
+ index={index}
+ key={`${task.generationId}-${task.asyncTaskId}`}
+ parameters={parameters}
+ ratio={isGrid ? gridRatio : undefined}
+ startedAt={peekGenerationClock(toolCallId)}
+ task={task}
+ />
+ ))}
+ </ImageCanvasGrid>
+ </PreviewGroup>
+ {model && <div className={styles.caption}>{[provider, model].filter(Boolean).join('/')}</div>}
+ </div>
);
});
diff --git a/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx b/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx
index 447929c404b..dd89bb52787 100644
--- a/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx
+++ b/packages/builtin-tool-image-generation/src/client/Render/GetImageGenerationStatus.tsx
@@ -1,46 +1,48 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block } from '@lobehub/ui';
-import { Alert, Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
+import { Alert, Button, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { downloadPreviewImage } from '@/features/Conversation/Messages/components/downloadPreviewImage';
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
+
import type { GetImageGenerationStatusParams, GetImageGenerationStatusState } from '../../types';
+import { resolveAspectRatio } from '../components/aspectRatio';
+import ImageCanvas from '../components/ImageCanvas';
+import ImageCanvasGrid from '../components/ImageCanvasGrid';
+import {
+ getStateAssetUrl,
+ getStateErrorDetail,
+ isTerminalStatus,
+ useGenerationStatus,
+} from '../components/useGenerationStatus';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- body: css`
+const styles = createStaticStyles(({ css }) => ({
+ root: css`
display: flex;
flex-direction: column;
gap: 8px;
- padding: 12px;
- `,
- image: css`
- width: 100%;
- max-height: 420px;
- border-radius: 8px;
-
- object-fit: contain;
- background: ${cssVar.colorFillTertiary};
- `,
- status: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
`,
}));
-const getAssetUrl = (state?: GetImageGenerationStatusState) => {
- const asset = state?.generation?.asset;
- return asset?.url || asset?.thumbnailUrl || asset?.originalUrl;
-};
+const getAsset = (state?: GetImageGenerationStatusState) => state?.generation?.asset;
export const GetImageGenerationStatusRender = memo<
BuiltinRenderProps<GetImageGenerationStatusParams, GetImageGenerationStatusState>
>(({ pluginError, pluginState }) => {
const { t } = useTranslation('plugin');
- const url = getAssetUrl(pluginState);
+ // The stored result is the snapshot taken when the tool returned. Keep polling
+ // from there so a card left mid-generation finishes on screen by itself.
+ const { data, error, isValidating, retry } = useGenerationStatus(
+ {
+ asyncTaskId: pluginState?.asyncTaskId as string,
+ generationId: pluginState?.generationId as string,
+ },
+ !!pluginState && !isTerminalStatus(pluginState.status),
+ );
if (pluginError) {
return (
@@ -55,21 +57,41 @@ export const GetImageGenerationStatusRender = memo<
if (!pluginState) return null;
+ const live = data ?? pluginState;
+ const status = error ? 'error' : live.status;
+ const url = getStateAssetUrl(live);
+ const asset = getAsset(live);
+ const ratio = resolveAspectRatio(undefined, asset);
+ const errorDetail = error instanceof Error ? error.message : getStateErrorDetail(live);
+ const canRetry = Boolean(error) && normalizeAsyncError(error).retryable;
+
return (
- <Block variant={'outlined'} width={'100%'}>
- <div className={styles.body}>
- <Text as={'span'} className={styles.status}>
- {pluginState.status}
- </Text>
- {url && (
- <img
- alt={t('builtins.lobe-image-generation.render.imageAlt', { index: 1 })}
- className={styles.image}
- src={url}
- />
- )}
- </div>
- </Block>
+ <div className={styles.root}>
+ {/* Same canvas the generateImage card uses, so a follow-up status check
+ reads as the same image continuing rather than a second card. */}
+ <ImageCanvasGrid count={1} ratio={ratio}>
+ <ImageCanvas
+ alt={t('builtins.lobe-image-generation.render.imageAlt', { index: 1 })}
+ badge={t(`builtins.lobe-image-generation.render.status.${status}`)}
+ ratio={ratio}
+ url={url}
+ onDownload={downloadPreviewImage}
+ >
+ {status === 'error' && !url && (
+ <>
+ <Text as={'span'} color={cssVar.colorError} fontSize={12}>
+ {errorDetail || t('builtins.lobe-image-generation.render.status.error')}
+ </Text>
+ {canRetry && (
+ <Button loading={isValidating} size={'small'} onClick={retry}>
+ {t('builtins.lobe-image-generation.render.retry')}
+ </Button>
+ )}
+ </>
+ )}
+ </ImageCanvas>
+ </ImageCanvasGrid>
+ </div>
);
});
diff --git a/packages/builtin-tool-image-generation/src/client/Streaming/GenerateImage.tsx b/packages/builtin-tool-image-generation/src/client/Streaming/GenerateImage.tsx
new file mode 100644
index 00000000000..b161e7ca601
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/Streaming/GenerateImage.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import type { BuiltinStreamingProps } from '@lobechat/types';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { GenerateImageParams } from '../../types';
+import { resolveAspectRatio } from '../components/aspectRatio';
+import { startGenerationClock } from '../components/generationClock';
+import ImageCanvas from '../components/ImageCanvas';
+import ImageCanvasGrid from '../components/ImageCanvasGrid';
+
+const MAX_CANVASES = 4;
+
+/**
+ * Fills the gap between "the model decided to draw" and "the tool returned":
+ * the same canvases the Render will develop the images on, already in place.
+ */
+export const GenerateImageStreaming = memo<BuiltinStreamingProps<Partial<GenerateImageParams>>>(
+ ({ args, toolCallId }) => {
+ const { t } = useTranslation('plugin');
+ const [startedAt] = useState(() => startGenerationClock(toolCallId));
+ const imageNum = typeof args?.imageNum === 'number' ? args.imageNum : 1;
+ const count = Math.min(MAX_CANVASES, Math.max(1, Math.round(imageNum)));
+ const ratio = resolveAspectRatio(args?.parameters);
+
+ return (
+ <ImageCanvasGrid count={count} ratio={ratio}>
+ {Array.from({ length: count }, (_, index) => (
+ <ImageCanvas
+ badge={t('builtins.lobe-image-generation.render.status.processing')}
+ key={index}
+ ratio={ratio}
+ seed={index}
+ startedAt={startedAt}
+ />
+ ))}
+ </ImageCanvasGrid>
+ );
+ },
+);
+
+GenerateImageStreaming.displayName = 'GenerateImageStreaming';
+
+export default GenerateImageStreaming;
diff --git a/packages/builtin-tool-image-generation/src/client/Streaming/index.ts b/packages/builtin-tool-image-generation/src/client/Streaming/index.ts
new file mode 100644
index 00000000000..c40e074eb75
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/Streaming/index.ts
@@ -0,0 +1,14 @@
+import type { BuiltinStreaming } from '@lobechat/types';
+
+import { ImageGenerationApiName } from '../../types';
+import GenerateImageStreaming from './GenerateImage';
+
+// Registered as a Streaming (not a Placeholder) on purpose: the tool detail only
+// consults Placeholders once a result message exists, while a Streaming renderer
+// also covers the argument-streaming phase — and image generation has no
+// perceivable state in between worth a second component.
+export const ImageGenerationStreamings: Record<string, BuiltinStreaming> = {
+ [ImageGenerationApiName.generateImage]: GenerateImageStreaming as BuiltinStreaming,
+};
+
+export { default as GenerateImageStreaming } from './GenerateImage';
diff --git a/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx b/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx
new file mode 100644
index 00000000000..d5cfe279450
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx
@@ -0,0 +1,314 @@
+'use client';
+
+import { Image } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx, keyframes } from 'antd-style';
+import type { CSSProperties, ReactNode } from 'react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+// Three colour blobs wander on independent, co-prime loops so the aura never
+// visibly repeats.
+const wanderA = keyframes`
+ 0%, 100% { transform: translate(-18%, -12%) scale(1); }
+ 50% { transform: translate(22%, 16%) scale(1.25); }
+`;
+
+const wanderB = keyframes`
+ 0%, 100% { transform: translate(20%, -16%) scale(1.15); }
+ 50% { transform: translate(-16%, 20%) scale(0.9); }
+`;
+
+const wanderC = keyframes`
+ 0%, 100% { transform: translate(0, 24%) scale(0.95); }
+ 50% { transform: translate(-6%, -22%) scale(1.2); }
+`;
+
+// The whole aura keeps reaching for focus and slipping back — the canvas reads
+// as a picture trying to resolve, not as a spinner. Transform and opacity only:
+// animating a filter would repaint the whole canvas every frame.
+const focus = keyframes`
+ 0%, 100% { opacity: 0.8; transform: scale(1.1); }
+ 50% { opacity: 1; transform: scale(0.94); }
+`;
+
+// The finished image comes out of the same blur the aura lives in, so waiting
+// and reveal are one continuous motion. Keyframes rather than a transition: a
+// cached image fires onLoad before the hidden state is painted, and a
+// transition would then skip straight to the end.
+const develop = keyframes`
+ from { opacity: 0; filter: blur(28px) saturate(1.4); transform: scale(1.04); }
+ to { opacity: 1; filter: blur(0) saturate(1); transform: scale(1); }
+`;
+
+// Fine film grain over the aura, so the blur reads as an emulsion developing
+// rather than a flat CSS gradient.
+const GRAIN = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`;
+
+const blob = `
+ position: absolute;
+ inset-block-start: 10%;
+ inset-inline-start: 10%;
+
+ width: 80%;
+ aspect-ratio: 1;
+ border-radius: 50%;
+
+ opacity: 0.75;
+ will-change: transform;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none !important;
+ }
+`;
+
+// Soft falloff baked into the gradient, so no blur filter is needed.
+const glow = (color: string) => {
+ // An eased ramp: linear stops leave a visible rim once there is no blur.
+ const mix = (percent: number) => `color-mix(in srgb, ${color} ${percent}%, transparent)`;
+ return `radial-gradient(circle closest-side, ${color} 0%, ${mix(78)} 18%, ${mix(52)} 36%, ${mix(28)} 54%, ${mix(11)} 72%, ${mix(3)} 88%, transparent 100%)`;
+};
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ aura: css`
+ position: absolute;
+ inset: 0;
+ transition: opacity 700ms ease;
+ `,
+ auraFocus: css`
+ will-change: transform, opacity;
+
+ position: absolute;
+ inset: -20%;
+
+ animation: ${focus} 4.2s ease-in-out infinite;
+ animation-delay: var(--aura-delay, 0s);
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ `,
+ auraHidden: css`
+ opacity: 0;
+ `,
+ auraStill: css`
+ opacity: 0.45;
+ filter: grayscale(1);
+
+ * {
+ animation: none !important;
+ }
+ `,
+ badge: css`
+ position: absolute;
+ z-index: 2;
+ inset-block-end: 12px;
+ inset-inline-end: 12px;
+
+ padding-block: 3px;
+ padding-inline: 10px;
+ border-radius: 999px;
+
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextSecondary};
+
+ background: color-mix(in srgb, ${cssVar.colorBgElevated} 72%, transparent);
+ backdrop-filter: blur(8px);
+ `,
+ blobA: css`
+ ${blob}
+ background: ${glow('var(--aura-a)')};
+ animation: ${wanderA} 9s ease-in-out infinite;
+ animation-delay: var(--aura-delay, 0s);
+ `,
+ blobB: css`
+ ${blob}
+ background: ${glow('var(--aura-b)')};
+ animation: ${wanderB} 11s ease-in-out infinite;
+ animation-delay: var(--aura-delay, 0s);
+ `,
+ blobC: css`
+ ${blob}
+ background: ${glow('var(--aura-c)')};
+ animation: ${wanderC} 13s ease-in-out infinite;
+ animation-delay: var(--aura-delay, 0s);
+ `,
+ canvas: css`
+ position: relative;
+
+ overflow: hidden;
+
+ width: 100%;
+ border-radius: 12px;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ grain: css`
+ position: absolute;
+ inset: 0;
+
+ opacity: 0.16;
+ background-image: ${GRAIN};
+ background-size: 160px 160px;
+ mix-blend-mode: overlay;
+ `,
+ image: css`
+ width: 100%;
+ height: 100%;
+ `,
+ layer: css`
+ position: absolute;
+ inset: 0;
+ `,
+ overlay: css`
+ position: absolute;
+ z-index: 1;
+ inset: 0;
+
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ align-items: center;
+ justify-content: center;
+
+ padding: 16px;
+
+ text-align: center;
+ `,
+ reveal: css`
+ position: absolute;
+ z-index: 1;
+ inset: 0;
+ opacity: 0;
+ `,
+ revealed: css`
+ opacity: 1;
+ animation: ${develop} 1100ms cubic-bezier(0.2, 0, 0, 1) both;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ `,
+}));
+
+// Tiles in one grid rotate through the palette instead of hue-rotating a filter,
+// which would have to be re-applied on every animation frame.
+const AURA_PALETTE = [cssVar.purple, cssVar.geekblue, cssVar.cyan, cssVar.magenta];
+
+// A negative delay of "time since generation started" puts every loop at the
+// phase it would have reached, so the aura does not jump back to its first frame
+// when the streaming canvas is swapped for the result canvas.
+const auraStyle = (seed: number, startedAt?: number) =>
+ ({
+ '--aura-a': AURA_PALETTE[seed % AURA_PALETTE.length],
+ '--aura-b': AURA_PALETTE[(seed + 1) % AURA_PALETTE.length],
+ '--aura-c': AURA_PALETTE[(seed + 2) % AURA_PALETTE.length],
+ '--aura-delay': startedAt ? `${-Math.max(0, Date.now() - startedAt) / 1000}s` : '0s',
+ }) as CSSProperties;
+
+const useElapsedSeconds = (startedAt?: number) => {
+ const [now, setNow] = useState(() => Date.now());
+
+ useEffect(() => {
+ if (!startedAt) return;
+ const timer = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(timer);
+ }, [startedAt]);
+
+ return startedAt ? Math.max(0, Math.floor((now - startedAt) / 1000)) : undefined;
+};
+
+export interface ImageCanvasProps {
+ alt?: string;
+ /**
+ * Status pill pinned to the bottom-right corner while the image is in flight.
+ */
+ badge?: string;
+ /**
+ * Centered content for non-image end states (error message, retry button).
+ * Freezes and desaturates the aura — nothing is being generated any more.
+ */
+ children?: ReactNode;
+ onDownload?: (source: string) => void | Promise<void>;
+ /**
+ * width / height
+ */
+ ratio?: number;
+ /**
+ * Varies the aura hue, so tiles in one grid don't look cloned.
+ */
+ seed?: number;
+ /**
+ * When generation started (ms epoch). Appends honest elapsed time to the
+ * badge; omitted when the real start is unknown.
+ */
+ startedAt?: number;
+ url?: string;
+}
+
+/**
+ * One image slot. It is the same element before and after the image exists:
+ * a drifting, grainy colour aura that keeps reaching for focus while
+ * generating, then the image develops out of that blur — so the chat never
+ * jumps when the result lands.
+ */
+export const ImageCanvas = memo<ImageCanvasProps>(
+ ({ alt, badge, children, onDownload, ratio = 1, seed = 0, startedAt, url }) => {
+ const { t } = useTranslation('plugin');
+ const [loadedUrl, setLoadedUrl] = useState<string>();
+ const loaded = !!url && loadedUrl === url;
+ const generating = !url && !children;
+ const elapsed = useElapsedSeconds(generating ? startedAt : undefined);
+ // Computed once per mount: recomputing on every re-render would restart the loops.
+ const [auraLayerStyle] = useState(() => auraStyle(seed, startedAt));
+
+ const badgeText =
+ badge && elapsed !== undefined
+ ? t('builtins.lobe-image-generation.render.status.elapsed', {
+ seconds: elapsed,
+ status: badge,
+ })
+ : badge;
+
+ return (
+ <div className={styles.canvas} style={{ aspectRatio: ratio }}>
+ <div
+ aria-hidden
+ className={cx(styles.aura, loaded && styles.auraHidden, !!children && styles.auraStill)}
+ >
+ <div className={styles.layer} style={auraLayerStyle}>
+ <div className={styles.auraFocus}>
+ <span className={styles.blobA} />
+ <span className={styles.blobB} />
+ <span className={styles.blobC} />
+ </div>
+ </div>
+ <div className={styles.grain} />
+ </div>
+ {url && (
+ <div className={cx(styles.reveal, loaded && styles.revealed)}>
+ <Image
+ alt={alt}
+ className={styles.image}
+ classNames={{ image: styles.image, wrapper: styles.image }}
+ height={'100%'}
+ objectFit={'cover'}
+ preview={onDownload ? { onDownload } : true}
+ src={url}
+ variant={'borderless'}
+ width={'100%'}
+ onError={() => setLoadedUrl(url)}
+ onLoad={() => setLoadedUrl(url)}
+ />
+ </div>
+ )}
+ {!url && children && <div className={styles.overlay}>{children}</div>}
+ {generating && badgeText && <span className={styles.badge}>{badgeText}</span>}
+ </div>
+ );
+ },
+);
+
+ImageCanvas.displayName = 'ImageCanvas';
+
+export default ImageCanvas;
diff --git a/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx b/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx
new file mode 100644
index 00000000000..dcde0c0c3e1
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/ImageCanvasGrid.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { createStaticStyles } from 'antd-style';
+import type { ReactNode } from 'react';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ grid: css`
+ display: grid;
+ gap: 8px;
+ width: 100%;
+ `,
+}));
+
+// A lone image is the hero of the message; several share the same footprint.
+const SINGLE_MAX_HEIGHT = 420;
+const SINGLE_MAX_WIDTH = 480;
+const MULTI_MAX_WIDTH = 560;
+
+interface ImageCanvasGridProps {
+ children: ReactNode;
+ count: number;
+ /**
+ * width / height of each canvas
+ */
+ ratio: number;
+}
+
+export const ImageCanvasGrid = memo<ImageCanvasGridProps>(({ children, count, ratio }) => {
+ const single = count <= 1;
+ const columns = single ? 1 : count === 3 ? 3 : 2;
+ // Cap a portrait hero by height so it cannot take over the viewport.
+ const maxWidth = single
+ ? Math.min(SINGLE_MAX_WIDTH, Math.round(SINGLE_MAX_HEIGHT * ratio))
+ : MULTI_MAX_WIDTH;
+
+ return (
+ <div
+ className={styles.grid}
+ style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`, maxWidth }}
+ >
+ {children}
+ </div>
+ );
+});
+
+ImageCanvasGrid.displayName = 'ImageCanvasGrid';
+
+export default ImageCanvasGrid;
diff --git a/packages/builtin-tool-image-generation/src/client/components/aspectRatio.test.ts b/packages/builtin-tool-image-generation/src/client/components/aspectRatio.test.ts
new file mode 100644
index 00000000000..ca4c112be8d
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/aspectRatio.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveAspectRatio } from './aspectRatio';
+
+describe('resolveAspectRatio', () => {
+ it('falls back to a square when nothing is known yet', () => {
+ expect(resolveAspectRatio()).toBe(1);
+ expect(resolveAspectRatio({}, null)).toBe(1);
+ expect(resolveAspectRatio({ aspectRatio: 'auto', size: 'auto' })).toBe(1);
+ });
+
+ it('prefers the final asset dimensions over the requested parameters', () => {
+ expect(resolveAspectRatio({ aspectRatio: '1:1' }, { height: 1024, width: 1536 })).toBe(1.5);
+ });
+
+ it('reads aspectRatio, size and width/height parameters', () => {
+ expect(resolveAspectRatio({ aspectRatio: '16:9' })).toBeCloseTo(16 / 9);
+ expect(resolveAspectRatio({ size: '1024x1536' })).toBeCloseTo(1024 / 1536);
+ expect(resolveAspectRatio({ height: 768, width: 1024 })).toBeCloseTo(4 / 3);
+ });
+
+ it('clamps extreme ratios so the canvas stays usable in the chat flow', () => {
+ expect(resolveAspectRatio({ aspectRatio: '10:1' })).toBeCloseTo(21 / 9);
+ expect(resolveAspectRatio({ height: 4000, width: 100 })).toBeCloseTo(9 / 21);
+ });
+
+ it('ignores an incomplete asset', () => {
+ expect(resolveAspectRatio({ aspectRatio: '3:2' }, { width: 1024 })).toBe(1.5);
+ });
+});
diff --git a/packages/builtin-tool-image-generation/src/client/components/aspectRatio.ts b/packages/builtin-tool-image-generation/src/client/components/aspectRatio.ts
new file mode 100644
index 00000000000..1f6d7a1d32c
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/aspectRatio.ts
@@ -0,0 +1,37 @@
+const MIN_RATIO = 9 / 21;
+const MAX_RATIO = 21 / 9;
+
+const clampRatio = (ratio: number) => Math.min(MAX_RATIO, Math.max(MIN_RATIO, ratio));
+
+const parsePair = (value: unknown, separator: RegExp) => {
+ if (typeof value !== 'string') return;
+ const [w, h] = value.split(separator).map(Number);
+ if (!w || !h || w <= 0 || h <= 0) return;
+ return w / h;
+};
+
+const positive = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
+
+/**
+ * Resolve the canvas aspect ratio (width / height) from whatever the call knows
+ * so far: the final asset dimensions, or the requested `aspectRatio` / `size` /
+ * `width`+`height` parameters. Falls back to a square so the canvas never
+ * collapses while the arguments are still streaming in.
+ */
+export const resolveAspectRatio = (
+ parameters?: Record<string, unknown> | null,
+ asset?: { height?: number; width?: number } | null,
+): number => {
+ const assetWidth = positive(asset?.width);
+ const assetHeight = positive(asset?.height);
+ if (assetWidth && assetHeight) return clampRatio(assetWidth / assetHeight);
+
+ const width = positive(parameters?.width);
+ const height = positive(parameters?.height);
+ if (width && height) return clampRatio(width / height);
+
+ const ratio = parsePair(parameters?.aspectRatio, /[:/]/) ?? parsePair(parameters?.size, /[x×*]/i);
+
+ return ratio ? clampRatio(ratio) : 1;
+};
diff --git a/packages/builtin-tool-image-generation/src/client/components/generationClock.test.ts b/packages/builtin-tool-image-generation/src/client/components/generationClock.test.ts
new file mode 100644
index 00000000000..51bf4903024
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/generationClock.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { peekGenerationClock, startGenerationClock } from './generationClock';
+
+describe('generationClock', () => {
+ it('keeps the first start time across remounts of the same call', () => {
+ expect(startGenerationClock('call_a', 1000)).toBe(1000);
+ expect(startGenerationClock('call_a', 5000)).toBe(1000);
+ expect(peekGenerationClock('call_a')).toBe(1000);
+ });
+
+ it('does not invent a start time for a call it never saw generating', () => {
+ expect(peekGenerationClock('call_from_history')).toBeUndefined();
+ });
+
+ it('ignores calls without an id', () => {
+ expect(startGenerationClock(undefined)).toBeUndefined();
+ expect(peekGenerationClock(undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tool-image-generation/src/client/components/generationClock.ts b/packages/builtin-tool-image-generation/src/client/components/generationClock.ts
new file mode 100644
index 00000000000..299869a0657
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/generationClock.ts
@@ -0,0 +1,24 @@
+/**
+ * When each image-generation tool call started, keyed by tool call id.
+ *
+ * The streaming canvas and the result canvas are different components, so the
+ * card remounts when the tool returns; keeping the start time here lets the
+ * elapsed counter carry on instead of resetting to zero.
+ */
+const startedAtByToolCall = new Map<string, number>();
+
+/** Start (or continue) the clock for a call that is generating right now. */
+export const startGenerationClock = (toolCallId?: string, now = Date.now()) => {
+ if (!toolCallId) return;
+ const existing = startedAtByToolCall.get(toolCallId);
+ if (existing) return existing;
+ startedAtByToolCall.set(toolCallId, now);
+ return now;
+};
+
+/**
+ * Read a clock without starting one. A card restored from history never saw its
+ * generation begin, so it gets no elapsed time rather than a misleading one.
+ */
+export const peekGenerationClock = (toolCallId?: string) =>
+ toolCallId ? startedAtByToolCall.get(toolCallId) : undefined;
diff --git a/packages/builtin-tool-image-generation/src/client/components/useGenerationStatus.ts b/packages/builtin-tool-image-generation/src/client/components/useGenerationStatus.ts
new file mode 100644
index 00000000000..6d865920a7d
--- /dev/null
+++ b/packages/builtin-tool-image-generation/src/client/components/useGenerationStatus.ts
@@ -0,0 +1,82 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { imageKeys } from '@/libs/swr/keys';
+import { generationService } from '@/services/generation';
+
+import type {
+ GeneratedImageTask,
+ GetImageGenerationStatusParams,
+ GetImageGenerationStatusState,
+} from '../../types';
+
+const POLLING_INTERVAL = 3000;
+
+export const isTerminalStatus = (status?: string) => status === 'success' || status === 'error';
+
+const assetUrl = (asset?: GeneratedImageTask['asset']) =>
+ asset?.url || asset?.thumbnailUrl || asset?.originalUrl;
+
+export const getStateAssetUrl = (state?: GetImageGenerationStatusState) =>
+ assetUrl(state?.generation?.asset);
+
+export const getTaskAssetUrl = (task: GeneratedImageTask) => assetUrl(task.asset);
+
+const errorDetail = (error?: GeneratedImageTask['error']) => {
+ if (!error) return;
+ const body = error.body;
+ if (typeof body === 'string') return body;
+ return body.detail;
+};
+
+export const getStateErrorDetail = (state?: GetImageGenerationStatusState) =>
+ errorDetail(state?.error);
+
+export const getTaskErrorDetail = (task: GeneratedImageTask) => errorDetail(task.error);
+
+/**
+ * Polls one generation until it reaches a terminal status, so a card whose
+ * stored result was still in flight keeps updating itself instead of animating
+ * forever. Polling stops on the first error and resumes on an explicit retry.
+ */
+export const useGenerationStatus = (params: GetImageGenerationStatusParams, enabled: boolean) => {
+ const [pollingStopped, setPollingStopped] = useState(false);
+
+ useEffect(() => {
+ setPollingStopped(false);
+ }, [params.asyncTaskId, params.generationId]);
+
+ const result = useClientDataSWR<GetImageGenerationStatusState>(
+ enabled && params.asyncTaskId
+ ? imageKeys.generationStatus(params.generationId, params.asyncTaskId)
+ : null,
+ async () => {
+ const result = await generationService.getGenerationStatus(
+ params.generationId,
+ params.asyncTaskId,
+ );
+ return {
+ ...result,
+ asyncTaskId: params.asyncTaskId,
+ generationId: params.generationId,
+ };
+ },
+ {
+ onError: () => setPollingStopped(true),
+ onSuccess: () => setPollingStopped(false),
+ refreshInterval: (data?: GetImageGenerationStatusState) =>
+ pollingStopped || isTerminalStatus(data?.status) ? 0 : POLLING_INTERVAL,
+ shouldRetryOnError: false,
+ },
+ );
+
+ const { mutate } = result;
+ const retry = useCallback(() => {
+ setPollingStopped(false);
+ void mutate();
+ }, [mutate]);
+
+ return { ...result, retry };
+};
diff --git a/packages/builtin-tool-image-generation/src/client/index.ts b/packages/builtin-tool-image-generation/src/client/index.ts
index e13ceb96f00..c0ee4ed793c 100644
--- a/packages/builtin-tool-image-generation/src/client/index.ts
+++ b/packages/builtin-tool-image-generation/src/client/index.ts
@@ -8,3 +8,4 @@ export {
ImageGenerationRenders,
ListImageModelsRender,
} from './Render';
+export { GenerateImageStreaming, ImageGenerationStreamings } from './Streaming';
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index 8494b9d8b1b..06930ea6a1e 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -68,6 +68,7 @@ import {
ImageGenerationInspectors,
ImageGenerationManifest,
ImageGenerationRenders,
+ ImageGenerationStreamings,
} from '@lobechat/builtin-tool-image-generation/client';
import {
KnowledgeBaseInspectors,
@@ -357,6 +358,7 @@ export const registerBuiltinToolSurfaces = (): void => {
[ClaudeCodeIdentifier]: ClaudeCodeStreamings as Record<string, BuiltinStreaming>,
[QODER_IDENTIFIER]: ClaudeCodeStreamings as Record<string, BuiltinStreaming>,
[CloudSandboxManifest.identifier]: CloudSandboxStreamings as Record<string, BuiltinStreaming>,
+ [ImageGenerationManifest.identifier]: ImageGenerationStreamings,
[GroupAgentBuilderManifest.identifier]: GroupAgentBuilderStreamings as Record<
string,
BuiltinStreaming
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 16e7b109794..3a3c4282a78 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -277,6 +277,8 @@ export default {
'builtins.lobe-group-management.inspector.speak.title': 'Designated Agent speaks:',
'builtins.lobe-group-management.title': 'Group Coordinator',
'builtins.lobe-image-generation.apiName.generateImage': 'Generate image',
+ 'builtins.lobe-image-generation.apiName.generateImage.completed': 'Created image',
+ 'builtins.lobe-image-generation.apiName.generateImage.loading': 'Creating image',
'builtins.lobe-image-generation.apiName.getImageGenerationStatus': 'Check image status',
'builtins.lobe-image-generation.apiName.getImageModelParameters': 'Inspect model parameters',
'builtins.lobe-image-generation.apiName.listImageModels': 'List image models',
@@ -298,6 +300,7 @@ export default {
'builtins.lobe-image-generation.render.parameterList.parameters_other': '{{count}} parameters',
'builtins.lobe-image-generation.render.retry': 'Retry',
'builtins.lobe-image-generation.render.statusCheckFailed': 'Failed to check image status',
+ 'builtins.lobe-image-generation.render.status.elapsed': '{{status}} · {{seconds}}s',
'builtins.lobe-image-generation.render.status.error': 'Failed',
'builtins.lobe-image-generation.render.status.pending': 'Pending',
'builtins.lobe-image-generation.render.status.processing': 'Generating',