π€― 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(file): share attachments sent in a public agent's conversation (#21958)
Lobehub Codera64d5c9f843f
diff --git a/apps/server/src/routers/lambda/file/procedures.ts b/apps/server/src/routers/lambda/file/procedures.tsindex dd737c1d359..ae883ab4cc9 100644--- a/apps/server/src/routers/lambda/file/procedures.ts+++ b/apps/server/src/routers/lambda/file/procedures.ts@@ -1,6 +1,7 @@import { TRPCError } from '@trpc/server';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { AgentModel } from '@/database/models/agent';import { AsyncTaskModel } from '@/database/models/asyncTask';import { ChunkModel } from '@/database/models/chunk';import { DocumentModel } from '@/database/models/document';@@ -23,6 +24,7 @@ export const fileProcedure = wsCompatProcedure.use(serverDatabase).use(async (opreturn opts.next({ctx: {+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId, wsId),chunkModel: new ChunkModel(ctx.serverDB, ctx.userId, wsId),documentModel: new DocumentModel(ctx.serverDB, ctx.userId, wsId),diff --git a/apps/server/src/routers/lambda/file/upload.conversationAttachment.test.ts b/apps/server/src/routers/lambda/file/upload.conversationAttachment.test.tsnew file mode 100644index 00000000000..fefa7adcf5b--- /dev/null+++ b/apps/server/src/routers/lambda/file/upload.conversationAttachment.test.ts@@ -0,0 +1,136 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { FileSource, LIBRARY_HIDDEN_FILE_SOURCES } from '@/types/files';++import { uploadRouter } from './upload';++const mocks = vi.hoisted(() => {+ const transaction = {};+ return {+ checkHash: vi.fn(),+ create: vi.fn(),+ getAgentVisibility: vi.fn(),+ serverDB: {+ transaction: vi.fn(async (callback: (trx: unknown) => unknown) => callback(transaction)),+ },+ transaction,+ };+});++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => mocks.serverDB) }));+vi.mock('@/business/server/lambda-routers/file', () => ({+ businessFileUploadCheck: vi.fn(),+}));+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(function () {+ return { getAgentVisibility: mocks.getAgentVisibility };+ }),+}));+vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: vi.fn() }));+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));+vi.mock('@/database/repositories/knowledge', () => ({ KnowledgeRepo: vi.fn() }));+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(function () {+ return { checkHash: mocks.checkHash, create: mocks.create };+ }),+}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {+ getFileAccessUrl: vi.fn(async ({ id }: { id: string }) => `https://lobehub.com/f/${id}`),+ getFileMetadata: vi.fn().mockResolvedValue({ contentLength: 100 }),+ };+ }),+}));+vi.mock('@/server/services/fileUpload', () => ({+ FileUploadService: vi.fn(function () {+ return {+ findLatest: vi.fn().mockResolvedValue(undefined),+ hasAnyLiveSession: vi.fn().mockResolvedValue(false),+ };+ }),+}));++const upload = {+ conversationAgentId: 'agent-1',+ fileType: 'application/pdf',+ hash: 'attachment-hash',+ metadata: {},+ name: 'notes.pdf',+ size: 100,+ url: 'files/notes.pdf',+};++const workspaceCaller = (extra: Record<string, unknown> = {}) =>+ uploadRouter.createCaller({ userId: 'uploader', workspaceId: 'workspace-1', ...extra } as any);++const expectCreated = (expected: Record<string, unknown>) =>+ expect(mocks.create).toHaveBeenCalledWith(+ expect.objectContaining(expected),+ true,+ mocks.transaction,+ );++describe('uploadRouter.createFile for a conversation attachment', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.checkHash.mockResolvedValue({ isExist: false });+ mocks.create.mockResolvedValue({ id: 'attachment' });+ });++ it('shares the attachment with readers of a public agent, outside the library', async () => {+ // Regression: the upload defaulted to private while every member could read+ // the conversation, so the card tombstoned for everyone but the uploader.+ mocks.getAgentVisibility.mockResolvedValue('public');++ await workspaceCaller().createFile(upload);++ expect(mocks.getAgentVisibility).toHaveBeenCalledWith('agent-1');+ expectCreated({ source: FileSource.ChatAttachment, visibility: 'public' });+ expect(LIBRARY_HIDDEN_FILE_SOURCES).toContain(FileSource.ChatAttachment);+ });++ it.each([['private'], [null]])('stays private for an agent resolving to %s', async (agent) => {+ mocks.getAgentVisibility.mockResolvedValue(agent);++ await workspaceCaller().createFile(upload);++ expectCreated({ source: undefined, visibility: 'private' });+ });++ it.each([+ ['an explicit private request', { visibility: 'private' as const }, undefined],+ ['its own source', { source: FileSource.PageEditor }, FileSource.PageEditor],+ ])('keeps %s private in a public agent', async (_label, extra, source) => {+ mocks.getAgentVisibility.mockResolvedValue('public');++ await workspaceCaller().createFile({ ...upload, ...extra });++ expectCreated({ source, visibility: 'private' });+ });++ it('never lets a run operation token publish an attachment', async () => {+ mocks.getAgentVisibility.mockResolvedValue('public');++ await workspaceCaller({+ heteroOperationCapabilities: ['acceptance:evidence'],+ heteroOperationScope: 'op_task_run',+ }).createFile(upload);++ expectCreated({ source: FileSource.Acceptance, visibility: 'private' });+ });++ it('leaves personal mode untouched', async () => {+ mocks.getAgentVisibility.mockResolvedValue('public');++ await uploadRouter.createCaller({ userId: 'uploader' } as any).createFile(upload);++ expect(mocks.getAgentVisibility).not.toHaveBeenCalled();+ expect(mocks.create.mock.lastCall?.[0]).toMatchObject({ source: undefined });+ expect(mocks.create.mock.lastCall?.[0]).not.toHaveProperty('visibility');+ });+});diff --git a/apps/server/src/routers/lambda/file/upload.ts b/apps/server/src/routers/lambda/file/upload.tsindex 544c34e7575..44c0ae52dd3 100644--- a/apps/server/src/routers/lambda/file/upload.ts+++ b/apps/server/src/routers/lambda/file/upload.ts@@ -96,6 +96,8 @@ export const uploadRouter = router({.use(withScopedPermission('file:upload')).input(UploadFileSchema.omit({ url: true }).extend({+ /** Agent whose conversation this upload is attached to. */+ conversationAgentId: z.string().optional(),parentId: z.string().optional(),url: z.string(),visibility: z.enum(['private', 'public']).optional(),@@ -131,6 +133,21 @@ export const uploadRouter = router({knowledgeBaseVisibility = knowledgeBase.visibility;}+ // Every member can read a public agent's conversation, so an attachment+ // defaulted to the uploader's private space would tombstone for them. The+ // agent is resolved here, never trusted from the client's cached state.+ const isPublicAgentAttachment =+ !!ctx.workspaceId &&+ !!input.conversationAgentId &&+ !input.knowledgeBaseId &&+ !input.source &&+ !input.visibility &&+ !parentDocument &&+ (await ctx.agentModel.getAgentVisibility(input.conversationAgentId)) === 'public';+ const fileSource = isPublicAgentAttachment+ ? FileSource.ChatAttachment+ : toFileSource(input.source);+// Visibility precedence (workspace mode only β personal mode ignores the// column entirely):// 1. A library upload always uses the knowledge base visibility.@@ -139,13 +156,18 @@ export const uploadRouter = router({// uploaded inside a private folder stays private.// 4. Agent-document uploads default to 'public' to match their document's// access contract; their source keeps them out of resource listings.- // 5. Otherwise default top-level uploads to 'private' so new content+ // 5. Attachments in a public agent's conversation default to 'public';+ // their source keeps them out of resource listings. Flipping one back+ // to private or deleting it still tombstones the card.+ // 6. Otherwise default top-level uploads to 'private' so new content// starts in the creator's private space (mirrors the Pages spec).const resolvedVisibility: 'private' | 'public' | undefined = ctx.workspaceId? (knowledgeBaseVisibility ??input.visibility ??parentVisibility ??- (input.source === FileSource.AgentDocument ? 'public' : 'private'))+ (input.source === FileSource.AgentDocument || isPublicAgentAttachment+ ? 'public'+ : 'private')): undefined;if (latestUpload?.status === 'settled') {@@ -162,7 +184,7 @@ export const uploadRouter = router({settledFile.name === input.name &&settledFile.parentId === (resolvedParentId ?? null) &&settledFile.size === input.size &&- (settledFile.source ?? undefined) === toFileSource(input.source) &&+ (settledFile.source ?? undefined) === fileSource &&settledFile.url === input.url &&(!ctx.workspaceId || settledFile.visibility === resolvedVisibility) &&isEqual(settledFile.metadata, metadata ?? null);@@ -268,7 +290,7 @@ export const uploadRouter = router({// wire type is a loose string for older clients, so unknown values// are dropped rather than persisted β `source` drives the resource// library's origin filter and its hidden-source exclusion.- source: toFileSource(input.source),+ source: fileSource,url: input.url,...(resolvedVisibility ? { visibility: resolvedVisibility } : {}),},diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex 48dd2e28dca..936a0731c4a 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -52,6 +52,7 @@ import {fileMatchesAccessScope,libraryVisibleFile,notAgentShareFile,+ ownChatAttachment,} from '../utils/fileVisibility';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';@@ -508,7 +509,13 @@ export class FileModel {q ? ilike(files.name, `%${q}%`) : undefined,this.ownership(callerAgentVisibility),visibility ? eq(files.visibility, visibility) : undefined,- libraryVisibleFile(files.source, files.metadata),+ or(+ libraryVisibleFile(files.source, files.metadata),+ and(+ ownChatAttachment(files.source, files.userId, this.userId),+ notAgentShareFile(files.metadata),+ ),+ ),);if (category && category !== FilesTabs.All && category !== FilesTabs.Home) {const categoryFilter = buildFileCategoryFilter(files.fileType, category as FilesTabs);diff --git a/packages/database/src/repositories/knowledge/__tests__/chatAttachmentLibrary.test.ts b/packages/database/src/repositories/knowledge/__tests__/chatAttachmentLibrary.test.tsnew file mode 100644index 00000000000..2fdeaa0e9f5--- /dev/null+++ b/packages/database/src/repositories/knowledge/__tests__/chatAttachmentLibrary.test.ts@@ -0,0 +1,56 @@+// @vitest-environment node+import { FileSource } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { FileModel } from '../../../models/file';+import { files, users } from '../../../schemas';+import { workspaces } from '../../../schemas/workspace';+import type { LobeChatDatabase } from '../../../type';+import { KnowledgeRepo } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();++const uploaderId = 'chat-attachment-uploader';+const memberId = 'chat-attachment-member';+const workspaceId = 'chat-attachment-workspace';+const name = 'shared-notes.pdf';++describe('conversation attachments in the library', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: uploaderId }, { id: memberId }]);+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Chat Attachment Workspace',+ primaryOwnerId: uploaderId,+ slug: workspaceId,+ });+ await serverDB.insert(files).values({+ fileType: 'application/pdf',+ name,+ size: 1024,+ source: FileSource.ChatAttachment,+ url: 'shared-notes-url',+ userId: uploaderId,+ visibility: 'public',+ workspaceId,+ });+ });++ it('lists an attachment for its uploader so they can unshare it', async () => {+ const items = await new KnowledgeRepo(serverDB, uploaderId, workspaceId).query();+ const rows = await new FileModel(serverDB, uploaderId, workspaceId).query();++ expect(items.map((item) => item.name)).toContain(name);+ expect(rows.map((row) => row.name)).toContain(name);+ });++ it('keeps it out of every other member library', async () => {+ const items = await new KnowledgeRepo(serverDB, memberId, workspaceId).query();+ const rows = await new FileModel(serverDB, memberId, workspaceId).query();++ expect(items.map((item) => item.name)).not.toContain(name);+ expect(rows.map((row) => row.name)).not.toContain(name);+ });+});diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.tsindex 6afed8ab622..6f41293546f 100644--- a/packages/database/src/repositories/knowledge/index.ts+++ b/packages/database/src/repositories/knowledge/index.ts@@ -38,7 +38,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 { notAgentShareFile, ownChatAttachment } from '../../utils/fileVisibility';import { buildWorkspaceWhere } from '../../utils/workspace';/**@@ -358,7 +358,11 @@ export class KnowledgeRepo {buildWorkspaceWhere(this.scope(), f),sourceFilter === ResourceSourceFilter.Acceptance? undefined- : or(isNull(f.source), notInArray(f.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ : or(+ isNull(f.source),+ notInArray(f.source, LIBRARY_HIDDEN_FILE_SOURCES),+ ownChatAttachment(f.source, f.userId, this.userId),+ ),notAgentShareFile(f.metadata),);@@ -824,6 +828,7 @@ export class KnowledgeRepo {return or(isNull(f.source),notInArray(f.source, [...AI_GENERATED_FILE_SOURCES, ...LIBRARY_HIDDEN_FILE_SOURCES]),+ ownChatAttachment(f.source, f.userId, this.userId),);}default: {diff --git a/packages/database/src/utils/fileVisibility.ts b/packages/database/src/utils/fileVisibility.tsindex ab0def7137d..9a52ea736d9 100644--- a/packages/database/src/utils/fileVisibility.ts+++ b/packages/database/src/utils/fileVisibility.ts@@ -1,5 +1,5 @@import type { FileAccessScope } from '@lobechat/types';-import { LIBRARY_HIDDEN_FILE_SOURCES, ordinaryFileAccessScope } from '@lobechat/types';+import { FileSource, 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';@@ -14,6 +14,13 @@ export const notAgentShareFile = (metadata: AnyPgColumn) =>export const libraryVisibleFileSource = (source: AnyPgColumn) =>or(isNull(source), notInArray(source, LIBRARY_HIDDEN_FILE_SOURCES));+/**+ * An uploader keeps their own conversation attachments in the library, the only+ * place they can unshare or delete one; other members never list them.+ */+export const ownChatAttachment = (source: AnyPgColumn, fileUserId: AnyPgColumn, userId: string) =>+ and(eq(source, FileSource.ChatAttachment), eq(fileUserId, userId));+/** Files that belong in ordinary library, knowledge, and search surfaces. */export const libraryVisibleFile = (source: AnyPgColumn, metadata: AnyPgColumn) =>and(libraryVisibleFileSource(source), notAgentShareFile(metadata));diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex 3e328dfe042..2c0a98f19f3 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -24,6 +24,8 @@ export enum FileSource {/** Original upload owned by an agent's document tree rather than the resource library. */AgentDocument = 'agent-document',Canvas = 'canvas',+ /** Attachment sent in a public agent's conversation; shared with the conversation, not the library. */+ ChatAttachment = 'chat-attachment',ImageGeneration = 'image_generation',PageEditor = 'page-editor',/**@@ -52,6 +54,7 @@ export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [FileSource.AgentDocument,FileSource.Canvas,FileSource.ToolResult,+ FileSource.ChatAttachment,];/** Sources a generation model wrote, as opposed to anything a human put there. */diff --git a/src/services/file/index.ts b/src/services/file/index.tsindex 7e69f6cfa67..147cbca2ca7 100644--- a/src/services/file/index.ts+++ b/src/services/file/index.ts@@ -12,6 +12,7 @@ import {} from '@/types/files';interface CreateFileParams extends Omit<UploadFileParams, 'url'> {+ conversationAgentId?: string;knowledgeBaseId?: string;parentId?: string;url: string;@@ -23,6 +24,8 @@ export class FileService {createFile = async (params: UploadFileParams & {+ /** Agent whose conversation this upload is attached to; the server resolves its visibility. */+ conversationAgentId?: string;parentId?: string;/*** Workspace visibility for the new file. `undefined` lets the serverdiff --git a/src/store/chat/slices/voiceMessage/action.ts b/src/store/chat/slices/voiceMessage/action.tsindex db24b71fbdb..4b95d6cf574 100644--- a/src/store/chat/slices/voiceMessage/action.ts+++ b/src/store/chat/slices/voiceMessage/action.ts@@ -399,6 +399,7 @@ export class VoiceMessageActionImpl {const result = await getFileStoreState().uploadWithProgress({abortController: transaction.abortController,+ conversationAgentId: transaction.context.agentId,file: transaction.recording.file,fileMetadata: {codec: transaction.recording.codec,diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex 5a8c15c4999..db9134325e5 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -300,6 +300,9 @@ describe('useFileStore:chat', () => {expect(toast.error).not.toHaveBeenCalled();expect(uploadWithProgress).toHaveBeenCalledTimes(1);+ expect(uploadWithProgress).toHaveBeenCalledWith(+ expect.objectContaining({ conversationAgentId: AGENT_ID }),+ );});it('uploadChatFiles should allow any file type for heterogeneous agents', async () => {diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 05700f0fee6..1cc077ed728 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -393,6 +393,7 @@ export class FileActionImpl {shareId,}): await this.#get().uploadWithProgress({+ conversationAgentId: agentId,file,onStatusUpdate: dispatchChatUploadFileList,});diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.tsindex 3f327ba8eba..f3cd9e674f3 100644--- a/src/store/file/slices/upload/action.ts+++ b/src/store/file/slices/upload/action.ts@@ -29,6 +29,11 @@ type OnStatusUpdate = (interface UploadWithProgressParams {abortController?: AbortController;+ /**+ * Agent whose conversation this upload is attached to. In a public agent the+ * server shares the attachment with the conversation's readers.+ */+ conversationAgentId?: string;file: File;/*** Additional metadata persisted with the file record. Media capture flows use@@ -150,6 +155,7 @@ export class FileUploadActionImpl {abortController,visibility,fileMetadata,+ conversationAgentId,}: UploadWithProgressParams): Promise<UploadWithProgressResult | undefined> => {const statusId = uploadId ?? file.name;let uploadedPathname: string | undefined;@@ -235,6 +241,7 @@ export class FileUploadActionImpl {const data = await fileService.createFile({+ conversationAgentId,fileType,hash,metadata: {