π€― 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
π fix: isolate agent share visitor files (#19649)
YuTengjing4366b09a92aa
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.tsindex e07e32835e4..f5654514d77 100644--- a/apps/server/src/routers/lambda/__tests__/file.test.ts+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts@@ -515,6 +515,29 @@ describe('fileRouter', () => {});});+ it('should strip forged agent-share provenance from an ordinary upload', async () => {+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });++ await caller.createFile({+ fileType: 'image/png',+ hash: 'test-hash',+ metadata: {+ agentShare: { shareId: 'share-1', visitorUserId: 'visitor-1' },+ width: 100,+ },+ name: 'cat.png',+ size: 100,+ url: 'files/cat.png',+ });++ expect(mockFileModelCreate).toHaveBeenCalledWith(+ expect.objectContaining({ metadata: { width: 100 } }),+ true,+ routerMocks.transactionClient,+ );+ });+it('should persist a known upload source so the origin filter can see it', async () => {mockFileModelCheckHash.mockResolvedValue({ isExist: false });mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });@@ -1246,7 +1269,9 @@ describe('fileRouter', () => {await caller.removeFile({ id: 'shared-file' });- expect(mockFileModelDelete).toHaveBeenCalledWith('shared-file', false);+ expect(mockFileModelDelete).toHaveBeenCalledWith('shared-file', {+ removeGlobalFile: false,+ });});});@@ -1257,7 +1282,9 @@ describe('fileRouter', () => {await caller.removeUnreferencedFile({ id: 'voice-file' });- expect(mockFileModelDeleteUnreferenced).toHaveBeenCalledWith('voice-file', false);+ expect(mockFileModelDeleteUnreferenced).toHaveBeenCalledWith('voice-file', {+ removeGlobalFile: false,+ });expect(mockFileServiceDeleteFile).not.toHaveBeenCalled();});@@ -1305,6 +1332,20 @@ describe('fileRouter', () => {expect(mockFileModelUpdate).toHaveBeenCalledWith('file-1', { parentId: 'docs_parent' });});++ it('should strip forged agent-share provenance from metadata updates', async () => {+ mockFileModelFindById.mockResolvedValue({ id: 'file-1', userId: 'test-user' });++ await caller.updateFile({+ id: 'file-1',+ metadata: {+ agentShare: { shareId: 'share-1', visitorUserId: 'visitor-1' },+ width: 100,+ },+ });++ expect(mockFileModelUpdate).toHaveBeenCalledWith('file-1', { metadata: { width: 100 } });+ });});describe('deleteKnowledgeItemsByQuery', () => {diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex d038ad550e4..381b11f8702 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -385,31 +385,24 @@ describe('shareChatRouter', () => {describe('attachments', () => {const fileIds = ['file-a', 'file-b'];- const shareFile = (id: string, overrides: Record<string, unknown> = {}) => ({- id,- metadata: { agentShare: { shareId: share.shareId, visitorUserId: VISITOR } },- source: 'agent_share',- ...overrides,- });it("forwards fileIds to the run after checking each one's share provenance in the CREATOR scope", async () => {- mockFileFindByIds.mockResolvedValue(fileIds.map((id) => shareFile(id)));+ mockFileFindByIds.mockResolvedValue(fileIds.map((id) => ({ id })));const caller = await createCaller();await caller.execAgent({ fileIds, prompt: 'look', shareId: 'share-1' });- // Share uploads are creator-owned rows (`createFile`), so the lookup- // runs as the creator; what proves they are THIS visitor's is the- // provenance on each row, not the scope.expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);- expect(mockFileFindByIds).toHaveBeenCalledWith(fileIds);+ expect(mockFileFindByIds).toHaveBeenCalledWith(fileIds, {+ shareId: share.shareId,+ type: 'agentShare',+ visitorUserId: VISITOR,+ });expect(mockExecAgent).toHaveBeenCalledWith(expect.objectContaining({ fileIds }));});- it("rejects with NOT_FOUND when any id is one of the creator's own files (no share provenance)", async () => {- // A visitor naming an arbitrary id must not get the creator's own- // document injected into the run. Fail closed on the whole request.- mockFileFindByIds.mockResolvedValue([shareFile('file-a'), { id: 'file-b', source: null }]);+ it('rejects with NOT_FOUND when the provenance-scoped lookup omits any id', async () => {+ mockFileFindByIds.mockResolvedValue([{ id: 'file-a' }]);const caller = await createCaller();await expect(@@ -419,37 +412,18 @@ describe('shareChatRouter', () => {expect(mockExecAgent).not.toHaveBeenCalled();});- it("rejects another visitor's upload on the same share, and this visitor's upload on another share", async () => {- const caller = await createCaller();-- mockFileFindByIds.mockResolvedValue([- shareFile('file-a', {- metadata: { agentShare: { shareId: share.shareId, visitorUserId: 'visitor-2' } },- }),- ]);- await expect(- caller.execAgent({ fileIds: ['file-a'], prompt: 'look', shareId: 'share-1' }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });-- mockFileFindByIds.mockResolvedValue([- shareFile('file-a', {- metadata: { agentShare: { shareId: 'share-other', visitorUserId: VISITOR } },- }),- ]);- await expect(- caller.execAgent({ fileIds: ['file-a'], prompt: 'look', shareId: 'share-1' }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });- expect(mockExecAgent).not.toHaveBeenCalled();- });-it('accepts duplicate ids as long as each distinct id is owned', async () => {- mockFileFindByIds.mockResolvedValue([shareFile('file-a')]);+ mockFileFindByIds.mockResolvedValue([{ id: 'file-a' }]);const caller = await createCaller();await expect(caller.execAgent({ fileIds: ['file-a', 'file-a'], prompt: 'look', shareId: 'share-1' }),).resolves.toMatchObject({ operationId: 'op-1' });- expect(mockFileFindByIds).toHaveBeenCalledWith(['file-a']);+ expect(mockFileFindByIds).toHaveBeenCalledWith(['file-a'], {+ shareId: share.shareId,+ type: 'agentShare',+ visitorUserId: VISITOR,+ });});it('skips the ownership lookup entirely when no fileIds are sent', async () => {@@ -794,7 +768,7 @@ describe('shareChatRouter', () => {});});- it('writes a creator-owned agent_share row with the visitor in its provenance and settles the session', async () => {+ it('writes a creator-owned row with visitor provenance and settles the session', async () => {const caller = await createCaller();const result = await caller.createFile(input);@@ -814,16 +788,13 @@ describe('shareChatRouter', () => {}),name: 'cat.png',size: 10,- source: 'agent_share',url: pathname,}),false,expect.anything(),);- // Share rows stay out of the hash-keyed `global_files` graph: no hash is- // stored and no global row is registered, so `removeFile` can always- // delete the row's own object (see the `exclusiveStorage` test below).expect(mockFileCreate.mock.calls[0][0]).not.toHaveProperty('fileHash');+ expect(mockFileCreate.mock.calls[0][0]).not.toHaveProperty('source');expect(mockUploadSettle).toHaveBeenCalledWith('upload-1', 'file-new', expect.anything());});@@ -916,35 +887,37 @@ describe('shareChatRouter', () => {});describe('removeFile', () => {- const provenance = { agentShare: { shareId: 'share-1', visitorUserId: VISITOR } };-it("deletes this visitor's own unsent share upload and the stored object", async () => {- mockFileFindById.mockResolvedValue({+ mockFileFindById.mockResolvedValue({ id: 'file-a' });+ mockFileDeleteUnreferenced.mockResolvedValue({id: 'file-a',- metadata: provenance,- source: 'agent_share',+ url: 'files/x/cat.png',});- mockFileDeleteUnreferenced.mockResolvedValue({ id: 'file-a', url: 'files/x/cat.png' });const caller = await createCaller();await caller.removeFile({ fileId: 'file-a', shareId: 'share-1' });expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);- // `exclusiveStorage`: the row owns its object outright (never registered- // in `global_files`), so the object is deleted whenever the row is, even- // if some other file happens to carry the same content hash.- expect(mockFileDeleteUnreferenced).toHaveBeenCalledWith('file-a', true, {- exclusiveStorage: true,+ expect(mockFileFindById).toHaveBeenCalledWith('file-a', {+ accessScope: {+ shareId: share.shareId,+ type: 'agentShare',+ visitorUserId: VISITOR,+ },+ });+ expect(mockFileDeleteUnreferenced).toHaveBeenCalledWith('file-a', {+ accessScope: {+ shareId: share.shareId,+ type: 'agentShare',+ visitorUserId: VISITOR,+ },+ removeGlobalFile: true,});expect(mockDeleteStoredFile).toHaveBeenCalledWith('files/x/cat.png');});it('leaves the stored object alone when the row is already referenced by a message', async () => {- mockFileFindById.mockResolvedValue({- id: 'file-a',- metadata: provenance,- source: 'agent_share',- });+ mockFileFindById.mockResolvedValue({ id: 'file-a' });mockFileDeleteUnreferenced.mockResolvedValue(undefined);const caller = await createCaller();@@ -953,22 +926,12 @@ describe('shareChatRouter', () => {expect(mockDeleteStoredFile).not.toHaveBeenCalled();});- it("refuses the creator's own file and another visitor's share upload alike", async () => {+ it('refuses a file outside the share and visitor provenance scope', async () => {const caller = await createCaller();- mockFileFindById.mockResolvedValue({ id: 'file-a', metadata: null, source: null });await expect(caller.removeFile({ fileId: 'file-a', shareId: 'share-1' }),).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'File not found' });-- mockFileFindById.mockResolvedValue({- id: 'file-a',- metadata: { agentShare: { shareId: 'share-1', visitorUserId: 'visitor-2' } },- source: 'agent_share',- });- await expect(- caller.removeFile({ fileId: 'file-a', shareId: 'share-1' }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });expect(mockFileDeleteUnreferenced).not.toHaveBeenCalled();});});diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.tsindex 633ec787862..54f4cdd3dc1 100644--- a/apps/server/src/routers/lambda/file.ts+++ b/apps/server/src/routers/lambda/file.ts@@ -38,7 +38,13 @@ import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermissimport { createResourceContentPreview } from '@/server/utils/resourceContentPreview';import { AsyncTaskStatus, AsyncTaskType, type IAsyncTaskError } from '@/types/asyncTask';import type { FileListItem, KnowledgeItemStatus } from '@/types/files';-import { FileSource, QueryFileListSchema, toFileSource, UploadFileSchema } from '@/types/files';+import {+ FileSource,+ QueryFileListSchema,+ stripAgentShareFileProvenance,+ toFileSource,+ UploadFileSchema,+} from '@/types/files';import { TransferErrorCode } from '@/types/transferError';import {@@ -231,6 +237,7 @@ export const fileRouter = router({}),).mutation(async ({ ctx, input }) => {+ const metadata = stripAgentShareFileProvenance(input.metadata);const existingFile = await ctx.fileModel.checkHash(input.hash!);const { isExist } = existingFile;const latestUpload = await ctx.fileUploadService.findLatest(input.url);@@ -285,7 +292,7 @@ export const fileRouter = router({(settledFile.source ?? undefined) === toFileSource(input.source) &&settledFile.url === input.url &&(!ctx.workspaceId || settledFile.visibility === resolvedVisibility) &&- isEqual(settledFile.metadata, input.metadata ?? null);+ isEqual(settledFile.metadata, metadata ?? null);if (isRetry) {return {@@ -367,7 +374,7 @@ export const fileRouter = router({await ctx.fileModel.updateGlobalFile(input.hash!,{- metadata: input.metadata,+ metadata,url: input.url,},trx,@@ -380,7 +387,7 @@ export const fileRouter = router({fileHash: input.hash,fileType: input.fileType,knowledgeBaseId: input.knowledgeBaseId,- metadata: input.metadata,+ metadata,name: input.name,parentId: resolvedParentId,size: actualSize,@@ -895,7 +902,9 @@ export const fileRouter = router({if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });await assertFileNotInRestrictedKnowledgeBase(ctx, input.id);- const file = await ctx.fileModel.delete(input.id, serverDBEnv.REMOVE_GLOBAL_FILE);+ const file = await ctx.fileModel.delete(input.id, {+ removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,+ });if (!file) return;@@ -911,7 +920,9 @@ export const fileRouter = router({if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });await assertFileNotInRestrictedKnowledgeBase(ctx, input.id);- const file = await ctx.fileModel.deleteUnreferenced(input.id, serverDBEnv.REMOVE_GLOBAL_FILE);+ const file = await ctx.fileModel.deleteUnreferenced(input.id, {+ removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,+ });if (!file) return;await ctx.fileService.deleteFile(file.url!);@@ -986,7 +997,7 @@ export const fileRouter = router({const updates: Parameters<typeof ctx.fileModel.update>[1] = {};if (metadata !== undefined) {- updates.metadata = metadata;+ updates.metadata = stripAgentShareFileProvenance(metadata);}if (name !== undefined) {diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex ebf6a1aad04..2b7edf4b022 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -8,7 +8,12 @@ import {SHARE_VISITOR_PROMPT_MAX_LENGTH,} from '@lobechat/const';import type { ChatMessageError } from '@lobechat/types';-import { ChatErrorType, entityIdPattern, FileSource, RequestTrigger } from '@lobechat/types';+import {+ agentShareFileAccessScope,+ ChatErrorType,+ entityIdPattern,+ RequestTrigger,+} from '@lobechat/types';import { nanoid } from '@lobechat/utils';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -250,19 +255,6 @@ const sanitizeUploadName = (name: string) =>.replaceAll(/\p{Cc}/gu, '').trim() || 'file';-const shareFileProvenance = (- file: { metadata?: unknown; source?: string | null } | undefined,-): { shareId: string; visitorUserId: string } | undefined => {- if (!file || file.source !== FileSource.AgentShare) return undefined;- const metadata = file.metadata as { agentShare?: unknown } | null | undefined;- const provenance = metadata?.agentShare as- { shareId?: unknown; visitorUserId?: unknown } | undefined;- if (typeof provenance?.shareId !== 'string' || typeof provenance.visitorUserId !== 'string') {- return undefined;- }- return { shareId: provenance.shareId, visitorUserId: provenance.visitorUserId };-};-/*** Every attachment id a visitor pins to a turn must be a file THIS visitor* uploaded through THIS share (`shareChat.createFile`). Visitor uploads live@@ -282,12 +274,11 @@ const assertShareVisitorFiles = async (if (!fileIds?.length) return;const uniqueIds = Array.from(new Set(fileIds));- const rows = await new FileModel(db, share.ownerId).findByIds(uniqueIds);- const owned = rows.filter((file) => {- const provenance = shareFileProvenance(file);- return provenance?.shareId === share.shareId && provenance.visitorUserId === visitorUserId;- });- if (owned.length !== uniqueIds.length) {+ const rows = await new FileModel(db, share.ownerId).findByIds(+ uniqueIds,+ agentShareFileAccessScope({ shareId: share.shareId, visitorUserId }),+ );+ if (rows.length !== uniqueIds.length) {throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });}};@@ -337,8 +328,7 @@ export const shareChatRouter = router({* The row is written under the CREATOR: share conversations are creator-owned* data (topics/messages already are), and the creator's storage quota is what* paid for the reservation in `createUploadUrl`. What makes it the visitor's- * attachment rather than a creator resource is `source: agent_share` (hidden- * from the creator's library and knowledge listings) plus the+ * attachment rather than a creator resource is the server-written* `metadata.agentShare` provenance every share read/write path checks.** Deliberately simpler than the owner path: no knowledge base / parent@@ -417,7 +407,6 @@ export const shareChatRouter = router({},name: sanitizeUploadName(input.name),size: actualSize,- source: FileSource.AgentShare,url: input.pathname,},false,@@ -937,9 +926,8 @@ export const shareChatRouter = router({* and only while no message references the row β once sent, the attachment* is part of a creator-owned conversation and stays put.*- * `exclusiveStorage`: share rows are created outside `global_files` (see- * `createFile`), so the row's `url` is the only reference to its object and- * the object goes whenever the row does.+ * Share rows are created outside `global_files` (see `createFile`), so their+ * persisted provenance tells `FileModel` that the row owns its object.*/removeFile: shareChatProcedure.input(z.object({ fileId: z.string().min(1).max(64), shareId: z.string() }))@@ -947,19 +935,19 @@ export const shareChatRouter = router({const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);const fileModel = new FileModel(ctx.serverDB, share.ownerId);- const existing = await fileModel.findById(input.fileId);- const provenance = shareFileProvenance(existing);- if (provenance?.shareId !== share.shareId || provenance.visitorUserId !== ctx.userId) {+ const accessScope = agentShareFileAccessScope({+ shareId: share.shareId,+ visitorUserId: ctx.userId,+ });+ const existing = await fileModel.findById(input.fileId, { accessScope });+ if (!existing) {throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });}- const file = await fileModel.deleteUnreferenced(- input.fileId,- serverDBEnv.REMOVE_GLOBAL_FILE,- {- exclusiveStorage: true,- },- );+ const file = await fileModel.deleteUnreferenced(input.fileId, {+ accessScope,+ removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,+ });if (!file) return;await new FileService(ctx.serverDB, share.ownerId).deleteFile(file.url!);diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.tsindex c33d5041bd9..b7b9037f9d9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts@@ -477,7 +477,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {prompt: 'What is in this image?',});- expect(mockFindByIds).toHaveBeenCalledWith(['file-img-1']);+ expect(mockFindByIds).toHaveBeenCalledWith(['file-img-1'], { type: 'ordinary' });const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');expect(userMessageCall![0].files).toEqual(['file-img-1']);@@ -516,7 +516,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {prompt: 'Summarize this document',});- expect(mockParseFile).toHaveBeenCalledWith('file-pdf-1');+ expect(mockParseFile).toHaveBeenCalledWith('file-pdf-1', { type: 'ordinary' });const createOpArgs = mockCreateOperation.mock.calls[0][0];const lastMessage = createOpArgs.initialMessages.at(-1);@@ -642,7 +642,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {});// FileModel.findByIds sees deduped input (cheaper query)- expect(mockFindByIds).toHaveBeenCalledWith(['file-img-1']);+ expect(mockFindByIds).toHaveBeenCalledWith(['file-img-1'], { type: 'ordinary' });// Only one link row will be insertedconst userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.tsindex 97ea60f312c..715f08498f2 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.ts@@ -19,11 +19,13 @@ const {mockResolveAttachmentsByFileIds: vi.fn(),}));-// `discoverTools` peeks at the attached files' MIME types (creator-scoped-// today; media routing only) β stub it so the bare mock db is never queried.+// `discoverTools` peeks at the attached files' MIME types for media routing.+// Stub file reads so the bare mock db is never queried.vi.mock('@/database/models/file', () => ({FileModel: vi.fn().mockImplementation(function () {- return { findByIds: vi.fn().mockResolvedValue([]) };+ return {+ findByIds: vi.fn().mockResolvedValue([]),+ };}),}));@@ -242,7 +244,15 @@ describe('AiAgentService.execAgent - share-visitor attachment scope', () => {});expect(mockResolveAttachmentsByFileIds).toHaveBeenCalledWith(- expect.objectContaining({ fileIds: ['file-visitor'], userId: creatorId }),+ expect.objectContaining({+ fileAccessScope: {+ shareId: 'share-1',+ type: 'agentShare',+ visitorUserId: visitorId,+ },+ fileIds: ['file-visitor'],+ userId: creatorId,+ }),);expect(mockResolveAttachmentsByFileIds).not.toHaveBeenCalledWith(expect.objectContaining({ userId: visitorId }),diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.tsindex e1f4878b7ba..ed7bb006a9c 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts@@ -10,6 +10,7 @@ import { AiAgentService } from '../../index';// below (which run before the test body) can wire them into stubbed models.const {mockCreateOperation,+ mockFindByIds,mockGetAgentConfig,mockGetUserSettings,mockMessageCreate,@@ -17,6 +18,7 @@ const {mockScheduleStaleConnectorToolsRefresh,} = vi.hoisted(() => ({mockCreateOperation: vi.fn(),+ mockFindByIds: vi.fn(),mockGetAgentConfig: vi.fn(),mockGetUserSettings: vi.fn(),mockMessageCreate: vi.fn(),@@ -26,6 +28,14 @@ const {mockScheduleStaleConnectorToolsRefresh: vi.fn(),}));+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn().mockImplementation(function () {+ return {+ findByIds: mockFindByIds,+ };+ }),+}));+vi.mock('@/libs/trusted-client', () => ({generateTrustedClientToken: vi.fn().mockReturnValue(undefined),getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),@@ -209,6 +219,7 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {success: true,});mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });+ mockFindByIds.mockResolvedValue([]);// Pinned plugins on the creator's agent β one granted by the share, the// other is a connector-backed identifier that must not be resolved for a// visitor.@@ -273,4 +284,26 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {expect.arrayContaining(['granted-plugin', 'ungranted-connector']),);});++ it('reads attached file types through the exact share visitor scope', async () => {+ mockFindByIds.mockResolvedValue([{ fileType: 'image/png', id: 'file-visitor' }]);++ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-visitor'],+ prompt: 'Describe the image',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(mockFindByIds).toHaveBeenCalledWith(['file-visitor'], {+ shareId: 'share-1',+ type: 'agentShare',+ visitorUserId: 'visitor-1',+ });+ });});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex fecbd02efb9..745500b056b 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -21,7 +21,11 @@ import type {import type { LobeChatDatabase } from '@lobechat/database';import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';import type { ChatTopicBotContext, RequestTrigger } from '@lobechat/types';-import { getActivePluginIds } from '@lobechat/types';+import {+ agentShareFileAccessScope,+ getActivePluginIds,+ ordinaryFileAccessScope,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import type { ModelAbilities } from 'model-bank';@@ -632,7 +636,11 @@ export const discoverTools = async (let attachedFileTypes: string[] = [];if (attachedFileIds && attachedFileIds.length > 0) {const fileModel = new FileModel(deps.db, deps.userId, deps.workspaceId);- const fileRecords = await fileModel.findByIds(Array.from(new Set(attachedFileIds)));+ const uniqueFileIds = Array.from(new Set(attachedFileIds));+ const fileRecords = await fileModel.findByIds(+ uniqueFileIds,+ shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,+ );attachedFileTypes = fileRecords.map((file) => file.fileType || '');}const inputFileTypes = [...externalFileTypes, ...attachedFileTypes];diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 34f9e2019e1..be448351a1e 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -6,11 +6,14 @@ import type {ChatFileItem,ChatTopicMetadata,ChatVideoItem,+ FileAccessScope,HeterogeneousProviderConfig,HeterogeneousTopicPin,} from '@lobechat/types';import {+ agentShareFileAccessScope,ChatErrorType,+ ordinaryFileAccessScope,RequestTrigger,resolveHeterogeneousProviderTopicModel,} from '@lobechat/types';@@ -144,10 +147,12 @@ const resolveRunAttachments = async (deps: TurnSetupDeps,{attachedFileIds,+ fileAccessScope,files,throwIfAborted,}: {attachedFileIds?: string[];+ fileAccessScope: FileAccessScope;files?: InternalExecAgentParams['files'];throwIfAborted: (stage: string) => Promise<void>;},@@ -270,6 +275,7 @@ const resolveRunAttachments = async (try {const resolved = await resolveAttachmentsByFileIds({db: deps.db,+ fileAccessScope,fileIds: attachedFileIds,userId: deps.userId,workspaceId: deps.workspaceId,@@ -662,6 +668,7 @@ export const setupTurn = async (// `attachedFileIds` β signed URLs + classification.const runAttachments = await resolveRunAttachments(deps, {attachedFileIds,+ fileAccessScope: shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,files,throwIfAborted: throwIfExecutionAborted,});diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.tsindex 09f13e3649a..41aa8459c37 100644--- a/apps/server/src/services/document/__tests__/index.test.ts+++ b/apps/server/src/services/document/__tests__/index.test.ts@@ -1,4 +1,5 @@import { type LobeChatDatabase } from '@lobechat/database';+import { agentShareFileAccessScope } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { PgDialect } from 'drizzle-orm/pg-core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -259,6 +260,29 @@ describe('DocumentService', () => {expect(result).toEqual(mockDoc);});+ it('should strip caller-provided agent-share provenance from document metadata', async () => {+ mockFileModel.create.mockResolvedValue({ id: 'file-1' });+ mockDocumentModel.create.mockResolvedValue({ id: 'doc-1' });++ await service.createDocument({+ title: 'Test',+ editorData: {},+ knowledgeBaseId: 'kb-1',+ metadata: {+ agentShare: { shareId: 'forged-share', visitorUserId: 'forged-visitor' },+ existingKey: 'value',+ },+ });++ expect(mockFileModel.create).toHaveBeenCalledWith(+ expect.objectContaining({ metadata: { existingKey: 'value' } }),+ false,+ );+ expect(mockDocumentModel.create).toHaveBeenCalledWith(+ expect.objectContaining({ metadata: { existingKey: 'value' } }),+ );+ });+it('should NOT create a file record when fileType is custom/folder', async () => {const mockDoc = { id: 'doc-1', title: 'My Folder' };mockDocumentModel.create.mockResolvedValue(mockDoc);@@ -1864,6 +1888,26 @@ describe('DocumentService', () => {expect(result).toEqual({ id: 'doc-1', title: 'Readme' });});+ it('should preserve agent-share provenance when downloading a visitor file', async () => {+ const accessScope = agentShareFileAccessScope({+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });+ vi.mocked(loadFile).mockResolvedValue({+ content: 'Visitor content',+ fileType: 'markdown',+ metadata: {},+ totalCharCount: 15,+ totalLineCount: 1,+ } as any);+ mockDocumentModel.create.mockResolvedValue({ id: 'doc-visitor' });++ await service.parseFile('file-visitor', accessScope);++ expect(mockDocumentModel.findByFileId).toHaveBeenCalledWith('file-visitor', accessScope);+ expect(mockFileService.downloadFileToLocal).toHaveBeenCalledWith('file-visitor', accessScope);+ });+it('should use file name as title (stripping extension) when metadata has no title', async () => {vi.mocked(loadFile).mockResolvedValue({content: 'Content',@@ -1966,7 +2010,9 @@ describe('DocumentService', () => {'workspace-1','public',);- expect(transactionModel.findByFileId).toHaveBeenCalledWith('file-1');+ expect(transactionModel.findByFileId).toHaveBeenCalledWith('file-1', {+ type: 'ordinary',+ });expect(transactionModel.create).toHaveBeenCalledTimes(1);expect(mockDocumentModel.create).not.toHaveBeenCalled();// Both have to happen after the lock is held β re-checking before it woulddiff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex cd15906904a..3ceafa73438 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -5,6 +5,8 @@ import { type LobeChatDatabase } from '@lobechat/database';import { type DocumentItem } from '@lobechat/database/schemas';import { documents, files } from '@lobechat/database/schemas';import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';+import type { FileAccessScope } from '@lobechat/types';+import { ordinaryFileAccessScope, stripAgentShareFileProvenance } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { and, eq, sql } from 'drizzle-orm';@@ -144,6 +146,7 @@ export class DocumentService {slug,visibility,} = params;+ const sanitizedMetadata = stripAgentShareFileProvenance(metadata);// Calculate character and line countsconst totalCharCount = content?.length || 0;@@ -176,7 +179,7 @@ export class DocumentService {{fileType,knowledgeBaseId,- metadata,+ metadata: sanitizedMetadata,name: title,parentId,size: totalCharCount,@@ -191,8 +194,8 @@ export class DocumentService {// Store knowledgeBaseId in metadata for folders (which don't have fileId)const finalMetadata =knowledgeBaseId && fileType === CUSTOM_FOLDER_FILE_TYPE- ? { ...metadata, knowledgeBaseId }- : metadata;+ ? { ...sanitizedMetadata, knowledgeBaseId }+ : sanitizedMetadata;const document = await this.documentModel.create({content,@@ -847,12 +850,18 @@ export class DocumentService {* transaction scoped, so a nested call would hold it until the outer* transaction commits instead of releasing it after the insert.*/- async parseFile(fileId: string): Promise<LobeDocument> {+ async parseFile(+ fileId: string,+ accessScope: FileAccessScope = ordinaryFileAccessScope,+ ): Promise<LobeDocument> {// Idempotent: return existing document if already parsed- const existingDoc = await this.documentModel.findByFileId(fileId);+ const existingDoc = await this.documentModel.findByFileId(fileId, accessScope);if (existingDoc) return existingDoc as LobeDocument;- const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(fileId);+ const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(+ fileId,+ accessScope,+ );const logPrefix = `[${file.name}]`;log(`${logPrefix} Starting to parse file, path: ${filePath}`);@@ -897,7 +906,7 @@ export class DocumentService {// Whoever inserted first wins; discard this parse rather than adding a// second document for the same file.- const raced = await transactionDocumentModel.findByFileId(fileId);+ const raced = await transactionDocumentModel.findByFileId(fileId, accessScope);if (raced) return raced;return transactionDocumentModel.create({diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex 5192caf84cd..0e1dc0aad98 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -1,3 +1,4 @@+import { agentShareFileAccessScope } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -61,8 +62,8 @@ describe('FileService', () => {beforeEach(() => {mockFileModel = {- findById: vi.fn(),delete: vi.fn(),+ findById: vi.fn(),updateGlobalFile: vi.fn(),};mockTempManager = {@@ -127,7 +128,10 @@ describe('FileService', () => {new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' }),);- expect(mockFileModel.delete).toHaveBeenCalledWith('test-file-id', false);+ expect(mockFileModel.delete).toHaveBeenCalledWith('test-file-id', {+ accessScope: { type: 'ordinary' },+ removeGlobalFile: false,+ });});it('should log error and rethrow for non-NoSuchKey errors', async () => {@@ -172,6 +176,39 @@ describe('FileService', () => {expect(mockTempManager.writeTempFile).toHaveBeenCalledWith(mockContent, mockFile.name);});++ it('should resolve an agent-share file only through its provenance scope', async () => {+ const accessScope = agentShareFileAccessScope({+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });+ const mockContent = new Uint8Array([1, 2, 3]);+ mockFileModel.findById.mockResolvedValue(mockFile);+ vi.mocked(service['impl'].getFileByteArray).mockResolvedValue(mockContent);+ mockTempManager.writeTempFile.mockResolvedValue('/tmp/test.txt');++ await service.downloadFileToLocal('test-file-id', accessScope);++ expect(mockFileModel.findById).toHaveBeenCalledWith('test-file-id', { accessScope });+ });++ it('should use the scoped cleanup path when an agent-share object is missing', async () => {+ const accessScope = agentShareFileAccessScope({+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });+ mockFileModel.findById.mockResolvedValue(mockFile);+ vi.mocked(service['impl'].getFileByteArray).mockRejectedValue({ Code: 'NoSuchKey' });++ await expect(service.downloadFileToLocal('test-file-id', accessScope)).rejects.toThrow(+ new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' }),+ );++ expect(mockFileModel.delete).toHaveBeenCalledWith('test-file-id', {+ accessScope,+ removeGlobalFile: false,+ });+ });});it('should delegate deleteFile to implementation', async () => {diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex 0348cb78427..9729d4b53fb 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -1,4 +1,6 @@import { type LobeChatDatabase, type Transaction } from '@lobechat/database';+import type { FileAccessScope } from '@lobechat/types';+import { ordinaryFileAccessScope } from '@lobechat/types';import { inferContentTypeFromImageUrl, nanoid, uuid } from '@lobechat/utils';import { TRPCError } from '@trpc/server';import { sha256 } from 'js-sha256';@@ -257,7 +259,7 @@ export class FileService {* @param fileId - File ID to delete from user's files table*/public async deleteUserFileRecord(fileId: string): Promise<void> {- await this.fileModel.delete(fileId, false); // false = don't remove globalFiles+ await this.fileModel.delete(fileId, { removeGlobalFile: false });}/**@@ -512,8 +514,9 @@ export class FileService {async downloadFileToLocal(fileId: string,+ accessScope: FileAccessScope = ordinaryFileAccessScope,): Promise<{ cleanup: () => void; file: FileItem; filePath: string }> {- const file = await this.fileModel.findById(fileId);+ const file = await this.fileModel.findById(fileId, { accessScope });if (!file) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' });}@@ -525,7 +528,10 @@ export class FileService {console.error(e);// if file not found, delete it from dbif ((e as any).Code === 'NoSuchKey') {- await this.fileModel.delete(fileId, serverDBEnv.REMOVE_GLOBAL_FILE);+ await this.fileModel.delete(fileId, {+ accessScope,+ removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,+ });throw new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' });}}diff --git a/apps/server/src/services/file/resolveAttachments.test.ts b/apps/server/src/services/file/resolveAttachments.test.tsindex 1175979d444..156e9e324ea 100644--- a/apps/server/src/services/file/resolveAttachments.test.ts+++ b/apps/server/src/services/file/resolveAttachments.test.ts@@ -1,21 +1,29 @@// @vitest-environment nodeimport type { LobeChatDatabase } from '@lobechat/database';+import { agentShareFileAccessScope } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { resolveAttachmentMetadata } from './resolveAttachments';+import { resolveAttachmentMetadata, resolveAttachmentsByFileIds } from './resolveAttachments';const mocks = vi.hoisted(() => ({findByIds: vi.fn(),getFullFileUrl: vi.fn(),+ parseFile: vi.fn(),}));vi.mock('@/database/models/file', () => ({FileModel: vi.fn().mockImplementation(function () {- return { findByIds: mocks.findByIds };+ return {+ findByIds: mocks.findByIds,+ };}),}));-vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));+vi.mock('@/server/services/document', () => ({+ DocumentService: vi.fn().mockImplementation(function () {+ return { parseFile: mocks.parseFile };+ }),+}));vi.mock('@/server/services/file', () => ({FileService: vi.fn().mockImplementation(function () {@@ -60,4 +68,61 @@ describe('resolveAttachmentMetadata', () => {},]);});++ it('uses the provenance-scoped reader for an agent-share run', async () => {+ const fileAccessScope = agentShareFileAccessScope({+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });+ mocks.findByIds.mockResolvedValue([+ {+ fileType: 'image/png',+ id: 'file-visitor',+ name: 'cat.png',+ size: 42,+ url: 'agent-share/cat.png',+ },+ ]);+ mocks.getFullFileUrl.mockResolvedValue('https://storage.example.com/agent-share/cat.png');++ const result = await resolveAttachmentsByFileIds({+ db: {} as LobeChatDatabase,+ fileAccessScope,+ fileIds: ['file-visitor'],+ userId: 'creator-1',+ });++ expect(mocks.findByIds).toHaveBeenCalledWith(['file-visitor'], fileAccessScope);+ expect(result.orderedFileIds).toEqual(['file-visitor']);+ });++ it('passes share provenance into document parsing', async () => {+ const fileAccessScope = agentShareFileAccessScope({+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });+ mocks.findByIds.mockResolvedValue([+ {+ fileType: 'application/pdf',+ id: 'file-visitor-pdf',+ name: 'report.pdf',+ size: 42,+ url: 'agent-share/report.pdf',+ },+ ]);+ mocks.getFullFileUrl.mockResolvedValue('https://storage.example.com/agent-share/report.pdf');+ mocks.parseFile.mockResolvedValue({ content: 'Visitor report' });++ const result = await resolveAttachmentsByFileIds({+ db: {} as LobeChatDatabase,+ fileAccessScope,+ fileIds: ['file-visitor-pdf'],+ userId: 'creator-1',+ });++ expect(mocks.parseFile).toHaveBeenCalledWith('file-visitor-pdf', fileAccessScope);+ expect(result.fileList).toEqual([+ expect.objectContaining({ content: 'Visitor report', id: 'file-visitor-pdf' }),+ ]);+ });});diff --git a/apps/server/src/services/file/resolveAttachments.ts b/apps/server/src/services/file/resolveAttachments.tsindex bc833062c05..1f24328fe98 100644--- a/apps/server/src/services/file/resolveAttachments.ts+++ b/apps/server/src/services/file/resolveAttachments.ts@@ -1,5 +1,12 @@import type { LobeChatDatabase } from '@lobechat/database';-import type { ChatAudioItem, ChatFileItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';+import type {+ ChatAudioItem,+ ChatFileItem,+ ChatImageItem,+ ChatVideoItem,+ FileAccessScope,+} from '@lobechat/types';+import { ordinaryFileAccessScope } from '@lobechat/types';import { readAudioDurationMs } from '@lobechat/utils/audio';import debug from 'debug';@@ -25,6 +32,7 @@ export interface ResolvedAttachments {interface ResolveArgs {db: LobeChatDatabase;+ fileAccessScope?: FileAccessScope;fileIds: string[];userId: string;workspaceId?: string;@@ -60,6 +68,7 @@ const getAudioMetadata = (*/export const resolveAttachmentsByFileIds = async ({db,+ fileAccessScope = ordinaryFileAccessScope,fileIds,userId,workspaceId,@@ -77,7 +86,7 @@ export const resolveAttachmentsByFileIds = async ({const dedupedFileIds = dedupe(fileIds);const fileModel = new FileModel(db, userId, workspaceId);const fileService = new FileService(db, userId, workspaceId);- const fileRecords = await fileModel.findByIds(dedupedFileIds);+ const fileRecords = await fileModel.findByIds(dedupedFileIds, fileAccessScope);if (fileRecords.length === 0) {log('no file records found for fileIds=%O', dedupedFileIds);return result;@@ -107,7 +116,7 @@ export const resolveAttachmentsByFileIds = async ({let content: string | undefined;let parseError: unknown;try {- const document = await documentService.parseFile(file.id);+ const document = await documentService.parseFile(file.id, fileAccessScope);content = document.content ?? undefined;} catch (error) {parseError = error;diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsindex 9a1c9ecdab3..ad3fe0ddd63 100644--- a/packages/database/src/models/__tests__/document.test.ts+++ b/packages/database/src/models/__tests__/document.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { agentShareFileAccessScope } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -376,6 +377,54 @@ describe('DocumentModel', () => {});describe('findById', () => {+ it('hides a document derived from an agent-share file from ordinary document reads', async () => {+ const { id: fileId } = await fileModel.create({+ fileType: 'application/pdf',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.pdf',+ size: 100,+ url: 'files/user/agent-share/share-a/visitor.pdf',+ });+ const { id: documentId, slug } = await documentModel.create({+ content: 'private visitor content',+ fileId,+ fileType: 'custom/document',+ filename: 'visitor',+ source: 'files/user/agent-share/share-a/visitor.pdf',+ sourceType: 'file',+ title: 'Visitor document',+ totalCharCount: 23,+ totalLineCount: 1,+ });++ await expect(documentModel.query({ sourceTypes: ['file'] })).resolves.toMatchObject({+ items: [],+ total: 0,+ });+ await expect(documentModel.findById(documentId)).resolves.toBeUndefined();+ await expect(documentModel.findByIds([documentId])).resolves.toEqual([]);+ await expect(documentModel.findByFileId(fileId)).resolves.toBeUndefined();+ await expect(documentModel.findBySlug(slug!)).resolves.toBeUndefined();+ await expect(+ documentModel.findByFileId(+ fileId,+ agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-a',+ }),+ ),+ ).resolves.toMatchObject({ id: documentId });+ await expect(+ documentModel.findByFileId(+ fileId,+ agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-b',+ }),+ ),+ ).resolves.toBeUndefined();+ });+it('should find document by id', async () => {const { documentId } = await createTestDocument(documentModel, fileModel, 'Test content');diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.tsindex ffbc2041d64..57955c0ea4f 100644--- a/packages/database/src/models/__tests__/file.test.ts+++ b/packages/database/src/models/__tests__/file.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { FileSource, FilesTabs, SortType } from '@lobechat/types';+import { agentShareFileAccessScope, FileSource, FilesTabs, SortType } from '@lobechat/types';import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -194,7 +194,7 @@ describe('FileModel', () => {fileHash: '1',});- await fileModel.delete(id, false);+ await fileModel.delete(id, { removeGlobalFile: false });const file = await serverDB.query.files.findFirst({ where: eq(files.id, id) });const globalFile = await serverDB.query.globalFiles.findFirst({@@ -352,33 +352,78 @@ describe('FileModel', () => {).resolves.toBeDefined();});- it('returns a hashless row only with exclusiveStorage, so its object can be deleted', async () => {- const create = () =>- fileModel.create(- { fileType: 'image/png', name: 'cat.png', size: 10, url: 'files/u/share/a/cat.png' },- false,- );-- // Default: no hash means no global-file bookkeeping, and the caller gets- // nothing back even though the row is gone.- const { id: silent } = await create();+ it('derives hashless agent-share object ownership from persisted provenance', async () => {+ const { id: silent } = await fileModel.create(+ { fileType: 'image/png', name: 'cat.png', size: 10, url: 'files/u/plain/cat.png' },+ false,+ );await expect(fileModel.deleteUnreferenced(silent)).resolves.toBeUndefined();await expect(serverDB.query.files.findFirst({ where: eq(files.id, silent) }),).resolves.toBeUndefined();- // exclusiveStorage: the row is the only owner of its object, so it is- // returned whenever it was deleted.- const { id } = await create();+ const { id } = await fileModel.create(+ {+ fileType: 'image/png',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'cat.png',+ size: 10,+ url: 'files/u/share/a/cat.png',+ },+ false,+ );+ await expect(fileModel.deleteUnreferenced(id)).resolves.toBeUndefined();+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, id) }),+ ).resolves.toBeDefined();+ await expect(+ fileModel.deleteUnreferenced(id, {+ accessScope: agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-b',+ }),+ }),+ ).resolves.toBeUndefined();await expect(- fileModel.deleteUnreferenced(id, true, { exclusiveStorage: true }),- ).resolves.toMatchObject({ id, url: 'files/u/share/a/cat.png' });+ fileModel.deleteUnreferenced(id, {+ accessScope: agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-a',+ }),+ }),+ ).resolves.toMatchObject({+ id,+ url: 'files/u/share/a/cat.png',+ });await expect(serverDB.query.files.findFirst({ where: eq(files.id, id) }),).resolves.toBeUndefined();++ const { id: removalDisabled } = await fileModel.create(+ {+ fileType: 'image/png',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'dog.png',+ size: 10,+ url: 'files/u/share/a/dog.png',+ },+ false,+ );+ await expect(+ fileModel.deleteUnreferenced(removalDisabled, {+ accessScope: agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-a',+ }),+ removeGlobalFile: false,+ }),+ ).resolves.toBeUndefined();+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, removalDisabled) }),+ ).resolves.toBeUndefined();});- it('returns a hashed row with exclusiveStorage even while another row shares the hash', async () => {+ it('keeps hashed rows on the global reference-count path even with share provenance', async () => {await fileModel.createGlobalFile({creator: userId,fileType: 'image/png',@@ -396,27 +441,24 @@ describe('FileModel', () => {const { id } = await fileModel.create({fileHash: 'shared-hash',fileType: 'image/png',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },name: 'second.png',size: 10,url: 'files/u/second.png',});- await expect(fileModel.deleteUnreferenced(id, true)).resolves.toBeUndefined();+ await expect(+ fileModel.deleteUnreferenced(id, {+ accessScope: agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-a',+ }),+ }),+ ).resolves.toBeUndefined();await expect(serverDB.query.files.findFirst({ where: eq(files.id, id) }),).resolves.toBeUndefined();- const { id: again } = await fileModel.create({- fileHash: 'shared-hash',- fileType: 'image/png',- name: 'third.png',- size: 10,- url: 'files/u/third.png',- });- await expect(- fileModel.deleteUnreferenced(again, true, { exclusiveStorage: true }),- ).resolves.toMatchObject({ id: again, url: 'files/u/third.png' });- // The shared global entry survives: the keeper still references it.await expect(serverDB.query.files.findFirst({ where: eq(files.id, keeper) }),).resolves.toBeDefined();@@ -875,6 +917,15 @@ describe('FileModel', () => {source: FileSource.Acceptance,url: 'acceptance-url',},+ {+ id: 'agent-share-file',+ name: 'visitor.txt',+ userId,+ fileType: 'text/plain',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ size: 100,+ url: 'visitor-url',+ },{id: 'generation-file',name: 'generated.png',@@ -887,7 +938,7 @@ describe('FileModel', () => {]);});- it('should exclude acceptance evidence and keep every other source', async () => {+ it('should exclude acceptance evidence and agent-share provenance', async () => {const result = await fileModel.query();expect(result.map((f) => f.id).sort()).toEqual(['generation-file', 'plain-file']);@@ -902,21 +953,19 @@ describe('FileModel', () => {});describe('countAgentShareUsage', () => {- it("sums only this user's agent_share files that belong to the given share", async () => {+ it("sums only this user's files with provenance for the given share", async () => {const base = { fileType: 'text/plain', url: 'https://example.com/f' };const visitorFile = (shareId: string, size: number) => ({...base,metadata: { agentShare: { shareId, visitorUserId: 'visitor' } },name: `${shareId}-${size}`,size,- source: FileSource.AgentShare,});await fileModel.create(visitorFile('share-a', 10));await fileModel.create(visitorFile('share-a', 20));await fileModel.create(visitorFile('share-b', 40));- // Same provenance shape on a plain library upload: not a visitor file.- await fileModel.create({ ...visitorFile('share-a', 80), source: undefined });+ await fileModel.create({ ...base, name: 'ordinary', size: 80 });// Another user's visitor file on the same share id.await new FileModel(serverDB, 'user2').create(visitorFile('share-a', 160));@@ -945,6 +994,35 @@ describe('FileModel', () => {userId,});});++ it('hides share-provenance files from ordinary reads and resolves them through the scoped API', async () => {+ const { id } = await fileModel.create({+ fileType: 'text/plain',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.txt',+ size: 100,+ url: 'https://example.com/visitor.txt',+ });++ await expect(fileModel.findById(id)).resolves.toBeUndefined();+ await expect(fileModel.findByIds([id])).resolves.toEqual([]);+ await expect(+ fileModel.findById(id, {+ accessScope: agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-a',+ }),+ }),+ ).resolves.toMatchObject({ id });+ await expect(+ fileModel.findById(id, {+ accessScope: agentShareFileAccessScope({+ shareId: 'share-a',+ visitorUserId: 'visitor-b',+ }),+ }),+ ).resolves.toBeUndefined();+ });});it('should update a file', async () => {@@ -1307,7 +1385,7 @@ describe('FileModel', () => {// Delete file in transactionawait serverDB.transaction(async (trx) => {- await fileModel.delete(id, true, trx);+ await fileModel.delete(id, { transaction: trx });// Verify file was deleted inside the transactionconst file = await trx.query.files.findFirst({ where: eq(files.id, id) });@@ -1346,7 +1424,7 @@ describe('FileModel', () => {// Intentionally fail the transactionawait expect(serverDB.transaction(async (trx) => {- await fileModel.delete(id, true, trx);+ await fileModel.delete(id, { transaction: trx });// Verify file was deleted inside the transactionconst file = await trx.query.files.findFirst({ where: eq(files.id, id) });@@ -1389,7 +1467,7 @@ describe('FileModel', () => {// Delete file in transaction, but keep global fileawait serverDB.transaction(async (trx) => {- await fileModel.delete(id, false, trx);+ await fileModel.delete(id, { removeGlobalFile: false, transaction: trx });});// Verify file was deleted@@ -1426,7 +1504,7 @@ describe('FileModel', () => {// Delete old file and create new file in the same transactionconst result = await serverDB.transaction(async (trx) => {// Delete old file- await fileModel.delete(deleteFileId, true, trx);+ await fileModel.delete(deleteFileId, { transaction: trx });// Create new fileconst { id: newFileId } = await fileModel.create(@@ -1553,7 +1631,7 @@ describe('FileModel', () => {// Insert chunks (this might need to be done through proper API)// For testing purposes, we'll delete the file which should trigger the batch deletion- await fileModel.delete(fileId, true);+ await fileModel.delete(fileId);// Verify the file is deletedconst deletedFile = await serverDB.query.files.findFirst({@@ -1611,7 +1689,7 @@ describe('FileModel', () => {// Skip documentChunks test, requires creating documents records first// Delete file, should clean up all related data- const result = await fileModel.delete(fileId, true);+ const result = await fileModel.delete(fileId);// Verify file was deletedconst deletedFile = await serverDB.query.files.findFirst({@@ -1669,7 +1747,7 @@ describe('FileModel', () => {.values([{ chunkId, embeddings: testEmbedding, model: 'test-model', userId }]);// Delete file- await fileModel.delete(fileId, true);+ await fileModel.delete(fileId);// Verify file was deletedconst deletedFile = await serverDB.query.files.findFirst({@@ -1731,7 +1809,7 @@ describe('FileModel', () => {expect(kbFile).toBeDefined();// Delete file- await fileModel.delete(fileId, true);+ await fileModel.delete(fileId);// Verify files in knowledge base were also completely deletedconst deletedFile = await serverDB.query.files.findFirst({diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex 7dd4aac7788..d07814e38aa 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -1,4 +1,6 @@import { AGENT_ARTIFACT_SOURCE_TYPES } from '@lobechat/const';+import type { FileAccessScope } from '@lobechat/types';+import { ordinaryFileAccessScope } from '@lobechat/types';import { and, asc, count, desc, eq, inArray, isNull, ne, notInArray, or, sum } from 'drizzle-orm';import type { DocumentItem, NewDocument } from '../schemas';@@ -13,6 +15,10 @@ import {works,} from '../schemas';import type { LobeChatDatabase } from '../type';+import {+ fileReferenceMatchesAccessScope,+ notAgentShareFileReference,+} from '../utils/fileVisibility';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';export interface QueryDocumentParams {@@ -68,6 +74,9 @@ export class DocumentModel {documents,);+ private ordinaryReadScope = () =>+ and(this.ownership(), notAgentShareFileReference(this.db, documents.fileId));+findOrCreateFolder = async (name: string, parentId?: string): Promise<DocumentItem> => {const existing = await this.db.query.documents.findFirst({where: and(@@ -141,7 +150,7 @@ export class DocumentModel {total: number;}> => {const offset = current * pageSize;- const conditions = [this.ownership()];+ const conditions = [this.ordinaryReadScope()];if (fileTypes?.length) {conditions.push(inArray(documents.fileType, fileTypes));@@ -233,34 +242,50 @@ export class DocumentModel {};findById = async (id: string): Promise<DocumentItem | undefined> => {- return this.db.query.documents.findFirst({- where: and(this.ownership(), eq(documents.id, id)),- });+ const [document] = await this.db+ .select()+ .from(documents)+ .where(and(this.ordinaryReadScope(), eq(documents.id, id)))+ .limit(1);+ return document;};findByIds = async (ids: string[]): Promise<DocumentItem[]> => {if (ids.length === 0) return [];- return this.db.query.documents.findMany({- where: and(this.ownership(), inArray(documents.id, ids)),- });+ return this.db+ .select()+ .from(documents)+ .where(and(this.ordinaryReadScope(), inArray(documents.id, ids)));};- findByFileId = async (fileId: string) => {- return this.db.query.documents.findFirst({+ findByFileId = async (fileId: string, accessScope: FileAccessScope = ordinaryFileAccessScope) => {+ const [document] = await this.db+ .select()+ .from(documents)// A file can legitimately own more than one document: `parseDocument`// writes a page-editor copy next to the parse cache `parseFile` writes.// Pick the oldest one explicitly instead of leaving the choice to the// query plan, so repeated lookups keep returning the same content.// `created_at` carries no uniqueness guarantee, so `id` breaks ties.- orderBy: [asc(documents.createdAt), asc(documents.id)],- where: and(this.ownership(), eq(documents.fileId, fileId)),- });+ .where(+ and(+ this.ownership(),+ eq(documents.fileId, fileId),+ fileReferenceMatchesAccessScope(this.db, documents.fileId, accessScope),+ ),+ )+ .orderBy(asc(documents.createdAt), asc(documents.id))+ .limit(1);+ return document;};findBySlug = async (slug: string): Promise<DocumentItem | undefined> => {- return this.db.query.documents.findFirst({- where: and(this.ownership(), eq(documents.slug, slug)),- });+ const [document] = await this.db+ .select()+ .from(documents)+ .where(and(this.ordinaryReadScope(), eq(documents.slug, slug)))+ .limit(1);+ return document;};/**@@ -274,13 +299,18 @@ export class DocumentModel {source: string,sourceType: NonNullable<NewDocument['sourceType']>,): Promise<DocumentItem | undefined> => {- return this.db.query.documents.findFirst({- where: and(- this.ownership(),- eq(documents.source, source),- eq(documents.sourceType, sourceType),- ),- });+ const [document] = await this.db+ .select()+ .from(documents)+ .where(+ and(+ this.ordinaryReadScope(),+ eq(documents.source, source),+ eq(documents.sourceType, sourceType),+ ),+ )+ .limit(1);+ return document;};update = async (id: string, value: Partial<DocumentItem>) => {diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex d3e763f13b6..5a7f07d81e9 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -1,5 +1,10 @@-import type { QueryFileListParams } from '@lobechat/types';-import { FileSource, FilesTabs, LIBRARY_HIDDEN_FILE_SOURCES, SortType } from '@lobechat/types';+import type { FileAccessScope, QueryFileListParams } from '@lobechat/types';+import {+ FilesTabs,+ getAgentShareFileProvenance,+ ordinaryFileAccessScope,+ SortType,+} from '@lobechat/types';import {and,asc,@@ -12,7 +17,6 @@ import {like,ne,notExists,- notInArray,or,sql,sum,@@ -38,6 +42,11 @@ import {} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';import { buildFileCategoryFilter } from '../utils/fileTypeCategory';+import {+ fileMatchesAccessScope,+ libraryVisibleFile,+ notAgentShareFile,+} from '../utils/fileVisibility';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';/**@@ -167,78 +176,85 @@ export class FileModel {};};- /**- * Delete a file row. Returns the row only when the caller should also- * remove the stored object: by default that is when the row's `fileHash`- * was the last reference to its `global_files` entry (content-deduplicated- * uploads share one object per hash). A row created outside that dedup- * graph (`insertToGlobalFiles: false`, no `fileHash`, its own object under- * `url`) is never counted there, so pass `exclusiveStorage: true` to get the- * row back whenever it was deleted β otherwise its object is orphaned.- */- delete = async (+ private deleteInTransaction = async (id: string,- removeGlobalFile: boolean = true,- trx?: Transaction,- options?: { exclusiveStorage?: boolean },+ removeGlobalFile: boolean,+ tx: Transaction,+ accessScope: FileAccessScope,) => {- const executeInTransaction = async (tx: Transaction) => {- // In pglite environment, non-transactional operations cannot be used within a transaction as it will block- const file = await this.findById(id, tx);- if (!file) return;+ // In pglite environment, non-transactional operations cannot be used within a transaction as it will block+ const file = await this.findById(id, { accessScope, transaction: tx });+ if (!file) return;- const fileHash = file.fileHash;+ const fileHash = file.fileHash;- // 1. Delete related chunks- await this.deleteFileChunks(tx as any, [id]);+ // 1. Delete related chunks+ await this.deleteFileChunks(tx as any, [id]);- // 2. Delete mirror documents whose source is this file. Without this,- // documents.fileId would be set null by FK and leave orphan rows behind- // (still indexed by BM25, still occupying KB slots).- await tx- .delete(documents)- .where(- and(- eq(documents.fileId, id),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),- eq(documents.sourceType, 'file'),- ),- );-- // 3. Delete the chunk/embedding asyncTasks tied to this file. files.chunkTaskId- // and embeddingTaskId are `set null` on the asyncTasks side, so without this- // the task rows would dangle in the DB forever.- const taskIds = [file.chunkTaskId, file.embeddingTaskId].filter((taskId): taskId is string =>- Boolean(taskId),+ // 2. Delete mirror documents whose source is this file. Without this,+ // documents.fileId would be set null by FK and leave orphan rows behind+ // (still indexed by BM25, still occupying KB slots).+ await tx+ .delete(documents)+ .where(+ and(+ eq(documents.fileId, id),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),+ eq(documents.sourceType, 'file'),+ ),);- if (taskIds.length > 0) {- await tx.delete(asyncTasks).where(inArray(asyncTasks.id, taskIds));- }- // 4. Delete file record- await tx.delete(files).where(and(eq(files.id, id), this.ownership()));+ // 3. Delete the chunk/embedding asyncTasks tied to this file. files.chunkTaskId+ // and embeddingTaskId are `set null` on the asyncTasks side, so without this+ // the task rows would dangle in the DB forever.+ const taskIds = [file.chunkTaskId, file.embeddingTaskId].filter((taskId): taskId is string =>+ Boolean(taskId),+ );+ if (taskIds.length > 0) {+ await tx.delete(asyncTasks).where(inArray(asyncTasks.id, taskIds));+ }- if (!fileHash) return options?.exclusiveStorage ? file : undefined;+ // 4. Delete file record+ await tx.delete(files).where(and(eq(files.id, id), this.ownership()));- const result = await tx- .select({ count: count() })- .from(files)- .where(eq(files.fileHash, fileHash));+ if (!fileHash) {+ return removeGlobalFile && getAgentShareFileProvenance(file.metadata) ? file : undefined;+ }- const fileCount = result[0].count;+ const result = await tx+ .select({ count: count() })+ .from(files)+ .where(eq(files.fileHash, fileHash));- // delete the file from global file if it is not used by other files- // if `DISABLE_REMOVE_GLOBAL_FILE` is true, we will not remove the global file- if (fileCount === 0 && removeGlobalFile) {- await tx.delete(globalFiles).where(eq(globalFiles.hashId, fileHash));+ const fileCount = result[0].count;- return file;- }+ // delete the file from global file if it is not used by other files+ // if `DISABLE_REMOVE_GLOBAL_FILE` is true, we will not remove the global file+ if (fileCount === 0 && removeGlobalFile) {+ await tx.delete(globalFiles).where(eq(globalFiles.hashId, fileHash));- return options?.exclusiveStorage ? file : undefined;- };+ return file;+ }++ return undefined;+ };++ /** Delete a file row within the caller's access scope. */+ delete = async (+ id: string,+ options: {+ accessScope?: FileAccessScope;+ removeGlobalFile?: boolean;+ transaction?: Transaction;+ } = {},+ ) => {+ const { accessScope = ordinaryFileAccessScope, removeGlobalFile = true, transaction } = options;+ const executeInTransaction = (tx: Transaction) =>+ this.deleteInTransaction(id, removeGlobalFile, tx, accessScope);- return await (trx ? executeInTransaction(trx) : this.db.transaction(executeInTransaction));+ return transaction+ ? executeInTransaction(transaction)+ : this.db.transaction(executeInTransaction);};/**@@ -246,20 +262,25 @@ export class FileModel {* Locking the file row serializes this cleanup with foreign-key inserts, so a late send either* wins ownership and preserves the file or observes the deletion and fails atomically.*- * Resolves to the row only when its stored object should be deleted too β- * see {@link delete} for the `exclusiveStorage` rule; `undefined` covers both- * "still referenced, kept" and "deleted, object still shared".+ * Resolves to the row only when its stored object should be deleted too;+ * `undefined` covers both "still referenced, kept" and "deleted, object still shared".*/deleteUnreferenced = async (id: string,- removeGlobalFile: boolean = true,- options?: { exclusiveStorage?: boolean },+ options: { accessScope?: FileAccessScope; removeGlobalFile?: boolean } = {},) => {+ const { accessScope = ordinaryFileAccessScope, removeGlobalFile = true } = options;return this.db.transaction(async (trx) => {const [file] = await trx.select({ id: files.id }).from(files)- .where(and(eq(files.id, id), this.ownership()))+ .where(+ and(+ eq(files.id, id),+ this.ownership(),+ fileMatchesAccessScope(files.metadata, accessScope),+ ),+ ).limit(1).for('update');if (!file) return;@@ -278,7 +299,7 @@ export class FileModel {.limit(1);if (sessionReference) return;- return this.delete(id, removeGlobalFile, trx, options);+ return this.deleteInTransaction(id, removeGlobalFile, trx, accessScope);});};@@ -299,8 +320,8 @@ export class FileModel {};/**- * Bytes occupied by one agent share's visitor uploads: this user's- * `agent_share` rows whose provenance names `shareId`. Backs the share's+ * Bytes occupied by one agent share's visitor uploads: this user's rows+ * whose provenance names `shareId`. Backs the share's* `maxFileStorage` cap (`shareChat.createUploadUrl`), so it accepts the* reservation transaction to be counted inside it.*/@@ -310,11 +331,7 @@ export class FileModel {.select({ totalSize: sum(files.size) }).from(files).where(- and(- this.ownership(),- eq(files.source, FileSource.AgentShare),- sql`${files.metadata} -> 'agentShare' ->> 'shareId' = ${shareId}`,- ),+ and(this.ownership(), sql`${files.metadata} -> 'agentShare' ->> 'shareId' = ${shareId}`),);return Number(row?.totalSize ?? 0);@@ -333,6 +350,7 @@ export class FileModel {where: and(inArray(files.id, ids),this.ownership(),+ notAgentShareFile(files.metadata),// Workspace bulk deletes from non-owner members only touch their own rows.options?.restrictToCreator ? eq(files.userId, this.userId) : undefined,),@@ -429,10 +447,7 @@ export class FileModel {q ? ilike(files.name, `%${q}%`) : undefined,this.ownership(callerAgentVisibility),visibility ? eq(files.visibility, visibility) : undefined,- // Artifacts owned by another surface (acceptance evidence) stay reachable- // by id, but never appear in a listing. Applied here rather than in- // `ownership()` so single-row reads and deletes still resolve them.- or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ libraryVisibleFile(files.source, files.metadata),);if (category && category !== FilesTabs.All && category !== FilesTabs.Home) {const categoryFilter = buildFileCategoryFilter(files.fileType, category as FilesTabs);@@ -537,16 +552,28 @@ export class FileModel {}));};- findByIds = async (ids: string[]) => {+ findByIds = async (ids: string[], accessScope: FileAccessScope = ordinaryFileAccessScope) => {return this.db.query.files.findMany({- where: and(inArray(files.id, ids), this.ownership()),+ where: and(+ inArray(files.id, ids),+ this.ownership(),+ fileMatchesAccessScope(files.metadata, accessScope),+ ),});};- findById = async (id: string, trx?: Transaction) => {- const database = trx || this.db;+ findById = async (+ id: string,+ options: { accessScope?: FileAccessScope; transaction?: Transaction } = {},+ ) => {+ const { accessScope = ordinaryFileAccessScope, transaction } = options;+ const database = transaction || this.db;return database.query.files.findFirst({- where: and(eq(files.id, id), this.ownership()),+ where: and(+ eq(files.id, id),+ this.ownership(),+ fileMatchesAccessScope(files.metadata, accessScope),+ ),});};diff --git a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.tsindex 186ed3fb8e5..6b461eabe6f 100644--- a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts+++ b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts@@ -1354,7 +1354,7 @@ describe('ElasticsearchFtsSearchBackend', () => {);});- it('searches files by name and rechecks hidden sources and restricted KB memberships in PG', async () => {+ it('searches files by name and rechecks non-library files and restricted KB memberships in PG', async () => {const longFileDescription = `Hydrated file description ${'x'.repeat(220)}`;await db.insert(knowledgeBases).values([{@@ -1401,6 +1401,16 @@ describe('ElasticsearchFtsSearchBackend', () => {userId,workspaceId,},+ {+ fileType: 'text/plain',+ id: 'file-agent-share',+ metadata: { agentShare: { shareId: 'share-1', visitorUserId: 'visitor-1' } },+ name: 'Search phrase visitor attachment',+ size: 30,+ url: 'file://file-agent-share',+ userId,+ workspaceId,+ },{fileType: 'custom/document',id: 'file-page-shell',@@ -1446,6 +1456,7 @@ describe('ElasticsearchFtsSearchBackend', () => {const client = createClient([{ _id: 'file-restricted', _score: 12 },{ _id: 'file-hidden-source', _score: 11 },+ { _id: 'file-agent-share', _score: 10.5 },{ _id: 'file-page-shell', _score: 10 },{ _id: 'file-private-other', _score: 9 },{ _id: 'file-deleted', _score: 8 },@@ -1714,6 +1725,41 @@ describe('ElasticsearchFtsSearchBackend', () => {);});+ it('does not hydrate a page derived from an agent-share file', async () => {+ await db.insert(files).values({+ fileType: 'application/pdf',+ id: 'page-agent-share-file',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.pdf',+ size: 100,+ url: 'file://page-agent-share-file',+ userId,+ workspaceId,+ });+ await db.insert(documents).values({+ content: 'Search phrase private visitor page',+ fileId: 'page-agent-share-file',+ fileType: 'custom/document',+ filename: 'visitor',+ id: 'page-agent-share-document',+ source: 'file://page-agent-share-file',+ sourceType: 'file',+ title: 'Visitor document',+ totalCharCount: 34,+ totalLineCount: 1,+ userId,+ workspaceId,+ });+ const client = createClient([{ _id: 'page-agent-share-document', _score: 10 }]);+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });++ const response = await backend.search(+ request('documents', { filters: { documentKind: 'page' } }),+ );++ expect(response.items).toEqual([]);+ });+it('hydrates inline and file-backed KB documents without truncating candidates by document size', async () => {const largeContent = `search phrase ${'x'.repeat(1_000_000)}`;await db.insert(knowledgeBases).values([@@ -1867,6 +1913,59 @@ describe('ElasticsearchFtsSearchBackend', () => {);});+ it('does not hydrate a knowledge-base document derived from an agent-share file', async () => {+ await db.insert(knowledgeBases).values({+ id: 'agent-share-document-kb',+ name: 'Agent share document KB',+ userId,+ visibility: 'public',+ workspaceId,+ });+ await db.insert(files).values({+ fileType: 'application/pdf',+ id: 'agent-share-document-file',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.pdf',+ size: 100,+ url: 'file://agent-share-document-file',+ userId,+ workspaceId,+ });+ await db.insert(knowledgeBaseFiles).values({+ fileId: 'agent-share-document-file',+ knowledgeBaseId: 'agent-share-document-kb',+ userId,+ workspaceId,+ });+ await db.insert(documents).values({+ content: 'Search phrase private visitor document',+ fileId: 'agent-share-document-file',+ fileType: 'application/pdf',+ filename: 'visitor.pdf',+ id: 'agent-share-document-row',+ source: 'file://agent-share-document-file',+ sourceType: 'file',+ title: 'Visitor document',+ totalCharCount: 38,+ totalLineCount: 1,+ userId,+ workspaceId,+ });+ const client = createClient([{ _id: 'agent-share-document-row', _score: 10 }]);+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });++ const response = await backend.search(+ request('documents', {+ filters: {+ documentKind: 'knowledgeBaseDocument',+ knowledgeBaseIds: ['agent-share-document-kb'],+ },+ }),+ );++ expect(response.items).toEqual([]);+ });+it('searches knowledge bases and rechecks visibility and restricted IDs in PG', async () => {await db.insert(knowledgeBases).values([{diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.tsindex d5b40e89365..d9987e6ae25 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts@@ -1,4 +1,3 @@-import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';import {and,eq,@@ -27,6 +26,7 @@ import {userMemories,} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';+import { libraryVisibleFile, notAgentShareFileReference } from '../../../utils/fileVisibility';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';import { searchableMessage } from '../../../utils/searchableMessage';import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';@@ -477,7 +477,7 @@ export const hydrateFiles = async (),buildWorkspaceWhere(scope, files),ne(files.fileType, 'custom/document'),- or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ libraryVisibleFile(files.source, files.metadata),),);const fileIds = rows.map(({ id }) => id);@@ -612,6 +612,7 @@ export const hydratePages = async (),buildWorkspaceWhere(scope, documents),eq(documents.fileType, 'custom/document'),+ notAgentShareFileReference(db, documents.fileId),),);const knowledgeBaseIdsByFile = await getKnowledgeBaseIdsByFile(@@ -667,6 +668,7 @@ export const hydrateKnowledgeBaseDocuments = async (),buildWorkspaceWhere(scope, documents),ne(documents.fileType, DOCUMENT_FOLDER_TYPE),+ notAgentShareFileReference(db, documents.fileId),),);const knowledgeBaseIdsByFile = await getKnowledgeBaseIdsByFile(@@ -698,7 +700,11 @@ export const hydrateKnowledgeBaseDocuments = async (}).from(documents).where(- and(inArray(documents.id, selectedDocumentIds), buildWorkspaceWhere(scope, documents)),+ and(+ inArray(documents.id, selectedDocumentIds),+ buildWorkspaceWhere(scope, documents),+ notAgentShareFileReference(db, documents.fileId),+ ),);const contentById = new Map(contentRows.map(({ content, id }) => [id, content] as const));diff --git a/packages/database/src/repositories/ftsSearch/index.test.ts b/packages/database/src/repositories/ftsSearch/index.test.tsindex 122147609b1..0405b5d114c 100644--- a/packages/database/src/repositories/ftsSearch/index.test.ts+++ b/packages/database/src/repositories/ftsSearch/index.test.ts@@ -419,6 +419,23 @@ describe.skipIf(!isServerDB)('FtsSearchRepo', () => {url: 'file://test-file.txt',userId,});++ await serverDB.insert(files).values({+ fileType: 'text/plain',+ metadata: { agentShare: { shareId: 'share-1', visitorUserId: 'visitor-1' } },+ name: 'visitor-secret-file.txt',+ size: 100,+ url: 'file://visitor-secret-file.txt',+ userId,+ });++ await serverDB.insert(files).values({+ fileType: 'text/plain',+ name: 'visitor-secret-library-file.txt',+ size: 100,+ url: 'file://visitor-secret-library-file.txt',+ userId,+ });});it('should filter by agent type', async () => {@@ -447,6 +464,12 @@ describe.skipIf(!isServerDB)('FtsSearchRepo', () => {expect(result.type).toBe('file');});});++ it('should exclude files carrying agent-share provenance', async () => {+ const results = await ftsSearchRepo.search({ query: 'visitor secret', type: 'file' });++ expect(results.map(({ title }) => title)).toEqual(['visitor-secret-library-file.txt']);+ });});describe('search - limit per type', () => {@@ -941,6 +964,35 @@ describe.skipIf(!isServerDB)('FtsSearchRepo', () => {expect(results[0].type).toBe('page');});+ it('should not find a page derived from an agent-share file', async () => {+ await serverDB.insert(files).values({+ fileType: 'application/pdf',+ id: 'page-agent-share-file',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.pdf',+ size: 100,+ url: 'file://page-agent-share-file',+ userId,+ });+ await serverDB.insert(documents).values({+ content: 'private visitor quantum phrase',+ fileId: 'page-agent-share-file',+ fileType: 'custom/document',+ filename: 'visitor',+ id: 'page-agent-share-document',+ source: 'file://page-agent-share-file',+ sourceType: 'file',+ title: 'Visitor document',+ totalCharCount: 30,+ totalLineCount: 1,+ userId,+ });++ const results = await ftsSearchRepo.search({ query: 'visitor quantum', type: 'page' });++ expect(results).toEqual([]);+ });+it('should return correct page structure', async () => {const results = await ftsSearchRepo.search({ query: 'notes', type: 'page' });@@ -1242,6 +1294,40 @@ describe.skipIf(!isServerDB)('FtsSearchRepo', () => {]);expect(results).toEqual([]);});++ it('does not surface a document derived from an agent-share file', async () => {+ await serverDB.insert(files).values({+ fileType: 'application/pdf',+ id: 'kb-agent-share-file',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.pdf',+ size: 100,+ url: 'file://kb-agent-share-file',+ userId,+ });+ await serverDB.insert(knowledgeBaseFiles).values({+ fileId: 'kb-agent-share-file',+ knowledgeBaseId: kbA,+ userId,+ });+ await serverDB.insert(documents).values({+ content: 'private visitor nebula phrase',+ fileId: 'kb-agent-share-file',+ fileType: 'application/pdf',+ filename: 'visitor.pdf',+ id: 'kb-agent-share-document',+ source: 'file://kb-agent-share-file',+ sourceType: 'file',+ title: 'Visitor PDF',+ totalCharCount: 29,+ totalLineCount: 1,+ userId,+ });++ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('visitor nebula', [kbA]);++ expect(results).toEqual([]);+ });});});diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts b/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.tsindex cad07711a4f..51384a8574a 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts+++ b/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts@@ -1,5 +1,4 @@-import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';-import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';import {agents,@@ -12,6 +11,10 @@ import {topics,} from '../../../schemas';import { sanitizeBm25Query } from '../../../utils/bm25';+import {+ libraryVisibleFileSource,+ notAgentShareFileReference,+} from '../../../utils/fileVisibility';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';import { searchableMessageText } from '../../../utils/searchableMessage';import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';@@ -348,8 +351,8 @@ export async function searchFiles(and(context.scanScopeWhere(files),ne(files.fileType, 'custom/document'),- // Hidden acceptance evidence must stay out of library search too.- or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ // Keep non-library files out of command-menu search.+ libraryVisibleFileSource(files.source),sql`${files.name} @@@ ${bm25Query}`,),)@@ -376,6 +379,8 @@ export async function searchFiles(.where(and(context.liftedScopeWhere(hits.workspaceId),+ // ParadeDB only supports indexed predicates inside its BM25 scan.+ notAgentShareFileReference(db, hits.id),// A file linked to any restricted KB is fully hidden. The subquery// avoids leaking it through a different joined membership row.excludeKbIds && excludeKbIds.length > 0diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts b/packages/database/src/repositories/ftsSearch/pgSearch/documents.tsindex 58d0e1c05d9..589d85168b9 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts+++ b/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts@@ -2,6 +2,7 @@ import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzleimport { DOCUMENT_FOLDER_TYPE, documents, knowledgeBaseFiles } from '../../../schemas';import { sanitizeBm25Query } from '../../../utils/bm25';+import { notAgentShareFileReference } from '../../../utils/fileVisibility';import { buildWorkspaceWhere } from '../../../utils/workspace';import type {FtsSearchBackendResponse,@@ -134,6 +135,7 @@ export async function searchPages(.where(and(context.liftedScopeWhere(hits.workspaceId),+ notAgentShareFileReference(db, hits.fileId),excludeKbIds && excludeKbIds.length > 0? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds)): undefined,@@ -210,6 +212,7 @@ export async function searchKnowledgeBaseDocuments(userClause,folderClause,inArray(documents.knowledgeBaseId, knowledgeBaseIds),+ notAgentShareFileReference(db, documents.fileId),matchClause,),)@@ -236,7 +239,9 @@ export async function searchKnowledgeBaseDocuments(inArray(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseIds),),)- .where(and(userClause, folderClause, matchClause))+ .where(+ and(userClause, folderClause, notAgentShareFileReference(db, documents.fileId), matchClause),+ ).orderBy(sql`paradedb.score(${documents.id}) DESC`).limit(limit);diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts b/packages/database/src/repositories/ftsSearchDocument/builder.test.tsindex 62e19d42ebe..f4c8576a90c 100644--- a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts+++ b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts@@ -338,6 +338,34 @@ describe('FtsSearchDocumentBuilder', () => {expect(result.map(({ id }) => id)).toEqual(['agent-1']);});+ it('omits files carrying agent-share provenance from the search projection', async () => {+ await db.insert(files).values({+ fileType: 'text/plain',+ id: 'file-agent-share',+ metadata: { agentShare: { shareId: 'share-1', visitorUserId: 'visitor-1' } },+ name: 'private visitor attachment.txt',+ size: 10,+ url: 'files/user/agent-share/share-1/private.txt',+ userId,+ });++ await expect(builder.buildByIds('files', ['file-agent-share'])).resolves.toEqual([]);++ await db.insert(documents).values({+ content: 'Private visitor attachment content',+ fileId: 'file-agent-share',+ fileType: 'text/plain',+ id: 'document-agent-share',+ source: 'files/user/agent-share/share-1/private.txt',+ sourceType: 'file',+ title: 'Private visitor attachment',+ totalCharCount: 34,+ totalLineCount: 1,+ userId,+ });+ await expect(builder.buildByIds('documents', ['document-agent-share'])).resolves.toEqual([]);+ });+it('rejects invalid batch limits before querying PostgreSQL', async () => {await expect(builder.buildBatch('agents', { limit: 0 })).rejects.toThrow('FTS search document batch limit must be a positive integer',diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.ts b/packages/database/src/repositories/ftsSearchDocument/builder.tsindex 6acd1f5c859..05f455058d6 100644--- a/packages/database/src/repositories/ftsSearchDocument/builder.ts+++ b/packages/database/src/repositories/ftsSearchDocument/builder.ts@@ -18,6 +18,7 @@ import {userPersonaDocuments,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { notAgentShareFile, notAgentShareFileReference } from '../../utils/fileVisibility';import { searchableMessage } from '../../utils/searchableMessage';import type {FtsSearchBuiltDocument,@@ -97,8 +98,8 @@ const dedupeKeys = (keys: FtsSearchDocumentKey[]) =>* Canonical PostgreSQL β search projection builder.** This repository is intentionally actor-agnostic: backfill, incremental sync, and reconciliation- * need the complete source-of-truth projection. Product reads must continue to use FtsSearchRepo,- * whose provider hydration reapplies authorization.+ * need the complete searchable projection. Files that are never library-searchable are omitted at+ * the projection boundary; product reads still use FtsSearchRepo, whose hydration reapplies access.*/export class FtsSearchDocumentBuilder {constructor(private db: LobeChatDatabase) {}@@ -371,11 +372,14 @@ export class FtsSearchDocumentBuilder {}).from(files).where(- selection.ids- ? inArray(files.id, selection.ids)- : selection.afterId- ? gt(files.id, selection.afterId)- : undefined,+ and(+ notAgentShareFile(files.metadata),+ selection.ids+ ? inArray(files.id, selection.ids)+ : selection.afterId+ ? gt(files.id, selection.afterId)+ : undefined,+ ),).orderBy(asc(files.id)).limit(selection.limit);@@ -929,16 +933,19 @@ export class FtsSearchDocumentBuilder {}).from(documents).where(- selection.ids- ? inArray(documents.id, selection.ids)- : and(- selection.afterId- ? gt(documents.id, selection.afterId)- : selection.fromId- ? gte(documents.id, selection.fromId)- : undefined,- selection.beforeId ? lt(documents.id, selection.beforeId) : undefined,- ),+ and(+ notAgentShareFileReference(this.db, documents.fileId),+ selection.ids+ ? inArray(documents.id, selection.ids)+ : and(+ selection.afterId+ ? gt(documents.id, selection.afterId)+ : selection.fromId+ ? gte(documents.id, selection.fromId)+ : undefined,+ selection.beforeId ? lt(documents.id, selection.beforeId) : undefined,+ ),+ ),).orderBy(asc(documents.id)).limit(selection.limit);diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.tsindex 78c8b7e15a2..2db500650c7 100644--- a/packages/database/src/repositories/knowledge/index.test.ts+++ b/packages/database/src/repositories/knowledge/index.test.ts@@ -1357,7 +1357,7 @@ describe('KnowledgeRepo', () => {});});- describe('acceptance evidence hiding', () => {+ describe('non-library file hiding', () => {beforeEach(async () => {await serverDB.insert(files).values([{@@ -1377,6 +1377,15 @@ describe('KnowledgeRepo', () => {url: 'evidence-url',userId,},+ {+ id: 'agent-share-file',+ fileType: 'text/plain',+ metadata: { agentShare: { shareId: 'share-a', visitorUserId: 'visitor-a' } },+ name: 'visitor.txt',+ size: 100,+ url: 'visitor-url',+ userId,+ },{id: 'generated-file',fileType: 'image/png',@@ -1396,12 +1405,14 @@ describe('KnowledgeRepo', () => {expect(ids).toContain('library-file');expect(ids).toContain('generated-file');expect(ids).not.toContain('evidence-file');+ expect(ids).not.toContain('agent-share-file');});it('should hide acceptance evidence from recent items', async () => {const result = await knowledgeRepo.queryRecent(50, 'file');expect(result.map((item) => item.fileId)).not.toContain('evidence-file');+ expect(result.map((item) => item.fileId)).not.toContain('agent-share-file');});it('should still resolve acceptance evidence by id', async () => {@@ -1409,6 +1420,10 @@ describe('KnowledgeRepo', () => {expect(result?.name).toBe('payload-execution.txt');});++ it('should not resolve an agent-share file through the ordinary resource API', async () => {+ await expect(knowledgeRepo.findById('agent-share-file', 'file')).resolves.toBeUndefined();+ });});describe('query - source filtering', () => {diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.tsindex 57fff9340f7..f4c2435ea55 100644--- a/packages/database/src/repositories/knowledge/index.ts+++ b/packages/database/src/repositories/knowledge/index.ts@@ -36,6 +36,7 @@ import { FileModel } from '../../models/file';import { DOCUMENT_FOLDER_TYPE, documents, files, knowledgeBaseFiles, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { buildDocumentCategoryFilter, buildFileCategoryFilter } from '../../utils/fileTypeCategory';+import { notAgentShareFile } from '../../utils/fileVisibility';import { buildWorkspaceWhere } from '../../utils/workspace';/**@@ -323,13 +324,10 @@ export class KnowledgeRepo {/*** Scope predicate every file listing shares: ownership plus the exclusion of- * sources that belong to another surface (acceptance evidence). Kept as one- * helper so a new listing can't accidentally pick up ownership alone and- * start leaking hundreds of verification artifacts back into the library.+ * acceptance evidence by source and visitor attachments by provenance.*- * `sourceFilter` is the only opt-out: asking for `acceptance` explicitly is a- * request for exactly the rows this predicate otherwise hides, so the- * exclusion is dropped and `fileSourceFilter` narrows to them instead.+ * Asking for `acceptance` opts out of only that source filter. Agent-share+ * provenance remains an access boundary for every ordinary resource read.*/private fileScope = (sourceFilter?: ResourceSourceFilter) =>and(@@ -337,6 +335,7 @@ export class KnowledgeRepo {sourceFilter === ResourceSourceFilter.Acceptance? undefined: or(isNull(f.source), notInArray(f.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ notAgentShareFile(f.metadata),);private documentScope = () => buildWorkspaceWhere(this.scope(), d);diff --git a/packages/database/src/utils/fileVisibility.ts b/packages/database/src/utils/fileVisibility.tsnew file mode 100644index 00000000000..ab0def7137d--- /dev/null+++ b/packages/database/src/utils/fileVisibility.ts@@ -0,0 +1,54 @@+import type { FileAccessScope } from '@lobechat/types';+import { LIBRARY_HIDDEN_FILE_SOURCES, ordinaryFileAccessScope } from '@lobechat/types';+import { and, eq, exists, isNull, notExists, notInArray, or, sql } from 'drizzle-orm';+import type { AnyPgColumn } from 'drizzle-orm/pg-core';++import { files } from '../schemas';+import type { LobeChatDatabase } from '../type';++/** Agent-share provenance is an access boundary, not a file origin. */+export const notAgentShareFile = (metadata: AnyPgColumn) =>+ sql<boolean>`NOT COALESCE(${metadata} ? 'agentShare', false)`;++/** Files whose source belongs in ordinary library surfaces. */+export const libraryVisibleFileSource = (source: AnyPgColumn) =>+ or(isNull(source), notInArray(source, LIBRARY_HIDDEN_FILE_SOURCES));++/** Files that belong in ordinary library, knowledge, and search surfaces. */+export const libraryVisibleFile = (source: AnyPgColumn, metadata: AnyPgColumn) =>+ and(libraryVisibleFileSource(source), notAgentShareFile(metadata));++/** Match a file row against the caller's explicit access scope. */+export const fileMatchesAccessScope = (metadata: AnyPgColumn, accessScope: FileAccessScope) =>+ accessScope.type === 'agentShare'+ ? and(+ sql`${metadata} -> 'agentShare' ->> 'shareId' = ${accessScope.shareId}`,+ sql`${metadata} -> 'agentShare' ->> 'visitorUserId' = ${accessScope.visitorUserId}`,+ )+ : notAgentShareFile(metadata);++/** Match a file-derived document against the caller's explicit access scope. */+export const fileReferenceMatchesAccessScope = (+ db: Pick<LobeChatDatabase, 'select'>,+ fileId: AnyPgColumn,+ accessScope: FileAccessScope,+) =>+ accessScope.type === 'agentShare'+ ? exists(+ db+ .select({ id: files.id })+ .from(files)+ .where(and(eq(files.id, fileId), fileMatchesAccessScope(files.metadata, accessScope))),+ )+ : notExists(+ db+ .select({ id: files.id })+ .from(files)+ .where(and(eq(files.id, fileId), sql`COALESCE(${files.metadata} ? 'agentShare', false)`)),+ );++/** Exclude a document derived from an agent-share attachment. */+export const notAgentShareFileReference = (+ db: Pick<LobeChatDatabase, 'select'>,+ fileId: AnyPgColumn,+) => fileReferenceMatchesAccessScope(db, fileId, ordinaryFileAccessScope);diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex ea0aec0b5c0..54260d909bd 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -21,13 +21,6 @@ export enum FileSource {* the user's library.*/Acceptance = 'acceptance',- /**- * Attachment a share VISITOR uploaded to a shared agent's conversation.- * Stored under the CREATOR (their storage quota, like every other share- * artifact) but authored by the visitor β `metadata.agentShare` records- * which share and visitor. Never a library resource of the creator.- */- AgentShare = 'agent_share',ImageGeneration = 'image_generation',PageEditor = 'page-editor',VideoGeneration = 'video_generation',@@ -42,17 +35,8 @@ export enum FileSource {** The one way back in is an explicit `ResourceSourceFilter.Acceptance` request:* the user asked for evidence, so burying it no longer applies.- *- * `AgentShare` files are hidden for a different reason: they sit under the- * creator's account only so the creator's storage quota pays for them, but- * they are a VISITOR's conversation attachments β surfacing them in the- * creator's library would expose visitor content the creator otherwise never- * sees (share conversations are hidden from the creator by default).*/-export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [- FileSource.Acceptance,- FileSource.AgentShare,-];+export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [FileSource.Acceptance];/** Sources a generation model wrote, as opposed to anything a human put there. */export const AI_GENERATED_FILE_SOURCES: FileSource[] = [diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.tsindex fbfe297a31b..29be1b0ec81 100644--- a/packages/types/src/files/upload.ts+++ b/packages/types/src/files/upload.ts@@ -96,14 +96,54 @@ export interface UploadFileItem {visibility?: 'private' | 'public';}+export const AgentShareFileProvenanceSchema = z.object({+ shareId: z.string(),+ visitorUserId: z.string(),+});++export type AgentShareFileProvenance = z.infer<typeof AgentShareFileProvenanceSchema>;++export type FileAccessScope =+ ({ type: 'agentShare' } & AgentShareFileProvenance) | { type: 'ordinary' };++export const ordinaryFileAccessScope = { type: 'ordinary' } as const satisfies FileAccessScope;++export const agentShareFileAccessScope = (+ provenance: AgentShareFileProvenance,+): FileAccessScope => ({+ shareId: provenance.shareId,+ type: 'agentShare',+ visitorUserId: provenance.visitorUserId,+});++/** Remove server-owned Agent Share provenance from caller-supplied metadata. */+export const stripAgentShareFileProvenance = <T>(metadata: T): T => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return metadata;++ return Object.fromEntries(+ Object.entries(metadata as Record<string, unknown>).filter(([key]) => key !== 'agentShare'),+ ) as T;+};++/** Read server-written agent-share provenance without trusting the rest of the JSON metadata. */+export const getAgentShareFileProvenance = (+ metadata: unknown,+): AgentShareFileProvenance | undefined => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return undefined;++ const result = AgentShareFileProvenanceSchema.safeParse(+ (metadata as { agentShare?: unknown }).agentShare,+ );+ return result.success ? result.data : undefined;+};+export const FileMetadataSchema = z.object({/**- * Provenance of a `FileSource.AgentShare` upload: the file row sits under- * the CREATOR (storage quota), this records which share and which visitor- * actually uploaded it. Server-written only; the share endpoints check it- * before letting a visitor attach or remove the file.+ * Provenance of an agent-share visitor upload. The file row sits under the+ * creator for storage accounting, while this records the share and visitor+ * that may access it. Server-written only.*/- agentShare: z.object({ shareId: z.string(), visitorUserId: z.string() }).optional(),+ agentShare: AgentShareFileProvenanceSchema.optional(),date: z.string(),dirname: z.string(),filename: z.string(),