π€― 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
Revert "π fix: resolve file access urls via file service (#15295)"
Arvin Xu47daf09be199
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 395aecb4a71..7c7b16729b1 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1,6 +1,6 @@import { INBOX_SESSION_ID } from '@lobechat/const';import { eq } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { uuid } from '@/utils/uuid';@@ -290,75 +290,24 @@ describe('MessageModel Query Tests', () => {});const domain = 'http://abc.com';- const postProcessUrl = vi.fn(- async (path: string | null, file: { id?: string | null }) => `${domain}/${file.id}/${path}`,- );// Call query method- const result = await messageModel.query({}, { postProcessUrl });+ const result = await messageModel.query(+ {},+ { postProcessUrl: async (path) => `${domain}/${path}` },+ );// Assert resultexpect(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-3', id: 'f-3', url: `${domain}/f-3/abc` },+ { alt: 'file-1', id: 'f-0', url: `${domain}/abc` },+ { alt: 'file-3', id: 'f-3', url: `${domain}/abc` },]);- expect(postProcessUrl).toHaveBeenCalledWith(- 'abc',- expect.objectContaining({ fileType: 'image/png', id: 'f-0' }),- );- expect(postProcessUrl).toHaveBeenCalledWith(- 'abc',- expect.objectContaining({ fileType: 'image/png', id: 'f-3' }),- );expect(result[1].id).toBe('2');expect(result[1].imageList).toEqual([]);});- it('should pass file id to postProcessUrl when querying messages by ids', async () => {- await serverDB.transaction(async (trx) => {- await trx.insert(messages).values({- id: 'query-by-id-message',- userId,- role: 'user',- content: 'message with file',- createdAt: new Date('2023-01-01'),- });- await trx.insert(files).values({- id: 'query-by-id-file',- url: 'files/query-by-id.png',- name: 'query-by-id.png',- userId,- fileType: 'image/png',- size: 1000,- });- await trx.insert(messagesFiles).values({- fileId: 'query-by-id-file',- messageId: 'query-by-id-message',- userId,- });- });-- const postProcessUrl = vi.fn(- async (path: string | null, file: { id?: string | null }) => `/f/${file.id}/${path}`,- );-- const result = await messageModel.queryByIds(['query-by-id-message'], { postProcessUrl });-- expect(result[0].imageList).toEqual([- {- alt: 'query-by-id.png',- id: 'query-by-id-file',- url: '/f/query-by-id-file/files/query-by-id.png',- },- ]);- expect(postProcessUrl).toHaveBeenCalledWith(- 'files/query-by-id.png',- expect.objectContaining({ fileType: 'image/png', id: 'query-by-id-file' }),- );- });-it('should include translate, tts and other extra fields in query result', async () => {// Create test dataawait serverDB.transaction(async (trx) => {diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 5a0f8794d02..534f2af6204 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -89,10 +89,7 @@ export interface QueryMessagesOptions {/*** Post-process function for file URLs*/- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;timing?: ModelTimingContext;/*** Topic ID for MessageGroup aggregation queries@@ -229,10 +226,7 @@ export class MessageModel {threadId,}: QueryMessageParams = {},options: {- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;timing?: ModelTimingContext;} = {},) => {@@ -570,10 +564,7 @@ export class MessageModel {topicId,}: {current: number;- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;result: { createdAt: Date }[];timing?: ModelTimingContext;topicId?: string;@@ -657,10 +648,7 @@ export class MessageModel {rawRelatedFileList.map(async (file) => ({...file,url: postProcessUrl- ? await postProcessUrl(- file.url,- file as unknown as { fileType: string; id?: string | null },- )+ ? await postProcessUrl(file.url, file as unknown as { fileType: string }): (file.url as string),})),),@@ -819,10 +807,7 @@ export class MessageModel {queryByIds = async (messageIds: string[],options: {- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;} = {},): Promise<UIChatMessage[]> => {if (messageIds.length === 0) return [];@@ -961,12 +946,7 @@ export class MessageModel {const relatedFileList = await Promise.all(rawRelatedFileList.map(async (file) => ({...file,- url: postProcessUrl- ? await postProcessUrl(- file.url,- file as unknown as { fileType: string; id?: string | null },- )- : (file.url as string),+ url: postProcessUrl ? await postProcessUrl(file.url, file as any) : (file.url as string),})),);@@ -1086,10 +1066,7 @@ export class MessageModel {private queryMessageGroupNodes = async (topicId: string,timeRange?: { endTime: Date; startTime: Date },- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>,+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>,timing?: ModelTimingContext,): Promise<UIChatMessage[]> => {// 1. Query MessageGroups for this topic, optionally filtered by time rangediff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.tsindex 2dde5703be7..40e431cbd6d 100644--- a/src/app/(backend)/f/[id]/route.ts+++ b/src/app/(backend)/f/[id]/route.ts@@ -68,8 +68,8 @@ export const GET = async (_req: Request, segmentData: { params: Params }) => {// Create file service with file owner's userIdconst fileService = new FileService(db, file.userId);- // Web: Generate S3 presigned URL (5 minutes expiry), normalizing legacy full S3 URLs.- const redirectUrl = await fileService.getFullFileUrl(file.url, 300);+ // Web: Generate S3 presigned URL (5 minutes expiry)+ const redirectUrl = await fileService.createPreSignedUrlForPreview(file.url, 300);log('Web S3 presigned URL generated (expires in 5 min)');// Cache the presigned URL in Redisdiff --git a/src/features/DailyBrief/index.tsx b/src/features/DailyBrief/index.tsxindex 70136e4069e..ae59312f2cc 100644--- a/src/features/DailyBrief/index.tsx+++ b/src/features/DailyBrief/index.tsx@@ -42,14 +42,7 @@ const DailyBrief = memo(() => {}if (briefs.length === 0) {- // Without a titled brief block above it, the bare recommendations list- // doesn't need the full section gap below the input area β offset the- // parent's gap so it sits closer to the input.- return recommendationsVisible ? (- <Flexbox style={{ marginBlockStart: -24 }}>- <Recommendations />- </Flexbox>- ) : null;+ return recommendationsVisible ? <Recommendations /> : null;}return (diff --git a/src/routes/(main)/home/features/index.tsx b/src/routes/(main)/home/features/index.tsxindex 50d9e4c89dd..4bf3863535c 100644--- a/src/routes/(main)/home/features/index.tsx+++ b/src/routes/(main)/home/features/index.tsx@@ -24,7 +24,11 @@ const Home = memo(() => {<InputArea /></Flexbox>- {isLogin && <DailyBrief />}+ {isLogin && (+ <Flexbox gap={40}>+ <DailyBrief />+ </Flexbox>+ )}</Flexbox>);});diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 8cfad24b9e8..812faa32edc 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -166,11 +166,11 @@ const archiveRuntimeToolResult = async (return archive.content === result.content ? result : { ...result, content: archive.content };};-// Builds a postProcessUrl callback that resolves keys in file-backed fields-// (imageList, videoList, fileList) to externally accessible URLs. Must be-// passed to every messageModel.query() call whose output is later fed to the-// LLM β otherwise the provider layer receives raw keys like-// `files/user_xxx/icon.png` and rejects them.+// Builds a postProcessUrl callback that resolves S3 keys in file-backed fields+// (imageList, videoList, fileList) to absolute URLs. Must be passed to every+// messageModel.query() call whose output is later fed to the LLM β otherwise+// the provider layer receives raw keys like `files/user_xxx/icon.png` and+// rejects them (see anthropic contextBuilder `Invalid image URL`).//// FileService is constructed lazily so environments without S3 config (unit// tests) don't fail at context-build time; failure returns undefined, which@@ -183,8 +183,7 @@ const buildPostProcessUrl = (ctx: Pick<RuntimeExecutorContext, 'serverDB' | 'use} catch {return undefined;}- return (path: string | null, file: { id?: string | null }) =>- fileService!.getFileAccessUrl({ id: file.id, url: path });+ return (path: string | null) => fileService!.getFullFileUrl(path);};const shouldRetryLLM = (kind: LLMErrorKind, attempt: number, maxRetries: number) =>@@ -2726,7 +2725,7 @@ export const createRuntimeExecutors = (// Must pass agentId to ensure correct query scope, otherwise when topicId is undefined,// the query will use isNull(topicId) condition which won't find messages with actual topicId//- // postProcessUrl resolves keys in imageList/videoList/fileList to external URLs;+ // postProcessUrl resolves S3 keys in imageList/videoList/fileList to absolute URLs;// without it the next LLM call sees raw keys and providers reject them.const latestMessages = await ctx.messageModel.query({diff --git a/src/server/routers/lambda/__tests__/file.test.ts b/src/server/routers/lambda/__tests__/file.test.tsindex 0021be0f2ee..f30f47b8d60 100644--- a/src/server/routers/lambda/__tests__/file.test.ts+++ b/src/server/routers/lambda/__tests__/file.test.ts@@ -4,8 +4,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { fileRouter } from '@/server/routers/lambda/file';import { AsyncTaskStatus } from '@/types/asyncTask';-const buildMockFileAccessUrl = ({ id }: { id: string }) => `https://lobehub.com/f/${id}`;-const routerMocks = vi.hoisted(() => {const transactionClient = {};@@ -36,7 +34,6 @@ function createCallerWithCtx(partialCtx: any = {}) {};const fileService = {- getFileAccessUrl: vi.fn(async (file: { id: string }) => buildMockFileAccessUrl(file)),getFullFileUrl: vi.fn().mockResolvedValue('full-url'),getFileMetadata: vi.fn().mockResolvedValue({ contentLength: 2048, contentType: 'text/plain' }),deleteFile: vi.fn().mockResolvedValue(undefined),@@ -150,14 +147,12 @@ vi.mock('@/database/models/file', () => ({}));const mockFileServiceGetFullFileUrl = vi.fn();-const mockFileServiceGetFileAccessUrl = vi.fn();const mockFileServiceGetFileMetadata = vi.fn();vi.mock('@/server/services/file', () => ({FileService: vi.fn(() => ({deleteFile: vi.fn(),deleteFiles: vi.fn(),- getFileAccessUrl: mockFileServiceGetFileAccessUrl,getFullFileUrl: mockFileServiceGetFullFileUrl,getFileMetadata: mockFileServiceGetFileMetadata,})),@@ -213,9 +208,6 @@ describe('fileRouter', () => {contentLength: 100,contentType: 'text/plain',});- mockFileServiceGetFileAccessUrl.mockImplementation(async (file: { id: string }) =>- buildMockFileAccessUrl(file),- );// Use actual context with default mocks({ ctx, caller } = createCallerWithCtx());diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex fb6678bbc32..996fc83bff5 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -22,17 +22,11 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { AiAgentService } from '@/server/services/aiAgent';import { AiChatService } from '@/server/services/aiChat';-import { getFileProxyUrl } from '@/server/services/file';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import { TaskLifecycleService } from '@/server/services/taskLifecycle';const log = debug('lobe-server:ai-agent-router');-const createUiMessageFileUrlResolver = () => {- return async (path: string | null, file: { fileType: string; id?: string | null }) =>- file.id ? getFileProxyUrl(file.id) : (path ?? '');-};-const extractTaskErrorMessage = (error: unknown): string | undefined => {if (!error || typeof error !== 'object') return undefined;@@ -502,17 +496,14 @@ export const aiAgentRouter = router({log('createClientGroupAgentTaskThread: created user message %s', userMessage.id);// 3. Query thread messages and main chat messages in parallel- const messageQueryOptions = {- postProcessUrl: createUiMessageFileUrlResolver(),- };const [threadMessages, messages] = await Promise.all([// Thread messages (messages within this thread)// DON'T pass agentId - thread query fetches parent messages via sourceMessageId// which may have different agentIds (supervisor vs worker in group chat)- ctx.messageModel.query({ threadId: thread.id, topicId }, messageQueryOptions),+ ctx.messageModel.query({ threadId: thread.id, topicId }),// Main chat messages (messages without threadId)// Only filter by groupId + topicId (not agentId) to include all agents' messages- ctx.messageModel.query({ groupId, topicId }, messageQueryOptions),+ ctx.messageModel.query({ groupId, topicId }),]);log(@@ -595,15 +586,12 @@ export const aiAgentRouter = router({log('createClientTaskThread: created user message %s', userMessage.id);// 3. Query thread messages and main chat messages in parallel- const messageQueryOptions = {- postProcessUrl: createUiMessageFileUrlResolver(),- };const [threadMessages, messages] = await Promise.all([// Thread messages (messages within this thread)- ctx.messageModel.query({ agentId, threadId: thread.id, topicId }, messageQueryOptions),+ ctx.messageModel.query({ agentId, threadId: thread.id, topicId }),// Main chat messages (messages without threadId, includes updated taskDetail)// Pass both agentId and groupId - query() prioritizes groupId when present- ctx.messageModel.query({ agentId, groupId, topicId }, messageQueryOptions),+ ctx.messageModel.query({ agentId, groupId, topicId }),]);log(@@ -1065,12 +1053,7 @@ export const aiAgentRouter = router({}// 6. Query thread messages for result content or current activity- const threadMessages = await ctx.messageModel.query(- { threadId },- {- postProcessUrl: createUiMessageFileUrlResolver(),- },- );+ const threadMessages = await ctx.messageModel.query({ threadId });const sortedMessages = threadMessages.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),);diff --git a/src/server/routers/lambda/file.ts b/src/server/routers/lambda/file.tsindex f19cd1df94f..46529c5863f 100644--- a/src/server/routers/lambda/file.ts+++ b/src/server/routers/lambda/file.ts@@ -9,6 +9,7 @@ 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 { DocumentService } from '@/server/services/document';@@ -17,6 +18,12 @@ import { AsyncTaskStatus, AsyncTaskType, type IAsyncTaskError } from '@/types/asimport type { FileListItem, KnowledgeItemStatus } from '@/types/files';import { 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 filterKnowledgeItems = <T extends {fileType: string;@@ -229,7 +236,7 @@ export const fileRouter = router({);});- return { id, url: await ctx.fileService.getFileAccessUrl({ id, url: input.url }) };+ return { id, url: getFileProxyUrl(id) };}),findById: fileProcedure.input(@@ -255,7 +262,7 @@ export const fileRouter = router({size: item.size,source: item.source,updatedAt: item.updatedAt,- url: await ctx.fileService.getFileAccessUrl(item),+ url: getFileProxyUrl(item.id),userId: item.userId,};}),@@ -289,7 +296,7 @@ export const fileRouter = router({size: item.size,sourceType: 'file' as const,updatedAt: item.updatedAt,- url: await ctx.fileService.getFileAccessUrl(item),+ url: getFileProxyUrl(item.id),};}),@@ -303,7 +310,7 @@ export const fileRouter = router({const fileItem = {...item,sourceType: 'file' as const,- url: await ctx.fileService.getFileAccessUrl(item),+ url: getFileProxyUrl(item.id),...status,} as FileListItem;resultFiles.push(fileItem);@@ -360,7 +367,7 @@ export const fileRouter = router({resultItems.push({...item,editorData: null,- url: await ctx.fileService.getFileAccessUrl(item),+ url: getFileProxyUrl(item.fileId || item.id),...status,} as FileListItem);} else {@@ -521,7 +528,7 @@ export const fileRouter = router({embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,sourceType: 'file' as const,- url: await ctx.fileService.getFileAccessUrl(item),+ url: getFileProxyUrl(item.fileId || item.id),} as FileListItem);}diff --git a/src/server/routers/lambda/knowledge.ts b/src/server/routers/lambda/knowledge.tsindex 84181479eeb..845de81b108 100644--- a/src/server/routers/lambda/knowledge.ts+++ b/src/server/routers/lambda/knowledge.ts@@ -65,7 +65,7 @@ export const knowledgeRouter = router({embeddingError: embeddingTask?.error ?? null,embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,- url: item.url ? await ctx.fileService.getFileAccessUrl(item) : undefined,+ url: item.url ? await ctx.fileService.getFullFileUrl(item.url) : undefined,} as FileListItem);} else {// Document item - no chunk processing needed, includes editorDatadiff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.tsindex e851e668339..b29711d73db 100644--- a/src/server/routers/lambda/message.ts+++ b/src/server/routers/lambda/message.ts@@ -210,8 +210,7 @@ export const messageRouter = router({return messageModel.query({ ...queryParams, topicId: share.topicId },{- postProcessUrl: (path, file) =>- fileService.getFileAccessUrl({ id: file.id, url: path }),+ postProcessUrl: (path) => fileService.getFullFileUrl(path),},);}@@ -225,7 +224,7 @@ export const messageRouter = router({const fileService = new FileService(ctx.serverDB, ctx.userId);return messageModel.query(queryParams, {- postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),+ postProcessUrl: (path) => fileService.getFullFileUrl(path),});}),diff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.tsindex cd5d0c37e00..b1e83b9090d 100644--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts@@ -108,11 +108,6 @@ vi.mock('@/server/services/klavis', () => ({vi.mock('@/server/services/file', () => ({FileService: vi.fn().mockImplementation(() => ({- getFileAccessUrl: vi- .fn()- .mockImplementation((file: { url: string }) =>- Promise.resolve(`https://s3.example.com/${file.url}`),- ),getFullFileUrl: vi.fn().mockImplementation((key: string) => Promise.resolve(`https://s3.example.com/${key}`)),diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex fae89c93e7e..87cb247e66b 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -1076,10 +1076,9 @@ export class AiAgentService {// Model metadata is needed both for tool support checks and agent-management context.const { loadModels } = await import('@/business/client/model-bank/loadModels');const builtinModels = await loadModels();- // Resolve file URLs before visual tool activation checks and context build.+ // Resolve S3 keys in imageList/videoList before visual tool activation checks and context build.const fileService = new FileService(this.db, this.userId);- const postProcessUrl = (path: string | null, file: { id?: string | null }) =>- fileService.getFileAccessUrl({ id: file.id, url: path });+ const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);let historyMessagesCache: any[] | undefined;const loadHistoryMessages = async () => {if (historyMessagesCache) return historyMessagesCache;@@ -1800,7 +1799,7 @@ export class AiAgentService {}fileIds.push(file.id);- const resolvedUrl = (await fileService.getFileAccessUrl(file)) || file.url;+ const resolvedUrl = (await fileService.getFullFileUrl(file.url)) || file.url;const fileType = file.fileType || '';if (fileType.startsWith('image')) {diff --git a/src/server/services/aiAgent/ingestAttachment.ts b/src/server/services/aiAgent/ingestAttachment.tsindex b5a8edfca38..29fbc56ea47 100644--- a/src/server/services/aiAgent/ingestAttachment.ts+++ b/src/server/services/aiAgent/ingestAttachment.ts@@ -164,9 +164,8 @@ export async function ingestAttachment(const pathname = `files/${userId}/${nanoid()}/${source.name || `file.${ext}`}`;const { fileId, key } = await fileService.uploadFromBuffer(buffer, mimeType, pathname);- // 5. Resolve access URL for images and videos.- const resolvedUrl =- isImage || isVideo ? await fileService.getFileAccessUrl({ id: fileId, url: key }) : '';+ // 5. Resolve full URL for images and videos (presigned or public)+ const resolvedUrl = isImage || isVideo ? await fileService.getFullFileUrl(key) : '';log('ingestAttachment: uploaded fileId=%s, key=%s, resolvedUrl=%s',diff --git a/src/server/services/aiChat/index.ts b/src/server/services/aiChat/index.tsindex 61b9167c22c..85a24c0ebb4 100644--- a/src/server/services/aiChat/index.ts+++ b/src/server/services/aiChat/index.ts@@ -59,8 +59,7 @@ export class AiChatService {'lambda.aiChat.messagesAndTopics.messageModel.query',() =>this.messageModel.query(messageParams, {- postProcessUrl: (path, file) =>- this.fileService.getFileAccessUrl({ id: file.id, url: path }),+ postProcessUrl: (path) => this.fileService.getFullFileUrl(path),...(messageTiming ? { timing: messageTiming } : {}),}),{diff --git a/src/server/services/file/index.ts b/src/server/services/file/index.tsindex 28b60a35b41..8e6633bfa63 100644--- a/src/server/services/file/index.ts+++ b/src/server/services/file/index.ts@@ -8,19 +8,10 @@ import { FileModel } from '@/database/models/file';import { type FileItem } from '@/database/schemas';import { appEnv } from '@/envs/app';import { TempFileManager } from '@/server/utils/tempFileManager';-import { isDev } from '@/utils/env';import { createFileServiceModule } from './impls';import { type FileServiceImpl } from './impls/type';-export const getFileProxyUrl = (fileId: string): string => `${appEnv.APP_URL}/f/${fileId}`;--export interface FileAccessUrlItem {- fileId?: string | null;- id?: string | null;- url?: string | null;-}-/*** File service class* Provides file operation services using a modular implementation approach@@ -103,21 +94,6 @@ export class FileService {return this.impl.getFullFileUrl(url, expiresIn);}- /**- * Resolve a file URL for consumers that need to read the file.- * Production uses the stable file proxy URL; local development falls back to- * the storage URL so remote model providers can download local test files.- */- public async getFileAccessUrl(file: FileAccessUrlItem): Promise<string> {- const fileId = file.fileId || file.id;-- if (!isDev && fileId) {- return getFileProxyUrl(fileId);- }-- return this.getFullFileUrl(file.url);- }-/*** Extract key from full URL*/@@ -203,9 +179,10 @@ export class FileService {!isExist, // insertToGlobalFiles);+ // Return unified proxy URL: ${APP_URL}/f/:idreturn {fileId: id,- url: await this.getFileAccessUrl({ id, url: params.url }),+ url: `${appEnv.APP_URL}/f/${id}`,};}diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.tsindex 9859bbfca08..8eea9537b4f 100644--- a/src/server/services/message/index.ts+++ b/src/server/services/message/index.ts@@ -63,8 +63,7 @@ export class MessageService {* Unified URL processing function*/private get postProcessUrl() {- return (path: string | null, file: { fileType: string; id?: string | null }) =>- this.fileService.getFileAccessUrl({ id: file.id, url: path });+ return (path: string | null) => this.fileService.getFullFileUrl(path);}/**diff --git a/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts b/src/server/services/toolExecution/serverRuntimes/knowledgeBase.tsindex 5739aa2f980..bbc81214059 100644--- a/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts+++ b/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts@@ -5,12 +5,14 @@ import { AgentModel } from '@/database/models/agent';import { FileModel } from '@/database/models/file';import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';import { KnowledgeRepo } from '@/database/repositories/knowledge';+import { appEnv } from '@/envs/app';import { DocumentService } from '@/server/services/document';-import { FileService } from '@/server/services/file';import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';import { type ServerRuntimeRegistration } from './types';+const getFileProxyUrl = (fileId: string): string => `${appEnv.APP_URL}/f/${fileId}`;+export const knowledgeBaseRuntime: ServerRuntimeRegistration = {factory: (context) => {const { userId, serverDB, agentId } = context;@@ -22,7 +24,6 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {const knowledgeBaseModel = new KnowledgeBaseModel(serverDB, userId);const knowledgeRepo = new KnowledgeRepo(serverDB, userId);const documentService = new DocumentService(serverDB, userId);- const fileService = new FileService(serverDB, userId);const searchService = new KnowledgeBaseSearchService(serverDB, userId);const agentModel = agentId ? new AgentModel(serverDB, userId) : null;@@ -144,7 +145,7 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {size: item.size,sourceType: 'file',updatedAt: item.updatedAt,- url: await fileService.getFileAccessUrl(item),+ url: getFileProxyUrl(item.id),};},getKnowledgeItems: async ({ category, limit, offset, q, showFilesInKnowledgeBase }) => {@@ -159,22 +160,20 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {const slice = hasMore ? items.slice(0, limit) : items;return {hasMore,- items: await Promise.all(- slice.map(async (item) => ({- createdAt: item.createdAt,- fileType: item.fileType,- id: item.id,- metadata: item.metadata ?? null,- name: item.name,- size: item.size,- sourceType: item.sourceType,- updatedAt: item.updatedAt,- url:- item.sourceType === 'file'- ? await fileService.getFileAccessUrl(item)- : item.url || '',- })),- ),+ items: slice.map((item) => ({+ createdAt: item.createdAt,+ fileType: item.fileType,+ id: item.id,+ metadata: item.metadata ?? null,+ name: item.name,+ size: item.size,+ sourceType: item.sourceType,+ updatedAt: item.updatedAt,+ url:+ item.sourceType === 'file'+ ? getFileProxyUrl(item.fileId || item.id)+ : item.url || '',+ })),};},},diff --git a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts b/src/server/services/toolExecution/serverRuntimes/lobeAgent.tsindex a8f39cc6783..d2777ab7340 100644--- a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -108,10 +108,7 @@ class LobeAgentExecutionRuntime {private queryScopeMessages = (messageModel: MessageModel,sourceMessage: ServerVisualSourceMessage,- postProcessUrl: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>,+ postProcessUrl: (path: string | null, file: { fileType: string }) => Promise<string>,) => {const topicId = this.topicId ?? sourceMessage.topicId ?? undefined;const threadId = sourceMessage.threadId ?? this.threadId ?? undefined;@@ -181,10 +178,7 @@ class LobeAgentExecutionRuntime {if (requestedRefs.length > 0) {const fileService = new FileService(this.db, this.userId);const messageModel = new MessageModel(this.db, this.userId);- const postProcessUrl = (- path: string | null,- file: { fileType: string; id?: string | null },- ) => fileService.getFileAccessUrl({ id: file.id, url: path });+ const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);const [sourceMessage] = await messageModel.queryByIds([this.messageId], {postProcessUrl,});