π€― 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: share agent document uploads and hide them from libraries (#19863)
Neko11b481b1c35e
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.tsindex f5654514d77..5d40e72b1da 100644--- a/apps/server/src/routers/lambda/__tests__/file.test.ts+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts@@ -559,6 +559,43 @@ describe('fileRouter', () => {);});+ /** @example Agent-document uploads are readable by other members of the workspace. */+ it('defaults agent-document uploads to public without changing ordinary upload defaults', async () => {+ // ROOT CAUSE:+ // Agent uploads used the ordinary private-file default while their document rows+ // were public. Other workspace members saw the document but its preview returned 404.+ // Default the dedicated upload source to public and retain private ordinary uploads.+ ({ caller } = createCallerWithCtx({ workspaceId: 'workspace-1' }));+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });+ const upload = {+ fileType: 'application/pdf',+ hash: 'agent-upload-hash',+ metadata: {},+ name: 'brief.pdf',+ size: 100,+ url: 'files/brief.pdf',+ };++ await caller.createFile({ ...upload, source: FileSource.AgentDocument });++ /** @example The persisted original file has the same public visibility as its document. */+ expect(mockFileModelCreate).toHaveBeenLastCalledWith(+ expect.objectContaining({ source: FileSource.AgentDocument, visibility: 'public' }),+ true,+ routerMocks.transactionClient,+ );++ await caller.createFile(upload);++ /** @example An ordinary upload still starts private. */+ expect(mockFileModelCreate).toHaveBeenLastCalledWith(+ expect.objectContaining({ source: undefined, visibility: 'private' }),+ true,+ routerMocks.transactionClient,+ );+ });+it('should drop an unrecognised source instead of failing the upload', async () => {mockFileModelCheckHash.mockResolvedValue({ isExist: false });mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });@@ -1276,6 +1313,17 @@ describe('fileRouter', () => {});describe('removeUnreferencedFile', () => {+ /** @example A client retry after server-side cleanup succeeds without touching storage. */+ it('accepts cleanup of an already removed upload', async () => {+ mockFileModelFindById.mockResolvedValue(undefined);+ /** @example Repeating cleanup is idempotent. */+ await expect(+ caller.removeUnreferencedFile({ id: 'removed-upload' }),+ ).resolves.toBeUndefined();+ /** @example Missing files do not trigger another storage deletion. */+ expect(mockFileServiceDeleteFile).not.toHaveBeenCalled();+ });+it('keeps object storage when the file became referenced before cleanup', async () => {mockFileModelFindById.mockResolvedValue({ id: 'voice-file', userId: 'test-user' });mockFileModelDeleteUnreferenced.mockResolvedValue(undefined);diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.tsindex 54f4cdd3dc1..02dc5c280b3 100644--- a/apps/server/src/routers/lambda/file.ts+++ b/apps/server/src/routers/lambda/file.ts@@ -269,10 +269,15 @@ export const fileRouter = router({// 2. Otherwise an explicit caller value wins.// 3. Otherwise inherit the parent document's visibility so a file// uploaded inside a private folder stays private.- // 4. Otherwise default top-level uploads to 'private' so new content+ // 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// starts in the creator's private space (mirrors the Pages spec).const resolvedVisibility: 'private' | 'public' | undefined = ctx.workspaceId- ? (knowledgeBaseVisibility ?? input.visibility ?? parentVisibility ?? 'private')+ ? (knowledgeBaseVisibility ??+ input.visibility ??+ parentVisibility ??+ (input.source === FileSource.AgentDocument ? 'public' : 'private')): undefined;if (latestUpload?.status === 'settled') {@@ -917,7 +922,8 @@ export const fileRouter = router({.input(z.object({ id: z.string() })).mutation(async ({ input, ctx }) => {const existing = await ctx.fileModel.findById(input.id);- if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ // Import failure cleanup can run on both server and client; retries are harmless.+ if (!existing) return;await assertFileNotInRestrictedKnowledgeBase(ctx, input.id);const file = await ctx.fileModel.deleteUnreferenced(input.id, {diff --git a/apps/server/src/services/agentDocumentVfs/index.test.ts b/apps/server/src/services/agentDocumentVfs/index.test.tsindex b82b563eedf..0976b2ca1f8 100644--- a/apps/server/src/services/agentDocumentVfs/index.test.ts+++ b/apps/server/src/services/agentDocumentVfs/index.test.ts@@ -1,11 +1,13 @@// @vitest-environment nodeimport { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { FileSource } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AgentAccess, AgentDocumentModel } from '@/database/models/agentDocuments';import type { LobeChatDatabase } from '@/database/type';import * as headlessEditor from '../agentDocuments/headlessEditor';+import { FileService } from '../file';import { AgentDocumentVfsService } from './index';import { createSkillMount } from './mounts/skills/createSkillMount';@@ -27,6 +29,13 @@ vi.mock('./mounts/skills/createSkillMount', () => ({createSkillMount: vi.fn(),}));+const removeUnreferencedFile = vi.hoisted(() => vi.fn());+vi.mock('../file', () => ({+ FileService: vi.fn(function () {+ return { removeUnreferencedFile };+ }),+}));+describe('AgentDocumentVfsService', () => {const db = {} as LobeChatDatabase;const userId = 'user-1';@@ -52,9 +61,12 @@ describe('AgentDocumentVfsService', () => {};beforeEach(() => {+ vi.mocked(FileService).mockClear();+ removeUnreferencedFile.mockReset().mockResolvedValue(undefined);for (const method of Object.values(mockAgentDocumentModel)) {method.mockReset();}+ mockAgentDocumentModel.permanentlyDelete.mockResolvedValue([]);for (const method of Object.values(mockSkillMount)) {method.mockReset();}@@ -68,6 +80,15 @@ describe('AgentDocumentVfsService', () => {});});+ /** @example Native VFS browsing remains available without object storage. */+ it('does not initialize storage when listing native documents', async () => {+ mockAgentDocumentModel.listByParent.mockResolvedValue([]);+ const service = new AgentDocumentVfsService(db, userId);+ await service.list('./', { agentId: 'agent-1' });+ /** @example Browsing a document tree has no storage configuration prerequisite. */+ expect(FileService).not.toHaveBeenCalled();+ });+afterEach(() => {vi.restoreAllMocks();});@@ -740,6 +761,12 @@ ${'lossless tool result\n'.repeat(100)}});it('permanently deletes ordinary directory subtrees child-first', async () => {+ // ROOT CAUSE:+ // Permanent deletion removed document rows without reclaiming hidden backing uploads.+ // Returned file IDs now go through reference-safe cleanup after each committed deletion.+ mockAgentDocumentModel.permanentlyDelete+ .mockResolvedValueOnce(['child-file'])+ .mockResolvedValueOnce([]);mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue({accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,content: '',@@ -780,6 +807,8 @@ ${'lossless tool result\n'.repeat(100)}2,'folder-agent-doc-1',);+ /** @example The child upload is reclaimed using the dedicated source policy. */+ expect(removeUnreferencedFile.mock.calls).toEqual([['child-file', FileSource.AgentDocument]]);});it('opts read-only mounted skill paths out of trash deletes', async () => {diff --git a/apps/server/src/services/agentDocumentVfs/index.ts b/apps/server/src/services/agentDocumentVfs/index.tsindex c524597f3e2..daa0cb5e3c8 100644--- a/apps/server/src/services/agentDocumentVfs/index.ts+++ b/apps/server/src/services/agentDocumentVfs/index.ts@@ -1,4 +1,5 @@import type { LobeChatDatabase } from '@lobechat/database';+import { FileSource } from '@lobechat/types';import type { AgentDocument } from '@/database/models/agentDocuments';import {@@ -13,6 +14,7 @@ import {RAW_TEXT_DOCUMENT_FILE_TYPE,} from '../agentDocuments/contentFormat';import { createMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';+import { FileService } from '../file';import { AgentDocumentVfsError } from './errors';import { createSkillMount } from './mounts/skills/createSkillMount';import {@@ -104,12 +106,22 @@ interface AgentDocumentCopyOptions {export class AgentDocumentVfsService {private agentDocumentModel: AgentDocumentModel;private skillMount: SkillMount;+ private fileServiceInstance?: FileService;- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {this.agentDocumentModel = new AgentDocumentModel(db, userId, workspaceId);this.skillMount = createSkillMount(db, userId, workspaceId);}+ /** Defers storage configuration until a permanent deletion actually has uploads to reclaim. */+ private get fileService(): FileService {+ return (this.fileServiceInstance ??= new FileService(this.db, this.userId, this.workspaceId));+ }+/*** Lists direct children for a unified VFS directory path.*@@ -619,7 +631,10 @@ export class AgentDocumentVfsService {const subtree = await this.collectOrdinarySubtree(root, ctx.agentId, true);for (const item of subtree.reverse()) {- await this.agentDocumentModel.permanentlyDelete(item.id);+ const fileIds = await this.agentDocumentModel.permanentlyDelete(item.id);+ for (const fileId of fileIds) {+ await this.fileService.removeUnreferencedFile(fileId, FileSource.AgentDocument);+ }}}diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.tsindex 90b28df9fc4..d02c2645ff8 100644--- a/apps/server/src/services/agentDocuments/index.test.ts+++ b/apps/server/src/services/agentDocuments/index.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';+import { FileSource } from '@lobechat/types';import { createHeadlessEditor } from '@lobehub/editor/headless';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -129,6 +130,7 @@ describe('AgentDocumentsService', () => {};const mockFileService = {getFileContent: vi.fn(),+ removeUnreferencedFile: vi.fn().mockResolvedValue(undefined),};const mockAgentModel = {getAgentConfigById: vi.fn(),@@ -177,6 +179,24 @@ describe('AgentDocumentsService', () => {});describe('createDocument', () => {+ /** @example Native document creation works without object-storage configuration. */+ it('does not initialize file storage when creating a native document', async () => {+ // ROOT CAUSE:+ // Eager cleanup-service construction made ordinary agent operations require S3.+ // Storage must only initialize when an operation actually needs file cleanup.+ vi.mocked(FileService).mockImplementationOnce(function () {+ throw new Error('Storage is not configured');+ });+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'native-document' });+ const service = new AgentDocumentsService(db, userId);+ /** @example Creating text content never contacts storage. */+ await expect(service.createDocument('agent-1', 'Note', 'hello')).resolves.toBeDefined();+ /** @example The storage dependency stays uninitialized. */+ expect(FileService).not.toHaveBeenCalled();+ vi.mocked(FileService).mockReset();+ });+it('should append a numeric suffix when the base filename already exists', async () => {mockModel.findByParentAndFilename.mockResolvedValueOnce({ id: 'existing-doc' })@@ -1145,6 +1165,36 @@ lossless tool result});describe('importFile', () => {+ /** @example A rejected import reclaims only the caller's dedicated upload. */+ it('reclaims a dedicated upload when the parent disappeared', async () => {+ mockFileModel.findById.mockResolvedValue({+ id: 'failed-upload',+ userId,+ source: FileSource.AgentDocument,+ });+ mockModel.findByDocumentId.mockResolvedValue(undefined);+ const service = new AgentDocumentsService(db, userId);+ /** @example The original validation failure still reaches the caller. */+ await expect(service.importFile('agent-1', 'failed-upload', 'missing')).rejects.toThrow(+ 'Parent folder not found',+ );+ /** @example Server-side cleanup still runs if the client has disconnected. */+ expect(mockFileService.removeUnreferencedFile.mock.calls).toEqual([+ ['failed-upload', FileSource.AgentDocument],+ ]);+ });++ /** @example A failed attachment never deletes a pre-existing Resources upload. */+ it('preserves ordinary resources after a rejected import', async () => {+ mockFileModel.findById.mockResolvedValue({ id: 'resource', userId });+ mockModel.findByDocumentId.mockResolvedValue(undefined);+ const service = new AgentDocumentsService(db, userId);+ /** @example Import rejects the invalid parent. */+ await expect(service.importFile('agent-1', 'resource', 'missing')).rejects.toThrow();+ /** @example Resources keeps its independent lifecycle. */+ expect(mockFileService.removeUnreferencedFile).not.toHaveBeenCalled();+ });+it('creates a file-backed agent document from an uploaded file', async () => {mockFileModel.findById.mockResolvedValue({fileType: 'application/pdf',diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex b0c02a836ed..a99a0548a72 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -9,7 +9,7 @@ import { buildAgentSkillIdentifier } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';import type { DocumentAccessScope } from '@lobechat/types';-import { ordinaryDocumentAccessScope } from '@lobechat/types';+import { FileSource, ordinaryDocumentAccessScope } from '@lobechat/types';import type {AgentDocument,@@ -33,6 +33,7 @@ import { isUuid } from '@/database/utils/uuid';import { AgentDocumentVfsError } from '../agentDocumentVfs/errors';import { isManagedSkillDocument } from '../agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';import { DocumentService } from '../document';+import { FileService } from '../file';import { TOOL_RESULTS_DIR_NAME } from '../toolExecution/constants';import { isRawTextAgentDocument } from './contentFormat';import {@@ -156,12 +157,13 @@ export class AgentDocumentsService {private agentDocumentModel: AgentDocumentModel;private documentService: DocumentService;private fileModel: FileModel;+ private fileServiceInstance?: FileService;private topicDocumentModel: TopicDocumentModel;constructor(- db: LobeChatDatabase,- userId: string,- workspaceId?: string,+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,callerAgentVisibility?: 'private' | 'public' | null,documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,) {@@ -180,6 +182,11 @@ export class AgentDocumentsService {this.topicDocumentModel = new TopicDocumentModel(db, userId, workspaceId, documentAccessScope);}+ /** Defers storage configuration until upload cleanup; native documents need only the database. */+ private get fileService(): FileService {+ return (this.fileServiceInstance ??= new FileService(this.db, this.userId, this.workspaceId));+ }+private async projectDocumentContent<T extends ProjectableAgentDocument>(doc: T): Promise<T>;private async projectDocumentContent<T extends ProjectableAgentDocument>(doc: T | undefined,@@ -553,43 +560,56 @@ export class AgentDocumentsService {const file = await this.fileModel.findById(fileId);if (!file) throw new Error(`File not found: ${fileId}`);- if (parentId) {- const parent = await this.agentDocumentModel.findByDocumentId(agentId, parentId);- if (!parent) throw new Error(`Parent folder not found: ${parentId}`);- if (parent.fileType !== DOCUMENT_FOLDER_TYPE) {- throw new Error(`Parent document is not a folder: ${parentId}`);+ try {+ if (parentId) {+ const parent = await this.agentDocumentModel.findByDocumentId(agentId, parentId);+ if (!parent) throw new Error(`Parent folder not found: ${parentId}`);+ if (parent.fileType !== DOCUMENT_FOLDER_TYPE) {+ throw new Error(`Parent document is not a folder: ${parentId}`);+ }}- }- const resolvedParentId = parentId ?? null;- const baseFilename = buildDocumentFilename(file.name);- let filename = baseFilename;- let suffix = 2;+ const resolvedParentId = parentId ?? null;+ const baseFilename = buildDocumentFilename(file.name);+ let filename = baseFilename;+ let suffix = 2;++ while (+ await this.agentDocumentModel.findByParentAndFilename(agentId, resolvedParentId, filename)+ ) {+ if (suffix > MAX_UNIQUE_FILENAME_ATTEMPTS) {+ throw new Error(+ `Unable to generate a unique filename for "${file.name}" after ${MAX_UNIQUE_FILENAME_ATTEMPTS} attempts.`,+ );+ }- while (- await this.agentDocumentModel.findByParentAndFilename(agentId, resolvedParentId, filename)- ) {- if (suffix > MAX_UNIQUE_FILENAME_ATTEMPTS) {- throw new Error(- `Unable to generate a unique filename for "${file.name}" after ${MAX_UNIQUE_FILENAME_ATTEMPTS} attempts.`,- );+ filename = appendSpacedFilenameSuffix(baseFilename, suffix);+ suffix += 1;}- filename = appendSpacedFilenameSuffix(baseFilename, suffix);- suffix += 1;- }-- const createParams = {- fileId: file.id,- fileType: file.fileType || 'application/octet-stream',- ...(resolvedParentId ? { parentId: resolvedParentId } : {}),- source: file.url,- sourceType: 'file' as const,- title: file.name,- };+ const createParams = {+ fileId: file.id,+ fileType: file.fileType || 'application/octet-stream',+ ...(resolvedParentId ? { parentId: resolvedParentId } : {}),+ source: file.url,+ sourceType: 'file' as const,+ title: file.name,+ };- // Imported bytes stay in files; preview reads the original rather than an editable copy.- return this.agentDocumentModel.create(agentId, filename, '', createParams);+ // Imported bytes stay in files; preview reads the original rather than an editable copy.+ return await this.agentDocumentModel.create(agentId, filename, '', createParams);+ } catch (error) {+ // Only reclaim dedicated uploads created by this caller. Existing Resources imports+ // retain their lifecycle, and committed/concurrent imports are protected by references.+ if (file.source === FileSource.AgentDocument && file.userId === this.userId) {+ await this.fileService+ .removeUnreferencedFile(file.id, FileSource.AgentDocument)+ .catch((cleanupError) => {+ console.error('Failed to reclaim an unbound agent upload', cleanupError);+ });+ }+ throw error;+ }}async createDocument(diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex 0e1dc0aad98..b69df2f7268 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -63,6 +63,7 @@ describe('FileService', () => {beforeEach(() => {mockFileModel = {delete: vi.fn(),+ deleteUnreferenced: vi.fn(),findById: vi.fn(),updateGlobalFile: vi.fn(),};@@ -96,6 +97,19 @@ describe('FileService', () => {expect(FileModel).toHaveBeenCalledWith(mockDb, mockUserId, 'workspace-1');});+ /** @example Shared blobs survive cleanup; exclusively owned blobs are removed. */+ it('deletes storage only when reference-safe cleanup returns the file', async () => {+ mockFileModel.deleteUnreferenced+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce({ id: 'exclusive', url: 'files/exclusive.pdf' });+ await service.removeUnreferencedFile('shared', FileSource.AgentDocument);+ /** @example A shared object is not removed. */+ expect(service['impl'].deleteFile).not.toHaveBeenCalled();+ await service.removeUnreferencedFile('exclusive', FileSource.AgentDocument);+ /** @example The exclusive object's key is removed after DB cleanup. */+ expect(service['impl'].deleteFile).toHaveBeenCalledWith('files/exclusive.pdf');+ });+describe('downloadFileToLocal', () => {const mockFile = {id: 'test-file-id',diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex 9729d4b53fb..2e668065492 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -1,5 +1,5 @@import { type LobeChatDatabase, type Transaction } from '@lobechat/database';-import type { FileAccessScope } from '@lobechat/types';+import type { FileAccessScope, FileSource } from '@lobechat/types';import { ordinaryFileAccessScope } from '@lobechat/types';import { inferContentTypeFromImageUrl, nanoid, uuid } from '@lobechat/utils';import { TRPCError } from '@trpc/server';@@ -49,6 +49,33 @@ export class FileService {return this.impl.deleteFile(key);}+ /**+ * Reclaims an unreferenced upload and its exclusively owned stored object.+ *+ * Use when:+ * - An import fails or its final owning document is permanently deleted.+ *+ * Expects:+ * - The file is in the caller's scope and matches the requested upload source.+ *+ * Returns:+ * - Void; referenced files and shared objects remain intact.+ *+ * Call stack:+ * AgentDocumentsService.importFile / AgentDocumentVfsService.deletePermanently+ * -> {@link FileService.removeUnreferencedFile}+ * -> {@link FileModel.deleteUnreferenced}+ * -> {@link FileService.deleteFile}+ */+ public async removeUnreferencedFile(id: string, source: FileSource): Promise<void> {+ const file = await this.fileModel.deleteUnreferenced(id, {+ removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,+ source,+ });+ // The model returns an object key only after its final file reference is removed.+ if (file) await this.deleteFile(file.url);+ }+/*** Delete files in batch*/diff --git a/packages/database/src/models/__tests__/agentDocuments.workspace.test.ts b/packages/database/src/models/__tests__/agentDocuments.workspace.test.tsindex 4b92a25c2f5..40127c14709 100644--- a/packages/database/src/models/__tests__/agentDocuments.workspace.test.ts+++ b/packages/database/src/models/__tests__/agentDocuments.workspace.test.ts@@ -1,11 +1,14 @@// @vitest-environment node+import { FileSource } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { KnowledgeRepo } from '../../repositories/knowledge';import { agentDocuments, agents, documents, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentDocumentModel } from '../agentDocuments';+import { FileModel } from '../file';const serverDB: LobeChatDatabase = await getTestDB();@@ -32,6 +35,68 @@ afterEach(async () => {});describe('AgentDocumentModel workspace scope', () => {+ /** @example A shared document and upload survive until their final binding is deleted. */+ it('returns backing files for cleanup only after deleting the final binding', async () => {+ // ROOT CAUSE:+ // Deleting a binding also deleted its document, even when another agent still used it.+ // Keep shared documents; return deleted documents' file IDs for safe storage cleanup.+ const model = new AgentDocumentModel(serverDB, userId, workspaceId);+ const fileModel = new FileModel(serverDB, userId, workspaceId);+ const { id: fileId } = await fileModel.create({+ fileType: 'application/pdf',+ name: 'shared.pdf',+ size: 100,+ source: FileSource.AgentDocument,+ url: 'files/shared.pdf',+ visibility: 'public',+ });+ const document = await model.create('workspace-agent-document-agent', 'shared.pdf', '', {+ fileId,+ fileType: 'application/pdf',+ sourceType: 'file',+ });+ await serverDB.insert(agents).values({ id: 'second-agent', userId, workspaceId });+ const second = await model.associate({+ agentId: 'second-agent',+ documentId: document.documentId,+ });++ await model.delete(document.id);+ await fileModel.deleteUnreferenced(fileId);+ /** @example Soft deletion preserves recoverable original bytes. */+ expect(await fileModel.findById(fileId)).toBeDefined();+ /** @example Deleting the first binding leaves the shared document in place. */+ expect(await model.permanentlyDelete(document.id)).toEqual([]);+ /** @example The other agent can still open the document. */+ expect(await model.findById(second.id)).toBeDefined();+ /** @example The final binding returns its backing file for reclamation. */+ expect(await model.permanentlyDelete(second.id)).toEqual([fileId]);+ await fileModel.deleteUnreferenced(fileId, { source: FileSource.AgentDocument });+ /** @example The now-unreferenced upload row is reclaimed. */+ expect(await fileModel.findById(fileId)).toBeUndefined();+ });++ /** @example A new agent document is public in its workspace but absent from Resources. */+ it('creates public agent documents without adding them to the resource library', async () => {+ const memberId = 'agent-document-other-member';+ await serverDB.insert(users).values({ id: memberId });+ const model = new AgentDocumentModel(serverDB, userId, workspaceId);+ const document = await model.create('workspace-agent-document-agent', 'shared.md', '# Shared');+ const [stored] = await serverDB+ .select({ visibility: documents.visibility })+ .from(documents)+ .where(eq(documents.id, document.documentId));++ /** @example The default is explicitly public, so members share the same agent resource. */+ expect(stored?.visibility).toBe('public');+ /** @example Another workspace member can read the bound agent document. */+ expect(+ await new AgentDocumentModel(serverDB, memberId, workspaceId).findById(document.id),+ ).toMatchObject({ content: '# Shared' });+ /** @example The agent source is excluded from ordinary resource browsing. */+ expect(await new KnowledgeRepo(serverDB, memberId, workspaceId).query()).toEqual([]);+ });+it('isolates document reads and deletes between personal and workspace scopes', async () => {const personalModel = new AgentDocumentModel(serverDB, userId);const workspaceModel = new AgentDocumentModel(serverDB, userId, workspaceId);diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.tsindex 57955c0ea4f..e7f3a6aef24 100644--- a/packages/database/src/models/__tests__/file.test.ts+++ b/packages/database/src/models/__tests__/file.test.ts@@ -292,6 +292,57 @@ describe('FileModel', () => {});describe('deleteUnreferenced', () => {+ /** @example Dedicated cleanup cannot remove an ordinary library file. */+ it('limits source-specific cleanup to agent uploads', async () => {+ const { id } = await fileModel.create({+ fileType: 'application/pdf',+ name: 'library.pdf',+ size: 100,+ url: 'files/library.pdf',+ });+ await fileModel.deleteUnreferenced(id, { source: FileSource.AgentDocument });+ /** @example Ordinary resources keep their independent lifecycle. */+ expect(await fileModel.findById(id)).toBeDefined();+ });++ /** @example A backing upload survives while another document or KB still uses it. */+ it('preserves document and knowledge-base references during agent upload cleanup', async () => {+ // ROOT CAUSE:+ // Cleanup only checked messages and sessions and could delete files still used by+ // documents or knowledge bases. Check these references under the same file-row lock.+ const { id } = await fileModel.create({+ fileType: 'application/pdf',+ name: 'shared.pdf',+ size: 100,+ source: FileSource.AgentDocument,+ url: 'files/shared.pdf',+ });+ const [document] = await serverDB+ .insert(documents)+ .values({+ fileId: id,+ fileType: 'application/pdf',+ filename: 'shared.pdf',+ source: 'files/shared.pdf',+ sourceType: 'file',+ userId,+ totalCharCount: 0,+ totalLineCount: 0,+ })+ .returning();+ await fileModel.deleteUnreferenced(id);+ /** @example Document-backed files must survive cleanup. */+ expect(await fileModel.findById(id)).toBeDefined();++ await serverDB.delete(documents).where(eq(documents.id, document.id));+ await serverDB+ .insert(knowledgeBaseFiles)+ .values({ fileId: id, knowledgeBaseId: 'kb1', userId });+ await fileModel.deleteUnreferenced(id);+ /** @example A KB relation independently keeps the file alive. */+ expect(await fileModel.findById(id)).toBeDefined();+ });+it('deletes an owned file that has no message or session references', async () => {await fileModel.createGlobalFile({creator: userId,diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex 09495156aea..6ea44186dd3 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -12,6 +12,7 @@ import {isNull,like,ne,+ notExists,or,sql,} from 'drizzle-orm';@@ -127,6 +128,27 @@ export class AgentDocumentModel {* Personal mode β `user_id = ? AND workspace_id IS NULL`; workspace mode β `workspace_id = ?`.*/private agentDocOwnership() {+ // NOTICE:+ // For now, we expect a caller authorized to access an agent to access all resources+ // bound under its agent documents, including backing files, without a separate+ // Resources publish step. Tool reads and UI previews need the same access contract.+ // Agent documents and backing files use separate visibility checks; uploads without+ // the agent-document source can expose a document in tools/the tree while its+ // original-file preview returns 404. Dedicated uploads now default to public.+ // Context: AgentDocumentsService.importFile and FileDocumentPreview; this predicate+ // scopes bindings but does not itself authorize access to the agent.+ // Replace this interim assumption when a consistent workspace authorization model+ // covers agent documents, backing files, tool execution, and resource publishing.++ // REVIEW: A private upload must not silently become readable merely because someone+ // can access its agent. Restricting preview or even one read tool is insufficient:+ // if an agent can read private content through another path or its existing context,+ // a user can prompt it to copy or summarize that content into a shared knowledge base+ // and leak it. The current assumption does not provide per-resource confidentiality.++ // TODO: Revisit this coarse model before extending workspace permission controls.+ // Define how sharing is authorized and how reads, execution context, and writes to+ // broader audiences are constrained; enforce the resulting rules across all paths.return and(buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentDocuments),exists(@@ -465,6 +487,8 @@ export class AgentDocumentModel {totalLineCount: stats.totalLineCount,updatedAt: updatedAt ?? createdAt,userId: this.userId,+ // Keep newly created agent resources shared within their existing workspace scope.+ visibility: 'public',workspaceId: this.workspaceId ?? null,};@@ -1591,46 +1615,91 @@ export class AgentDocumentModel {);}- async permanentlyDelete(documentId: string): Promise<void> {+ /**+ * Removes a binding and its document when no other agent still owns that document.+ *+ * Use when:+ * - Permanently deleting an agent trash entry.+ * Expects:+ * - The binding belongs to the current scope.+ * Returns:+ * - Backing file IDs for reference-safe cleanup by the storage service after commit.+ */+ async permanentlyDelete(documentId: string): Promise<string[]> {const existing = await this.findByIdWithOptions(documentId, { includeDeleted: true });- if (!existing) return;+ if (!existing) return [];- await this.db.transaction(async (trx) => {+ return this.db.transaction(async (trx) => {await trx.delete(agentDocuments).where(and(eq(agentDocuments.id, documentId), this.agentDocOwnership()));- await trx- .delete(documents)- .where(and(eq(documents.id, existing.documentId), this.documentOwnership()));+ return this.deleteUnboundDocuments(trx, [existing.documentId]);});}+ /**+ * Permanently removes a subtree's bindings and documents without deleting shared documents.+ *+ * Use when:+ * - Erasing a complete document subtree in one transaction.+ * Expects:+ * - The root belongs to the requested agent and current scope.+ * Returns:+ * - Backing file IDs requiring reference-safe storage cleanup after commit.+ */async permanentlyDeleteSubtreeByDocumentId(agentId: string,rootDocumentId: string,- ): Promise<void> {+ ): Promise<string[]> {const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId, {includeDeleted: true,});- if (subtree.length === 0) return;+ if (subtree.length === 0) return [];const agentDocumentIds = subtree.map((item) => item.id);const documentIds = subtree.map((item) => item.documentId);- await this.db.transaction(async (trx) => {+ return this.db.transaction(async (trx) => {await trx.delete(agentDocuments).where(and(this.agentDocOwnership(), inArray(agentDocuments.id, agentDocumentIds)));- await trx- .delete(documents)- .where(and(this.documentOwnership(), inArray(documents.id, documentIds)));+ return this.deleteUnboundDocuments(trx, documentIds);});}+ /** Removes only documents with no surviving agent binding and returns their backing files. */+ private async deleteUnboundDocuments(trx: Transaction, documentIds: string[]): Promise<string[]> {+ // Serialize deletion with concurrent binding FK inserts before inspecting surviving owners.+ await trx+ .select({ id: documents.id })+ .from(documents)+ .where(and(this.documentOwnership(), inArray(documents.id, documentIds)))+ .orderBy(documents.id)+ .for('update');+ // Removing one agent's binding must not cascade through another agent's shared document.+ const removed = await trx+ .delete(documents)+ .where(+ and(+ this.documentOwnership(),+ inArray(documents.id, documentIds),+ notExists(+ trx+ .select({ id: agentDocuments.id })+ .from(agentDocuments)+ .where(eq(agentDocuments.documentId, documents.id)),+ ),+ ),+ )+ .returning({ fileId: documents.fileId });++ return [...new Set(removed.flatMap(({ fileId }) => (fileId ? [fileId] : [])))];+ }+async deleteByAgent(agentId: string, deleteReason?: string): Promise<void> {await this.db.update(agentDocuments)diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex 5a7f07d81e9..8bd352a7fab 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -1,4 +1,4 @@-import type { FileAccessScope, QueryFileListParams } from '@lobechat/types';+import type { FileAccessScope, FileSource, QueryFileListParams } from '@lobechat/types';import {FilesTabs,getAgentShareFileProvenance,@@ -25,6 +25,7 @@ import type { PgTransaction } from 'drizzle-orm/pg-core';import type { FileItem, NewFile, NewGlobalFile } from '../schemas';import {+ agentsFiles,asyncTasks,chunks,documentChunks,@@ -33,12 +34,15 @@ import {fileChunks,files,filesToSessions,+ generations,globalFiles,knowledgeBaseFiles,messages,messagesFiles,+ messageTTS,topics,users,+ verifyEvidence,} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';import { buildFileCategoryFilter } from '../utils/fileTypeCategory';@@ -258,7 +262,8 @@ export class FileModel {};/**- * Delete a transient upload only while no persisted message or session references it.+ * Delete a transient upload only while no persisted content references it.+ * This also covers documents, knowledge bases, agents, generated media, TTS and evidence.* 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.*@@ -267,7 +272,12 @@ export class FileModel {*/deleteUnreferenced = async (id: string,- options: { accessScope?: FileAccessScope; removeGlobalFile?: boolean } = {},+ options: {+ accessScope?: FileAccessScope;+ removeGlobalFile?: boolean;+ /** Only reclaim this upload source; omitted preserves the general cleanup behavior. */+ source?: FileSource;+ } = {},) => {const { accessScope = ordinaryFileAccessScope, removeGlobalFile = true } = options;return this.db.transaction(async (trx) => {@@ -278,6 +288,7 @@ export class FileModel {and(eq(files.id, id),this.ownership(),+ options.source ? eq(files.source, options.source) : undefined,fileMatchesAccessScope(files.metadata, accessScope),),)@@ -299,6 +310,43 @@ export class FileModel {.limit(1);if (sessionReference) return;+ // Content references keep hidden uploads alive, including soft-deleted documents.+ // The file lock conflicts with FK inserts, so concurrent attachments cannot be lost.+ // Upload sessions and derived chunks are bookkeeping, not surviving content owners.+ const [contentReference] = await trx+ .select({ id: documents.fileId })+ .from(documents)+ .where(eq(documents.fileId, id))+ .unionAll(+ trx+ .select({ id: knowledgeBaseFiles.fileId })+ .from(knowledgeBaseFiles)+ .where(eq(knowledgeBaseFiles.fileId, id)),+ )+ .unionAll(+ trx+ .select({ id: agentsFiles.fileId })+ .from(agentsFiles)+ .where(eq(agentsFiles.fileId, id)),+ )+ .unionAll(+ trx+ .select({ id: generations.fileId })+ .from(generations)+ .where(eq(generations.fileId, id)),+ )+ .unionAll(+ trx.select({ id: messageTTS.fileId }).from(messageTTS).where(eq(messageTTS.fileId, id)),+ )+ .unionAll(+ trx+ .select({ id: verifyEvidence.fileId })+ .from(verifyEvidence)+ .where(eq(verifyEvidence.fileId, id)),+ )+ .limit(1);+ if (contentReference) return;+return this.deleteInTransaction(id, removeGlobalFile, trx, accessScope);});};diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.tsindex 2db500650c7..e6e7b3cfddf 100644--- a/packages/database/src/repositories/knowledge/index.test.ts+++ b/packages/database/src/repositories/knowledge/index.test.ts@@ -3,6 +3,7 @@ import { FileSource, FilesTabs, ResourceSourceFilter } from '@lobechat/types';import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { FileModel } from '../../models/file';import type { NewDocument, NewFile } from '../../schemas/file';import { documents, files, knowledgeBaseFiles, knowledgeBases } from '../../schemas/file';import { chunks, embeddings } from '../../schemas/rag';@@ -1426,6 +1427,115 @@ describe('KnowledgeRepo', () => {});});+ /** @example Agent uploads are shared attachments without becoming library entries. */+ describe('agent-document uploads', () => {+ const workspaceId = 'agent-upload-workspace';+ const agentFileId = 'agent-upload-file';+ const libraryFileId = 'regular-upload-file';+ const knowledgeBaseId = 'agent-upload-kb';++ beforeEach(async () => {+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Agent upload workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await serverDB.insert(knowledgeBases).values({+ id: knowledgeBaseId,+ name: 'Reference library',+ userId,+ workspaceId,+ });+ await serverDB.insert(files).values([+ {+ id: agentFileId,+ fileType: 'application/pdf',+ name: 'agent-brief.pdf',+ size: 100,+ source: FileSource.AgentDocument,+ url: 'files/agent-brief.pdf',+ userId,+ visibility: 'public',+ workspaceId,+ },+ {+ id: libraryFileId,+ fileType: 'application/pdf',+ name: 'library-brief.pdf',+ size: 100,+ url: 'files/library-brief.pdf',+ userId,+ visibility: 'public',+ workspaceId,+ },+ ]);+ await serverDB.insert(documents).values({+ fileId: agentFileId,+ fileType: 'application/pdf',+ filename: 'agent-brief.pdf',+ source: 'files/agent-brief.pdf',+ sourceType: 'file',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ visibility: 'public',+ workspaceId,+ });+ });++ /** @example A shared agent PDF stays out of Resources, including filtered and recent lists. */+ it('hides agent uploads while retaining ordinary files with the same MIME type', async () => {+ // ROOT CAUSE:+ // Making backing uploads public fixes previews but exposes them in resource lists+ // unless their origin is excluded. Filtering MIME types would also hide ordinary PDFs.+ // Reuse the hidden-source predicate for every list instead of changing the file type.+ const repo = new KnowledgeRepo(serverDB, otherUserId, workspaceId);+ const resources = await repo.query({ category: FilesTabs.Documents });+ const uploads = await repo.query({ sourceFilter: ResourceSourceFilter.Uploaded });+ const recent = await repo.queryRecent(50, 'file');+ const directList = await new FileModel(serverDB, otherUserId, workspaceId).query({});++ /** @example Each list includes the ordinary PDF and excludes the agent's PDF. */+ expect([resources, uploads, recent].map((rows) => rows.map((row) => row.fileId))).toEqual([+ [libraryFileId],+ [libraryFileId],+ [libraryFileId],+ ]);+ /** @example File-model lists apply the same exclusion as the Resources repository. */+ expect(directList.map((row) => row.id)).toEqual([libraryFileId]);+ });++ /** @example A knowledge-base listing cannot reintroduce an agent-only attachment. */+ it('excludes agent uploads from knowledge-base listings', async () => {+ await serverDB.insert(knowledgeBaseFiles).values([+ { fileId: agentFileId, knowledgeBaseId, userId },+ { fileId: libraryFileId, knowledgeBaseId, userId },+ ]);+ const repo = new KnowledgeRepo(serverDB, otherUserId, workspaceId);++ /** @example Only the ordinary resource is listed, even when both have a KB relation. */+ expect((await repo.query({ knowledgeBaseId })).map((row) => row.fileId)).toEqual([+ libraryFileId,+ ]);+ });++ /** @example Hidden-from-library files remain directly readable inside their workspace. */+ it('allows a second workspace user to read the file without exposing it in personal mode', async () => {+ const workspaceFiles = new FileModel(serverDB, otherUserId, workspaceId);+ const personalFiles = new FileModel(serverDB, otherUserId);++ /** @example Another member can fetch metadata for the agent file preview. */+ expect(await workspaceFiles.findById(agentFileId)).toMatchObject({+ id: agentFileId,+ source: FileSource.AgentDocument,+ visibility: 'public',+ });+ /** @example Public workspace visibility does not remove workspace isolation. */+ expect(await personalFiles.findById(agentFileId)).toBeUndefined();+ });+ });+describe('query - source filtering', () => {beforeEach(async () => {await serverDB.insert(files).values([diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex 54260d909bd..95a892559d4 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -21,6 +21,8 @@ export enum FileSource {* the user's library.*/Acceptance = 'acceptance',+ /** Original upload owned by an agent's document tree rather than the resource library. */+ AgentDocument = 'agent-document',ImageGeneration = 'image_generation',PageEditor = 'page-editor',VideoGeneration = 'video_generation',@@ -29,14 +31,19 @@ export enum FileSource {/*** Sources whose files are attachments of some other surface rather than library* resources. They stay fully readable through the surface that owns them (an- * acceptance report renders its evidence via `verify_evidence.file_id`), but+ * acceptance report renders its evidence via `verify_evidence.file_id`, and an+ * agent document previews its original upload via `documents.file_id`), but* never show up in the resource library listings β a single verification run* uploads hundreds of artifacts and would otherwise bury real content.** The one way back in is an explicit `ResourceSourceFilter.Acceptance` request:* the user asked for evidence, so burying it no longer applies.+ * That exception only reveals acceptance evidence; agent uploads stay hidden.*/-export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [FileSource.Acceptance];+export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [+ FileSource.Acceptance,+ FileSource.AgentDocument,+];/** Sources a generation model wrote, as opposed to anything a human put there. */export const AI_GENERATED_FILE_SOURCES: FileSource[] = [diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.tsindex 63582ada901..cd8a9542519 100644--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts@@ -1,4 +1,5 @@import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';+import { FileSource } from '@lobechat/types';import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -7,6 +8,7 @@ import { useDocumentTreeOps } from './useDocumentTreeOps';const toastError = vi.hoisted(() => vi.fn());const importFileMock = vi.hoisted(() => vi.fn());+const removeUnreferencedFileMock = vi.hoisted(() => vi.fn());const uploadWithProgressMock = vi.hoisted(() => vi.fn());const dispatchDockFileListMock = vi.hoisted(() => vi.fn());@@ -31,6 +33,10 @@ vi.mock('@/store/file', () => ({},}));+vi.mock('@/services/file', () => ({+ fileService: { removeUnreferencedFile: removeUnreferencedFileMock },+}));+vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string) => key,@@ -62,6 +68,7 @@ describe('useDocumentTreeOps.uploadFiles', () => {beforeEach(() => {toastError.mockReset();importFileMock.mockReset();+ removeUnreferencedFileMock.mockReset().mockResolvedValue(undefined);uploadWithProgressMock.mockReset();dispatchDockFileListMock.mockReset();mutate.mockReset();@@ -81,8 +88,9 @@ describe('useDocumentTreeOps.uploadFiles', () => {expect(dispatchDockFileListMock).toHaveBeenCalledWith(expect.objectContaining({ type: 'addFiles' }),);+ /** @example The upload carries the source used for shared visibility and library exclusion. */expect(uploadWithProgressMock).toHaveBeenCalledWith(- expect.objectContaining({ skipCheckFileType: true }),+ expect.objectContaining({ skipCheckFileType: true, source: FileSource.AgentDocument }),);expect(importFileMock).toHaveBeenCalledWith({agentId: 'agent-1',@@ -141,6 +149,19 @@ describe('useDocumentTreeOps.uploadFiles', () => {expect(toastError).toHaveBeenCalled();expect(importFileMock).toHaveBeenCalledTimes(2);expect(mutate).toHaveBeenCalledTimes(1);+ /** @example Only the failed import's upload is reclaimed. */+ expect(removeUnreferencedFileMock.mock.calls).toEqual([['file-1']]);+ });++ /** @example A failed list refresh after import must not delete the imported file. */+ it('keeps a successfully imported file when refreshing the tree fails', async () => {+ mutate.mockRejectedValueOnce(new Error('refresh failed'));+ const { result } = renderHook(() =>+ useDocumentTreeOps({ agentId: 'agent-1', data: [], mutate }),+ );+ await result.current.uploadFiles(null, [new File(['a'], 'a.md')]);+ /** @example The committed document retains its file despite the refresh error. */+ expect(removeUnreferencedFileMock).not.toHaveBeenCalled();});it('ignores blacklisted system files', async () => {diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.tsindex 8d2fb1ec7ab..649c064d81c 100644--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts@@ -1,3 +1,4 @@+import { FileSource } from '@lobechat/types';import { confirmModal, toast } from '@lobehub/ui/base-ui';import { nanoid } from 'nanoid';import { useCallback, useMemo, useRef } from 'react';@@ -7,6 +8,7 @@ import type { KeyedMutator } from 'swr';import { FILE_UPLOAD_BLACKLIST } from '@/const/file';import { useSingleton } from '@/hooks/useSingleton';import { agentDocumentService } from '@/services/agentDocument';+import { fileService } from '@/services/file';import { useFileStore } from '@/store/file';import type { AgentDocumentItem } from '../types';@@ -271,16 +273,26 @@ export const useDocumentTreeOps = ({file,onStatusUpdate: dispatchDockFileList,skipCheckFileType: true,+ source: FileSource.AgentDocument,uploadId,});if (!result?.id) continue;- await agentDocumentService.importFile({- agentId,- fileId: result.id,- parentId: parentDocumentId,- });+ try {+ await agentDocumentService.importFile({+ agentId,+ fileId: result.id,+ parentId: parentDocumentId,+ });+ } catch (error) {+ // Also covers transport/auth failures before import reaches the server.+ // A committed import is protected by the server's reference checks.+ await fileService.removeUnreferencedFile(result.id).catch((cleanupError) => {+ console.error('Failed to reclaim an unbound agent upload', cleanupError);+ });+ throw error;+ }await mutate();} catch (error) {toast.error(