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: resolve file access urls via file service (#15295)

YuTengjing41172a6740f7
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 7c7b16729b1..395aecb4a71 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 } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { uuid } from '@/utils/uuid';
@@ -290,24 +290,75 @@ describe('MessageModel Query Tests', () => {
});
const domain = 'http://abc.com';
- // Call query method
- const result = await messageModel.query(
- {},
- { postProcessUrl: async (path) => `${domain}/${path}` },
+ 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 });
// Assert result
expect(result).toHaveLength(2);
expect(result[0].id).toBe('1');
expect(result[0].imageList).toEqual([
- { alt: 'file-1', id: 'f-0', url: `${domain}/abc` },
- { alt: 'file-3', id: 'f-3', url: `${domain}/abc` },
+ { alt: 'file-1', id: 'f-0', url: `${domain}/f-0/abc` },
+ { alt: 'file-3', id: 'f-3', url: `${domain}/f-3/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 data
await serverDB.transaction(async (trx) => {
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 534f2af6204..5a0f8794d02 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -89,7 +89,10 @@ export interface QueryMessagesOptions {
/**
* Post-process function for file URLs
*/
- postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>;
timing?: ModelTimingContext;
/**
* Topic ID for MessageGroup aggregation queries
@@ -226,7 +229,10 @@ export class MessageModel {
threadId,
}: QueryMessageParams = {},
options: {
- postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>;
timing?: ModelTimingContext;
} = {},
) => {
@@ -564,7 +570,10 @@ export class MessageModel {
topicId,
}: {
current: number;
- postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>;
result: { createdAt: Date }[];
timing?: ModelTimingContext;
topicId?: string;
@@ -648,7 +657,10 @@ export class MessageModel {
rawRelatedFileList.map(async (file) => ({
...file,
url: postProcessUrl
- ? await postProcessUrl(file.url, file as unknown as { fileType: string })
+ ? await postProcessUrl(
+ file.url,
+ file as unknown as { fileType: string; id?: string | null },
+ )
: (file.url as string),
})),
),
@@ -807,7 +819,10 @@ export class MessageModel {
queryByIds = async (
messageIds: string[],
options: {
- postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>;
} = {},
): Promise<UIChatMessage[]> => {
if (messageIds.length === 0) return [];
@@ -946,7 +961,12 @@ export class MessageModel {
const relatedFileList = await Promise.all(
rawRelatedFileList.map(async (file) => ({
...file,
- url: postProcessUrl ? await postProcessUrl(file.url, file as any) : (file.url as string),
+ url: postProcessUrl
+ ? await postProcessUrl(
+ file.url,
+ file as unknown as { fileType: string; id?: string | null },
+ )
+ : (file.url as string),
})),
);
@@ -1066,7 +1086,10 @@ export class MessageModel {
private queryMessageGroupNodes = async (
topicId: string,
timeRange?: { endTime: Date; startTime: Date },
- postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>,
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>,
timing?: ModelTimingContext,
): Promise<UIChatMessage[]> => {
// 1. Query MessageGroups for this topic, optionally filtered by time range
diff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.ts
index 40e431cbd6d..2dde5703be7 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 userId
const fileService = new FileService(db, file.userId);
- // Web: Generate S3 presigned URL (5 minutes expiry)
- const redirectUrl = await fileService.createPreSignedUrlForPreview(file.url, 300);
+ // Web: Generate S3 presigned URL (5 minutes expiry), normalizing legacy full S3 URLs.
+ const redirectUrl = await fileService.getFullFileUrl(file.url, 300);
log('Web S3 presigned URL generated (expires in 5 min)');
// Cache the presigned URL in Redis
diff --git a/src/features/DailyBrief/index.tsx b/src/features/DailyBrief/index.tsx
index ae59312f2cc..70136e4069e 100644
--- a/src/features/DailyBrief/index.tsx
+++ b/src/features/DailyBrief/index.tsx
@@ -42,7 +42,14 @@ const DailyBrief = memo(() => {
}
if (briefs.length === 0) {
- return recommendationsVisible ? <Recommendations /> : null;
+ // 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 (
diff --git a/src/routes/(main)/home/features/index.tsx b/src/routes/(main)/home/features/index.tsx
index 4bf3863535c..50d9e4c89dd 100644
--- a/src/routes/(main)/home/features/index.tsx
+++ b/src/routes/(main)/home/features/index.tsx
@@ -24,11 +24,7 @@ const Home = memo(() => {
<InputArea />
</Flexbox>
- {isLogin && (
- <Flexbox gap={40}>
- <DailyBrief />
- </Flexbox>
- )}
+ {isLogin && <DailyBrief />}
</Flexbox>
);
});
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index 812faa32edc..8cfad24b9e8 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 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`).
+// 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.
//
// FileService is constructed lazily so environments without S3 config (unit
// tests) don't fail at context-build time; failure returns undefined, which
@@ -183,7 +183,8 @@ const buildPostProcessUrl = (ctx: Pick<RuntimeExecutorContext, 'serverDB' | 'use
} catch {
return undefined;
}
- return (path: string | null) => fileService!.getFullFileUrl(path);
+ return (path: string | null, file: { id?: string | null }) =>
+ fileService!.getFileAccessUrl({ id: file.id, url: path });
};
const shouldRetryLLM = (kind: LLMErrorKind, attempt: number, maxRetries: number) =>
@@ -2725,7 +2726,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 S3 keys in imageList/videoList/fileList to absolute URLs;
+ // postProcessUrl resolves keys in imageList/videoList/fileList to external 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.ts
index f30f47b8d60..0021be0f2ee 100644
--- a/src/server/routers/lambda/__tests__/file.test.ts
+++ b/src/server/routers/lambda/__tests__/file.test.ts
@@ -4,6 +4,8 @@ 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 = {};
@@ -34,6 +36,7 @@ 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),
@@ -147,12 +150,14 @@ 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,
})),
@@ -208,6 +213,9 @@ 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.ts
index 996fc83bff5..fb6678bbc32 100644
--- a/src/server/routers/lambda/aiAgent.ts
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -22,11 +22,17 @@ 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;
@@ -496,14 +502,17 @@ 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 }),
+ ctx.messageModel.query({ threadId: thread.id, topicId }, messageQueryOptions),
// Main chat messages (messages without threadId)
// Only filter by groupId + topicId (not agentId) to include all agents' messages
- ctx.messageModel.query({ groupId, topicId }),
+ ctx.messageModel.query({ groupId, topicId }, messageQueryOptions),
]);
log(
@@ -586,12 +595,15 @@ 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 }),
+ ctx.messageModel.query({ agentId, threadId: thread.id, topicId }, messageQueryOptions),
// 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 }),
+ ctx.messageModel.query({ agentId, groupId, topicId }, messageQueryOptions),
]);
log(
@@ -1053,7 +1065,12 @@ export const aiAgentRouter = router({
}
// 6. Query thread messages for result content or current activity
- const threadMessages = await ctx.messageModel.query({ threadId });
+ const threadMessages = await ctx.messageModel.query(
+ { threadId },
+ {
+ postProcessUrl: createUiMessageFileUrlResolver(),
+ },
+ );
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.ts
index 46529c5863f..f19cd1df94f 100644
--- a/src/server/routers/lambda/file.ts
+++ b/src/server/routers/lambda/file.ts
@@ -9,7 +9,6 @@ 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';
@@ -18,12 +17,6 @@ import { AsyncTaskStatus, AsyncTaskType, type IAsyncTaskError } from '@/types/as
import 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;
@@ -236,7 +229,7 @@ export const fileRouter = router({
);
});
- return { id, url: getFileProxyUrl(id) };
+ return { id, url: await ctx.fileService.getFileAccessUrl({ id, url: input.url }) };
}),
findById: fileProcedure
.input(
@@ -262,7 +255,7 @@ export const fileRouter = router({
size: item.size,
source: item.source,
updatedAt: item.updatedAt,
- url: getFileProxyUrl(item.id),
+ url: await ctx.fileService.getFileAccessUrl(item),
userId: item.userId,
};
}),
@@ -296,7 +289,7 @@ export const fileRouter = router({
size: item.size,
sourceType: 'file' as const,
updatedAt: item.updatedAt,
- url: getFileProxyUrl(item.id),
+ url: await ctx.fileService.getFileAccessUrl(item),
};
}),
@@ -310,7 +303,7 @@ export const fileRouter = router({
const fileItem = {
...item,
sourceType: 'file' as const,
- url: getFileProxyUrl(item.id),
+ url: await ctx.fileService.getFileAccessUrl(item),
...status,
} as FileListItem;
resultFiles.push(fileItem);
@@ -367,7 +360,7 @@ export const fileRouter = router({
resultItems.push({
...item,
editorData: null,
- url: getFileProxyUrl(item.fileId || item.id),
+ url: await ctx.fileService.getFileAccessUrl(item),
...status,
} as FileListItem);
} else {
@@ -528,7 +521,7 @@ export const fileRouter = router({
embeddingStatus: embeddingTask?.status as AsyncTaskStatus,
finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,
sourceType: 'file' as const,
- url: getFileProxyUrl(item.fileId || item.id),
+ url: await ctx.fileService.getFileAccessUrl(item),
} as FileListItem);
}
diff --git a/src/server/routers/lambda/knowledge.ts b/src/server/routers/lambda/knowledge.ts
index 845de81b108..84181479eeb 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.getFullFileUrl(item.url) : undefined,
+ url: item.url ? await ctx.fileService.getFileAccessUrl(item) : undefined,
} as FileListItem);
} else {
// Document item - no chunk processing needed, includes editorData
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index b29711d73db..e851e668339 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -210,7 +210,8 @@ export const messageRouter = router({
return messageModel.query(
{ ...queryParams, topicId: share.topicId },
{
- postProcessUrl: (path) => fileService.getFullFileUrl(path),
+ postProcessUrl: (path, file) =>
+ fileService.getFileAccessUrl({ id: file.id, url: path }),
},
);
}
@@ -224,7 +225,7 @@ export const messageRouter = router({
const fileService = new FileService(ctx.serverDB, ctx.userId);
return messageModel.query(queryParams, {
- postProcessUrl: (path) => fileService.getFullFileUrl(path),
+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
});
}),
diff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
index b1e83b9090d..cd5d0c37e00 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
@@ -108,6 +108,11 @@ 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.ts
index 87cb247e66b..fae89c93e7e 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -1076,9 +1076,10 @@ 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 S3 keys in imageList/videoList before visual tool activation checks and context build.
+ // Resolve file URLs before visual tool activation checks and context build.
const fileService = new FileService(this.db, this.userId);
- const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);
+ const postProcessUrl = (path: string | null, file: { id?: string | null }) =>
+ fileService.getFileAccessUrl({ id: file.id, url: path });
let historyMessagesCache: any[] | undefined;
const loadHistoryMessages = async () => {
if (historyMessagesCache) return historyMessagesCache;
@@ -1799,7 +1800,7 @@ export class AiAgentService {
}
fileIds.push(file.id);
- const resolvedUrl = (await fileService.getFullFileUrl(file.url)) || file.url;
+ const resolvedUrl = (await fileService.getFileAccessUrl(file)) || 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.ts
index 29fbc56ea47..b5a8edfca38 100644
--- a/src/server/services/aiAgent/ingestAttachment.ts
+++ b/src/server/services/aiAgent/ingestAttachment.ts
@@ -164,8 +164,9 @@ export async function ingestAttachment(
const pathname = `files/${userId}/${nanoid()}/${source.name || `file.${ext}`}`;
const { fileId, key } = await fileService.uploadFromBuffer(buffer, mimeType, pathname);
- // 5. Resolve full URL for images and videos (presigned or public)
- const resolvedUrl = isImage || isVideo ? await fileService.getFullFileUrl(key) : '';
+ // 5. Resolve access URL for images and videos.
+ const resolvedUrl =
+ isImage || isVideo ? await fileService.getFileAccessUrl({ id: fileId, url: 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.ts
index 85a24c0ebb4..61b9167c22c 100644
--- a/src/server/services/aiChat/index.ts
+++ b/src/server/services/aiChat/index.ts
@@ -59,7 +59,8 @@ export class AiChatService {
'lambda.aiChat.messagesAndTopics.messageModel.query',
() =>
this.messageModel.query(messageParams, {
- postProcessUrl: (path) => this.fileService.getFullFileUrl(path),
+ postProcessUrl: (path, file) =>
+ this.fileService.getFileAccessUrl({ id: file.id, url: path }),
...(messageTiming ? { timing: messageTiming } : {}),
}),
{
diff --git a/src/server/services/file/index.ts b/src/server/services/file/index.ts
index 8e6633bfa63..28b60a35b41 100644
--- a/src/server/services/file/index.ts
+++ b/src/server/services/file/index.ts
@@ -8,10 +8,19 @@ 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
@@ -94,6 +103,21 @@ 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
*/
@@ -179,10 +203,9 @@ export class FileService {
!isExist, // insertToGlobalFiles
);
- // Return unified proxy URL: ${APP_URL}/f/:id
return {
fileId: id,
- url: `${appEnv.APP_URL}/f/${id}`,
+ url: await this.getFileAccessUrl({ id, url: params.url }),
};
}
diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.ts
index 8eea9537b4f..9859bbfca08 100644
--- a/src/server/services/message/index.ts
+++ b/src/server/services/message/index.ts
@@ -63,7 +63,8 @@ export class MessageService {
* Unified URL processing function
*/
private get postProcessUrl() {
- return (path: string | null) => this.fileService.getFullFileUrl(path);
+ return (path: string | null, file: { fileType: string; id?: string | null }) =>
+ this.fileService.getFileAccessUrl({ id: file.id, url: path });
}
/**
diff --git a/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts b/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts
index bbc81214059..5739aa2f980 100644
--- a/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts
+++ b/src/server/services/toolExecution/serverRuntimes/knowledgeBase.ts
@@ -5,14 +5,12 @@ 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;
@@ -24,6 +22,7 @@ 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;
@@ -145,7 +144,7 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
size: item.size,
sourceType: 'file',
updatedAt: item.updatedAt,
- url: getFileProxyUrl(item.id),
+ url: await fileService.getFileAccessUrl(item),
};
},
getKnowledgeItems: async ({ category, limit, offset, q, showFilesInKnowledgeBase }) => {
@@ -160,20 +159,22 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
const slice = hasMore ? items.slice(0, limit) : items;
return {
hasMore,
- 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 || '',
- })),
+ 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 || '',
+ })),
+ ),
};
},
},
diff --git a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts b/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts
index d2777ab7340..a8f39cc6783 100644
--- a/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/src/server/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -108,7 +108,10 @@ class LobeAgentExecutionRuntime {
private queryScopeMessages = (
messageModel: MessageModel,
sourceMessage: ServerVisualSourceMessage,
- postProcessUrl: (path: string | null, file: { fileType: string }) => Promise<string>,
+ postProcessUrl: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>,
) => {
const topicId = this.topicId ?? sourceMessage.topicId ?? undefined;
const threadId = sourceMessage.threadId ?? this.threadId ?? undefined;
@@ -178,7 +181,10 @@ 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) => fileService.getFullFileUrl(path);
+ const postProcessUrl = (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => fileService.getFileAccessUrl({ id: file.id, url: path });
const [sourceMessage] = await messageModel.queryByIds([this.messageId], {
postProcessUrl,
});