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(task): stream attachment downloads in browser (#18368)

Tsukif3080811d7a3
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.md
index 71c14284579..3a95d07d579 100644
--- a/.agents/acceptance/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -278,7 +278,9 @@ Routes worth jumping to:
| `/` | Home (has a chat input) |
| `/agent/<agentId>` | Agent conversation (latest topic) |
| `/agent/<agentId>/<topicId>` | Specific topic in a conversation |
-| `/task` · `/task/<taskId>` | Task list / task detail |
+| `/tasks` | Task list |
+| `/task` | Task assistant |
+| `/task/<taskId>` | Task detail |
| `/page` | Documents (文稿) |
| `/settings` | Settings |
| `/community` | Discover / community |
diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.md
index a65572f20c8..2450ee5e0ba 100644
--- a/.agents/acceptance/references/probe-field-notes.md
+++ b/.agents/acceptance/references/probe-field-notes.md
@@ -1308,3 +1308,14 @@ active: true, remoteServerUrl: 'http://localhost:<port>', storageMode: 'selfHost
gives assertable output; reuse `-t` to keep multi-step cases in one topic.
Root cause (local JWKS mismatch) is worth a separate investigation, not a test-run fix.
The CLI-as-run-driver methodology this enables lives in PROJECT.md §4 CLI.
+
+### E44. Task SPA routes can show a debug fallback before the real route is ready
+
+- **Situation**: opening the Task UI in local SPA development can briefly show the dynamic-route
+ debug fallback, while an `agent-browser` screenshot may keep an older frame even after the DOM
+ has advanced to the real Task page.
+- **Doesn't work**: treating `/task` as the Task list, or declaring the renderer blank solely from
+ one screenshot when `innerText` and element geometry already show mounted Task content.
+- **Works**: use `/tasks` for the list and `/task/<identifier>` for detail, wait for a route-specific
+ heading or control, and compare DOM text plus target geometry with a raw CDP screenshot. If only
+ `agent-browser` remains stale, reset that browser session and reseed its auth state before retrying.
diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.ts
index dcb90a80d29..4bcdbc1923d 100644
--- a/apps/server/src/modules/S3/index.test.ts
+++ b/apps/server/src/modules/S3/index.test.ts
@@ -425,6 +425,25 @@ describe('FileS3', () => {
});
});
+ describe('createPreSignedUrlForDownload', () => {
+ it('should request attachment delivery with an encoded file name', async () => {
+ const s3 = new FileS3();
+
+ const result = await s3.createPreSignedUrlForDownload('video-file.mp4', '拼贴 动画.mp4');
+
+ expect(GetObjectCommand).toHaveBeenCalledWith({
+ Bucket: 'test-bucket',
+ Key: 'video-file.mp4',
+ ResponseContentDisposition:
+ "attachment; filename*=UTF-8''%E6%8B%BC%E8%B4%B4%20%E5%8A%A8%E7%94%BB.mp4",
+ });
+ expect(mockGetSignedUrl).toHaveBeenCalledWith(expect.anything(), expect.anything(), {
+ expiresIn: 7200,
+ });
+ expect(result).toBe('https://presigned-url.example.com');
+ });
+ });
+
describe('uploadBuffer', () => {
it('should upload buffer with correct parameters', async () => {
const s3 = new FileS3();
diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.ts
index 3942f69c3b4..1c95569ac85 100644
--- a/apps/server/src/modules/S3/index.ts
+++ b/apps/server/src/modules/S3/index.ts
@@ -26,6 +26,12 @@ export type FileType = z.infer<typeof fileSchema>;
const DEFAULT_S3_REGION = 'us-east-1';
const PUBLIC_READ_ACL_HEADER = 'public-read';
+const encodeContentDispositionFilename = (fileName: string) =>
+ encodeURIComponent(fileName || 'download').replaceAll(
+ /['()*]/g,
+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
+ );
+
export interface PreSignedUpload {
headers?: Record<string, string>;
url: string;
@@ -169,6 +175,22 @@ export class S3 {
});
}
+ public async createPreSignedUrlForDownload(
+ key: string,
+ fileName: string,
+ expiresIn?: number,
+ ): Promise<string> {
+ const command = new GetObjectCommand({
+ Bucket: this.bucket,
+ Key: key,
+ ResponseContentDisposition: `attachment; filename*=UTF-8''${encodeContentDispositionFilename(fileName)}`,
+ });
+
+ return getSignedUrl(this.client, command, {
+ expiresIn: expiresIn ?? fileEnv.S3_PREVIEW_URL_EXPIRE_IN,
+ });
+ }
+
/**
* Upload buffer with specified content type
*/
diff --git a/apps/server/src/services/file/impls/s3.test.ts b/apps/server/src/services/file/impls/s3.test.ts
index 6c9b31ddc2d..d84c4c75242 100644
--- a/apps/server/src/services/file/impls/s3.test.ts
+++ b/apps/server/src/services/file/impls/s3.test.ts
@@ -41,6 +41,9 @@ vi.mock('@/libs/redis', () => ({
// 模拟 S3 类
vi.mock('@/server/modules/S3', () => ({
FileS3: vi.fn().mockImplementation(() => ({
+ createPreSignedUrlForDownload: vi
+ .fn()
+ .mockResolvedValue('https://presigned.example.com/download'),
createPreSignedUrlForPreview: vi
.fn()
.mockResolvedValue('https://presigned.example.com/test.jpg'),
@@ -83,6 +86,23 @@ describe('S3StaticFileImpl', () => {
fileService = new S3StaticFileImpl(mockDb);
});
+ describe('createDownloadUrl', () => {
+ it('should normalize the storage key and request attachment delivery', async () => {
+ const createPreSignedUrlForDownload = fileService['s3'].createPreSignedUrlForDownload;
+ vi.spyOn(fileService, 'getKeyFromFullUrl').mockResolvedValue('path/to/video.mp4');
+
+ await expect(
+ fileService.createDownloadUrl('https://cdn.example.com/video.mp4', 'Collageanimation.mp4'),
+ ).resolves.toBe('https://presigned.example.com/download');
+
+ expect(createPreSignedUrlForDownload).toHaveBeenCalledWith(
+ 'path/to/video.mp4',
+ 'Collageanimation.mp4',
+ undefined,
+ );
+ });
+ });
+
describe('getFullFileUrl', () => {
it('should return empty string for null or undefined input', async () => {
expect(await fileService.getFullFileUrl(null)).toBe('');
diff --git a/apps/server/src/services/file/impls/s3.ts b/apps/server/src/services/file/impls/s3.ts
index ac9c0a914eb..f4942ce36fd 100644
--- a/apps/server/src/services/file/impls/s3.ts
+++ b/apps/server/src/services/file/impls/s3.ts
@@ -76,6 +76,14 @@ export class S3StaticFileImpl implements FileServiceImpl {
return this.s3.createPreSignedUrlForPreview(key, expiresIn);
}
+ async createPreSignedUrlForDownload(
+ key: string,
+ fileName: string,
+ expiresIn?: number,
+ ): Promise<string> {
+ return this.s3.createPreSignedUrlForDownload(key, fileName, expiresIn);
+ }
+
private async getStorageKeyFromUrl(url: string): Promise<string> {
if (!url.startsWith('http://') && !url.startsWith('https://')) return url;
@@ -87,6 +95,12 @@ export class S3StaticFileImpl implements FileServiceImpl {
return extractedKey;
}
+ async createDownloadUrl(url: string, fileName: string, expiresIn?: number): Promise<string> {
+ const key = await this.getStorageKeyFromUrl(url);
+
+ return this.createPreSignedUrlForDownload(key, fileName, expiresIn);
+ }
+
private async getCachedPreSignedUrlForPreview(key: string, expiresIn?: number): Promise<string> {
const expiresInSeconds = expiresIn ?? fileEnv.S3_PREVIEW_URL_EXPIRE_IN;
const cacheKey = createPresignedPreviewCacheKey(key, expiresInSeconds);
diff --git a/apps/server/src/services/file/impls/type.ts b/apps/server/src/services/file/impls/type.ts
index e5139694121..0d37d1aa0ad 100644
--- a/apps/server/src/services/file/impls/type.ts
+++ b/apps/server/src/services/file/impls/type.ts
@@ -11,6 +11,11 @@ export interface FileServiceImpl {
*/
createCachedPreSignedUrlForPreview: (url?: string | null, expiresIn?: number) => Promise<string>;
+ /**
+ * Resolve a stored file URL to a pre-signed browser download URL.
+ */
+ createDownloadUrl: (url: string, fileName: string, expiresIn?: number) => Promise<string>;
+
/**
* Create pre-signed upload descriptor
*/
@@ -21,6 +26,15 @@ export interface FileServiceImpl {
*/
createPreSignedUrl: (key: string) => Promise<string>;
+ /**
+ * Create a pre-signed URL that asks the browser to download the file.
+ */
+ createPreSignedUrlForDownload: (
+ key: string,
+ fileName: string,
+ expiresIn?: number,
+ ) => Promise<string>;
+
/**
* Create pre-signed preview URL
*/
diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.ts
index 0b4e8636078..1ebc8d3b9fc 100644
--- a/apps/server/src/services/file/index.ts
+++ b/apps/server/src/services/file/index.ts
@@ -96,6 +96,17 @@ export class FileService {
return this.impl.createPreSignedUrlForPreview(key, expiresIn);
}
+ /**
+ * Create a storage URL whose response is delivered as a browser download.
+ */
+ public async createDownloadUrl(
+ url: string,
+ fileName: string,
+ expiresIn?: number,
+ ): Promise<string> {
+ return this.impl.createDownloadUrl(url, fileName, expiresIn);
+ }
+
/**
* Create cached pre-signed preview URL
*/
diff --git a/apps/server/src/services/file/resolveAttachments.test.ts b/apps/server/src/services/file/resolveAttachments.test.ts
new file mode 100644
index 00000000000..1dd64163b01
--- /dev/null
+++ b/apps/server/src/services/file/resolveAttachments.test.ts
@@ -0,0 +1,59 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveAttachmentMetadata } from './resolveAttachments';
+
+const mocks = vi.hoisted(() => ({
+ findByIds: vi.fn(),
+ getFullFileUrl: vi.fn(),
+}));
+
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn().mockImplementation(() => ({ findByIds: mocks.findByIds })),
+}));
+
+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ getFullFileUrl: mocks.getFullFileUrl })),
+ getFileProxyUrl: (fileId: string) => `https://app.lobehub.com/f/${fileId}`,
+}));
+
+describe('resolveAttachmentMetadata', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns a stable proxy URL alongside refreshed preview URLs', async () => {
+ mocks.findByIds.mockResolvedValue([
+ {
+ fileType: 'application/pdf',
+ id: 'file_historical',
+ name: 'report.pdf',
+ size: 42,
+ url: 'tasks/report.pdf',
+ },
+ ]);
+ mocks.getFullFileUrl.mockResolvedValue(
+ 'https://storage.example.com/tasks/report.pdf?X-Amz-Signature=current',
+ );
+
+ const result = await resolveAttachmentMetadata({
+ db: {} as LobeChatDatabase,
+ fileIds: ['file_historical'],
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual([
+ {
+ downloadUrl: 'https://app.lobehub.com/f/file_historical',
+ fileType: 'application/pdf',
+ id: 'file_historical',
+ name: 'report.pdf',
+ size: 42,
+ url: 'https://storage.example.com/tasks/report.pdf?X-Amz-Signature=current',
+ },
+ ]);
+ });
+});
diff --git a/apps/server/src/services/file/resolveAttachments.ts b/apps/server/src/services/file/resolveAttachments.ts
index 07b9b3b058c..bc833062c05 100644
--- a/apps/server/src/services/file/resolveAttachments.ts
+++ b/apps/server/src/services/file/resolveAttachments.ts
@@ -5,7 +5,7 @@ import debug from 'debug';
import { FileModel } from '@/database/models/file';
import { DocumentService } from '@/server/services/document';
-import { FileService } from '@/server/services/file';
+import { FileService, getFileProxyUrl } from '@/server/services/file';
const log = debug('lobe-server:resolveAttachments');
@@ -197,11 +197,12 @@ export const resolveAttachmentMetadata = async ({
const fileService = signUrls ? new FileService(db, userId, workspaceId) : null;
const recordById = new Map(fileRecords.map((f) => [f.id, f]));
const items = await Promise.all(
- dedupedFileIds.map(async (id) => {
+ dedupedFileIds.map(async (id): Promise<ChatFileItem | undefined> => {
const file = recordById.get(id);
if (!file) return undefined;
const url = fileService ? (await fileService.getFullFileUrl(file.url)) || file.url : file.url;
return {
+ downloadUrl: getFileProxyUrl(file.id),
fileType: file.fileType || 'application/octet-stream',
id: file.id,
name: file.name || 'file',
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 457aa6e1af1..52d9a8894d0 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -38,6 +38,8 @@ export type UIMessageRoleType =
export interface ChatFileItem {
content?: string;
+ /** Stable application proxy URL used for browser-native downloads. */
+ downloadUrl?: string;
fileType: string;
id: string;
/**
diff --git a/src/app/(backend)/f/[id]/route.test.ts b/src/app/(backend)/f/[id]/route.test.ts
index 5fa8886535a..711d81fb211 100644
--- a/src/app/(backend)/f/[id]/route.test.ts
+++ b/src/app/(backend)/f/[id]/route.test.ts
@@ -12,6 +12,7 @@ import { GET } from './route';
const fileServiceMocks = vi.hoisted(() => {
const instance = {
createCachedPreSignedUrlForPreview: vi.fn(),
+ createDownloadUrl: vi.fn(),
getFullFileUrl: vi.fn(),
};
@@ -44,12 +45,16 @@ describe('file proxy route', () => {
vi.mocked(getServerDB).mockResolvedValue(db);
vi.mocked(FileModel.getFileById).mockResolvedValue({
id: 'file-id',
+ name: 'image.png',
url: 'files/user-id/image.png',
userId: 'owner-user-id',
} as FileItem);
fileServiceMocks.instance.createCachedPreSignedUrlForPreview.mockResolvedValue(
'https://s3.example.com/presigned-preview-url',
);
+ fileServiceMocks.instance.createDownloadUrl.mockResolvedValue(
+ 'https://s3.example.com/presigned-download-url',
+ );
});
it('should redirect to a cached presigned preview URL instead of a public full file URL', async () => {
@@ -66,4 +71,18 @@ describe('file proxy route', () => {
);
expect(fileServiceMocks.instance.getFullFileUrl).not.toHaveBeenCalled();
});
+
+ it('should redirect download requests to a content-disposition attachment URL', async () => {
+ const response = await GET(new Request('https://lobehub.com/f/file-id?download=1'), {
+ params: Promise.resolve({ id: 'file-id' }),
+ });
+
+ expect(response.status).toBe(302);
+ expect(response.headers.get('location')).toBe('https://s3.example.com/presigned-download-url');
+ expect(fileServiceMocks.instance.createDownloadUrl).toHaveBeenCalledWith(
+ 'files/user-id/image.png',
+ 'image.png',
+ );
+ expect(fileServiceMocks.instance.createCachedPreSignedUrlForPreview).not.toHaveBeenCalled();
+ });
});
diff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.ts
index e6ccecbc8b5..22aa8340c08 100644
--- a/src/app/(backend)/f/[id]/route.ts
+++ b/src/app/(backend)/f/[id]/route.ts
@@ -22,7 +22,7 @@ type Params = Promise<{ id: string }>;
* of which can attach auth headers/cookies. Adding `checkAuth` here would break
* every previously-shared `/f/:id` link, so access stays public by id.
*/
-export const GET = async (_req: Request, segmentData: { params: Params }) => {
+export const GET = async (req: Request, segmentData: { params: Params }) => {
try {
const params = await segmentData.params;
const { id } = params;
@@ -45,9 +45,11 @@ export const GET = async (_req: Request, segmentData: { params: Params }) => {
// Create file service with file owner's userId
const fileService = new FileService(db, file.userId);
- // Web: Generate a cached S3 presigned URL, normalizing legacy full S3 URLs.
- const redirectUrl = await fileService.createCachedPreSignedUrlForPreview(file.url);
- log('Web S3 presigned URL generated');
+ const isDownload = new URL(req.url).searchParams.get('download') === '1';
+ const redirectUrl = isDownload
+ ? await fileService.createDownloadUrl(file.url, file.name)
+ : await fileService.createCachedPreSignedUrlForPreview(file.url);
+ log('Web S3 presigned URL generated (%s)', isDownload ? 'download' : 'preview');
// Return 302 redirect
return Response.redirect(redirectUrl, 302);
diff --git a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx
index beabafd5788..ed86d264199 100644
--- a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx
@@ -15,7 +15,7 @@ import {
import { Button, confirmModal } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
import { MessageCircle, MoreHorizontal, Pencil, Trash } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AttachmentUploadButton } from '@/features/AttachmentInput';
@@ -67,14 +67,18 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {
[activity.content, activity.editorData],
);
- const handleEdit = useCallback(() => {
- // Seed URL→fileId map so attachments serialize back to fileIds on save.
+ useEffect(() => {
if (activity.files && activity.files.length > 0) {
- seedAttachments(activity.files.map((f) => ({ id: f.id, url: f.url })));
+ seedAttachments(
+ activity.files.map((f) => ({ downloadUrl: f.downloadUrl, id: f.id, url: f.url })),
+ );
}
- setIsEditing(true);
}, [activity.files]);
+ const handleEdit = useCallback(() => {
+ setIsEditing(true);
+ }, []);
+
const handleCancel = useCallback(() => {
setIsEditing(false);
}, []);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx
index 05fea52aaca..c95ddc57865 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx
@@ -77,7 +77,9 @@ const TaskInstruction = memo(() => {
useEffect(() => {
if (persistedFiles && persistedFiles.length > 0) {
- seedAttachments(persistedFiles.map((f) => ({ id: f.id, url: f.url })));
+ seedAttachments(
+ persistedFiles.map((f) => ({ downloadUrl: f.downloadUrl, id: f.id, url: f.url })),
+ );
}
}, [persistedFiles]);
diff --git a/src/features/EditorCanvas/LinearFilePlugin.tsx b/src/features/EditorCanvas/LinearFilePlugin.tsx
index 207469f4f30..675c371ec90 100644
--- a/src/features/EditorCanvas/LinearFilePlugin.tsx
+++ b/src/features/EditorCanvas/LinearFilePlugin.tsx
@@ -1,6 +1,5 @@
'use client';
-import { downloadFile } from '@lobechat/utils/client';
import { FilePlugin, UploadPlugin, useLexicalComposerContext } from '@lobehub/editor';
import { ActionIcon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
@@ -21,6 +20,7 @@ import { formatSize, formatSpeed, formatTime } from '@/utils/format';
import type { EditorFileUploadTracker } from './editorFileUploadTracker';
import { createEditorFileUploadTracker } from './editorFileUploadTracker';
+import { openFileDownload } from './fileDownload';
import type { EditorAttachmentUpload } from './useImageUpload';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -241,7 +241,7 @@ export const LinearFileCard = memo<LinearFileCardProps>(({ node, uploadTracker }
event.stopPropagation();
event.preventDefault();
if (!fileUrl) return;
- void downloadFile(fileUrl, name);
+ openFileDownload(fileUrl);
};
return (
diff --git a/src/features/EditorCanvas/attachmentRegistry.test.ts b/src/features/EditorCanvas/attachmentRegistry.test.ts
new file mode 100644
index 00000000000..777b986e2ae
--- /dev/null
+++ b/src/features/EditorCanvas/attachmentRegistry.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { getFileIdForUrl, getRegisteredAttachment, seedAttachments } from './attachmentRegistry';
+
+describe('attachmentRegistry', () => {
+ it('matches refreshed presigned URLs without relying on their query signatures', () => {
+ seedAttachments([
+ {
+ downloadUrl: 'https://app.lobehub.com/f/file_historical',
+ id: 'file_historical',
+ url: 'https://storage.example.com/tasks/report.pdf?X-Amz-Signature=current',
+ },
+ ]);
+
+ const historicalUrl = 'https://storage.example.com/tasks/report.pdf?X-Amz-Signature=historical';
+
+ expect(getFileIdForUrl(historicalUrl)).toBe('file_historical');
+ expect(getRegisteredAttachment(historicalUrl)).toEqual({
+ downloadUrl: 'https://app.lobehub.com/f/file_historical',
+ fileId: 'file_historical',
+ });
+ });
+});
diff --git a/src/features/EditorCanvas/attachmentRegistry.ts b/src/features/EditorCanvas/attachmentRegistry.ts
index cb1f7a1c4a2..f3851ab78da 100644
--- a/src/features/EditorCanvas/attachmentRegistry.ts
+++ b/src/features/EditorCanvas/attachmentRegistry.ts
@@ -10,20 +10,58 @@
* existing editor must `seedAttachments(...)` from persisted file metadata.
*/
-const urlToFileId = new Map<string, string>();
+export interface RegisteredAttachment {
+ downloadUrl?: string;
+ fileId: string;
+}
-export const registerAttachment = (url: string, fileId: string): void => {
+const urlToAttachment = new Map<string, RegisteredAttachment>();
+
+const getUrlKeys = (url: string): string[] => {
+ const keys = [url];
+
+ try {
+ const normalizedUrl = new URL(url);
+ normalizedUrl.hash = '';
+ normalizedUrl.search = '';
+ const normalized = normalizedUrl.toString();
+ if (normalized !== url) keys.push(normalized);
+ } catch {
+ const normalized = url.split(/[?#]/, 1)[0];
+ if (normalized && normalized !== url) keys.push(normalized);
+ }
+
+ return keys;
+};
+
+export const registerAttachment = (url: string, fileId: string, downloadUrl?: string): void => {
if (!url) return;
- urlToFileId.set(url, fileId);
+
+ const attachment = { downloadUrl, fileId } satisfies RegisteredAttachment;
+ for (const key of getUrlKeys(url)) urlToAttachment.set(key, attachment);
};
-export const getFileIdForUrl = (url: string | undefined): string | undefined => {
+export const getRegisteredAttachment = (
+ url: string | undefined,
+): RegisteredAttachment | undefined => {
if (!url) return undefined;
- return urlToFileId.get(url);
+
+ for (const key of getUrlKeys(url)) {
+ const attachment = urlToAttachment.get(key);
+ if (attachment) return attachment;
+ }
+
+ return undefined;
+};
+
+export const getFileIdForUrl = (url: string | undefined): string | undefined => {
+ return getRegisteredAttachment(url)?.fileId;
};
-export const seedAttachments = (items: Array<{ id: string; url: string }>): void => {
+export const seedAttachments = (
+ items: Array<{ downloadUrl?: string; id: string; url: string }>,
+): void => {
for (const item of items) {
- if (item?.url && item?.id) urlToFileId.set(item.url, item.id);
+ if (item?.url && item?.id) registerAttachment(item.url, item.id, item.downloadUrl);
}
};
diff --git a/src/features/EditorCanvas/fileDownload.test.ts b/src/features/EditorCanvas/fileDownload.test.ts
new file mode 100644
index 00000000000..0294f81c8b3
--- /dev/null
+++ b/src/features/EditorCanvas/fileDownload.test.ts
@@ -0,0 +1,69 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { seedAttachments } from './attachmentRegistry';
+import { getFileDownloadUrl, openFileDownload } from './fileDownload';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('fileDownload', () => {
+ it('requests attachment delivery for file proxy URLs', () => {
+ expect(
+ getFileDownloadUrl('/f/file_123', {
+ baseUrl: 'https://app.lobehub.com/tasks/T-201',
+ }),
+ ).toBe('https://app.lobehub.com/f/file_123?download=1');
+ });
+
+ it('keeps unregistered direct storage URLs unchanged', () => {
+ const url = 'https://storage.example.com/video.mp4?X-Amz-Signature=signature';
+
+ expect(getFileDownloadUrl(url, { baseUrl: 'https://app.lobehub.com/tasks/T-201' })).toBe(url);
+ });
+
+ it('routes direct storage URLs through the stable file download proxy', () => {
+ const url = 'https://storage.example.com/video.mp4?X-Amz-Signature=signature';
+
+ expect(
+ getFileDownloadUrl(url, {
+ downloadUrl: 'https://app.lobehub.com/f/file_video',
+ fileId: 'file_video',
+ }),
+ ).toBe('https://app.lobehub.com/f/file_video?download=1');
+ });
+
+ it('opens the download synchronously in a new tab', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+
+ openFileDownload('/f/file_123');
+
+ expect(open).toHaveBeenCalledWith(
+ expect.stringContaining('/f/file_123?download=1'),
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ });
+
+ it('opens historical presigned URLs through the registered download proxy', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ seedAttachments([
+ {
+ downloadUrl: 'https://app.lobehub.com/f/file_historical',
+ id: 'file_historical',
+ url: 'https://storage.example.com/tasks/report.pdf?X-Amz-Signature=current',
+ },
+ ]);
+
+ openFileDownload('https://storage.example.com/tasks/report.pdf?X-Amz-Signature=historical');
+
+ expect(open).toHaveBeenCalledWith(
+ 'https://app.lobehub.com/f/file_historical?download=1',
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ });
+});
diff --git a/src/features/EditorCanvas/fileDownload.ts b/src/features/EditorCanvas/fileDownload.ts
new file mode 100644
index 00000000000..01154e73f07
--- /dev/null
+++ b/src/features/EditorCanvas/fileDownload.ts
@@ -0,0 +1,53 @@
+import { getRegisteredAttachment } from './attachmentRegistry';
+
+const FILE_PROXY_PATH = /^\/f\/[^/]+$/;
+
+interface FileDownloadUrlOptions {
+ appOrigin?: string;
+ baseUrl?: string;
+ downloadUrl?: string;
+ fileId?: string;
+}
+
+/**
+ * The file proxy normally returns an inline preview URL. Opting into its download
+ * response lets the browser stream the file and expose native progress instead of
+ * waiting for the whole file to become a client-side Blob (LOBE-12762).
+ */
+export const getFileDownloadUrl = (url: string, options: FileDownloadUrlOptions = {}): string => {
+ const baseUrl =
+ options.baseUrl ?? (typeof window === 'undefined' ? undefined : window.location.href);
+
+ try {
+ const downloadUrl = new URL(options.downloadUrl ?? url, baseUrl);
+
+ if (FILE_PROXY_PATH.test(downloadUrl.pathname)) {
+ downloadUrl.searchParams.set('download', '1');
+ return downloadUrl.toString();
+ }
+
+ if (options.fileId && options.appOrigin) {
+ const proxyUrl = new URL(`/f/${encodeURIComponent(options.fileId)}`, options.appOrigin);
+ proxyUrl.searchParams.set('download', '1');
+ return proxyUrl.toString();
+ }
+
+ return url;
+ } catch {
+ return url;
+ }
+};
+
+export const openFileDownload = (url: string): void => {
+ // Keep this synchronous with the click gesture so popup blockers allow the download tab.
+ const attachment = getRegisteredAttachment(url);
+ window.open(
+ getFileDownloadUrl(url, {
+ appOrigin: window.location.origin,
+ downloadUrl: attachment?.downloadUrl,
+ fileId: attachment?.fileId,
+ }),
+ '_blank',
+ 'noopener,noreferrer',
+ );
+};