🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
:recycle: refactor: use /f/:fid as file mode
arvinxx3b01174d4ffa
diff --git a/src/server/routers/lambda/__tests__/file.test.ts b/src/server/routers/lambda/__tests__/file.test.tsindex 267308c454e..050be3e9cd4 100644--- a/src/server/routers/lambda/__tests__/file.test.ts+++ b/src/server/routers/lambda/__tests__/file.test.ts@@ -66,6 +66,12 @@ vi.mock('@/config/db', () => ({},}));+vi.mock('@/envs/app', () => ({+ appEnv: {+ APP_URL: 'https://lobehub.com',+ },+}));+const mockAsyncTaskFindByIds = vi.fn();const mockAsyncTaskFindById = vi.fn();const mockAsyncTaskDelete = vi.fn();@@ -87,15 +93,23 @@ vi.mock('@/database/models/chunk', () => ({})),}));+const mockFileModelCheckHash = vi.fn();+const mockFileModelCreate = vi.fn();+const mockFileModelDelete = vi.fn();+const mockFileModelDeleteMany = vi.fn();+const mockFileModelFindById = vi.fn();+const mockFileModelQuery = vi.fn();+const mockFileModelClear = vi.fn();+vi.mock('@/database/models/file', () => ({FileModel: vi.fn(() => ({- checkHash: vi.fn(),- create: vi.fn(),- delete: vi.fn(),- deleteMany: vi.fn(),- findById: vi.fn(),- query: vi.fn(),- clear: vi.fn(),+ checkHash: mockFileModelCheckHash,+ create: mockFileModelCreate,+ delete: mockFileModelDelete,+ deleteMany: mockFileModelDeleteMany,+ findById: mockFileModelFindById,+ query: mockFileModelQuery,+ clear: mockFileModelClear,})),}));@@ -171,6 +185,25 @@ describe('fileRouter', () => {}),).rejects.toThrow();});++ it('should return proxy URL format ${APP_URL}/f/:id', async () => {+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });++ const result = await caller.createFile({+ hash: 'test-hash',+ fileType: 'text',+ name: 'test.txt',+ size: 100,+ url: 'files/test.txt',+ metadata: {},+ });++ expect(result).toEqual({+ id: 'new-file-id',+ url: 'https://lobehub.com/f/new-file-id',+ });+ });});describe('findById', () => {@@ -179,22 +212,56 @@ describe('fileRouter', () => {await expect(caller.findById({ id: 'invalid-id' })).rejects.toThrow(TRPCError);});++ it('should return proxy URL format ${APP_URL}/f/:id', async () => {+ mockFileModelFindById.mockResolvedValue(mockFile);++ const result = await caller.findById({ id: 'test-id' });++ expect(result.url).toBe('https://lobehub.com/f/test-id');+ });});describe('getFileItemById', () => {it('should throw error when file not found', async () => {- ctx.fileModel.findById.mockResolvedValue(null);+ mockFileModelFindById.mockResolvedValue(null);await expect(caller.getFileItemById({ id: 'invalid-id' })).rejects.toThrow(TRPCError);});++ it('should return proxy URL format ${APP_URL}/f/:id', async () => {+ mockFileModelFindById.mockResolvedValue(mockFile);++ const result = await caller.getFileItemById({ id: 'test-id' });++ expect(result?.url).toBe('https://lobehub.com/f/test-id');+ });});describe('getFiles', () => {it('should handle fileModel.query returning undefined', async () => {- ctx.fileModel.query.mockResolvedValue(undefined);+ mockFileModelQuery.mockResolvedValue(undefined);await expect(caller.getFiles({})).rejects.toThrow();});++ it('should return proxy URL format ${APP_URL}/f/:id for each file', async () => {+ const files = [+ { ...mockFile, id: 'file-1' },+ { ...mockFile, id: 'file-2' },+ ];+ mockFileModelQuery.mockResolvedValue(files);+ mockChunkCountByFileIds.mockResolvedValue([+ { id: 'file-1', count: 5 },+ { id: 'file-2', count: 3 },+ ]);++ const result = await caller.getFiles({});++ expect(result).toHaveLength(2);+ expect(result[0].url).toBe('https://lobehub.com/f/file-1');+ expect(result[1].url).toBe('https://lobehub.com/f/file-2');+ });});describe('getKnowledgeItems', () => {@@ -233,7 +300,7 @@ describe('fileRouter', () => {finishEmbedding: true,id: 'file-1',sourceType: 'file',- url: 'https://example.com/test-url',+ url: 'https://lobehub.com/f/file-1',});expect(result.items[1]).toMatchObject({chunkCount: null,diff --git a/src/server/routers/lambda/file.ts b/src/server/routers/lambda/file.tsindex 10092f8278f..a65fe5e3e57 100644--- a/src/server/routers/lambda/file.ts+++ b/src/server/routers/lambda/file.ts@@ -8,12 +8,19 @@ import { ChunkModel } from '@/database/models/chunk';import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';import { KnowledgeRepo } from '@/database/repositories/knowledge';+import { appEnv } from '@/envs/app';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';import { AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';import { type FileListItem, QueryFileListSchema, UploadFileSchema } from '@/types/files';+/**+ * Generate file proxy URL+ * Returns a unified proxy URL format: ${APP_URL}/f/:id+ */+const getFileProxyUrl = (fileId: string): string => `${appEnv.APP_URL}/f/${fileId}`;+const fileProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -72,7 +79,7 @@ export const fileRouter = router({!isExist,);- return { id, url: await ctx.fileService.getFullFileUrl(input.url) };+ return { id, url: getFileProxyUrl(id) };}),findById: fileProcedure.input(@@ -98,7 +105,7 @@ export const fileRouter = router({size: item.size,source: item.source,updatedAt: item.updatedAt,- url: await ctx.fileService.getFullFileUrl(item.url),+ url: getFileProxyUrl(item.id),userId: item.userId,};}),@@ -140,7 +147,7 @@ export const fileRouter = router({size: item.size,sourceType: 'file' as const,updatedAt: item.updatedAt,- url: await ctx.fileService.getFullFileUrl(item.url!),+ url: getFileProxyUrl(item.id),};}),@@ -178,7 +185,7 @@ export const fileRouter = router({embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,sourceType: 'file' as const,- url: await ctx.fileService.getFullFileUrl(item.url!),+ url: getFileProxyUrl(item.id),} as FileListItem;resultFiles.push(fileItem);}@@ -243,7 +250,7 @@ export const fileRouter = router({embeddingError: embeddingTask?.error ?? null,embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,- url: await ctx.fileService.getFullFileUrl(item.url!),+ url: getFileProxyUrl(item.id),} as FileListItem);} else {// Document item - no chunk processing needed, includes editorData@@ -319,7 +326,7 @@ export const fileRouter = router({embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,sourceType: 'file' as const,- url: await ctx.fileService.getFullFileUrl(item.url!),+ url: getFileProxyUrl(item.id),} as FileListItem);}diff --git a/src/server/services/file/__tests__/index.test.ts b/src/server/services/file/__tests__/index.test.tsindex 739d2662d8b..4a2c5cb58af 100644--- a/src/server/services/file/__tests__/index.test.ts+++ b/src/server/services/file/__tests__/index.test.ts@@ -12,6 +12,12 @@ vi.mock('@/config/db', () => ({},}));+vi.mock('@/envs/app', () => ({+ appEnv: {+ APP_URL: 'https://lobehub.com',+ },+}));+vi.mock('../impls', () => ({createFileServiceModule: () => ({deleteFile: vi.fn(),@@ -247,4 +253,88 @@ describe('FileService', () => {expect(service['impl'].uploadMedia).toHaveBeenCalledWith(testKey, testBuffer);expect(result).toBe(expectedResult);});++ describe('createFileRecord', () => {+ beforeEach(() => {+ mockFileModel.checkHash = vi.fn();+ mockFileModel.create = vi.fn();+ });++ it('should return proxy URL format ${APP_URL}/f/:id', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: false });+ mockFileModel.create.mockResolvedValue({ id: 'new-file-id' });++ const result = await service.createFileRecord({+ fileHash: 'test-hash',+ fileType: 'image/png',+ name: 'test.png',+ size: 1024,+ url: 'files/test.png',+ });++ expect(result).toEqual({+ fileId: 'new-file-id',+ url: 'https://lobehub.com/f/new-file-id',+ });+ });++ it('should use custom id when provided', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: true });+ mockFileModel.create.mockResolvedValue({ id: 'custom-id' });++ const result = await service.createFileRecord({+ fileHash: 'test-hash',+ fileType: 'image/png',+ id: 'custom-id',+ name: 'test.png',+ size: 1024,+ url: 'files/test.png',+ });++ expect(result).toEqual({+ fileId: 'custom-id',+ url: 'https://lobehub.com/f/custom-id',+ });+ });++ it('should insert to global files when hash does not exist', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: false });+ mockFileModel.create.mockResolvedValue({ id: 'file-id' });++ await service.createFileRecord({+ fileHash: 'new-hash',+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'files/test.txt',+ });++ expect(mockFileModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ fileHash: 'new-hash',+ }),+ true, // insertToGlobalFiles = true when hash doesn't exist+ );+ });++ it('should not insert to global files when hash already exists', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: true });+ mockFileModel.create.mockResolvedValue({ id: 'file-id' });++ await service.createFileRecord({+ fileHash: 'existing-hash',+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'files/test.txt',+ });++ expect(mockFileModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ fileHash: 'existing-hash',+ }),+ false, // insertToGlobalFiles = false when hash exists+ );+ });+ });});diff --git a/src/server/services/file/impls/index.ts b/src/server/services/file/impls/index.tsindex 38cfc8179e7..e569d104bf9 100644--- a/src/server/services/file/impls/index.ts+++ b/src/server/services/file/impls/index.ts@@ -1,19 +1,11 @@-import { isDesktop } from '@/const/version';--import { DesktopLocalFileImpl } from './local';import { S3StaticFileImpl } from './s3';import { type FileServiceImpl } from './type';/*** Create file service module- * Automatically selects between S3 or desktop local file implementation based on environment+ * Returns S3 file implementation for cloud storage*/export const createFileServiceModule = (): FileServiceImpl => {- // If in desktop application environment, use local file implementation- if (isDesktop) {- return new DesktopLocalFileImpl();- }-return new S3StaticFileImpl();};diff --git a/src/server/services/file/impls/local.test.ts b/src/server/services/file/impls/local.test.tsdeleted file mode 100644index 39ae4f36c8e..00000000000--- a/src/server/services/file/impls/local.test.ts+++ /dev/null@@ -1,445 +0,0 @@-import { existsSync, readFileSync } from 'node:fs';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { electronIpcClient } from '@/server/modules/ElectronIPCClient';--import { DesktopLocalFileImpl } from './local';--// 模拟依赖项-vi.mock('node:fs', async (importOriginal) => ({- ...((await importOriginal()) as any),- existsSync: vi.fn(),- readFileSync: vi.fn(),-}));--vi.mock('@/server/modules/ElectronIPCClient', () => ({- electronIpcClient: {- getFilePathById: vi.fn(),- deleteFiles: vi.fn(),- createFile: vi.fn(),- },-}));--describe('DesktopLocalFileImpl', () => {- let service: DesktopLocalFileImpl;- const testFilePath = '/path/to/file.txt';- const testFileKey = 'desktop://file.txt';- const testFileContent = 'test file content';- const testFileBuffer = Buffer.from(testFileContent);-- beforeEach(() => {- service = new DesktopLocalFileImpl();-- // 重置所有模拟- vi.resetAllMocks();-- // 设置默认模拟行为- vi.mocked(electronIpcClient.getFilePathById).mockResolvedValue(testFilePath);- vi.mocked(existsSync).mockReturnValue(true);- vi.mocked(readFileSync).mockReturnValueOnce(testFileBuffer);- });-- describe('getLocalFileUrl', () => {- it.skip('应该返回 localhost 的 http url', async () => {});- });-- describe('createPreSignedUrl', () => {- it('应该返回原始键', async () => {- const result = await service.createPreSignedUrl(testFileKey);-- expect(result).toBe(testFileKey);- });- });-- describe('createPreSignedUrlForPreview', () => {- it('应该调用getLocalFileUrl获取预览URL', async () => {- // 准备- const getLocalFileUrlSpy = vi.spyOn(service as any, 'getLocalFileUrl');- getLocalFileUrlSpy.mockResolvedValueOnce('data:text/plain;base64,dGVzdA==');-- // 执行- const result = await service.createPreSignedUrlForPreview(testFileKey);-- // 验证- expect(getLocalFileUrlSpy).toHaveBeenCalledWith(testFileKey);- expect(result).toBe('data:text/plain;base64,dGVzdA==');- });- });-- describe('deleteFile', () => {- it('应该调用deleteFiles方法删除单个文件', async () => {- // 准备- vi.mocked(electronIpcClient.deleteFiles).mockResolvedValueOnce({ success: true });- const deleteFilesSpy = vi.spyOn(service, 'deleteFiles');-- // 执行- await service.deleteFile(testFileKey);-- // 验证- expect(deleteFilesSpy).toHaveBeenCalledWith([testFileKey]);- });- });-- describe('deleteFiles', () => {- it('应该成功删除有效的文件', async () => {- // 准备- const keys = ['desktop://file1.txt', 'desktop://file2.png'];- vi.mocked(electronIpcClient.deleteFiles).mockResolvedValueOnce({ success: true });-- // 执行- const result = await service.deleteFiles(keys);-- // 验证- expect(electronIpcClient.deleteFiles).toHaveBeenCalledWith(keys);- expect(result).toEqual({ success: true });- });-- it('当提供无效键时应返回错误', async () => {- // 准备: 包含无效的文件路径- const keys = ['invalid://file1.txt', 'desktop://file2.png'];-- // 执行- const result = await service.deleteFiles(keys);-- // 验证- expect(electronIpcClient.deleteFiles).not.toHaveBeenCalled();- expect(result.success).toBe(false);- expect(result.errors).toBeDefined();- expect(result.errors!.length).toBe(1);- expect(result.errors![0].path).toBe('invalid://file1.txt');- });-- it('当未提供键时应返回成功', async () => {- // 执行- const result = await service.deleteFiles([]);-- // 验证- expect(electronIpcClient.deleteFiles).not.toHaveBeenCalled();- expect(result).toEqual({ success: true });- });-- it('当删除过程中出现错误时应正确处理', async () => {- // 准备- const keys = ['desktop://file1.txt'];- vi.mocked(electronIpcClient.deleteFiles).mockRejectedValueOnce(new Error('删除错误'));-- // 执行- const result = await service.deleteFiles(keys);-- // 验证- expect(result.success).toBe(false);- expect(result.errors).toBeDefined();- expect(result.errors![0].message).toContain('删除错误');- });- });-- describe.skip('getFileByteArray', () => {- it('应该返回文件的字节数组', async () => {- // 准备- vi.mocked(readFileSync).mockReturnValueOnce(Buffer.from('测试内容'));-- // 执行- const result = await service.getFileByteArray(testFileKey);-- // 验证- expect(electronIpcClient.getFilePathById).toHaveBeenCalledWith(testFileKey);- expect(existsSync).toHaveBeenCalledWith(testFilePath);- expect(readFileSync).toHaveBeenCalledWith(testFilePath);- expect(result).toBeInstanceOf(Uint8Array);- expect(Buffer.from(result).toString()).toBe('测试内容');- });-- it('当文件不存在时应返回空数组', async () => {- // 准备- vi.mocked(existsSync).mockReturnValueOnce(false);-- // 执行- const result = await service.getFileByteArray(testFileKey);-- // 验证- expect(result).toBeInstanceOf(Uint8Array);- expect(result.length).toBe(0);- });-- it('当发生错误时应返回空数组', async () => {- // 准备- vi.mocked(electronIpcClient.getFilePathById).mockRejectedValueOnce(new Error('测试错误'));-- // 执行- const result = await service.getFileByteArray(testFileKey);-- // 验证- expect(result).toBeInstanceOf(Uint8Array);- expect(result.length).toBe(0);- });- });-- describe.skip('getFileContent', () => {- it('应该返回文件内容', async () => {- // 准备- vi.mocked(readFileSync).mockReturnValueOnce('文件内容');-- // 执行- const result = await service.getFileContent(testFileKey);-- // 验证- expect(electronIpcClient.getFilePathById).toHaveBeenCalledWith(testFileKey);- expect(existsSync).toHaveBeenCalledWith(testFilePath);- expect(readFileSync).toHaveBeenCalledWith(testFilePath, 'utf8');- expect(result).toBe('文件内容');- });-- it('当文件不存在时应返回空字符串', async () => {- // 准备- vi.mocked(existsSync).mockReturnValueOnce(false);-- // 执行- const result = await service.getFileContent(testFileKey);-- // 验证- expect(result).toBe('');- });-- it('当发生错误时应返回空字符串', async () => {- // 准备- vi.mocked(electronIpcClient.getFilePathById).mockRejectedValueOnce(new Error('测试错误'));-- // 执行- const result = await service.getFileContent(testFileKey);-- // 验证- expect(result).toBe('');- });- });-- describe('getFullFileUrl', () => {- it('应该调用getLocalFileUrl获取完整URL', async () => {- // 准备- const getLocalFileUrlSpy = vi.spyOn(service as any, 'getLocalFileUrl');- getLocalFileUrlSpy.mockResolvedValueOnce('data:image/png;base64,test');-- // 执行- const result = await service.getFullFileUrl(testFileKey);-- // 验证- expect(getLocalFileUrlSpy).toHaveBeenCalledWith(testFileKey);- expect(result).toBe('data:image/png;base64,test');- });-- it('当url为空时应返回空字符串', async () => {- // 执行- const result = await service.getFullFileUrl(null);-- // 验证- expect(result).toBe('');- });-- // Legacy bug compatibility tests - https://github.com/lobehub/lobe-chat/issues/8994- describe('legacy bug compatibility', () => {- it('should handle full URL input by extracting key', async () => {- const fullUrl = 'http://localhost:3000/desktop-file/documents/test.txt';-- // Mock getKeyFromFullUrl and getLocalFileUrl- vi.spyOn(service, 'getKeyFromFullUrl').mockReturnValue('desktop://documents/test.txt');- const getLocalFileUrlSpy = vi.spyOn(service as any, 'getLocalFileUrl');- getLocalFileUrlSpy.mockResolvedValueOnce('data:image/png;base64,test');-- const result = await service.getFullFileUrl(fullUrl);-- expect(service.getKeyFromFullUrl).toHaveBeenCalledWith(fullUrl);- expect(getLocalFileUrlSpy).toHaveBeenCalledWith('desktop://documents/test.txt');- expect(result).toBe('data:image/png;base64,test');- });-- it('should handle normal desktop:// key input without extraction', async () => {- const key = 'desktop://documents/test.txt';-- const extractSpy = vi.spyOn(service, 'getKeyFromFullUrl');- const getLocalFileUrlSpy = vi.spyOn(service as any, 'getLocalFileUrl');- getLocalFileUrlSpy.mockResolvedValueOnce('data:image/png;base64,test');-- const result = await service.getFullFileUrl(key);-- expect(extractSpy).not.toHaveBeenCalled();- expect(getLocalFileUrlSpy).toHaveBeenCalledWith(key);- expect(result).toBe('data:image/png;base64,test');- });-- it('should handle https:// URLs for legacy compatibility', async () => {- const httpsUrl = 'https://localhost:3000/desktop-file/images/photo.jpg';-- vi.spyOn(service, 'getKeyFromFullUrl').mockReturnValue('desktop://images/photo.jpg');- const getLocalFileUrlSpy = vi.spyOn(service as any, 'getLocalFileUrl');- getLocalFileUrlSpy.mockResolvedValueOnce('data:image/jpeg;base64,test');-- const result = await service.getFullFileUrl(httpsUrl);-- expect(service.getKeyFromFullUrl).toHaveBeenCalledWith(httpsUrl);- expect(getLocalFileUrlSpy).toHaveBeenCalledWith('desktop://images/photo.jpg');- expect(result).toBe('data:image/jpeg;base64,test');- });- });- });-- describe('uploadContent', () => {- it('应该正确处理上传内容的请求', async () => {- // 目前这个方法未实现,仅验证调用不会导致错误- const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});-- await service.uploadContent('path/to/file', 'content');-- expect(consoleSpy).toHaveBeenCalledWith(- 'uploadContent not implemented for Desktop local file service',- 'path/to/file',- 'content',- );- });- });-- describe('getKeyFromFullUrl', () => {- it('应该从HTTP URL中正确提取desktop://路径', () => {- // 准备- const url = 'http://localhost:3000/desktop-file/documents/test.txt';-- // 执行- const result = service.getKeyFromFullUrl(url);-- // 验证- expect(result).toBe('desktop://documents/test.txt');- });-- it('应该处理复杂的文件路径', () => {- // 准备- const url = 'http://localhost:3000/desktop-file/folder/subfolder/image.png';-- // 执行- const result = service.getKeyFromFullUrl(url);-- // 验证- expect(result).toBe('desktop://folder/subfolder/image.png');- });-- it('应该处理根目录下的文件', () => {- // 准备- const url = 'http://localhost:3000/desktop-file/test.pdf';-- // 执行- const result = service.getKeyFromFullUrl(url);-- // 验证- expect(result).toBe('desktop://test.pdf');- });-- it('当URL格式不正确时应返回空字符串', () => {- // 准备- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- const invalidUrl = 'not-a-valid-url';-- // 执行- const result = service.getKeyFromFullUrl(invalidUrl);-- // 验证- expect(result).toBe('');- expect(consoleSpy).toHaveBeenCalled();- });- });-- describe('uploadMedia', () => {- it('应该成功上传媒体文件', async () => {- // 准备- const testKey = 'desktop://images/test.jpg';- const testBuffer = Buffer.from('fake image data');- const mockResult = {- success: true,- metadata: {- path: testKey,- filename: 'test.jpg',- dirname: 'desktop://images',- date: new Date().toISOString(),- },- };-- vi.mocked(electronIpcClient.createFile).mockResolvedValueOnce(mockResult);-- // 执行- const result = await service.uploadMedia(testKey, testBuffer);-- // 验证- expect(electronIpcClient.createFile).toHaveBeenCalledWith({- content: testBuffer.toString('base64'),- filename: 'test.jpg',- hash: expect.any(String), // SHA256 hash- path: testKey,- type: 'image/jpeg',- });- expect(result).toEqual({ key: testKey });- });-- it('应该正确处理PNG文件', async () => {- // 准备- const testKey = 'desktop://images/test.png';- const testBuffer = Buffer.from('fake png data');- const mockResult = {- success: true,- metadata: {- path: testKey,- filename: 'test.png',- dirname: 'desktop://images',- date: new Date().toISOString(),- },- };-- vi.mocked(electronIpcClient.createFile).mockResolvedValueOnce(mockResult);-- // 执行- const result = await service.uploadMedia(testKey, testBuffer);-- // 验证- expect(electronIpcClient.createFile).toHaveBeenCalledWith(- expect.objectContaining({- filename: 'test.png',- type: 'image/png',- }),- );- expect(result).toEqual({ key: testKey });- });-- it('当上传失败时应抛出错误', async () => {- // 准备- const testKey = 'desktop://images/test.jpg';- const testBuffer = Buffer.from('fake image data');- const mockResult = {- success: false,- metadata: {- path: testKey,- filename: 'test.jpg',- dirname: 'desktop://images',- date: new Date().toISOString(),- },- error: 'Upload failed',- };-- vi.mocked(electronIpcClient.createFile).mockResolvedValueOnce(mockResult);- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});-- // 执行和验证- await expect(service.uploadMedia(testKey, testBuffer)).rejects.toThrow(- 'Failed to upload file via Electron IPC',- );- expect(consoleSpy).toHaveBeenCalled();- });-- it('当IPC调用失败时应抛出错误', async () => {- // 准备- const testKey = 'desktop://images/test.jpg';- const testBuffer = Buffer.from('fake image data');-- vi.mocked(electronIpcClient.createFile).mockRejectedValueOnce(new Error('IPC error'));- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});-- // 执行和验证- await expect(service.uploadMedia(testKey, testBuffer)).rejects.toThrow('IPC error');- expect(consoleSpy).toHaveBeenCalled();- });- });-});diff --git a/src/server/services/file/impls/local.ts b/src/server/services/file/impls/local.tsdeleted file mode 100644index af38c14f1d6..00000000000--- a/src/server/services/file/impls/local.ts+++ /dev/null@@ -1,215 +0,0 @@-import debug from 'debug';-import { sha256 } from 'js-sha256';-import { existsSync, readFileSync } from 'node:fs';-import path from 'node:path';--import { electronIpcClient } from '@/server/modules/ElectronIPCClient';-import { inferContentTypeFromImageUrl } from '@/utils/url';--import { type FileServiceImpl } from './type';-import { extractKeyFromUrlOrReturnOriginal } from './utils';--const log = debug('lobe-file:desktop-local');--/**- * Desktop application local file service implementation- */-export class DesktopLocalFileImpl implements FileServiceImpl {- /**- * Get local file URL- * Retrieve HTTP URL from main process via IPC- */- private async getLocalFileUrl(key: string): Promise<string> {- try {- return await electronIpcClient.getFileHTTPURL(key);- } catch (e) {- console.error('[DesktopLocalFileImpl] Failed to get file HTTP URL via IPC:', e);- return '';- }- }-- /**- * Create pre-signed upload URL (local version directly returns file path, may need further extension)- */- async createPreSignedUrl(key: string): Promise<string> {- // In desktop application local file implementation, pre-signed URL is not needed- // Directly return the file path- return key;- }-- /**- * Create pre-signed preview URL (local version accesses local files via HTTP path)- */- async createPreSignedUrlForPreview(key: string): Promise<string> {- return this.getLocalFileUrl(key);- }-- async deleteFile(key: string): Promise<any> {- return await this.deleteFiles([key]);- }-- /**- * Delete files in batch- */- async deleteFiles(keys: string[]): Promise<any> {- try {- if (!keys || keys.length === 0) return { success: true };-- // Ensure all paths are valid desktop:// paths- const invalidKeys = keys.filter((key) => !key.startsWith('desktop://'));- if (invalidKeys.length > 0) {- console.error('Invalid desktop file paths:', invalidKeys);- return {- errors: invalidKeys.map((key) => ({ message: 'Invalid desktop file path', path: key })),- success: false,- };- }-- // Use electronIpcClient's dedicated method- return await electronIpcClient.deleteFiles(keys);- } catch (error) {- console.error('Failed to delete files:', error);- return {- errors: [- {- message: `Batch delete failed: ${(error as Error).message}`,- path: 'batch',- },- ],- success: false,- };- }- }-- /**- * Get file byte array- */- async getFileByteArray(key: string): Promise<Uint8Array> {- try {- // Get absolute file path from Electron- const filePath = await electronIpcClient.getFilePathById(key);-- // Check if file exists- if (!existsSync(filePath)) {- console.error(`File not found: ${filePath}`);- return new Uint8Array();- }-- // Read file content and convert to Uint8Array- const buffer = readFileSync(filePath);- return new Uint8Array(buffer);- } catch (e) {- console.error('Failed to get file byte array:', e);- return new Uint8Array();- }- }-- /**- * Get file content- */- async getFileContent(key: string): Promise<string> {- try {- // Get absolute file path from Electron- const filePath = await electronIpcClient.getFilePathById(key);-- // Check if file exists- if (!existsSync(filePath)) {- console.error(`File not found: ${filePath}`);- return '';- }-- // Read file content and convert to string- return readFileSync(filePath, 'utf8');- } catch (e) {- console.error('Failed to get file content:', e);- return '';- }- }-- /**- * Get full file URL- */- async getFullFileUrl(url?: string | null): Promise<string> {- if (!url) return '';-- // Handle legacy data compatibility using shared utility- const key = extractKeyFromUrlOrReturnOriginal(url, this.getKeyFromFullUrl.bind(this));-- return this.getLocalFileUrl(key);- }-- /**- * Upload content- * Note: This feature may require extension of Electron IPC interface- */- async uploadContent(filePath: string, content: string): Promise<any> {- // Need to extend electronIpcClient to support uploading file content- // For example: return electronIpcClient.uploadContent(filePath, content);- console.warn('uploadContent not implemented for Desktop local file service', filePath, content);- return;- }-- /**- * Extract key from full URL- * Extract desktop:// format path from HTTP URL- */- getKeyFromFullUrl(url: string): string {- try {- const urlObj = new URL(url);- const pathSegments = urlObj.pathname.split('/').filter((segment) => segment !== '');-- // Remove first path segment (desktop-file)- pathSegments.shift();-- // Recombine remaining path segments- const filePath = pathSegments.join('/');-- // Return desktop:// format path- return `desktop://${filePath}`;- } catch (e) {- console.error('[DesktopLocalFileImpl] Failed to extract key from URL:', e);- return '';- }- }-- /**- * Upload media file- */- async uploadMedia(key: string, buffer: Buffer): Promise<{ key: string }> {- try {- // Convert Buffer to Base64 string- const content = buffer.toString('base64');-- // Extract filename from key- const filename = path.basename(key);-- // Calculate SHA256 hash of the file- const hash = sha256(buffer);-- // Infer MIME type from file URL- const type = inferContentTypeFromImageUrl(key)!;-- // Construct upload parameters- const uploadParams = {- content,- filename,- hash,- path: key,- type,- };-- // Call electronIpcClient to upload file- const result = await electronIpcClient.createFile(uploadParams);-- if (!result.success) {- throw new Error('Failed to upload file via Electron IPC');- }-- log('File uploaded successfully: %O', result.metadata);- return { key: result.metadata.path };- } catch (error) {- console.error('[DesktopLocalFileImpl] Failed to upload media file:', error);- throw error;- }- }-}diff --git a/src/server/services/file/index.ts b/src/server/services/file/index.tsindex b02510411fa..2030c1f511e 100644--- a/src/server/services/file/index.ts+++ b/src/server/services/file/index.ts@@ -6,6 +6,7 @@ import { sha256 } from 'js-sha256';import { serverDBEnv } from '@/config/db';import { FileModel } from '@/database/models/file';import { type FileItem } from '@/database/schemas';+import { appEnv } from '@/envs/app';import { TempFileManager } from '@/server/utils/tempFileManager';import { type FileServiceImpl, createFileServiceModule } from './impls';@@ -128,10 +129,10 @@ export class FileService {!isExist, // insertToGlobalFiles);- // Return unified proxy URL: /f/:id+ // Return unified proxy URL: ${APP_URL}/f/:idreturn {fileId: id,- url: `/f/${id}`,+ url: `${appEnv.APP_URL}/f/${id}`,};}