Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: stabilize chat image layout while loading (#18814)

Arvin Xu8bda45526030
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 03c2d31a09b..3e2c90d2934 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -303,7 +303,15 @@ describe('MessageModel Query Tests', () => {
},
]);
await trx.insert(files).values([
- { id: 'f-0', url: 'abc', name: 'file-1', userId, fileType: 'image/png', size: 1000 },
+ {
+ id: 'f-0',
+ url: 'abc',
+ name: 'file-1',
+ userId,
+ fileType: 'image/png',
+ metadata: { height: 600, ratio: 1.3333, width: 800 },
+ size: 1000,
+ },
{ id: 'f-1', url: 'abc', name: 'file-1', userId, fileType: 'image/png', size: 100 },
{ id: 'f-3', url: 'abc', name: 'file-3', userId, fileType: 'image/png', size: 400 },
]);
@@ -329,7 +337,14 @@ describe('MessageModel Query Tests', () => {
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
expect(result[0].imageList).toEqual([
- { alt: 'file-1', id: 'f-0', url: `${domain}/f-0/abc` },
+ {
+ alt: 'file-1',
+ height: 600,
+ id: 'f-0',
+ ratio: 1.3333,
+ url: `${domain}/f-0/abc`,
+ width: 800,
+ },
{ alt: 'file-3', id: 'f-3', url: `${domain}/f-3/abc` },
]);
expect(postProcessUrl).toHaveBeenCalledWith(
@@ -360,6 +375,7 @@ describe('MessageModel Query Tests', () => {
name: 'query-by-id.png',
userId,
fileType: 'image/png',
+ metadata: { height: 720, ratio: 1.7778, width: 1280 },
size: 1000,
});
await trx.insert(messagesFiles).values({
@@ -378,8 +394,11 @@ describe('MessageModel Query Tests', () => {
expect(result[0].imageList).toEqual([
{
alt: 'query-by-id.png',
+ height: 720,
id: 'query-by-id-file',
+ ratio: 1.7778,
url: '/f/query-by-id-file/files/query-by-id.png',
+ width: 1280,
},
]);
expect(postProcessUrl).toHaveBeenCalledWith(
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 9057f0abf7c..b29acefebc0 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -86,6 +86,47 @@ import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
import { WorkModel } from './work';
+const createChatImageItem = ({
+ id,
+ metadata,
+ name,
+ url,
+}: {
+ id: string;
+ metadata: unknown;
+ name: string;
+ url: string;
+}): ChatImageItem => {
+ const imageMetadata = isPlainRecord(metadata) ? metadata : {};
+ const height =
+ typeof imageMetadata.height === 'number' &&
+ Number.isFinite(imageMetadata.height) &&
+ imageMetadata.height > 0
+ ? imageMetadata.height
+ : undefined;
+ const ratio =
+ typeof imageMetadata.ratio === 'number' &&
+ Number.isFinite(imageMetadata.ratio) &&
+ imageMetadata.ratio > 0
+ ? imageMetadata.ratio
+ : undefined;
+ const width =
+ typeof imageMetadata.width === 'number' &&
+ Number.isFinite(imageMetadata.width) &&
+ imageMetadata.width > 0
+ ? imageMetadata.width
+ : undefined;
+
+ return {
+ alt: name,
+ ...(height && { height }),
+ id,
+ ...(ratio && { ratio }),
+ url,
+ ...(width && { width }),
+ };
+};
+
export class HumanApprovalAlreadyResolvedError extends Error {
constructor(messageId: string) {
super(`Human approval is no longer pending for tool message ${messageId}`);
@@ -955,8 +996,9 @@ export class MessageModel {
),
imageList: imageList
.filter((relation) => relation.messageId === item.id)
-
- .map<ChatImageItem>(({ id, url, name }) => ({ alt: name!, id, url })),
+ .map(({ id, metadata, name, url }) =>
+ createChatImageItem({ id, metadata, name: name!, url }),
+ ),
model,
@@ -1622,7 +1664,9 @@ export class MessageModel {
),
imageList: imageList
.filter((relation) => relation.messageId === item.id)
- .map<ChatImageItem>(({ id, url, name }) => ({ alt: name!, id, url })),
+ .map(({ id, metadata, name, url }) =>
+ createChatImageItem({ id, metadata, name: name!, url }),
+ ),
model,
diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.ts
index df3d09b9d98..7429054065d 100644
--- a/packages/types/src/files/upload.ts
+++ b/packages/types/src/files/upload.ts
@@ -51,6 +51,12 @@ export interface UploadFileItem {
* base64 data, it will use in other data
*/
base64Url?: string;
+ /** Intrinsic dimensions captured for image uploads. */
+ dimensions?: {
+ height: number;
+ ratio: number;
+ width: number;
+ };
/** Human-readable reason retained on the originating upload surface. */
error?: string;
/** Stable business reason used to render an in-context remedy action. */
diff --git a/packages/types/src/message/common/image.ts b/packages/types/src/message/common/image.ts
index f9cf341c7ed..4eec5d9302f 100644
--- a/packages/types/src/message/common/image.ts
+++ b/packages/types/src/message/common/image.ts
@@ -2,14 +2,23 @@ import { z } from 'zod';
export interface ChatImageItem {
alt: string;
+ /** Intrinsic image height in pixels, when known from upload metadata. */
+ height?: number;
id: string;
+ /** Intrinsic aspect ratio (width / height), when known from upload metadata. */
+ ratio?: number;
url: string;
+ /** Intrinsic image width in pixels, when known from upload metadata. */
+ width?: number;
}
export const ChatImageItemSchema = z.object({
alt: z.string(),
+ height: z.number().optional(),
id: z.string(),
+ ratio: z.number().optional(),
url: z.string(),
+ width: z.number().optional(),
});
export interface ChatImageChunk {
diff --git a/src/components/ImageItem/index.tsx b/src/components/ImageItem/index.tsx
index f8524ed51c3..3d631d40389 100644
--- a/src/components/ImageItem/index.tsx
+++ b/src/components/ImageItem/index.tsx
@@ -33,18 +33,40 @@ interface ImageItemProps {
alwaysShowClose?: boolean;
className?: string;
editable?: boolean;
+ height?: number;
loading?: boolean;
onClick?: () => void;
onRemove?: () => void;
preview?: ImageProps['preview'];
+ ratio?: number;
style?: CSSProperties;
url?: string;
+ width?: number;
}
const ImageItem = memo<ImageItemProps>(
- ({ className, style, editable, alt, onRemove, url, loading, alwaysShowClose, preview }) => {
+ ({
+ className,
+ style,
+ editable,
+ alt,
+ onRemove,
+ url,
+ loading,
+ alwaysShowClose,
+ preview,
+ ratio,
+ width,
+ height,
+ }) => {
const IMAGE_SIZE = editable ? MIN_IMAGE_SIZE : '100%';
const { isSafari } = usePlatform();
+ const aspectRatio =
+ ratio && ratio > 0
+ ? ratio
+ : width && width > 0 && height && height > 0
+ ? width / height
+ : undefined;
return (
<Image
@@ -56,7 +78,6 @@ const ImageItem = memo<ImageItemProps>(
preview={preview}
size={IMAGE_SIZE}
src={url}
- style={{ height: isSafari ? 'auto' : '100%', width: '100%', ...style }}
actions={
editable && (
<ActionIcon
@@ -71,6 +92,12 @@ const ImageItem = memo<ImageItemProps>(
/>
)
}
+ style={{
+ aspectRatio,
+ height: aspectRatio || isSafari ? 'auto' : '100%',
+ width: '100%',
+ ...style,
+ }}
/>
);
},
diff --git a/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx b/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx
index 6f7efe3b4c6..39151f6830b 100644
--- a/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx
+++ b/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx
@@ -1,3 +1,4 @@
+import { type ChatImageItem } from '@lobechat/types';
import { PreviewGroup } from '@lobehub/ui';
import { memo } from 'react';
@@ -6,16 +7,8 @@ import ImageItem from '@/components/ImageItem';
import { downloadPreviewImage } from '../../components/downloadPreviewImage';
-interface ImageFileItem {
- alt?: string;
- id: string;
- loading?: boolean;
- onRemove?: (id: string) => void;
- url: string;
-}
-
interface FileListProps {
- items: ImageFileItem[];
+ items: ChatImageItem[];
}
const ImageFileListViewer = memo<FileListProps>(({ items }) => {
diff --git a/src/features/Conversation/Messages/components/ImageFileListViewer.tsx b/src/features/Conversation/Messages/components/ImageFileListViewer.tsx
index e8581f9053c..49a4e0f5b90 100644
--- a/src/features/Conversation/Messages/components/ImageFileListViewer.tsx
+++ b/src/features/Conversation/Messages/components/ImageFileListViewer.tsx
@@ -1,3 +1,4 @@
+import { type ChatImageItem } from '@lobechat/types';
import { PreviewGroup } from '@lobehub/ui';
import { memo } from 'react';
@@ -6,16 +7,8 @@ import ImageItem from '@/components/ImageItem';
import { downloadPreviewImage } from './downloadPreviewImage';
-interface ImageFileItem {
- alt?: string;
- id: string;
- loading?: boolean;
- onRemove?: (id: string) => void;
- url: string;
-}
-
interface FileListProps {
- items: ImageFileItem[];
+ items: ChatImageItem[];
}
const ImageFileListViewer = memo<FileListProps>(({ items }) => {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 1de47360463..a99b122a237 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -924,6 +924,7 @@ export class ConversationLifecycleActionImpl {
const tempImages: ChatImageItem[] = filesForPreview
.filter((f) => f.file?.type?.startsWith('image'))
.map((f) => ({
+ ...f.dimensions,
id: f.id,
url: f.fileUrl || f.base64Url || f.previewUrl || '',
alt: f.file?.name || f.id,
diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.ts
index 1ca1b24dc64..78dc06c8f3c 100644
--- a/src/store/file/slices/upload/action.test.ts
+++ b/src/store/file/slices/upload/action.test.ts
@@ -360,6 +360,7 @@ describe('FileUploadAction', () => {
id: mockFile.name,
type: 'updateFile',
value: {
+ dimensions: mockDimensions,
fileUrl: mockFileResponse.url,
id: mockFileResponse.id,
status: 'success',
@@ -923,15 +924,28 @@ describe('FileUploadAction', () => {
vi.spyOn(fileService, 'checkFileHash').mockResolvedValue(mockCheckResult);
vi.spyOn(uploadService, 'uploadFileToS3').mockResolvedValue(mockUploadResult);
vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);
+ const onStatusUpdate = vi.fn();
const uploadResult = await act(async () => {
return await result.current.uploadWithProgress({
file: mockFile,
+ onStatusUpdate,
});
});
expect(getImageDimensions).toHaveBeenCalledWith(mockFile);
expect(uploadResult?.dimensions).toEqual(mockDimensions);
+ expect(onStatusUpdate).toHaveBeenLastCalledWith({
+ id: mockFile.name,
+ type: 'updateFile',
+ value: {
+ dimensions: mockDimensions,
+ fileUrl: mockFileResponse.url,
+ id: mockFileResponse.id,
+ status: 'success',
+ uploadState: { progress: 100, restTime: 0, speed: 0 },
+ },
+ });
});
it('should return undefined dimensions for non-image files', async () => {
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index 022a113e1b0..2b635d72565 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -249,6 +249,7 @@ export class FileUploadActionImpl {
id: statusId,
type: 'updateFile',
value: {
+ ...(dimensions && { dimensions }),
fileUrl: data.url,
id: data.id,
status: 'success',