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: handle generated asset metadata dedup (#16057)

YuTengjinga97e3317274f
diff --git a/apps/server/src/routers/async/video.ts b/apps/server/src/routers/async/video.ts
index 75511b2dcf0..f45f6ca5565 100644
--- a/apps/server/src/routers/async/video.ts
+++ b/apps/server/src/routers/async/video.ts
@@ -20,8 +20,8 @@ import { GenerationModel } from '@/database/models/generation';
import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { VideoGenerationService } from '@/server/services/generation/video';
+import { buildVideoGenerationFilePayload } from '@/server/services/generation/videoFile';
import { FileSource } from '@/types/files';
-import { sanitizeFileName } from '@/utils/sanitizeFileName';
const log = debug('lobe-video:async');
@@ -196,13 +196,11 @@ export const videoRouter = router({
url: processResult.videoKey,
width: processResult.width,
},
- {
- fileHash: processResult.fileHash,
- fileType: processResult.mimeType,
- name: `${sanitizeFileName(batch?.prompt ?? '', generationId)}.mp4`,
- size: processResult.fileSize,
- url: processResult.videoKey,
- },
+ buildVideoGenerationFilePayload({
+ generationId,
+ processResult,
+ prompt: batch?.prompt,
+ }),
FileSource.VideoGeneration,
);
diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.ts
index 5e9d620b596..f5aa7c4686f 100644
--- a/apps/server/src/services/file/__tests__/index.test.ts
+++ b/apps/server/src/services/file/__tests__/index.test.ts
@@ -301,6 +301,34 @@ describe('FileService', () => {
expect(result).toBe(expectedResult);
});
+ describe('uploadBase64', () => {
+ beforeEach(() => {
+ mockFileModel.checkHash = vi.fn().mockResolvedValue({ isExist: false });
+ mockFileModel.create = vi.fn().mockResolvedValue({ id: 'new-file-id' });
+ vi.mocked(service['impl'].uploadMedia).mockResolvedValue({
+ key: 'assets/generations/2026-06-19/generated.png',
+ });
+ });
+
+ it('should write metadata compatible with UI upload path', async () => {
+ await service.uploadBase64(
+ Buffer.from('test content').toString('base64'),
+ 'assets/generations/2026-06-19/generated.png',
+ );
+
+ expect(mockFileModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ dirname: 'assets/generations/2026-06-19',
+ filename: 'generated.png',
+ path: 'assets/generations/2026-06-19/generated.png',
+ }),
+ }),
+ expect.any(Boolean),
+ );
+ });
+ });
+
describe('uploadFromBuffer', () => {
beforeEach(() => {
mockFileModel.checkHash = vi.fn().mockResolvedValue({ isExist: false });
diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.ts
index 609935bcf9b..5823b533869 100644
--- a/apps/server/src/services/file/index.ts
+++ b/apps/server/src/services/file/index.ts
@@ -329,6 +329,7 @@ export class FileService {
// Extract filename from pathname
const name = pathname.split('/').pop() || 'unknown';
+ const dirname = pathname.split('/').slice(0, -1).join('/');
// Calculate file metadata
const size = buffer.length;
@@ -343,6 +344,13 @@ export class FileService {
fileHash: hash,
fileType,
id: fileId, // Use UUID instead of auto-generated ID
+ // Keep generated/base64 uploads compatible with UI hash-dedup, which reads metadata.path.
+ metadata: {
+ date: new Date().toISOString().slice(0, 10),
+ dirname,
+ filename: name,
+ path: key,
+ },
name,
size,
url: key, // Store original key (S3 key or desktop://)
diff --git a/apps/server/src/services/generation/videoBackgroundPolling.test.ts b/apps/server/src/services/generation/videoBackgroundPolling.test.ts
index 5717c100888..ff0d79fe725 100644
--- a/apps/server/src/services/generation/videoBackgroundPolling.test.ts
+++ b/apps/server/src/services/generation/videoBackgroundPolling.test.ts
@@ -123,6 +123,15 @@ describe('videoBackgroundPolling', () => {
expect.objectContaining({
fileHash: 'hash-abc',
fileType: 'video/mp4',
+ metadata: expect.objectContaining({
+ dirname: '',
+ duration: 10,
+ filename: 'test-prompt-gen-456.mp4',
+ generationId: 'gen-456',
+ height: 1080,
+ path: 'video-key-789',
+ width: 1920,
+ }),
name: 'test-prompt-gen-456.mp4',
size: 1024,
url: 'video-key-789',
diff --git a/apps/server/src/services/generation/videoBackgroundPolling.ts b/apps/server/src/services/generation/videoBackgroundPolling.ts
index eff86264211..5cf5464dafb 100644
--- a/apps/server/src/services/generation/videoBackgroundPolling.ts
+++ b/apps/server/src/services/generation/videoBackgroundPolling.ts
@@ -8,10 +8,10 @@ import { GenerationModel } from '@/database/models/generation';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { VideoGenerationService } from '@/server/services/generation/video';
+import { buildVideoGenerationFilePayload } from '@/server/services/generation/videoFile';
import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';
import { FileSource } from '@/types/files';
import type { VideoGenerationAsset } from '@/types/generation';
-import { sanitizeFileName } from '@/utils/sanitizeFileName';
const log = debug('lobe-video:background-polling');
@@ -88,13 +88,11 @@ export async function processBackgroundVideoPolling(
await generationModel.createAssetAndFile(
generationId,
asset,
- {
- fileHash: processResult.fileHash,
- fileType: processResult.mimeType,
- name: `${sanitizeFileName(batch?.prompt ?? '', generationId)}.mp4`,
- size: processResult.fileSize,
- url: processResult.videoKey,
- },
+ buildVideoGenerationFilePayload({
+ generationId,
+ processResult,
+ prompt: batch?.prompt,
+ }),
FileSource.VideoGeneration,
);
diff --git a/apps/server/src/services/generation/videoFile.test.ts b/apps/server/src/services/generation/videoFile.test.ts
new file mode 100644
index 00000000000..a66d17f0a29
--- /dev/null
+++ b/apps/server/src/services/generation/videoFile.test.ts
@@ -0,0 +1,48 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { buildVideoGenerationFilePayload } from './videoFile';
+
+describe('buildVideoGenerationFilePayload', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('should include upload metadata for generated video hash dedup', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-19T10:20:30Z'));
+
+ const payload = buildVideoGenerationFilePayload({
+ generationId: 'gen-456',
+ processResult: {
+ coverKey: 'generations/videos/video_cover.webp',
+ duration: 12,
+ fileHash: 'hash-abc',
+ fileSize: 1024,
+ height: 1080,
+ mimeType: 'video/mp4',
+ thumbnailKey: 'generations/videos/video_thumb.webp',
+ videoKey: 'generations/videos/video_raw.mp4',
+ width: 1920,
+ },
+ prompt: 'test prompt',
+ });
+
+ expect(payload).toEqual({
+ fileHash: 'hash-abc',
+ fileType: 'video/mp4',
+ metadata: {
+ date: '2026-06-19',
+ dirname: 'generations/videos',
+ duration: 12,
+ filename: 'test prompt.mp4',
+ generationId: 'gen-456',
+ height: 1080,
+ path: 'generations/videos/video_raw.mp4',
+ width: 1920,
+ },
+ name: 'test prompt.mp4',
+ size: 1024,
+ url: 'generations/videos/video_raw.mp4',
+ });
+ });
+});
diff --git a/apps/server/src/services/generation/videoFile.ts b/apps/server/src/services/generation/videoFile.ts
new file mode 100644
index 00000000000..72d2291d84c
--- /dev/null
+++ b/apps/server/src/services/generation/videoFile.ts
@@ -0,0 +1,38 @@
+import type { VideoProcessResult } from '@/server/services/generation/video';
+import { sanitizeFileName } from '@/utils/sanitizeFileName';
+
+interface BuildVideoGenerationFilePayloadParams {
+ generationId: string;
+ processResult: VideoProcessResult;
+ prompt?: string | null;
+}
+
+/**
+ * Keeps generated video files compatible with UI hash dedup, which reads metadata.path.
+ */
+export const buildVideoGenerationFilePayload = ({
+ generationId,
+ processResult,
+ prompt,
+}: BuildVideoGenerationFilePayloadParams) => {
+ const name = `${sanitizeFileName(prompt ?? '', generationId)}.mp4`;
+ const dirname = processResult.videoKey.split('/').slice(0, -1).join('/');
+
+ return {
+ fileHash: processResult.fileHash,
+ fileType: processResult.mimeType,
+ metadata: {
+ date: new Date().toISOString().slice(0, 10),
+ dirname,
+ duration: processResult.duration,
+ filename: name,
+ generationId,
+ height: processResult.height,
+ path: processResult.videoKey,
+ width: processResult.width,
+ },
+ name,
+ size: processResult.fileSize,
+ url: processResult.videoKey,
+ };
+};
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
index 7bbb953588d..4e363f9b9c6 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
@@ -22,15 +22,26 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorErrorBg};
}
`,
+ content: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ min-width: 0;
+ `,
icon: css`
position: relative;
+ display: flex;
flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
width: 18px;
height: 18px;
border-radius: 4px;
+ line-height: 0;
+
img,
video {
width: 100%;
@@ -45,6 +56,7 @@ const styles = createStaticStyles(({ css }) => ({
min-width: 0;
+ line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
`,
@@ -83,17 +95,25 @@ const ContextItem = memo<FileItemProps>((props) => {
});
return (
<Tag closable size={'large'} onClick={handleClick} onClose={handleClose}>
- <Flexbox className={styles.icon}>
- <Content {...props} />
- {isUploading && (
- <div className={styles.progress}>
- <Progress percent={progress} showInfo={false} size={14} strokeWidth={2} type="circle" />
- </div>
- )}
+ <Flexbox horizontal align={'center'} className={styles.content}>
+ <Flexbox className={styles.icon}>
+ <Content {...props} />
+ {isUploading && (
+ <div className={styles.progress}>
+ <Progress
+ percent={progress}
+ showInfo={false}
+ size={14}
+ strokeWidth={2}
+ type="circle"
+ />
+ </div>
+ )}
+ </Flexbox>
+ <Tooltip title={file.name}>
+ <span className={styles.name}>{basename}</span>
+ </Tooltip>
</Flexbox>
- <Tooltip title={file.name}>
- <span className={styles.name}>{basename}</span>
- </Tooltip>
</Tag>
);
});
diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.ts
index b4acb7c7773..e9c12dd6dd8 100644
--- a/src/store/file/slices/upload/action.test.ts
+++ b/src/store/file/slices/upload/action.test.ts
@@ -254,6 +254,53 @@ describe('FileUploadAction', () => {
filename: mockFile.name,
});
});
+
+ it('should reuse the existing hash url when existing metadata is null', async () => {
+ const { result } = renderHook(() => useStore());
+
+ const mockFile = new File(['test content'], 'generated.png', { type: 'image/png' });
+ const mockDimensions = { height: 100, ratio: 2, width: 200 };
+ const mockCheckResult = {
+ isExist: true,
+ metadata: null,
+ url: 'assets/generations/2026-06-19/W4ipNrmH.png',
+ };
+ const mockFileResponse = {
+ id: 'file-id-generated',
+ url: 'https://example.com/generated.png',
+ };
+ const onStatusUpdate = vi.fn();
+
+ vi.mocked(getImageDimensions).mockResolvedValue(mockDimensions);
+ vi.spyOn(fileService, 'checkFileHash').mockResolvedValue(mockCheckResult);
+ vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);
+ const uploadToS3Spy = vi.spyOn(uploadService, 'uploadFileToS3');
+
+ const uploadResult = await act(async () => {
+ return await result.current.uploadWithProgress({
+ file: mockFile,
+ onStatusUpdate,
+ });
+ });
+
+ expect(uploadToS3Spy).not.toHaveBeenCalled();
+ expect(fileService.createFile).toHaveBeenCalledWith(
+ {
+ fileType: mockFile.type,
+ hash: 'mock-hash-value',
+ metadata: mockDimensions,
+ name: mockFile.name,
+ size: mockFile.size,
+ url: mockCheckResult.url,
+ },
+ undefined,
+ );
+ expect(uploadResult).toEqual({
+ ...mockFileResponse,
+ dimensions: mockDimensions,
+ filename: mockFile.name,
+ });
+ });
});
describe('file does not exist (new upload)', () => {
@@ -346,13 +393,11 @@ describe('FileUploadAction', () => {
vi.spyOn(fileService, 'checkFileHash').mockResolvedValue(mockCheckResult);
// Mock uploadFileToS3 to call onProgress
- vi.spyOn(uploadService, 'uploadFileToS3').mockImplementation(
- async (file, { onProgress }) => {
- onProgress?.('uploading', { progress: 50, restTime: 5, speed: 1024 });
- onProgress?.('success', { progress: 100, restTime: 0, speed: 2048 });
- return mockUploadResult;
- },
- );
+ vi.spyOn(uploadService, 'uploadFileToS3').mockImplementation(async (_, { onProgress }) => {
+ onProgress?.('uploading', { progress: 50, restTime: 5, speed: 1024 });
+ onProgress?.('success', { progress: 100, restTime: 0, speed: 2048 });
+ return mockUploadResult;
+ });
vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);
await act(async () => {
@@ -412,7 +457,7 @@ describe('FileUploadAction', () => {
// Mock uploadFileToS3 to call onNotSupported
vi.spyOn(uploadService, 'uploadFileToS3').mockImplementation(
- async (file, { onNotSupported }) => {
+ async (_, { onNotSupported }) => {
onNotSupported?.();
return { data: {} as any, success: false };
},
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index f266de7c797..c52001f8a04 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -8,7 +8,7 @@ import { message } from '@/components/AntdStaticMethods';
import { fileService } from '@/services/file';
import { uploadService } from '@/services/upload';
import { type StoreSetter } from '@/store/types';
-import { type FileMetadata, type UploadFileItem } from '@/types/files';
+import { type UploadFileItem } from '@/types/files';
import { getImageDimensions } from '@/utils/client/imageDimensions';
import { type FileStore } from '../../store';
@@ -71,6 +71,15 @@ const normalizeUploadedImageFileType = async (
});
};
+type ExistingFileMetadata = Record<string, unknown> & { path?: string };
+
+const normalizeExistingFileMetadata = (metadata: unknown): ExistingFileMetadata => {
+ // Existing hash records can come from generated assets or older upload paths where metadata is null.
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return {};
+
+ return metadata as ExistingFileMetadata;
+};
+
type Setter = StoreSetter<FileStore>;
export const createFileUploadSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
@@ -131,11 +140,11 @@ export class FileUploadActionImpl {
const hash = sha256(fileArrayBuffer);
const checkStatus = await fileService.checkFileHash(hash);
- let metadata: FileMetadata;
+ let metadata: ExistingFileMetadata;
// 3. if file exist, just skip upload
if (checkStatus.isExist) {
- metadata = checkStatus.metadata as FileMetadata;
+ metadata = normalizeExistingFileMetadata(checkStatus.metadata);
onStatusUpdate?.({
id: statusId,
type: 'updateFile',
@@ -168,7 +177,7 @@ export class FileUploadActionImpl {
});
if (!success) return;
- metadata = data;
+ metadata = { ...data };
}
// 4. use more powerful file type detector to get file type
@@ -188,6 +197,10 @@ export class FileUploadActionImpl {
if (audioMime && !fileType.startsWith('audio/')) fileType = audioMime;
// 5. create file to db
+ // Fall back to the global file URL when legacy/generated metadata has no `path`.
+ const fileUrl = metadata.path || checkStatus.url;
+ if (!fileUrl) throw new Error('File upload failed: missing file url');
+
const data = await fileService.createFile(
{
fileType,
@@ -197,7 +210,7 @@ export class FileUploadActionImpl {
parentId,
size: normalizedFile.size,
source,
- url: metadata.path || checkStatus.url,
+ url: fileUrl,
},
knowledgeBaseId,
);