🤯 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
✨ feat(agent-share): let share visitors attach files to a turn (#19569)
YuTengjing0ec5e3e4045f
diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsindex 9e6503376ac..d35bbc5c166 100644--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -63,6 +63,13 @@ vi.mock('@/database/models/topic', () => ({}),}));+const mockCountAgentShareUsage = vi.fn();+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(function () {+ return { countAgentShareUsage: mockCountAgentShareUsage };+ }),+}));+const mockGetAgentShareMonthlySpend = vi.fn();vi.mock('@/business/server/agent-share/spendGate', () => ({getAgentShareMonthlySpend: (...args: unknown[]) => mockGetAgentShareMonthlySpend(...args),@@ -97,6 +104,7 @@ describe('agentShareRouter', () => {});mockUpdateVisibility.mockResolvedValue(share);mockCountShareVisitors.mockResolvedValue({ topicCount: 7, visitorCount: 3 });+ mockCountAgentShareUsage.mockResolvedValue(0);mockGetAgentShareMonthlySpend.mockResolvedValue(null);mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });});@@ -402,9 +410,13 @@ describe('agentShareRouter', () => {userViewCount: 42,});mockGetAgentShareMonthlySpend.mockResolvedValue(2.5);+ mockCountAgentShareUsage.mockResolvedValue(3 * 1024 * 1024);const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));await expect(caller.getShareStats({ agentId: 'agent-1' })).resolves.toEqual({+ fileStorageUsed: 3 * 1024 * 1024,+ // Cap missing from a share saved before the field existed → default.+ maxFileStorage: 512 * 1024 * 1024,monthlySpend: 2.5,monthlySpendLimit: 10,topicCount: 7,@@ -412,12 +424,27 @@ describe('agentShareRouter', () => {visitorCount: 3,});expect(mockCountShareVisitors).toHaveBeenCalledWith({ agentId: 'agent-1' });+ // Keyed by the share INSTANCE, not the agent: a share that was turned+ // off and re-created must not inherit the old instance's bytes.+ expect(mockCountAgentShareUsage).toHaveBeenCalledWith('share-1');expect(mockGetAgentShareMonthlySpend).toHaveBeenCalledWith({agentId: 'agent-1',ownerUserId: 'user-1',});});+ it('reports the configured upload cap when the owner has set one', async () => {+ mockGetByAgentId.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, maxFileStorage: 0 },+ });+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ const stats = await caller.getShareStats({ agentId: 'agent-1' });++ expect(stats.maxFileStorage).toBe(0);+ });+it('reports unknown spend as null rather than zero', async () => {const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex 4b4aa27eac2..cbde5d7283a 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -26,6 +26,35 @@ vi.mock('@/database/models/topic', () => ({},}));+const loadModelsMock = vi.hoisted(() => vi.fn());+const findByIdAndProviderMock = vi.hoisted(() => vi.fn());+const aiModelModelConstructor = vi.hoisted(() => vi.fn());++vi.mock('@/business/client/model-bank/loadModels', () => ({+ loadModels: loadModelsMock,+}));++vi.mock('@/database/models/aiModel', () => ({+ AiModelModel: class {+ constructor(...args: unknown[]) {+ aiModelModelConstructor(...args);+ }+ findByIdAndProvider = findByIdAndProviderMock;+ },+}));++const resolveModelSelectionMock = vi.hoisted(() => vi.fn());+const agentServiceConstructor = vi.hoisted(() => vi.fn());++vi.mock('@/server/services/agent', () => ({+ AgentService: class {+ constructor(...args: unknown[]) {+ agentServiceConstructor(...args);+ }+ resolveModelSelection = resolveModelSelectionMock;+ },+}));+vi.mock('@/database/models/topicShare', () => ({TopicShareModel: {findByShareIdWithAccessCheck: vi.fn(),@@ -83,8 +112,10 @@ describe('shareRouter', () => {agentBackgroundColor: '#ffffff',agentDescription: 'A shared agent',agentId: 'agent-1',+ agentModel: 'gpt-4o',agentName: 'Alice',agentOpeningQuestions: ['What can you do?'],+ agentProvider: 'openai',agentTags: ['research'],agentTitle: 'Research Assistant',ownerId: 'owner-user',@@ -110,6 +141,15 @@ describe('shareRouter', () => {vi.mocked(AgentShareModel.assertShareAccess).mockReturnValue(undefined);vi.mocked(AgentShareModel.incrementUserViewCount).mockResolvedValue(undefined);countShareVisitors.mockResolvedValue({ topicCount: 12, visitorCount: 7 });+ loadModelsMock.mockResolvedValue([+ {+ abilities: { audio: false, video: false, vision: true },+ id: 'gpt-4o',+ providerId: 'openai',+ },+ ]);+ findByIdAndProviderMock.mockResolvedValue(undefined);+ resolveModelSelectionMock.mockResolvedValue({ model: 'gpt-4o', provider: 'openai' });});it('requires authentication without resolving or counting the share', async () => {@@ -145,13 +185,18 @@ describe('shareRouter', () => {stats: { conversations: 12, views: 42, visitors: 7 },terms: {allowCreatorViewSessions: false,+ maxFileStorage: 512 * 1024 * 1024,maxTopicsPerVisitor: 5,maxTurnsPerTopic: 20,},// Identifier only: the granted API list is owner-facing configuration.toolGrants: ['lobe-web-browsing'],+ // Derived from the agent's model abilities; the model itself stays hidden.+ uploadAbility: { audio: false, image: true, video: false },visibility: 'link',});+ expect(result).not.toHaveProperty('agentModel');+ expect(result).not.toHaveProperty('agentProvider');expect(result).not.toHaveProperty('ownerId');expect(result).not.toHaveProperty('shareConfig');expect(result).not.toHaveProperty('userViewCount');@@ -169,6 +214,86 @@ describe('shareRouter', () => {);});+ describe('uploadAbility', () => {+ const resolve = async () => {+ const caller = shareRouter.createCaller(+ await createContextInner({ userId: 'visitor-user' }),+ );+ return (await caller.getSharedAgent({ slugOrId: 'shared-agent' })).uploadAbility;+ };++ it('looks the model up as the OWNER, whose overrides the run itself honours', async () => {+ await resolve();++ expect(agentServiceConstructor).toHaveBeenCalledWith(expect.anything(), 'owner-user');+ expect(resolveModelSelectionMock).toHaveBeenCalledWith({+ model: 'gpt-4o',+ provider: 'openai',+ });+ expect(aiModelModelConstructor).toHaveBeenCalledWith(expect.anything(), 'owner-user');+ expect(findByIdAndProviderMock).toHaveBeenCalledWith('gpt-4o', 'openai');+ });++ it("prefers the owner's stored ability override over the bundled list", async () => {+ findByIdAndProviderMock.mockResolvedValue({+ abilities: { audio: true, video: true, vision: false },+ });++ await expect(resolve()).resolves.toEqual({ audio: true, image: false, video: true });+ });++ it("gates on the OWNER's effective model when the agent has none configured", async () => {+ // The run merges the owner's default agent config over the global+ // default, so an agent with no model of its own answers with the+ // owner's default model — the gate must look at that one, not at the+ // global constant.+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue({+ ...agentShare,+ agentModel: null,+ agentProvider: null,+ } as any);+ resolveModelSelectionMock.mockResolvedValue({+ model: 'claude-sonnet-4',+ provider: 'anthropic',+ });+ loadModelsMock.mockResolvedValue([+ {+ abilities: { audio: false, video: false, vision: true },+ id: 'gpt-4o',+ providerId: 'openai',+ },+ {+ abilities: { audio: true, video: false, vision: false },+ id: 'claude-sonnet-4',+ providerId: 'anthropic',+ },+ ]);++ await expect(resolve()).resolves.toEqual({ audio: true, image: false, video: false });+ expect(resolveModelSelectionMock).toHaveBeenCalledWith({ model: null, provider: null });+ expect(findByIdAndProviderMock).toHaveBeenCalledWith('claude-sonnet-4', 'anthropic');+ });++ it('fails closed when the effective model cannot be resolved', async () => {+ resolveModelSelectionMock.mockRejectedValue(new Error('settings unavailable'));++ await expect(resolve()).resolves.toEqual({ audio: false, image: false, video: false });+ expect(findByIdAndProviderMock).not.toHaveBeenCalled();+ });++ it('fails closed (no media) when the capability lookup throws', async () => {+ loadModelsMock.mockRejectedValue(new Error('bundle missing'));++ await expect(resolve()).resolves.toEqual({ audio: false, image: false, video: false });+ });++ it('fails closed when the model is unknown to both the owner and the bundle', async () => {+ loadModelsMock.mockResolvedValue([]);++ await expect(resolve()).resolves.toEqual({ audio: false, image: false, video: false });+ });+ });+it('does not count owner views', async () => {const caller = shareRouter.createCaller(await createContextInner({ userId: 'owner-user' }));diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex ba8dde27426..d038ad550e4 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -6,9 +6,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type * as MessageModelModule from '@/database/models/message';import { createContextInner } from '@/libs/trpc/lambda/context';+const mockServerDB = {+ transaction: vi.fn(async (fn: (trx: unknown) => Promise<unknown>) => fn({ trx: true })),+};vi.mock('@/database/core/db-adaptor', () => ({getServerDB: vi.fn(function () {- return {};+ return mockServerDB;}),}));@@ -49,8 +52,12 @@ vi.mock('@/server/featureFlags', () => ({}));const mockAccessCheck = vi.fn();+const mockLockUploadAdmission = vi.fn();vi.mock('@/database/models/agentShare', () => ({- AgentShareModel: { findByShareIdWithAccessCheck: (...args: any[]) => mockAccessCheck(...args) },+ AgentShareModel: {+ findByShareIdWithAccessCheck: (...args: any[]) => mockAccessCheck(...args),+ lockUploadAdmission: (...args: any[]) => mockLockUploadAdmission(...args),+ },}));const mockFindById = vi.fn();@@ -96,6 +103,70 @@ vi.mock('@/database/models/user', () => ({}),}));+const mockFileFindByIds = vi.fn();+const mockFileFindById = vi.fn();+const mockFileCreate = vi.fn();+const mockFileDeleteUnreferenced = vi.fn();+const mockFileCountAgentShareUsage = vi.fn();+const FileModelMock = vi.fn(function () {+ return {+ countAgentShareUsage: mockFileCountAgentShareUsage,+ create: mockFileCreate,+ deleteUnreferenced: mockFileDeleteUnreferenced,+ findById: mockFileFindById,+ findByIds: mockFileFindByIds,+ };+});+vi.mock('@/database/models/file', () => ({+ FileModel: FileModelMock,+}));++const mockReserveUpload = vi.fn();+vi.mock('@/server/services/fileUploadReservation', () => ({+ reserveUpload: (...args: any[]) => mockReserveUpload(...args),+}));++const mockUploadCountLiveUnderPrefix = vi.fn();+const FileUploadModelMock = vi.fn(function () {+ return { countLiveUsageUnderPrefix: mockUploadCountLiveUnderPrefix };+});+vi.mock('@/database/models/fileUpload', () => ({+ FileUploadModel: FileUploadModelMock,+}));++const mockUploadTouchActive = vi.fn();+const mockUploadFindLatest = vi.fn();+const mockUploadRelease = vi.fn();+const mockUploadReleaseBestEffort = vi.fn();+const mockUploadFindLatestForUpdate = vi.fn();+const mockUploadSettle = vi.fn();+const FileUploadServiceMock = vi.fn(function () {+ return {+ findLatest: mockUploadFindLatest,+ model: {+ findLatestByPathnameForUpdate: mockUploadFindLatestForUpdate,+ settle: mockUploadSettle,+ },+ release: mockUploadRelease,+ releaseBestEffort: mockUploadReleaseBestEffort,+ touchActive: mockUploadTouchActive,+ };+});+vi.mock('@/server/services/fileUpload', () => ({+ FileUploadService: FileUploadServiceMock,+}));++const mockCreatePreSignedUrl = vi.fn();+vi.mock('@/server/modules/S3', () => ({+ FileS3: vi.fn(function () {+ return { createPreSignedUrl: mockCreatePreSignedUrl };+ }),+}));++vi.mock('@/config/db', () => ({+ serverDBEnv: { REMOVE_GLOBAL_FILE: true },+}));+const mockExecAgent = vi.fn();const mockInterruptTask = vi.fn();const mockSetQueuedMessages = vi.fn();@@ -110,9 +181,16 @@ vi.mock('@/server/services/aiAgent', () => ({AiAgentService: AiAgentServiceMock,}));+const mockGetFileAccessUrl = vi.fn();+const mockGetFileMetadata = vi.fn();+const mockDeleteStoredFile = vi.fn();vi.mock('@/server/services/file', () => ({FileService: vi.fn(function () {- return { getFileAccessUrl: vi.fn() };+ return {+ deleteFile: mockDeleteStoredFile,+ getFileAccessUrl: mockGetFileAccessUrl,+ getFileMetadata: mockGetFileMetadata,+ };}),}));@@ -171,6 +249,21 @@ describe('shareChatRouter', () => {mockSetQueuedMessages.mockResolvedValue({ success: true });mockSignUserJWT.mockResolvedValue('visitor-jwt');mockSpendGate.mockResolvedValue({ allowed: true });+ mockFileFindByIds.mockResolvedValue([]);+ mockFileFindById.mockResolvedValue(undefined);+ mockFileCreate.mockResolvedValue({ id: 'file-new' });+ mockFileDeleteUnreferenced.mockResolvedValue(undefined);+ mockReserveUpload.mockResolvedValue({ id: 'upload-1', size: 10 });+ mockCreatePreSignedUrl.mockResolvedValue('https://s3/put');+ mockUploadTouchActive.mockResolvedValue(undefined);+ mockUploadFindLatest.mockResolvedValue(undefined);+ mockUploadRelease.mockResolvedValue(true);+ mockUploadReleaseBestEffort.mockResolvedValue(undefined);+ mockUploadFindLatestForUpdate.mockResolvedValue(undefined);+ mockUploadSettle.mockResolvedValue(true);+ mockGetFileAccessUrl.mockResolvedValue('https://s3/get');+ mockGetFileMetadata.mockResolvedValue({ contentLength: 10 });+ mockDeleteStoredFile.mockResolvedValue(undefined);});describe('execAgent', () => {@@ -290,6 +383,95 @@ 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)));+ 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(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 }]);+ const caller = await createCaller();++ await expect(+ caller.execAgent({ fileIds, prompt: 'look', shareId: 'share-1' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'File not found' });+ expect(mockCountBySender).not.toHaveBeenCalled();+ 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')]);+ 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']);+ });++ it('skips the ownership lookup entirely when no fileIds are sent', async () => {+ const caller = await createCaller();++ await caller.execAgent({ prompt: 'hi', shareId: 'share-1' });++ expect(FileModelMock).not.toHaveBeenCalled();+ });++ it('rejects more than SHARE_VISITOR_MAX_FILES_PER_TURN ids at the schema, before any lookup', async () => {+ const caller = await createCaller();+ const tooMany = Array.from({ length: 11 }, (_, i) => `file-${i}`);++ await expect(+ caller.execAgent({ fileIds: tooMany, prompt: 'look', shareId: 'share-1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(FileModelMock).not.toHaveBeenCalled();+ expect(mockExecAgent).not.toHaveBeenCalled();+ });+ });+// Regression for Codex P1 (`shareChat.ts` prompt schema): a// direct RPC caller (bypassing any client-side textarea limit) could// previously submit an HTTP-infrastructure-limit-sized `prompt`, which@@ -398,6 +580,399 @@ describe('shareChatRouter', () => {});});+ describe('createUploadUrl', () => {+ const prefix = `files/${OWNER}/agent-share/share-1/`;+ const MB = 1024 * 1024;++ beforeEach(() => {+ mockFileCountAgentShareUsage.mockResolvedValue(0);+ mockUploadCountLiveUnderPrefix.mockResolvedValue(0);+ // Run the share's `admit` hook the way the real reservation does: inside+ // the transaction, before anything is inserted.+ mockReserveUpload.mockImplementation(+ async (params: { admit?: (trx: unknown) => Promise<void>; size: number }) => {+ await params.admit?.({ trx: true });+ return { id: 'upload-1', size: params.size };+ },+ );+ });++ it("counts the share's settled files and live reservations inside the reservation transaction", async () => {+ mockFileCountAgentShareUsage.mockResolvedValue(500 * MB);+ mockUploadCountLiveUnderPrefix.mockResolvedValue(11 * MB);+ const caller = await createCaller();++ // 500 + 11 + 1 = 512 MB: exactly at the default cap is still admitted.+ await caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 1 * MB });++ expect(mockFileCountAgentShareUsage).toHaveBeenCalledWith('share-1', { trx: true });+ expect(mockUploadCountLiveUnderPrefix).toHaveBeenCalledWith(prefix, { trx: true });+ expect(mockCreatePreSignedUrl).toHaveBeenCalled();+ });++ it('serializes the cap decision on the share BEFORE counting, inside the same transaction', async () => {+ // The counts alone are racy: nothing row-locks a sum over two tables, and+ // the reservation's own users-row lock is taken after `admit`. Two+ // concurrent visitors must therefore queue on the share lock first.+ const order: string[] = [];+ mockLockUploadAdmission.mockImplementation(async () => {+ order.push('lock');+ });+ mockFileCountAgentShareUsage.mockImplementation(async () => {+ order.push('settled');+ return 0;+ });+ mockUploadCountLiveUnderPrefix.mockImplementation(async () => {+ order.push('reserved');+ return 0;+ });+ const caller = await createCaller();++ await caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 10 });++ expect(mockLockUploadAdmission).toHaveBeenCalledWith({ trx: true }, 'share-1');+ expect(order).toEqual(['lock', 'settled', 'reserved']);+ });++ it('rejects a zero-byte reservation even though it would add nothing to the cap sum', async () => {+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 0 }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockReserveUpload).not.toHaveBeenCalled();+ });++ it("refuses with a share_limit block once the share's upload space is used up", async () => {+ mockFileCountAgentShareUsage.mockResolvedValue(500 * MB);+ mockUploadCountLiveUnderPrefix.mockResolvedValue(11 * MB);+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 2 * MB }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'storage_block:share_limit' });+ expect(mockCreatePreSignedUrl).not.toHaveBeenCalled();+ });++ it('honours a creator-configured cap and turns attachments off at 0 before any reservation', async () => {+ mockAccessCheck.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, maxFileStorage: 0 },+ });+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 1 }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'storage_block:share_limit' });+ expect(mockReserveUpload).not.toHaveBeenCalled();+ });++ it('refuses even a request that clears the size pre-check when the cap is 0', async () => {+ // Guards the `maxFileStorage <= 0` branch on its own: a request whose size+ // slips past `size > maxFileStorage` (only possible at 0 with a size of 0,+ // which zod refuses, or via a future relaxation) must still be turned away.+ mockAccessCheck.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, maxFileStorage: -1 },+ });+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 1 }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'storage_block:share_limit' });+ expect(mockReserveUpload).not.toHaveBeenCalled();+ });++ it("reserves the upload under the CREATOR's storage quota and returns a share-prefixed key", async () => {+ const caller = await createCaller();++ const result = await caller.createUploadUrl({+ name: 'cat.png',+ shareId: 'share-1',+ size: 10,+ });++ expect(result.pathname.startsWith(prefix)).toBe(true);+ expect(result.pathname.endsWith('/cat.png')).toBe(true);+ expect(result.url).toBe('https://s3/put');+ // The quota that pays is the one reserved: creator, never the visitor.+ expect(FileUploadModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(mockReserveUpload).toHaveBeenCalledWith(+ expect.objectContaining({ pathname: result.pathname, size: 10, userId: OWNER }),+ );+ expect(mockReserveUpload.mock.calls[0][0].workspaceId).toBeUndefined();+ expect(mockCreatePreSignedUrl).toHaveBeenCalledWith(result.pathname, 10);+ });++ it('keeps a visitor-supplied name from steering the key out of the share prefix', async () => {+ const caller = await createCaller();++ const result = await caller.createUploadUrl({+ name: '../../etc/passwd',+ shareId: 'share-1',+ size: 1,+ });++ expect(result.pathname.startsWith(prefix)).toBe(true);+ expect(result.pathname.endsWith('/.._.._etc_passwd')).toBe(true);+ });++ it("collapses the creator's storage_block reason to a visitor-safe code and never reaches S3", async () => {+ // The original reason describes the creator's billing state — a+ // stranger with the link must not learn it.+ mockReserveUpload.mockRejectedValue(+ new TRPCError({ code: 'FORBIDDEN', message: 'storage_block:subscription_past_due' }),+ );+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 10 }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'storage_block:creator_quota' });+ expect(mockCreatePreSignedUrl).not.toHaveBeenCalled();+ });++ it('passes other reservation failures through untouched', async () => {+ mockReserveUpload.mockRejectedValue(+ new TRPCError({ code: 'CONFLICT', message: 'Upload pathname is already reserved' }),+ );+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 10 }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'Upload pathname is already reserved' });+ });++ it('releases the reservation when minting the pre-signed URL fails', async () => {+ mockCreatePreSignedUrl.mockRejectedValue(new Error('s3 down'));+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 10 }),+ ).rejects.toThrow('s3 down');+ expect(mockUploadReleaseBestEffort).toHaveBeenCalledWith(+ expect.stringMatching(new RegExp(`^${prefix}`)),+ );+ });++ it('rejects a file over SHARE_VISITOR_MAX_FILE_SIZE at the schema', async () => {+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'big.bin', shareId: 'share-1', size: 33 * 1024 * 1024 }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockReserveUpload).not.toHaveBeenCalled();+ });++ it('is refused on a private share like every other visitor procedure', async () => {+ mockAccessCheck.mockResolvedValue({ ...share, visibility: 'private' });+ const caller = await createCaller();++ await expect(+ caller.createUploadUrl({ name: 'cat.png', shareId: 'share-1', size: 10 }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockReserveUpload).not.toHaveBeenCalled();+ });+ });++ describe('createFile', () => {+ const pathname = `files/${OWNER}/agent-share/share-1/abc/cat.png`;+ const input = {+ fileType: 'image/png',+ metadata: { height: 2, ratio: 0.5, width: 1 },+ name: 'cat.png',+ pathname,+ shareId: 'share-1',+ size: 10,+ };++ beforeEach(() => {+ mockUploadTouchActive.mockResolvedValue({ id: 'upload-1', size: 10, status: 'active' });+ mockUploadFindLatestForUpdate.mockResolvedValue({+ id: 'upload-1',+ size: 10,+ status: 'active',+ });+ });++ it('writes a creator-owned agent_share row with the visitor in its provenance and settles the session', async () => {+ const caller = await createCaller();++ const result = await caller.createFile(input);++ expect(result).toEqual({ id: 'file-new', url: 'https://s3/get' });+ expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(mockFileCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: 'image/png',+ metadata: expect.objectContaining({+ agentShare: { shareId: 'share-1', visitorUserId: VISITOR },+ dirname: `files/${OWNER}/agent-share/share-1/abc`,+ filename: 'cat.png',+ height: 2,+ path: pathname,+ width: 1,+ }),+ 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(mockUploadSettle).toHaveBeenCalledWith('upload-1', 'file-new', expect.anything());+ });++ it('ignores a client-supplied hash instead of registering the object for dedup', async () => {+ const caller = await createCaller();++ await caller.createFile({ ...input, hash: 'h'.repeat(64) } as typeof input);++ expect(mockFileCreate.mock.calls[0][0]).not.toHaveProperty('fileHash');+ expect(mockFileCreate.mock.calls[0][1]).toBe(false);+ });++ it('refuses a pathname outside the share prefix (a creator-owned reservation)', async () => {+ const caller = await createCaller();++ await expect(+ caller.createFile({ ...input, pathname: `files/${OWNER}/2026/own.png` }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'Upload not found' });+ expect(mockUploadTouchActive).not.toHaveBeenCalled();+ expect(mockFileCreate).not.toHaveBeenCalled();+ });++ it("refuses another share's prefix even for the same creator", async () => {+ const caller = await createCaller();++ await expect(+ caller.createFile({ ...input, pathname: `files/${OWNER}/agent-share/share-2/abc/cat.png` }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockFileCreate).not.toHaveBeenCalled();+ });++ it('rejects when there is no active reservation (no legacy path for share uploads)', async () => {+ mockUploadTouchActive.mockResolvedValue(undefined);+ const caller = await createCaller();++ await expect(caller.createFile(input)).rejects.toMatchObject({ code: 'CONFLICT' });+ expect(mockFileCreate).not.toHaveBeenCalled();+ });++ it('releases the reservation when the stored object size does not match', async () => {+ mockGetFileMetadata.mockResolvedValue({ contentLength: 11 });+ const caller = await createCaller();++ await expect(caller.createFile(input)).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message: 'Uploaded file size mismatch',+ });+ expect(mockUploadReleaseBestEffort).toHaveBeenCalledWith(pathname);+ expect(mockFileCreate).not.toHaveBeenCalled();+ });++ it('drops unknown metadata keys at the schema so provenance can only be server-written', async () => {+ const caller = await createCaller();++ await caller.createFile({+ ...input,+ metadata: {+ ...input.metadata,+ agentShare: { shareId: 'share-1', visitorUserId: 'someone-else' },+ } as any,+ });++ expect(mockFileCreate.mock.calls[0][0].metadata.agentShare).toEqual({+ shareId: 'share-1',+ visitorUserId: VISITOR,+ });+ });+ });++ describe('abortUpload', () => {+ it('releases an active reservation under the share prefix', async () => {+ const pathname = `files/${OWNER}/agent-share/share-1/abc/cat.png`;+ mockUploadFindLatest.mockResolvedValue({ status: 'active' });+ const caller = await createCaller();++ await caller.abortUpload({ pathname, shareId: 'share-1' });++ expect(FileUploadServiceMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(mockUploadRelease).toHaveBeenCalledWith(pathname);+ });++ it("cannot release a reservation outside the share prefix (the creator's own upload)", async () => {+ const caller = await createCaller();++ await expect(+ caller.abortUpload({ pathname: `files/${OWNER}/2026/own.png`, shareId: 'share-1' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockUploadRelease).not.toHaveBeenCalled();+ });+ });++ 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({+ id: 'file-a',+ metadata: provenance,+ source: 'agent_share',+ });+ 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(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',+ });+ mockFileDeleteUnreferenced.mockResolvedValue(undefined);+ const caller = await createCaller();++ await caller.removeFile({ fileId: 'file-a', shareId: 'share-1' });++ expect(mockDeleteStoredFile).not.toHaveBeenCalled();+ });++ it("refuses the creator's own file and another visitor's share upload alike", 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();+ });+ });+describe('interruptTask', () => {it('interrupts a running operation that matches the topic ownership and running marker', async () => {const caller = await createCaller();diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex c4838e2bb96..cd576a2863a 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -1,9 +1,13 @@-import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';+import {+ AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,+ AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT,+} from '@lobechat/const';import { TRPCError } from '@trpc/server';import { z } from 'zod';import { getAgentShareMonthlySpend } from '@/business/server/agent-share/spendGate';import { AgentShareModel } from '@/database/models/agentShare';+import { FileModel } from '@/database/models/file';import { TopicModel } from '@/database/models/topic';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -37,6 +41,8 @@ export const agentShareConfigSchema = z.object({allowCreatorViewSessions: z.boolean().optional(),allowReadMemory: z.boolean().optional(),+ /** Bytes; `0` is a real value (attachments off), so non-negative rather than positive. */+ maxFileStorage: z.number().int().nonnegative().optional(),/*** The visitor topic list (`TopicModel.queryBySender`) is not paginated* and is bounded by `AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT`, so a cap@@ -121,18 +127,26 @@ export const agentShareRouter = router({* Visitor counts come from `topics.senderId` (set for share-originated* topics only); `monthlySpend` comes from the billing business slot and is* `null` in deployments that do not meter share spend, which the UI renders- * as "no spend data" rather than as zero.+ * as "no spend data" rather than as zero. `fileStorageUsed` is the settled+ * bytes visitors have uploaded through this share — the same sum+ * `shareChat.createUploadUrl` holds against `maxFileStorage` (minus+ * in-flight reservations, which are transient) — so the owner can see how+ * close the share is to its cap, including drafts visitors never sent.*/getShareStats: agentShareProcedure.input(agentIdInput).query(async ({ input, ctx }) => {const share = requireShare(await ctx.agentShareModel.getByAgentId(input.agentId));const topicModel = new TopicModel(ctx.serverDB, ctx.userId);- const [visitors, monthlySpend] = await Promise.all([+ const fileModel = new FileModel(ctx.serverDB, ctx.userId);+ const [visitors, monthlySpend, fileStorageUsed] = await Promise.all([topicModel.countShareVisitors({ agentId: input.agentId }),getAgentShareMonthlySpend({ agentId: input.agentId, ownerUserId: ctx.userId }),+ fileModel.countAgentShareUsage(share.id),]);return {+ fileStorageUsed,+ maxFileStorage: share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,monthlySpend,monthlySpendLimit: share.shareConfig.monthlySpendLimit,topicCount: visitors.topicCount,diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex d793a5d9702..5ad82126f5d 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -1,22 +1,91 @@import {+ AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,} from '@lobechat/const';-import { type SharedAgentData, type SharedTopicData } from '@lobechat/types';+import {+ type SharedAgentData,+ type SharedAgentUploadAbility,+ type SharedTopicData,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';+import type { ModelAbilities } from 'model-bank';import { z } from 'zod';import { AgentShareModel } from '@/database/models/agentShare';+import { AiModelModel } from '@/database/models/aiModel';import { TopicModel } from '@/database/models/topic';import { TopicShareModel } from '@/database/models/topicShare';+import type { LobeChatDatabase } from '@/database/type';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/resolveModelMediaCapabilities';+import { AgentService } from '@/server/services/agent';import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';const log = debug('lobe-server:router:share');+/**+ * What media a visitor may attach to a turn on this share.+ *+ * Mirrors the runtime's own check (`toolDiscovery` → `resolveModelMediaCapabilities`+ * with the OWNER's model overrides on top of the bundled list) so the composer+ * gate and the context builder agree — an image the composer accepts must be+ * one the run can actually feed to the model. Resolved as the owner because+ * the run executes as them; the visitor's own provider setup is irrelevant.+ *+ * The model itself is resolved the way the run resolves it+ * (`AgentService.resolveModelSelection`): an agent with no model of its own+ * runs on the OWNER's default agent config, not on the global default, so+ * the gate has to look at that model too.+ *+ * Fails closed on lookup errors: media silently dropped server-side is worse+ * than a composer that refuses it with a reason. Documents never go through+ * this gate.+ */+const resolveVisitorUploadAbility = async (+ db: LobeChatDatabase,+ share: { agentModel: string | null; agentProvider: string | null; ownerId: string },+): Promise<SharedAgentUploadAbility> => {+ try {+ const { loadModels } = await import('@/business/client/model-bank/loadModels');+ const [builtinModels, { model, provider }] = await Promise.all([+ loadModels(),+ new AgentService(db, share.ownerId).resolveModelSelection({+ model: share.agentModel,+ provider: share.agentProvider,+ }),+ ]);+ const ownerModel = await new AiModelModel(db, share.ownerId).findByIdAndProvider(+ model,+ provider,+ );+ const abilities = resolveModelMediaCapabilities({+ builtinModels,+ model,+ provider,+ userAbilities: ownerModel?.abilities as ModelAbilities | undefined,+ });++ return {+ audio: abilities?.audio === true,+ image: abilities?.vision === true,+ video: abilities?.video === true,+ };+ } catch (error) {+ log(+ 'failed to resolve upload ability for %s/%s (owner %s): %O',+ share.agentProvider,+ share.agentModel,+ share.ownerId,+ error,+ );+ return { audio: false, image: false, video: false };+ }+};+export const shareRouter = router({/*** Resolve the visitor-facing metadata for an agent share, by its custom@@ -63,13 +132,18 @@ export const shareRouter = router({// them. Best-effort — analytics must never turn a valid share page into// an error.let stats = { conversations: 0, visitors: 0 };- try {- const topicModel = new TopicModel(ctx.serverDB, share.ownerId);- const counts = await topicModel.countShareVisitors({ agentId: share.agentId });- stats = { conversations: counts.topicCount, visitors: counts.visitorCount };- } catch (error) {- log('failed to count share visitors for %s: %O', share.shareId, error);- }+ const [uploadAbility] = await Promise.all([+ resolveVisitorUploadAbility(ctx.serverDB, share),+ (async () => {+ try {+ const topicModel = new TopicModel(ctx.serverDB, share.ownerId);+ const counts = await topicModel.countShareVisitors({ agentId: share.agentId });+ stats = { conversations: counts.topicCount, visitors: counts.visitorCount };+ } catch (error) {+ log('failed to count share visitors for %s: %O', share.shareId, error);+ }+ })(),+ ]);return {agentId: share.agentId,@@ -92,6 +166,7 @@ export const shareRouter = router({stats: { ...stats, views: share.userViewCount },terms: {allowCreatorViewSessions: share.shareConfig.allowCreatorViewSessions ?? false,+ maxFileStorage: share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,maxTopicsPerVisitor:share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,maxTurnsPerTopic:@@ -100,6 +175,7 @@ export const shareRouter = router({// Identifiers only. The granted API list is owner-facing configuration// and must not reach a visitor.toolGrants: (share.shareConfig.toolGrants ?? []).map((grant) => grant.identifier),+ uploadAbility,// TODO(cloud budget gate): the spend gate itself is already enforced —// `shareChat.execAgent` checks `checkAgentShareSpendAllowance` before// dispatching a run. This READ-ONLY endpoint just doesn't yet exposediff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex 7175f8c9512..ebf6a1aad04 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -1,16 +1,24 @@import {+ AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ SHARE_UPLOAD_STORAGE_BLOCK_PREFIX,+ SHARE_VISITOR_MAX_FILE_SIZE,+ SHARE_VISITOR_MAX_FILES_PER_TURN,SHARE_VISITOR_PROMPT_MAX_LENGTH,} from '@lobechat/const';import type { ChatMessageError } from '@lobechat/types';-import { ChatErrorType, entityIdPattern, RequestTrigger } from '@lobechat/types';+import { ChatErrorType, entityIdPattern, FileSource, RequestTrigger } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';import { TRPCError } from '@trpc/server';import debug from 'debug';import { z } from 'zod';import { checkAgentShareSpendAllowance } from '@/business/server/agent-share/spendGate';+import { serverDBEnv } from '@/config/db';import { AgentShareModel } from '@/database/models/agentShare';+import { FileModel } from '@/database/models/file';+import { FileUploadModel } from '@/database/models/fileUpload';import { MessageModel, sanitizeVisitorError } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';@@ -18,9 +26,12 @@ import type { LobeChatDatabase } from '@/database/type';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { signUserJWT } from '@/libs/trpc/utils/internalJwt';+import { FileS3 } from '@/server/modules/S3';import { AiAgentService } from '@/server/services/aiAgent';import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';import { FileService } from '@/server/services/file';+import { FileUploadService } from '@/server/services/fileUpload';+import { reserveUpload } from '@/server/services/fileUploadReservation';import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';@@ -198,7 +209,309 @@ const authorizeVisitorRunningOperation = async (return { aiAgentService, share };};+/**+ * Storage key prefix for a share's visitor uploads, under the CREATOR's file+ * namespace. The prefix is what ties an upload session / file row back to a+ * specific share on the settle and abort paths: a visitor can only complete or+ * release reservations that live under their share's prefix, never one of the+ * creator's own uploads.+ */+const shareUploadPrefix = (ownerId: string, shareId: string) =>+ `files/${ownerId}/agent-share/${shareId}/`;++/**+ * Visitor-facing storage refusal, one shape for two causes: the share's own+ * `maxFileStorage` cap (`share_limit`), or the creator's account-level block+ * from the deployment's upload check (`creator_quota`). The latter's original+ * reason describes the creator's billing state; it is collapsed here because+ * a stranger with the link must not learn it, and the visitor's remedy is the+ * same either way. The client matches only the prefix.+ */+const shareStorageBlocked = (cause: 'creator_quota' | 'share_limit') =>+ new TRPCError({ code: 'FORBIDDEN', message: `${SHARE_UPLOAD_STORAGE_BLOCK_PREFIX}${cause}` });++const toVisitorStorageBlock = (error: unknown) => {+ if (+ error instanceof TRPCError &&+ error.code === 'FORBIDDEN' &&+ error.message.startsWith(SHARE_UPLOAD_STORAGE_BLOCK_PREFIX) &&+ error.message !== `${SHARE_UPLOAD_STORAGE_BLOCK_PREFIX}share_limit`+ ) {+ log('creator storage block collapsed for visitor: %s', error.message);+ return shareStorageBlocked('creator_quota');+ }+ return error;+};++/** Basename only — a visitor-supplied name must not steer the storage key. */+const sanitizeUploadName = (name: string) =>+ name+ .replaceAll(/[/\\]/g, '_')+ .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+ * under the creator's account, so a creator-scoped lookup would happily+ * resolve any of the creator's files — the `agentShare` provenance on the row+ * is the only thing that stops a visitor from naming an arbitrary id and+ * having the creator's own document injected into the run. `NOT_FOUND` on+ * purpose — same fail-closed shape as the topic guard, revealing nothing+ * about whether the id exists for someone else.+ */+const assertShareVisitorFiles = async (+ db: LobeChatDatabase,+ share: { ownerId: string; shareId: string },+ visitorUserId: string,+ fileIds: string[] | undefined,+) => {+ 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) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ }+};++/**+ * Metadata a visitor may attach to their upload — the same intrinsic+ * image/audio facts the owner upload path records client-side, so share+ * attachments render (dimensions, duration) exactly like owner ones. Anything+ * else (notably `agentShare`) is server-written.+ */+const ShareUploadMetadataSchema = z+ .object({+ codec: z.string().max(64),+ durationMs: z.number().nonnegative(),+ height: z.number().positive(),+ mimeType: z.string().max(255),+ ratio: z.number().positive(),+ width: z.number().positive(),+ })+ .partial();+export const shareChatRouter = router({+ /**+ * Release a share upload reservation the visitor abandoned (PUT failed or+ * was cancelled). Scoped to the share's own key prefix so a visitor cannot+ * release one of the creator's in-flight uploads.+ */+ abortUpload: shareChatProcedure+ .input(z.object({ pathname: z.string().min(1), shareId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);+ if (!input.pathname.startsWith(shareUploadPrefix(share.ownerId, share.shareId))) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });+ }++ const fileUploadService = new FileUploadService(ctx.serverDB, share.ownerId);+ const upload = await fileUploadService.findLatest(input.pathname);+ if (upload?.status === 'active') await fileUploadService.release(input.pathname);++ return { success: true };+ }),++ /**+ * Settle a share upload into a file row — the visitor counterpart of+ * `file.createFile`.+ *+ * 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+ * `metadata.agentShare` provenance every share read/write path checks.+ *+ * Deliberately simpler than the owner path: no knowledge base / parent+ * folder / visibility, and no content hash at all. Every share upload is its+ * own object under its own reserved key, so the row must stay OUT of the+ * hash-keyed `global_files` dedup graph: a row registered there with a hash+ * some other file already holds would have its object skipped by the+ * refcount in `FileModel.delete` and orphaned in storage on `removeFile`+ * (with the visitor never able to see or free it), while its share-cap bytes+ * were released. A visitor attachment is only ever reached through the+ * message it was sent with, so nothing needs the hash.+ */+ createFile: shareChatProcedure+ .input(+ z.object({+ fileType: z.string().min(1).max(255),+ metadata: ShareUploadMetadataSchema.optional(),+ name: z.string().min(1).max(255),+ pathname: z.string().min(1),+ shareId: z.string(),+ size: z.number().int().min(0).max(SHARE_VISITOR_MAX_FILE_SIZE),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);+ if (!input.pathname.startsWith(shareUploadPrefix(share.ownerId, share.shareId))) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });+ }++ const fileUploadService = new FileUploadService(ctx.serverDB, share.ownerId);+ const fileService = new FileService(ctx.serverDB, share.ownerId);++ // No legacy (reservation-less) path here: the share upload flow was born+ // with reservations, so a pathname without an active session is either+ // expired, already settled, or never ours.+ const activeUpload = await fileUploadService.touchActive(input.pathname);+ if (!activeUpload) {+ throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });+ }++ let actualSize: number;+ try {+ actualSize = (await fileService.getFileMetadata(input.pathname)).contentLength;+ } catch {+ await fileUploadService.releaseBestEffort(input.pathname);+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Uploaded file is unavailable' });+ }+ if (input.size !== activeUpload.size || actualSize !== activeUpload.size) {+ await fileUploadService.releaseBestEffort(input.pathname);+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Uploaded file size mismatch' });+ }++ const parts = input.pathname.split('/');+ const filename = parts.pop()!;+ const dirname = parts.join('/');++ const { id } = await ctx.serverDB.transaction(async (trx) => {+ const lockedUpload = await fileUploadService.model.findLatestByPathnameForUpdate(+ input.pathname,+ trx,+ );+ if (lockedUpload?.id !== activeUpload.id || lockedUpload.status !== 'active') {+ throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });+ }++ const file = await new FileModel(ctx.serverDB, share.ownerId).create(+ {+ fileType: input.fileType,+ metadata: {+ ...input.metadata,+ agentShare: { shareId: share.shareId, visitorUserId: ctx.userId },+ date: new Date().toISOString().slice(0, 10),+ dirname,+ filename,+ path: input.pathname,+ },+ name: sanitizeUploadName(input.name),+ size: actualSize,+ source: FileSource.AgentShare,+ url: input.pathname,+ },+ false,+ trx,+ );++ const settled = await fileUploadService.model.settle(lockedUpload.id, file.id, trx);+ if (!settled) {+ throw new TRPCError({ code: 'CONFLICT', message: 'Upload could not be settled' });+ }+ return file;+ });++ log('createFile: share=%s visitor=%s file=%s', input.shareId, ctx.userId, id);++ return { id, url: await fileService.getFileAccessUrl({ id, url: input.pathname }) };+ }),++ /**+ * Reserve storage and mint a pre-signed PUT for a visitor attachment — the+ * visitor counterpart of `upload.createS3PreSignedUrl`.+ *+ * The reservation is taken under the CREATOR: the bytes count against the+ * creator's storage quota, so it is the creator's `storage_block:*` reason+ * (not the visitor's plan) that decides whether the upload is admitted. The+ * key lives under the share's own prefix so `createFile` / `abortUpload` can+ * prove the session belongs to this share.+ */+ createUploadUrl: shareChatProcedure+ .input(+ z.object({+ name: z.string().min(1).max(255),+ shareId: z.string(),+ // `min(1)` is load-bearing beyond validation: the reservation runs the+ // size through the deployment's upload check AS THE CREATOR, so a+ // visitor-supplied negative size must never reach it — and a zero-byte+ // reservation adds nothing to the cap sum, so it would let unbounded+ // rows (and objects) pile up under the creator's prefix.+ size: z.number().int().min(1).max(SHARE_VISITOR_MAX_FILE_SIZE),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const maxFileStorage =+ share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE;+ // Cheap pre-check before any storage round-trip; the real, race-free+ // check is `admit` below. `<= 0` is the creator turning attachments off+ // and refuses regardless of size.+ if (maxFileStorage <= 0 || input.size > maxFileStorage) {+ throw shareStorageBlocked('share_limit');+ }++ const prefix = shareUploadPrefix(share.ownerId, share.shareId);+ const pathname = `${prefix}${nanoid()}/${sanitizeUploadName(input.name)}`;+ const s3 = new FileS3();+ const uploadModel = new FileUploadModel(ctx.serverDB, share.ownerId);+ const fileModel = new FileModel(ctx.serverDB, share.ownerId);++ try {+ await reserveUpload({+ // The share's own cap: settled visitor files plus every live+ // reservation under the share prefix, counted inside the reservation+ // transaction. The counts alone are not race-free (the reservation's+ // own row lock comes after this hook), so the decision is serialized+ // per share first — see `AgentShareModel.lockUploadAdmission`.+ admit: async (transaction) => {+ await AgentShareModel.lockUploadAdmission(transaction, share.shareId);+ const settled = await fileModel.countAgentShareUsage(share.shareId, transaction);+ const reserved = await uploadModel.countLiveUsageUnderPrefix(prefix, transaction);+ if (settled + reserved + input.size > maxFileStorage) {+ throw shareStorageBlocked('share_limit');+ }+ },+ clientIp: ctx.clientIp ?? undefined,+ db: ctx.serverDB,+ model: uploadModel,+ pathname,+ size: input.size,+ storage: s3,+ userId: share.ownerId,+ });+ } catch (error) {+ throw toVisitorStorageBlock(error);+ }++ try {+ return { pathname, url: await s3.createPreSignedUrl(pathname, input.size) };+ } catch (error) {+ await new FileUploadService(ctx.serverDB, share.ownerId).releaseBestEffort(pathname);+ throw error;+ }+ }),+/*** Execute a shared agent as a visitor — the gateway-transport mirror of* `aiAgent.execAgent`, restricted to the share surface: fixed agent, no@@ -215,6 +528,15 @@ export const shareChatRouter = router({userMessageId: z.string().regex(entityIdPattern('messages')).optional(),}).optional(),+ /**+ * Ids of files the VISITOR uploaded through `shareChat.createFile`.+ * Re-checked below against the file rows' share provenance — see+ * `assertShareVisitorFiles`.+ */+ fileIds: z+ .array(z.string().min(1).max(64))+ .max(SHARE_VISITOR_MAX_FILES_PER_TURN)+ .optional(),/** See `SHARE_VISITOR_PROMPT_MAX_LENGTH`'s JSDoc for the size-bound rationale. */prompt: z.string().max(SHARE_VISITOR_PROMPT_MAX_LENGTH),shareId: z.string(),@@ -245,6 +567,12 @@ export const shareChatRouter = router({});}+ // Verify every attachment is this visitor's own share upload before it+ // is handed to a run that executes (and reads files) as the creator.+ // Also ahead of any row creation, like the spend gate — a foreign id+ // must not leave a topic behind.+ await assertShareVisitorFiles(ctx.serverDB, share, ctx.userId, input.fileIds);+// Runtime-normalized (findByShareIdWithAccessCheck fills defaults), but// the config TYPE keeps every field optional — re-apply the same default// constants rather than asserting non-null.@@ -338,6 +666,9 @@ export const shareChatRouter = router({appContext: { topicId: input.topicId },clientIds: input.clientIds,clientIp: ctx.clientIp ?? undefined,+ // Share uploads are creator-owned rows (see `createFile` below), so+ // the creator-scoped runtime resolves them like any owner attachment.+ fileIds: input.fileIds,// `interactiveStart: true` (the `aiAgent.execAgent` owner path's// default) makes `TopicModel.tryReserveTaskCallback` skip its// `runningOperation` liveness check entirely — a policy that is safe@@ -599,6 +930,40 @@ export const shareChatRouter = router({return { token };}),++ /**+ * Drop a share upload the visitor removed from their draft before sending.+ * Only the uploading visitor's own share files qualify (provenance check),+ * 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.+ */+ removeFile: shareChatProcedure+ .input(z.object({ fileId: z.string().min(1).max(64), shareId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ 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) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ }++ const file = await fileModel.deleteUnreferenced(+ input.fileId,+ serverDBEnv.REMOVE_GLOBAL_FILE,+ {+ exclusiveStorage: true,+ },+ );+ if (!file) return;++ await new FileService(ctx.serverDB, share.ownerId).deleteFile(file.url!);+ }),});export type ShareChatRouter = typeof shareChatRouter;diff --git a/apps/server/src/routers/lambda/upload.ts b/apps/server/src/routers/lambda/upload.tsindex 522f45c6aae..8a3fa77e87b 100644--- a/apps/server/src/routers/lambda/upload.ts+++ b/apps/server/src/routers/lambda/upload.ts@@ -1,17 +1,14 @@import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';import type { FileUploadItem } from '@lobechat/database/schemas';-import { TRPCError } from '@trpc/server';import { z } from 'zod';-import { businessFileUploadCheck } from '@/business/server/lambda-routers/file';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';-import type { FileUploadModel } from '@/database/models/fileUpload';-import type { LobeChatDatabase, Transaction } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileS3 } from '@/server/modules/S3';-import { FILE_UPLOAD_SESSION_TTL, FileUploadService } from '@/server/services/fileUpload';+import { FileUploadService } from '@/server/services/fileUpload';+import { reserveUpload, uploadConflict } from '@/server/services/fileUploadReservation';const MAX_MULTIPART_PARTS = 10_000;const MULTIPART_PART_SIZE = 32 * 1024 * 1024;@@ -47,88 +44,6 @@ const uploadProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =});});-const uploadConflict = (message: string) => new TRPCError({ code: 'CONFLICT', message });--const matchesReservation = (- upload: FileUploadItem | undefined,- params: { multipartPartSize?: number; size: number },-) =>- upload?.size === params.size && upload.multipartPartSize === (params.multipartPartSize ?? null);--const isMissingObject = (error: unknown) => {- if (!error || typeof error !== 'object') return false;- const value = error as { $metadata?: { httpStatusCode?: number }; name?: string };- return value.name === 'NotFound' || value.$metadata?.httpStatusCode === 404;-};--const reserveUpload = async (params: {- clientIp?: string;- db: LobeChatDatabase;- model: FileUploadModel;- multipartPartSize?: number;- pathname: string;- size: number;- storage: Pick<FileS3, 'getFileMetadata'>;- userId: string;- workspaceId?: string | null;-}): Promise<FileUploadItem> => {- const expiresAt = new Date(Date.now() + FILE_UPLOAD_SESSION_TTL);-- return params.db.transaction(async (transaction: Transaction) => {- const existing = await params.model.findActiveByPathname(params.pathname, transaction);- if (existing) {- if (!matchesReservation(existing, params)) {- throw uploadConflict('Upload pathname is already reserved');- }-- return (await params.model.touchActive(params.pathname, expiresAt, transaction))!;- }-- // A reservation authorizes deleting its own pathname on abort, so it must never be- // granted over an object that already exists and therefore belongs to someone else.- const objectExists = await params.storage- .getFileMetadata(params.pathname)- .then(() => true)- .catch((error: unknown) => {- if (isMissingObject(error)) return false;- throw error;- });- if (objectExists) throw uploadConflict('Upload pathname is already in use');-- try {- await businessFileUploadCheck({- actualSize: params.size,- clientIp: params.clientIp,- inputSize: params.size,- transaction,- url: params.pathname,- userId: params.userId,- workspaceId: params.workspaceId,- });- } catch (error) {- const concurrent = await params.model.findActiveByPathname(params.pathname, transaction);- if (matchesReservation(concurrent, params)) return concurrent!;- throw error;- }-- const created = await params.model.create(- {- expiresAt,- multipartPartSize: params.multipartPartSize,- pathname: params.pathname,- size: params.size,- },- transaction,- );- if (created) return created;-- const concurrent = await params.model.findActiveByPathname(params.pathname, transaction);- if (matchesReservation(concurrent, params)) return concurrent!;-- throw uploadConflict('Upload pathname is already reserved');- });-};-const getMultipartPartSize = (size: number) =>Math.max(MULTIPART_PART_SIZE, Math.ceil(size / MAX_MULTIPART_PARTS));diff --git a/apps/server/src/services/agent/index.test.ts b/apps/server/src/services/agent/index.test.tsindex 7eca0fba9f3..103f14badb2 100644--- a/apps/server/src/services/agent/index.test.ts+++ b/apps/server/src/services/agent/index.test.ts@@ -480,6 +480,53 @@ describe('AgentService', () => {});});+ describe('resolveModelSelection', () => {+ it("layers the user's default over the server default for an agent without a model", async () => {+ (parseAgentConfig as any).mockReturnValue({ model: 'server-model', provider: 'server' });+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValueOnce({+ config: { model: 'user-preferred-model', provider: 'user-provider' },+ });++ await expect(service.resolveModelSelection({ model: null, provider: null })).resolves.toEqual(+ { model: 'user-preferred-model', provider: 'user-provider' },+ );+ });++ it('falls back to the server default, then the hardcoded default, without a user default', async () => {+ (parseAgentConfig as any).mockReturnValue({ model: 'server-model' });+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValueOnce(undefined);++ await expect(service.resolveModelSelection({})).resolves.toEqual({+ model: 'server-model',+ provider: DEFAULT_AGENT_CONFIG.provider,+ });+ });++ it("keeps the agent's own model over every default", async () => {+ (parseAgentConfig as any).mockReturnValue({ model: 'server-model', provider: 'server' });+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValueOnce({+ config: { model: 'user-preferred-model', provider: 'user-provider' },+ });++ await expect(+ service.resolveModelSelection({ model: 'claude-3-opus', provider: 'anthropic' }),+ ).resolves.toEqual({ model: 'claude-3-opus', provider: 'anthropic' });+ });++ it('does not let a workspace agent inherit a personal default model', async () => {+ (parseAgentConfig as any).mockReturnValue({});+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValueOnce({+ config: { model: 'user-preferred-model', provider: 'user-provider' },+ });+ const workspaceService = new AgentService(mockDb, mockUserId, mockWorkspaceId);++ await expect(workspaceService.resolveModelSelection({})).resolves.toEqual({+ model: DEFAULT_AGENT_CONFIG.model,+ provider: DEFAULT_AGENT_CONFIG.provider,+ });+ });+ });+describe('getAgentConfigById', () => {it('should return null if agent does not exist', async () => {const mockAgentModel = {diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.tsindex 0b4610695ef..e161bf1a0b3 100644--- a/apps/server/src/services/agent/index.ts+++ b/apps/server/src/services/agent/index.ts@@ -1,6 +1,7 @@import { type BuiltinAgentSlug } from '@lobechat/builtin-agents';import { BUILTIN_AGENTS } from '@lobechat/builtin-agents';-import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';+import { DEFAULT_PROVIDER } from '@lobechat/business-const';+import { DEFAULT_AGENT_CONFIG, DEFAULT_MODEL } from '@lobechat/const';import { type LobeChatDatabase } from '@lobechat/database';import { type AgentItem, type LobeAgentChatConfig, type LobeAgentConfig } from '@lobechat/types';import { cleanObject, merge } from '@lobechat/utils';@@ -180,6 +181,29 @@ export class AgentService {return normalizedConfig;}+ /**+ * The model and provider a run of this agent actually uses: the same+ * `DEFAULT_AGENT_CONFIG` → server default → user default → agent layering+ * as {@link getAgentConfig}, narrowed to those two fields. For read paths+ * that only need to know which model will answer (deriving what media a+ * share visitor may attach, for instance) without loading the agent's+ * knowledge and documents.+ */+ async resolveModelSelection(agent: {+ model?: string | null;+ provider?: string | null;+ }): Promise<{ model: string; provider: string }> {+ const defaultAgentConfig = await this.userModel.getUserSettingsDefaultAgentConfig();+ const merged = this.mergeDefaultConfig(+ { model: agent.model, provider: agent.provider },+ defaultAgentConfig,+ )!;++ // `LobeAgentConfig` types both as optional even though `DEFAULT_AGENT_CONFIG`+ // always supplies them; the fallbacks are those same constants.+ return { model: merged.model ?? DEFAULT_MODEL, provider: merged.provider ?? DEFAULT_PROVIDER };+ }+/*** Get AI-generated welcome data from Redis* Returns null if Redis is disabled or data doesn't existdiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.tsnew file mode 100644index 00000000000..97ea60f312c--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorFiles.test.ts@@ -0,0 +1,260 @@+import type * as ModelBankModule from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++const {+ mockCreateOperation,+ mockGetAgentConfig,+ mockGetUserSettings,+ mockMessageCreate,+ mockReserveShareVisitorTurn,+ mockResolveAttachmentsByFileIds,+} = vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockGetAgentConfig: vi.fn(),+ mockGetUserSettings: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockReserveShareVisitorTurn: vi.fn(),+ 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.+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn().mockImplementation(function () {+ return { findByIds: vi.fn().mockResolvedValue([]) };+ }),+}));++vi.mock('@/server/services/file/resolveAttachments', () => ({+ resolveAttachmentsByFileIds: mockResolveAttachmentsByFileIds,+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ };+ }),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn(),+ queryAgents: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: mockGetAgentConfig,+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return {+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),+ };+ }),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ }),+}));++// `UserModel` here is what actually resolves `userTimezone`. Constructed with+// the userId it was called with, so the test can distinguish "read the+// creator's settings" from "read the visitor's settings" purely by which id+// the call site passed in.+vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function (_db: unknown, userId: string) {+ return {+ getUserPreference: vi.fn().mockResolvedValue({}),+ getUserSettings: () => mockGetUserSettings(userId),+ };+ }),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ createOperation: mockCreateOperation,+ };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(function () {+ return {+ getComposioManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {+ uploadFromUrl: vi.fn(),+ };+ }),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++// The share path's atomic cap reservations open real DB transactions — stub+// them so the forced-headless test below can drive execAgent with a bare mock db.+vi.mock('../shareVisitorAbuseGuards', () => ({+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ reserveShareVisitorTurn: mockReserveShareVisitorTurn,+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++describe('AiAgentService.execAgent - share-visitor attachment scope', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const creatorId = 'creator-1';+ const visitorId = 'visitor-1';++ beforeEach(() => {+ vi.clearAllMocks();+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ });+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: '',+ });+ mockGetUserSettings.mockResolvedValue({});+ mockReserveShareVisitorTurn.mockResolvedValue({ id: 'msg-1' });+ mockResolveAttachmentsByFileIds.mockResolvedValue({+ audioList: [],+ fileList: [],+ imageList: [{ alt: 'cat.png', id: 'file-visitor', url: 'https://s3/cat.png' }],+ orderedFileIds: ['file-visitor'],+ videoList: [],+ warnings: [],+ });+ service = new AiAgentService(mockDb, creatorId);+ });++ it('resolves attachments under the CREATOR on a normal run', async () => {+ await service.execAgent({ agentId: 'agent-1', fileIds: ['file-own'], prompt: 'Hello' });++ expect(mockResolveAttachmentsByFileIds).toHaveBeenCalledWith(+ expect.objectContaining({ fileIds: ['file-own'], userId: creatorId }),+ );+ });++ it('resolves attachments under the CREATOR on a share-visitor run too, and attaches them to the turn', async () => {+ // Share uploads are creator-owned rows (`shareChat.createFile` writes them+ // under the creator with share provenance), so the run resolves them in+ // the same scope it executes in — never under the visitor, whose own+ // account holds no share files at all.+ await service.execAgent({+ agentId: 'agent-1',+ fileIds: ['file-visitor'],+ prompt: 'Hello',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: visitorId,+ },+ });++ expect(mockResolveAttachmentsByFileIds).toHaveBeenCalledWith(+ expect.objectContaining({ fileIds: ['file-visitor'], userId: creatorId }),+ );+ expect(mockResolveAttachmentsByFileIds).not.toHaveBeenCalledWith(+ expect.objectContaining({ userId: visitorId }),+ );+ // The resolved ids are stamped on the visitor's user message row (persisted+ // under the creator via the turn reservation), so the message-file+ // relation exists for the visitor's own read-back.+ expect(mockReserveShareVisitorTurn).toHaveBeenCalledWith(+ expect.objectContaining({ ownerId: creatorId }),+ expect.objectContaining({ files: ['file-visitor'], role: 'user' }),+ undefined,+ );+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/fileUploadReservation.ts b/apps/server/src/services/fileUploadReservation.tsnew file mode 100644index 00000000000..0aee6eda6a3--- /dev/null+++ b/apps/server/src/services/fileUploadReservation.ts@@ -0,0 +1,109 @@+import type { FileUploadItem } from '@lobechat/database/schemas';+import { TRPCError } from '@trpc/server';++import { businessFileUploadCheck } from '@/business/server/lambda-routers/file';+import type { FileUploadModel } from '@/database/models/fileUpload';+import type { LobeChatDatabase, Transaction } from '@/database/type';+import type { FileS3 } from '@/server/modules/S3';+import { FILE_UPLOAD_SESSION_TTL } from '@/server/services/fileUpload';++export const uploadConflict = (message: string) => new TRPCError({ code: 'CONFLICT', message });++const matchesReservation = (+ upload: FileUploadItem | undefined,+ params: { multipartPartSize?: number; size: number },+) =>+ upload?.size === params.size && upload.multipartPartSize === (params.multipartPartSize ?? null);++const isMissingObject = (error: unknown) => {+ if (!error || typeof error !== 'object') return false;+ const value = error as { $metadata?: { httpStatusCode?: number }; name?: string };+ return value.name === 'NotFound' || value.$metadata?.httpStatusCode === 404;+};++/**+ * Reserve an upload pathname for `params.userId` before any credentials are+ * issued: serializes the storage-quota check with the reservation insert so+ * concurrent uploads cannot both slip under the cap.+ *+ * Shared between the owner upload router (`upload.createS3PreSignedUrl` /+ * `createS3MultipartUpload`) and the agent-share visitor upload+ * (`shareChat.createUploadUrl`), where `userId` is the CREATOR rather than the+ * caller — the quota that pays for the bytes is the one that gets reserved.+ */+export const reserveUpload = async (params: {+ /**+ * Caller-specific admission (e.g. the agent-share upload cap), run inside+ * the same serialized transaction as the quota check so two concurrent+ * reservations cannot both slip under a cap that counts live reservations.+ * Throw to refuse; nothing has been inserted yet.+ */+ admit?: (transaction: Transaction) => Promise<void>;+ clientIp?: string;+ db: LobeChatDatabase;+ model: FileUploadModel;+ multipartPartSize?: number;+ pathname: string;+ size: number;+ storage: Pick<FileS3, 'getFileMetadata'>;+ userId: string;+ workspaceId?: string | null;+}): Promise<FileUploadItem> => {+ const expiresAt = new Date(Date.now() + FILE_UPLOAD_SESSION_TTL);++ return params.db.transaction(async (transaction: Transaction) => {+ const existing = await params.model.findActiveByPathname(params.pathname, transaction);+ if (existing) {+ if (!matchesReservation(existing, params)) {+ throw uploadConflict('Upload pathname is already reserved');+ }++ return (await params.model.touchActive(params.pathname, expiresAt, transaction))!;+ }++ // A reservation authorizes deleting its own pathname on abort, so it must never be+ // granted over an object that already exists and therefore belongs to someone else.+ const objectExists = await params.storage+ .getFileMetadata(params.pathname)+ .then(() => true)+ .catch((error: unknown) => {+ if (isMissingObject(error)) return false;+ throw error;+ });+ if (objectExists) throw uploadConflict('Upload pathname is already in use');++ await params.admit?.(transaction);++ try {+ await businessFileUploadCheck({+ actualSize: params.size,+ clientIp: params.clientIp,+ inputSize: params.size,+ transaction,+ url: params.pathname,+ userId: params.userId,+ workspaceId: params.workspaceId,+ });+ } catch (error) {+ const concurrent = await params.model.findActiveByPathname(params.pathname, transaction);+ if (matchesReservation(concurrent, params)) return concurrent!;+ throw error;+ }++ const created = await params.model.create(+ {+ expiresAt,+ multipartPartSize: params.multipartPartSize,+ pathname: params.pathname,+ size: params.size,+ },+ transaction,+ );+ if (created) return created;++ const concurrent = await params.model.findActiveByPathname(params.pathname, transaction);+ if (matchesReservation(concurrent, params)) return concurrent!;++ throw uploadConflict('Upload pathname is already reserved');+ });+};diff --git a/apps/workbench/vite.config.rr.mts b/apps/workbench/vite.config.rr.mtsindex 3d7db424396..cf4abaa1486 100644--- a/apps/workbench/vite.config.rr.mts+++ b/apps/workbench/vite.config.rr.mts@@ -83,8 +83,18 @@ const workbenchClientShikiCdn = (): Plugin => ({// Referenced in the client graph only from store tails that never execute in// workbench flows; requesting one at runtime degrades to raw keys instead of-// bundling 18 locale files each.-const I18N_DEAD_NS = new Set(['electron', 'file', 'modelProvider', 'setting', 'topic', 'video']);+// bundling 18 locale files each. `agent` is pulled in by the agent-share+// visitor upload branch of the chat upload store, a surface workbench has no+// route for.+const I18N_DEAD_NS = new Set([+ 'agent',+ 'electron',+ 'file',+ 'modelProvider',+ 'setting',+ 'topic',+ 'video',+]);const I18N_NS_PATTERNS = [/useTranslation\(\s*['"]([A-Za-z]+)['"]/g,diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 71b36a36054..d911bf22500 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "WeChat account identifier returned by the authorization flow.","share.entry": "Share this Agent","share.settings.limits.desc": "Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.",+ "share.settings.limits.maxFileStorage": "File storage limit (MB)",+ "share.settings.limits.maxFileStorageHint": "Files visitors attach are stored on your account. Uploads stop once they reach this total; set 0 to turn attachments off.","share.settings.limits.maxTopicsPerVisitor": "Conversations per visitor","share.settings.limits.maxTopicsPerVisitorHint": "How many separate conversations each signed-in visitor can start.","share.settings.limits.maxTurnsPerTopic": "Turns per conversation",@@ -363,6 +365,9 @@"share.settings.updateError": "Could not save the change. Please try again.","share.settings.usage.conversations": "Conversations","share.settings.usage.desc": "What this share has attracted, and what it has cost you.",+ "share.settings.usage.fileStorage": "File storage",+ "share.settings.usage.fileStorageOfLimit": "{{used}} of {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · attachments off","share.settings.usage.loadFailed": "Usage could not be loaded","share.settings.usage.monthlySpend": "This month’s spend","share.settings.usage.spendOfLimit": "${{spend}} of ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Sign in","share.visitor.access.signInDesc": "Sign in to start chatting with this shared agent. Your conversations stay tied to your account.","share.visitor.access.signInTitle": "Sign in to continue",+ "share.visitor.errors.fileUnavailable": "One of the attachments is no longer available. Remove it and try again.","share.visitor.errors.generic": "Failed to send the message. Please try again.","share.visitor.errors.heterogeneousUnsupported": "This shared agent isn't available for visitor chat yet. Please contact its owner.","share.visitor.errors.insufficientBudget": "This shared agent has run out of budget. Please contact its owner.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} tools are open to visitors.","share.visitor.profile.terms.topics": "You can open up to {{count}} conversations.","share.visitor.profile.terms.turns": "Each conversation allows up to {{count}} turns.",+ "share.visitor.profile.terms.uploads": "You can attach files; this Agent has {{size}} of file storage for visitors.",+ "share.visitor.profile.terms.uploadsOff": "Attachments are turned off.","share.visitor.profile.terms.visibilityCreator": "The creator has turned on session review, so they can read this conversation.","share.visitor.profile.terms.visibilityPrivate": "Only you can see your conversations.","share.visitor.topBar.home": "Go to my LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "New conversation","share.visitor.topics.title": "Conversations","share.visitor.topics.untitled": "Untitled conversation",+ "share.visitor.upload.creatorStorageBlocked": "This Agent's upload space is full. Ask its creator to free up room or raise the cap.",+ "share.visitor.upload.fileTooLarge": "Files must be under {{max}}.",+ "share.visitor.upload.tooManyFiles": "You can attach up to {{max}} files per message.","transfer.button": "Move","transfer.confirm.botChannels": "Bot channel connections may need to be refreshed after moving","transfer.confirm.chatGroups": "Multi-agent group associations will be removed",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 1227cd2f07c..666d01a50dd 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "通过授权流程返回的微信账号标识符。","share.entry": "分享此助手","share.settings.limits.desc": "访客的每次运行都记在你的账户上,这些上限是分享链接不会跑出高额账单的唯一保障。上限始终生效,你可以调整数值,但不能关闭。",+ "share.settings.limits.maxFileStorage": "文件存储上限(MB)",+ "share.settings.limits.maxFileStorageHint": "访客上传的文件会存放在你的账号里。累计达到这个总量后就不能再上传;填 0 表示关闭附件功能。","share.settings.limits.maxTopicsPerVisitor": "每位访客的会话数","share.settings.limits.maxTopicsPerVisitorHint": "每位已登录访客最多能发起多少个独立会话。","share.settings.limits.maxTurnsPerTopic": "每个会话的轮次",@@ -363,6 +365,9 @@"share.settings.updateError": "保存失败,请重试。","share.settings.usage.conversations": "会话数","share.settings.usage.desc": "这个分享带来了多少访问,又花了你多少钱。",+ "share.settings.usage.fileStorage": "文件存储",+ "share.settings.usage.fileStorageOfLimit": "{{used}} / {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · 附件已关闭","share.settings.usage.loadFailed": "用量加载失败","share.settings.usage.monthlySpend": "本月消耗","share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "登录","share.visitor.access.signInDesc": "登录后即可与这个分享助手对话,你的会话会保留在自己的账号下。","share.visitor.access.signInTitle": "登录后继续",+ "share.visitor.errors.fileUnavailable": "有附件已不可用,请移除后重试。","share.visitor.errors.generic": "消息发送失败,请重试。","share.visitor.errors.heterogeneousUnsupported": "该分享助手暂不支持访客对话,请联系创建者。","share.visitor.errors.insufficientBudget": "该分享助手的额度已用尽,请联系创建者。",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "有 {{count}} 个工具对访客开放。","share.visitor.profile.terms.topics": "你最多可以开 {{count}} 个会话。","share.visitor.profile.terms.turns": "每个会话最多 {{count}} 轮。",+ "share.visitor.profile.terms.uploads": "你可以上传附件,这个智能体为访客预留了 {{size}} 的文件存储空间。",+ "share.visitor.profile.terms.uploadsOff": "附件功能已关闭。","share.visitor.profile.terms.visibilityCreator": "创建者开启了会话查看权限,可以读到这段对话。","share.visitor.profile.terms.visibilityPrivate": "你的对话只有你自己能看到。","share.visitor.topBar.home": "回到我的 LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "新建会话","share.visitor.topics.title": "会话","share.visitor.topics.untitled": "未命名会话",+ "share.visitor.upload.creatorStorageBlocked": "这个智能体的上传空间已满,请联系创建者清理文件或调高上限。",+ "share.visitor.upload.fileTooLarge": "单个文件不能超过 {{max}}。",+ "share.visitor.upload.tooManyFiles": "每条消息最多可附加 {{max}} 个文件。","transfer.button": "移动","transfer.confirm.botChannels": "移动后可能需要重新刷新机器人频道连接","transfer.confirm.chatGroups": "多助理群组关联将被移除",diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.tsindex ac2edc664ff..cb0f55c75e6 100644--- a/packages/const/src/agentShare.ts+++ b/packages/const/src/agentShare.ts@@ -55,6 +55,51 @@ export const AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT = 10;*/export const SHARE_VISITOR_PROMPT_MAX_LENGTH = 20_000;+/**+ * Upper bound on attachments a share visitor may pin to one turn.+ *+ * Visitor attachments are stored under the CREATOR's account (the creator's+ * storage quota pays for them, like every other share artifact), and every+ * attached document is parsed and injected into the creator-billed model call+ * while every image rides along as vision input. This cap bounds that per-turn+ * cost; together with {@link SHARE_VISITOR_MAX_FILE_SIZE} it bounds how much+ * storage one visitor turn can put on the creator. Ten mirrors what a single+ * owner turn realistically carries.+ */+export const SHARE_VISITOR_MAX_FILES_PER_TURN = 10;++/**+ * Largest single file a share visitor may upload, in bytes.+ *+ * Far below the owner's own `MAX_UPLOAD_FILE_SIZE` (2 GB): the bytes land on+ * the CREATOR's storage quota and a visitor is an untrusted party. Also kept+ * under the client's multipart threshold (64 MB) so the share upload path is+ * a single reserved PUT — no multipart session to abort or resume.+ */+export const SHARE_VISITOR_MAX_FILE_SIZE = 32 * 1024 * 1024;++/**+ * Default `AgentShareConfig.maxFileStorage` (bytes) applied when a share is+ * first created and whenever a partial config is normalized.+ *+ * Total storage a share's visitor uploads may occupy on the CREATOR's+ * account — settled files plus in-flight reservations. Mandatory like+ * `monthlySpendLimit`: the creator can move the number (or set `0` to turn+ * visitor attachments off) but never clear it — without a ceiling, anyone+ * with the link could upload, never send, and fill the creator's quota. The+ * creator's own plan limit still applies on top.+ */+export const AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE = 512 * 1024 * 1024;++/**+ * Message prefix of the `FORBIDDEN` error `shareChat.createUploadUrl` throws+ * when a visitor upload is refused for storage reasons — the share's+ * `maxFileStorage` cap or the creator's own account-level block. The client+ * matches the prefix only; the suffix is a visitor-safe cause, never the+ * creator's billing state.+ */+export const SHARE_UPLOAD_STORAGE_BLOCK_PREFIX = 'storage_block:';+/*** Validates `AgentShareConfig.slug`: lowercase alphanumerics and hyphens* only, 3-64 characters, no leading/trailing hyphen. Deliberately excludesdiff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex cea4a49755d..db121e9e2c2 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { eq } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -174,6 +174,7 @@ describe('AgentShareModel', () => {expect(ownerShare?.shareConfig).toEqual({allowCreatorViewSessions: false,allowReadMemory: false,+ maxFileStorage: 512 * 1024 * 1024,maxTopicsPerVisitor: 5,maxTurnsPerTopic: 20,monthlySpendLimit: 10,@@ -190,6 +191,7 @@ describe('AgentShareModel', () => {const config: AgentShareConfig = {allowCreatorViewSessions: true,allowReadMemory: true,+ maxFileStorage: 256 * 1024 * 1024,maxTopicsPerVisitor: 10,maxTurnsPerTopic: 40,monthlySpendLimit: 25,@@ -584,6 +586,26 @@ describe('AgentShareModel', () => {});});+ describe('lockUploadAdmission', () => {+ const heldAdvisoryLocks = async (db: LobeChatDatabase) => {+ const { rows } = await db.execute(+ sql`SELECT count(*)::int AS held FROM pg_locks WHERE locktype = 'advisory'`,+ );+ return (rows[0] as { held: number }).held;+ };++ it('holds a transaction-scoped advisory lock that is released at commit', async () => {+ await serverDB.transaction(async (tx) => {+ await AgentShareModel.lockUploadAdmission(tx, 'share-lock-test');+ await expect(heldAdvisoryLocks(tx)).resolves.toBe(1);+ // Re-entrant within the same transaction: a retry does not deadlock.+ await AgentShareModel.lockUploadAdmission(tx, 'share-lock-test');+ });++ await expect(heldAdvisoryLocks(serverDB)).resolves.toBe(0);+ });+ });+describe('incrementUserViewCount', () => {it('atomically records successful page views', async () => {const created = await agentShareModel.create(agentId);diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.tsindex 87353afc8ff..ffbc2041d64 100644--- a/packages/database/src/models/__tests__/file.test.ts+++ b/packages/database/src/models/__tests__/file.test.ts@@ -352,6 +352,79 @@ 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();+ 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();+ await expect(+ fileModel.deleteUnreferenced(id, true, { exclusiveStorage: true }),+ ).resolves.toMatchObject({ id, url: 'files/u/share/a/cat.png' });+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, id) }),+ ).resolves.toBeUndefined();+ });++ it('returns a hashed row with exclusiveStorage even while another row shares the hash', async () => {+ await fileModel.createGlobalFile({+ creator: userId,+ fileType: 'image/png',+ hashId: 'shared-hash',+ size: 10,+ url: 'files/u/first.png',+ });+ const { id: keeper } = await fileModel.create({+ fileHash: 'shared-hash',+ fileType: 'image/png',+ name: 'first.png',+ size: 10,+ url: 'files/u/first.png',+ });+ const { id } = await fileModel.create({+ fileHash: 'shared-hash',+ fileType: 'image/png',+ name: 'second.png',+ size: 10,+ url: 'files/u/second.png',+ });++ await expect(fileModel.deleteUnreferenced(id, true)).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();+ await expect(+ serverDB.query.globalFiles.findFirst({ where: eq(globalFiles.hashId, 'shared-hash') }),+ ).resolves.toBeDefined();+ });+it("does not delete another user's unreferenced file", async () => {await serverDB.insert(files).values({fileType: 'audio/webm',@@ -828,6 +901,31 @@ describe('FileModel', () => {});});+ describe('countAgentShareUsage', () => {+ it("sums only this user's agent_share files that belong to 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 });+ // Another user's visitor file on the same share id.+ await new FileModel(serverDB, 'user2').create(visitorFile('share-a', 160));++ expect(await fileModel.countAgentShareUsage('share-a')).toBe(30);+ expect(await fileModel.countAgentShareUsage('share-b')).toBe(40);+ expect(await fileModel.countAgentShareUsage('share-none')).toBe(0);+ });+ });+describe('findById', () => {it('should find a file by id', async () => {const { id } = await fileModel.create({diff --git a/packages/database/src/models/__tests__/fileUpload.test.ts b/packages/database/src/models/__tests__/fileUpload.test.tsindex 9897d089f8a..7be5372801f 100644--- a/packages/database/src/models/__tests__/fileUpload.test.ts+++ b/packages/database/src/models/__tests__/fileUpload.test.ts@@ -31,6 +31,31 @@ afterEach(async () => {});describe('FileUploadModel', () => {+ it('counts live bytes under a key prefix for this user only, matching `_` literally', async () => {+ const personal = new FileUploadModel(serverDB, userId);+ const other = new FileUploadModel(serverDB, otherUserId);+ const prefix = 'files/u_1/agent-share/share_a/';++ await personal.create({ expiresAt, pathname: `${prefix}x/a.png`, size: 10 });+ await personal.create({ expiresAt, pathname: `${prefix}y/b.png`, size: 20 });+ await personal.create({+ expiresAt,+ pathname: 'files/u_1/agent-share/share_b/z/c.png',+ size: 40,+ });+ // Differs exactly where the prefix has `_` — a LIKE wildcard would match it.+ await personal.create({+ expiresAt,+ pathname: 'files/u-1/agent-share/share_a/w/d.png',+ size: 80,+ });+ await other.create({ expiresAt, pathname: `${prefix}o/e.png`, size: 160 });++ expect(await personal.countLiveUsageUnderPrefix(prefix)).toBe(30);+ expect(await other.countLiveUsageUnderPrefix(prefix)).toBe(160);+ expect(await personal.countLiveUsageUnderPrefix('files/u_1/agent-share/none/')).toBe(0);+ });+it('scopes sessions and counts only live bytes in the matching quota scope', async () => {const personal = new FileUploadModel(serverDB, userId);const other = new FileUploadModel(serverDB, otherUserId);diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex 41937f34f80..73ba6589e3b 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -1,4 +1,5 @@import {+ AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT,@@ -23,6 +24,7 @@ import { isUuid } from '../utils/uuid';const DEFAULT_AGENT_SHARE_CONFIG = {allowCreatorViewSessions: false,allowReadMemory: false,+ maxFileStorage: AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,maxTopicsPerVisitor: AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,maxTurnsPerTopic: AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,monthlySpendLimit: AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT,@@ -38,6 +40,7 @@ const normalizeAgentShareConfig = (allowCreatorViewSessions:config?.allowCreatorViewSessions ?? DEFAULT_AGENT_SHARE_CONFIG.allowCreatorViewSessions,allowReadMemory: config?.allowReadMemory ?? DEFAULT_AGENT_SHARE_CONFIG.allowReadMemory,+ maxFileStorage: config?.maxFileStorage ?? DEFAULT_AGENT_SHARE_CONFIG.maxFileStorage,maxTopicsPerVisitor:config?.maxTopicsPerVisitor ?? DEFAULT_AGENT_SHARE_CONFIG.maxTopicsPerVisitor,maxTurnsPerTopic: config?.maxTurnsPerTopic ?? DEFAULT_AGENT_SHARE_CONFIG.maxTurnsPerTopic,@@ -420,6 +423,23 @@ export class AgentShareModel {};};+ /**+ * Serialize the per-share upload cap decision, to be called from inside the+ * reservation transaction BEFORE the usage is counted. The cap is a sum over+ * two tables (settled visitor files + live reservations) that no row lock+ * covers, and the only lock the reservation itself takes — the creator's+ * users row, inside the deployment's quota check — comes AFTER the caller's+ * admission hook. Without this barrier two concurrent visitors both read the+ * pre-insert sum and both slip under the cap. Transaction-scoped advisory+ * lock keyed by share id (same pattern as the slug barrier), released+ * automatically at commit/rollback.+ */+ static lockUploadAdmission = async (tx: LobeChatDatabase, shareId: string): Promise<void> => {+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(hashtext(${`agent_share_upload:${shareId}`}))`,+ );+ };+/*** Whether an in-flight visitor run is STILL authorized to continue: the* agent's share row must exist, still be the SAME instance the run was@@ -483,8 +503,12 @@ export class AgentShareModel {agentBackgroundColor: agents.backgroundColor,agentDescription: agents.description,agentId: agentShares.agentId,+ // Model identity is for a server-side capability lookup only (what+ // media a visitor may attach); the visitor payload never carries it.+ agentModel: agents.model,agentName: agents.name,agentOpeningQuestions: agents.openingQuestions,+ agentProvider: agents.provider,agentSlug: agents.slug,agentTags: agents.tags,agentTitle: agents.title,diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex 5bfe66c5bc6..d3e763f13b6 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -1,5 +1,5 @@import type { QueryFileListParams } from '@lobechat/types';-import { FilesTabs, LIBRARY_HIDDEN_FILE_SOURCES, SortType } from '@lobechat/types';+import { FileSource, FilesTabs, LIBRARY_HIDDEN_FILE_SOURCES, SortType } from '@lobechat/types';import {and,asc,@@ -167,7 +167,21 @@ export class FileModel {};};- delete = async (id: string, removeGlobalFile: boolean = true, trx?: Transaction) => {+ /**+ * 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 (+ id: string,+ removeGlobalFile: boolean = true,+ trx?: Transaction,+ options?: { exclusiveStorage?: boolean },+ ) => {const executeInTransaction = async (tx: Transaction) => {// In pglite environment, non-transactional operations cannot be used within a transaction as it will blockconst file = await this.findById(id, tx);@@ -204,7 +218,7 @@ export class FileModel {// 4. Delete file recordawait tx.delete(files).where(and(eq(files.id, id), this.ownership()));- if (!fileHash) return;+ if (!fileHash) return options?.exclusiveStorage ? file : undefined;const result = await tx.select({ count: count() })@@ -220,6 +234,8 @@ export class FileModel {return file;}++ return options?.exclusiveStorage ? file : undefined;};return await (trx ? executeInTransaction(trx) : this.db.transaction(executeInTransaction));@@ -229,8 +245,16 @@ export class FileModel {* Delete a transient upload only while no persisted message or session references it.* 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".*/- deleteUnreferenced = async (id: string, removeGlobalFile: boolean = true) => {+ deleteUnreferenced = async (+ id: string,+ removeGlobalFile: boolean = true,+ options?: { exclusiveStorage?: boolean },+ ) => {return this.db.transaction(async (trx) => {const [file] = await trx.select({ id: files.id })@@ -254,7 +278,7 @@ export class FileModel {.limit(1);if (sessionReference) return;- return this.delete(id, removeGlobalFile, trx);+ return this.delete(id, removeGlobalFile, trx, options);});};@@ -274,6 +298,28 @@ export class FileModel {return parseInt(result[0].totalSize!) || 0;};+ /**+ * Bytes occupied by one agent share's visitor uploads: this user's+ * `agent_share` rows whose provenance names `shareId`. Backs the share's+ * `maxFileStorage` cap (`shareChat.createUploadUrl`), so it accepts the+ * reservation transaction to be counted inside it.+ */+ countAgentShareUsage = async (shareId: string, trx?: Transaction) => {+ const db = trx ?? this.db;+ const [row] = await db+ .select({ totalSize: sum(files.size) })+ .from(files)+ .where(+ and(+ this.ownership(),+ eq(files.source, FileSource.AgentShare),+ sql`${files.metadata} -> 'agentShare' ->> 'shareId' = ${shareId}`,+ ),+ );++ return Number(row?.totalSize ?? 0);+ };+deleteMany = async (ids: string[],removeGlobalFile: boolean = true,diff --git a/packages/database/src/models/fileUpload.ts b/packages/database/src/models/fileUpload.tsindex 412621845bd..93fff959545 100644--- a/packages/database/src/models/fileUpload.ts+++ b/packages/database/src/models/fileUpload.ts@@ -1,5 +1,5 @@import type { FileUploadSessionStatus } from '@lobechat/types';-import { and, asc, desc, eq, inArray, isNull, lte, or, sum } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNull, lte, or, sql, sum } from 'drizzle-orm';import type { FileUploadItem, NewFileUpload } from '../schemas';import { fileUploads } from '../schemas';@@ -100,6 +100,30 @@ export class FileUploadModel {return Number(row?.totalSize ?? 0);};+ /**+ * Live reservation bytes under one storage-key prefix, for this user. The+ * agent-share upload cap uses it: every visitor upload of a share lives+ * under `files/<owner>/agent-share/<shareId>/`. `starts_with` rather than+ * `LIKE` because ids in the prefix may contain `_`, a LIKE wildcard.+ */+ countLiveUsageUnderPrefix = async (+ prefix: string,+ transaction?: Transaction,+ ): Promise<number> => {+ const [row] = await (transaction ?? this.db)+ .select({ totalSize: sum(fileUploads.size) })+ .from(fileUploads)+ .where(+ and(+ this.ownership(),+ inArray(fileUploads.status, LIVE_STATUSES),+ sql`starts_with(${fileUploads.pathname}, ${prefix})`,+ ),+ );++ return Number(row?.totalSize ?? 0);+ };+static countLiveUsageForWorkspace = async (db: Database,workspaceId: string,diff --git a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.tsindex 11dc1a2b8f9..186ed3fb8e5 100644--- a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts+++ b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { FileSource } from '@lobechat/types';+import { FileSource, LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../../core/getTestDB';@@ -1484,7 +1484,7 @@ describe('ElasticsearchFtsSearchBackend', () => {],must_not: expect.arrayContaining([{ term: { file_type: 'custom/document' } },- { terms: { source: [FileSource.Acceptance] } },+ { terms: { source: LIBRARY_HIDDEN_FILE_SOURCES } },{ terms: { knowledge_base_ids: ['file-kb-restricted'] } },]),}),diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex f81959c73e2..224ee3ce21c 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -16,6 +16,13 @@ export interface AgentShareConfig {* a shared conversation. Defaults to `false`.*/allowReadMemory?: boolean;+ /**+ * Total bytes this share's visitor uploads may occupy on the creator's+ * account (settled files plus in-flight reservations). Mandatory like+ * `monthlySpendLimit` — normalized to a default, never cleared; `0` turns+ * visitor attachments off entirely. Enforced by `shareChat.createUploadUrl`.+ */+ maxFileStorage?: number;/** Maximum number of topics each signed-in visitor can create for this share. */maxTopicsPerVisitor?: number;/** Maximum number of message turns allowed in each shared topic. */@@ -65,7 +72,10 @@ export interface AgentShareConfig {* is guaranteed present, so enforcement paths never have to re-derive a* default (and can never mistake a missing cap for "unlimited").*/-export type NormalizedAgentShareConfig = AgentShareConfig & { monthlySpendLimit: number };+export type NormalizedAgentShareConfig = AgentShareConfig & {+ maxFileStorage: number;+ monthlySpendLimit: number;+};/*** Client-owned config fields accepted by atomic server-side patch updates.diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 7a4a42e4068..8062c9e8474 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -396,6 +396,9 @@ export default {'share.entry': 'Share this Agent','share.settings.limits.desc':'Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.',+ 'share.settings.limits.maxFileStorage': 'File storage limit (MB)',+ 'share.settings.limits.maxFileStorageHint':+ 'Files visitors attach are stored on your account. Uploads stop once they reach this total; set 0 to turn attachments off.','share.settings.limits.maxTopicsPerVisitor': 'Conversations per visitor','share.settings.limits.maxTopicsPerVisitorHint':'How many separate conversations each signed-in visitor can start.',@@ -452,6 +455,9 @@ export default {'share.settings.title': 'Share Agent','share.settings.usage.conversations': 'Conversations','share.settings.usage.desc': 'What this share has attracted, and what it has cost you.',+ 'share.settings.usage.fileStorage': 'File storage',+ 'share.settings.usage.fileStorageOfLimit': '{{used}} of {{limit}}',+ 'share.settings.usage.fileStorageOff': '{{used}} · attachments off','share.settings.usage.loadFailed': 'Usage could not be loaded','share.settings.usage.monthlySpend': 'This month’s spend','share.settings.usage.spendOfLimit': '${{spend}} of ${{limit}}',@@ -484,6 +490,8 @@ export default {'share.visitor.access.signInDesc':'Sign in to start chatting with this shared agent. Your conversations stay tied to your account.','share.visitor.access.signInTitle': 'Sign in to continue',+ 'share.visitor.errors.fileUnavailable':+ 'One of the attachments is no longer available. Remove it and try again.','share.visitor.errors.generic': 'Failed to send the message. Please try again.','share.visitor.errors.heterogeneousUnsupported':"This shared agent isn't available for visitor chat yet. Please contact its owner.",@@ -535,6 +543,9 @@ export default {'share.visitor.profile.terms.tools_other': '{{count}} tools are open to visitors.','share.visitor.profile.terms.topics': 'You can open up to {{count}} conversations.','share.visitor.profile.terms.turns': 'Each conversation allows up to {{count}} turns.',+ 'share.visitor.profile.terms.uploads':+ 'You can attach files; this Agent has {{size}} of file storage for visitors.',+ 'share.visitor.profile.terms.uploadsOff': 'Attachments are turned off.','share.visitor.profile.terms.visibilityCreator':'The creator has turned on session review, so they can read this conversation.','share.visitor.profile.terms.visibilityPrivate': 'Only you can see your conversations.',@@ -543,6 +554,10 @@ export default {'share.visitor.topics.new': 'New conversation','share.visitor.topics.title': 'Conversations','share.visitor.topics.untitled': 'Untitled conversation',+ 'share.visitor.upload.creatorStorageBlocked':+ "This Agent's upload space is full. Ask its creator to free up room or raise the cap.",+ 'share.visitor.upload.fileTooLarge': 'Files must be under {{max}}.',+ 'share.visitor.upload.tooManyFiles': 'You can attach up to {{max}} files per message.','transfer.title': 'Move','transfer.copyTo': 'Copy to…',diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.tsindex 196aeaaa46c..bd140035628 100644--- a/packages/types/src/agent/share.ts+++ b/packages/types/src/agent/share.ts@@ -9,6 +9,11 @@ import type { ShareVisibility } from '../topic';export interface SharedAgentTerms {/** Whether the creator opted into reading visitor conversations. */allowCreatorViewSessions: boolean;+ /**+ * Total upload space (bytes) the creator opened to visitor attachments on+ * this share; `0` means attachments are off and the composer hides them.+ */+ maxFileStorage: number;/** Maximum conversations this visitor may open against the share. */maxTopicsPerVisitor: number;/** Maximum message turns allowed inside one shared conversation. */@@ -26,6 +31,12 @@ export interface SharedAgentStats {}/** Agent metadata exposed to signed-in visitors of an agent share. */+export interface SharedAgentUploadAbility {+ audio: boolean;+ image: boolean;+ video: boolean;+}+export interface SharedAgentData {agentId: string;agentMeta: {@@ -67,6 +78,13 @@ export interface SharedAgentData {* — never the granted API list, which is owner-facing configuration.*/toolGrants: string[];+ /**+ * Which media the visitor composer may attach, derived server-side from+ * the agent's model abilities so the model itself stays hidden (it is+ * owner-facing unless `showModelInfo` opts in). Documents are always+ * allowed; these only gate direct media input.+ */+ uploadAbility: SharedAgentUploadAbility;visibility: ShareVisibility;}diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex 54260d909bd..ea0aec0b5c0 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -21,6 +21,13 @@ 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',@@ -35,8 +42,17 @@ 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];+export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [+ FileSource.Acceptance,+ FileSource.AgentShare,+];/** 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 2c2f93e3213..fbfe297a31b 100644--- a/packages/types/src/files/upload.ts+++ b/packages/types/src/files/upload.ts@@ -77,6 +77,12 @@ export interface UploadFileItem {* it will use in the file preview before send the message*/previewUrl?: string;+ /**+ * Set when the draft was uploaded as an agent-share VISITOR: the file lives+ * under the creator's account, so remove/retry must go through the+ * share-scoped endpoints instead of the visitor's own file API.+ */+ shareId?: string;/*** marks a draft entry that references an already-persisted file still backing* an existing message (e.g. restored via "restore to input"). Removing such@@ -91,6 +97,13 @@ export interface UploadFileItem {}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.+ */+ agentShare: z.object({ shareId: z.string(), visitorUserId: z.string() }).optional(),date: z.string(),dirname: z.string(),filename: z.string(),diff --git a/src/services/shareChat.ts b/src/services/shareChat.tsindex b9bea9dcbb1..bb946d9e362 100644--- a/src/services/shareChat.ts+++ b/src/services/shareChat.ts@@ -5,6 +5,12 @@ import { lambdaClient } from '@/libs/trpc/client';export interface ShareChatExecParams {/** Client-minted ids for the rows this run creates (fresh sends only). */clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };+ /**+ * Files the visitor uploaded through {@link ShareChatService.createFile} to+ * attach to this turn. The server re-checks each id's share provenance, so+ * ids of anyone else's files are rejected rather than leaked.+ */+ fileIds?: string[];prompt: string;shareId: string;/** The prompt was queued behind a running turn and renders as its continuation. */@@ -19,7 +25,63 @@ export interface ShareChatExecParams {* visitor-scoped topic/message reads — all keyed by shareId, authorized* server-side against `topics.senderId`.*/+export interface ShareUploadMetadata {+ codec?: string;+ durationMs?: number;+ height?: number;+ mimeType?: string;+ ratio?: number;+ width?: number;+}++export interface ShareCreateFileParams {+ fileType: string;+ metadata?: ShareUploadMetadata;+ name: string;+ pathname: string;+ shareId: string;+ size: number;+}+class ShareChatService {+ /**+ * Release an abandoned share upload reservation (PUT failed / cancelled).+ * Best-effort: the server sweeps expired reservations anyway.+ */+ async abortUpload(shareId: string, pathname: string) {+ try {+ await lambdaClient.shareChat.abortUpload.mutate({ pathname, shareId });+ } catch (error) {+ console.error('Failed to release share upload:', error);+ }+ }++ /** Settle a PUT-completed share upload into a file the visitor can attach. */+ async createFile(params: ShareCreateFileParams): Promise<{ id: string; url: string }> {+ return await lambdaClient.shareChat.createFile.mutate(params);+ }++ /**+ * Reserve storage (on the CREATOR's quota) and get a pre-signed PUT URL for+ * one visitor attachment. Rejects with the creator's `storage_block:*`+ * reason when their quota cannot admit the bytes.+ */+ async createUploadUrl(+ shareId: string,+ file: { name: string; size: number },+ ): Promise<{ pathname: string; url: string }> {+ return await lambdaClient.shareChat.createUploadUrl.mutate({+ name: file.name,+ shareId,+ size: file.size,+ });+ }++ /** Drop a not-yet-sent share upload the visitor removed from their draft. */+ async removeFile(shareId: string, fileId: string) {+ await lambdaClient.shareChat.removeFile.mutate({ fileId, shareId });+ }+async execAgentTask(params: ShareChatExecParams,options?: { signal?: AbortSignal },diff --git a/src/services/upload.ts b/src/services/upload.tsindex 434a70f947c..09657fe49bd 100644--- a/src/services/upload.ts+++ b/src/services/upload.ts@@ -206,6 +206,51 @@ class UploadService {return result;};+ /**+ * PUT a file to a pre-signed URL someone else minted (the agent-share+ * visitor path: `shareChat.createUploadUrl` reserves the key under the+ * CREATOR's quota and hands back the URL). Single PUT only — callers cap the+ * size below the multipart threshold. Reports progress in the same+ * `FileUploadState` shape as {@link uploadToServerS3}; abort/cleanup of the+ * reservation is the caller's job since only it knows which endpoint to hit.+ */+ uploadToPresignedUrl = async (+ file: File,+ url: string,+ {+ abortController,+ onProgress,+ }: {+ abortController?: AbortController;+ onProgress?: (status: FileUploadStatus, state: FileUploadState) => void;+ } = {},+ ): Promise<void> => {+ const startTime = Date.now();++ try {+ await this.putBlob(+ url,+ file,+ abortController?.signal,+ (loaded) => {+ onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));+ },+ file.type,+ );+ } catch (error) {+ if (abortController?.signal.aborted) {+ onProgress?.('cancelled', { progress: 0, restTime: 0, speed: 0 });+ }+ throw error;+ }++ onProgress?.('success', {+ progress: 100,+ restTime: 0,+ speed: file.size / Math.max((Date.now() - startTime) / 1000, 0.001),+ });+ };+private getUploadState = (loaded: number, total: number, startTime: number): FileUploadState => {const elapsed = Math.max((Date.now() - startTime) / 1000, 0.001);const speed = loaded / elapsed;diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 0b35eae355a..7f7543fffda 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -797,9 +797,9 @@ export class GatewayActionImpl {}// Agent-share visitor surface: dispatch through the share-authorized mirror.- // It accepts only the share-safe subset (prompt / topic / clientIds) —- // everything else (tools, devices, mentions) is decided server-side by the- // share config, never by this client.+ // It accepts only the share-safe subset (prompt / topic / clientIds /+ // the visitor's share-uploaded fileIds) — everything else (tools, devices, mentions) is+ // decided server-side by the share config, never by this client.const agentShareId = executionContext.agentShareId;const result =@@ -808,6 +808,7 @@ export class GatewayActionImpl {? await shareChatService.execAgentTask({clientIds,+ fileIds,prompt: message,shareId: agentShareId,steer: metadata?.steer,diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex b41f7fea202..a0884a09a43 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -4,6 +4,8 @@ import { act, renderHook } from '@testing-library/react';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { fileService } from '@/services/file';+import { ragService } from '@/services/rag';+import { shareChatService } from '@/services/shareChat';import { agentByIdSelectors } from '@/store/agent/selectors';import { useFileStore as useStore } from '../../store';@@ -33,6 +35,20 @@ vi.mock('@/services/rag', () => ({},}));+const { mockUploadShareVisitorFile } = vi.hoisted(() => ({+ mockUploadShareVisitorFile: vi.fn(),+}));+vi.mock('./shareVisitorUpload', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ uploadShareVisitorFile: mockUploadShareVisitorFile,+}));++vi.mock('@/services/shareChat', () => ({+ shareChatService: {+ removeFile: vi.fn().mockResolvedValue(undefined),+ },+}));+vi.mock('i18next', () => ({t: (key: string, options?: { reason?: string }) => {if (key === 'upload.permissionDenied') {@@ -291,7 +307,121 @@ describe('useFileStore:chat', () => {]);});+ describe('uploadChatFiles as an agent-share visitor', () => {+ const SHARE_ID = 'share-1';++ it('routes the upload through the share path, tags the draft with shareId, and skips the visitor-side parse', async () => {+ // The visitor's agent store never holds the creator's agent, so the+ // mode selectors would say "agent mode" here only by accident.+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });+ mockUploadShareVisitorFile.mockResolvedValue({ id: 'file-share', url: 'https://s3/doc' });+ const { result } = renderHook(() => useStore());+ const uploadWithProgress = vi.spyOn(result.current, 'uploadWithProgress');+ const file = new File(['test'], 'notes.pdf', { type: 'application/pdf' });++ await act(async () => {+ await result.current.uploadChatFiles([file], AGENT_ID, { shareId: SHARE_ID });+ });++ expect(mockUploadShareVisitorFile).toHaveBeenCalledWith(+ expect.objectContaining({ file, shareId: SHARE_ID }),+ );+ expect(uploadWithProgress).not.toHaveBeenCalled();+ // Creator-owned row: the visitor's `document.parseFileContent` could not+ // reach it; the run parses it on the creator's account instead.+ expect(ragService.parseFileContent).not.toHaveBeenCalled();+ expect(result.current.chatUploadFileList).toEqual([+ expect.objectContaining({ agentId: AGENT_ID, id: 'notes.pdf', shareId: SHARE_ID }),+ ]);+ });++ it('always enforces the chat file-type whitelist on the share path', async () => {+ mockAgentMode({ enableAgentMode: true, heterogeneous: true });+ const { result } = renderHook(() => useStore());+ const file = new File(['x'], 'tool.exe', { type: 'application/octet-stream' });++ await act(async () => {+ await result.current.uploadChatFiles([file], AGENT_ID, { shareId: SHARE_ID });+ });++ expect(mockUploadShareVisitorFile).not.toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalled();+ expect(result.current.chatUploadFileList).toEqual([]);+ });++ it('rejects a file over SHARE_VISITOR_MAX_FILE_SIZE before any request', async () => {+ mockAgentMode({ enableAgentMode: false, heterogeneous: false });+ const { result } = renderHook(() => useStore());+ const big = new File([''], 'big.pdf', { type: 'application/pdf' });+ Object.defineProperty(big, 'size', { value: 33 * 1024 * 1024 });++ await act(async () => {+ await result.current.uploadChatFiles([big], AGENT_ID, { shareId: SHARE_ID });+ });++ expect(mockUploadShareVisitorFile).not.toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalledWith('share.visitor.upload.fileTooLarge');+ expect(result.current.chatUploadFileList).toEqual([]);+ });++ it("surfaces the creator's storage block as share copy, not the visitor's own plan", async () => {+ mockAgentMode({ enableAgentMode: false, heterogeneous: false });+ mockUploadShareVisitorFile.mockRejectedValue(new Error('storage_block:upgrade_required'));+ const { result } = renderHook(() => useStore());+ const file = new File(['test'], 'notes.pdf', { type: 'application/pdf' });++ await act(async () => {+ await result.current.uploadChatFiles([file], AGENT_ID, { shareId: SHARE_ID });+ });++ expect(result.current.chatUploadFileList).toEqual([+ expect.objectContaining({+ error: 'share.visitor.upload.creatorStorageBlocked',+ id: 'notes.pdf',+ status: 'error',+ }),+ ]);+ });+ });+describe('removeChatUploadFile', () => {+ it('removes a share-uploaded draft through the share endpoint, not the visitor file API', async () => {+ const removeFile = vi.spyOn(fileService, 'removeFile').mockResolvedValue(undefined);+ const { result } = renderHook(() => useStore());++ act(() => {+ useStore.setState({+ chatUploadFileList: [{ id: 'file-1', shareId: 'share-1', status: 'success' }] as any,+ });+ });++ await act(async () => {+ await result.current.removeChatUploadFile('file-1');+ });++ expect(result.current.chatUploadFileList).toEqual([]);+ expect(shareChatService.removeFile).toHaveBeenCalledWith('share-1', 'file-1');+ expect(removeFile).not.toHaveBeenCalled();+ });++ it('drops an unsettled share draft locally without calling the share endpoint', async () => {+ const { result } = renderHook(() => useStore());++ act(() => {+ // Still keyed by file name: nothing exists server-side to delete.+ useStore.setState({+ chatUploadFileList: [{ id: 'cat.png', shareId: 'share-1', status: 'error' }] as any,+ });+ });++ await act(async () => {+ await result.current.removeChatUploadFile('cat.png');+ });++ expect(result.current.chatUploadFileList).toEqual([]);+ expect(shareChatService.removeFile).not.toHaveBeenCalled();+ });+it('deletes the underlying file for a normal uploaded item', async () => {const removeFile = vi.spyOn(fileService, 'removeFile').mockResolvedValue(undefined);const { result } = renderHook(() => useStore());diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex b2d4aa3470f..04cc5ea404f 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -1,3 +1,4 @@+import { SHARE_VISITOR_MAX_FILE_SIZE } from '@lobechat/const';import { type ChatContextContent } from '@lobechat/types';import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';import { toast } from '@lobehub/ui/base-ui';@@ -7,6 +8,7 @@ import { t } from 'i18next';import { FILE_UPLOAD_BLACKLIST } from '@/const/file';import { fileService } from '@/services/file';import { ragService } from '@/services/rag';+import { shareChatService } from '@/services/shareChat';import { UPLOAD_NETWORK_ERROR } from '@/services/upload';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -20,6 +22,11 @@ import { sleep } from '@/utils/sleep';import { setNamespace } from '@/utils/storeDebug';import { type FileStore } from '../../store';+import {+ isShareFileTooLarge,+ isShareStorageBlockError,+ uploadShareVisitorFile,+} from './shareVisitorUpload';import { filterSupportedChatUploadFiles } from './uploadGuard';const n = setNamespace('chat');@@ -47,9 +54,26 @@ const getErrorMessage = (error: unknown): string => {return String(error);};+export interface ChatUploadOptions {+ /**+ * Upload as an agent-share VISITOR: files go through the share-scoped+ * endpoints onto the CREATOR's account and storage quota (see+ * `uploadShareVisitorFile`) instead of the caller's own file API.+ */+ shareId?: string;+}++const formatShareUploadLimit = () => `${Math.round(SHARE_VISITOR_MAX_FILE_SIZE / 1024 / 1024)} MB`;+const getUploadErrorDescription = (error: unknown): string => {if (error === UPLOAD_NETWORK_ERROR) return t('upload.networkError', { ns: 'error' });+ // A share upload is admitted by the CREATOR's storage quota, so the block+ // is theirs to lift — never route the visitor to their own plan/usage page.+ if (isShareStorageBlockError(error)) {+ return t('share.visitor.upload.creatorStorageBlocked', { ns: 'agent' });+ }+if (getTrpcErrorCode(error) === 'FORBIDDEN') {return t('upload.permissionDenied', { ns: 'error' });}@@ -168,11 +192,22 @@ export class FileActionImpl {// Restored entries reference an already-persisted file that still backs the// original message — only drop the draft item, never delete the file itself.- const skipRemoveFile = chatUploadFileList.find((item) => item.id === id)?.skipRemoveFile;+ const item = chatUploadFileList.find((entry) => entry.id === id);dispatchChatUploadFileList({ id, type: 'removeFile' });- if (skipRemoveFile) return;+ if (item?.skipRemoveFile) return;++ // Share uploads are creator-owned rows the visitor's own file API cannot+ // see; the share endpoint deletes them only while still unsent.+ if (item?.shareId) {+ // Only a settled upload has a server row to drop; a pending or failed+ // draft is client-side only (its id is still the file name) and the+ // share endpoint would just reject it.+ if (item.status !== 'success') return;+ await shareChatService.removeFile(item.shareId, id);+ return;+ }await fileService.removeFile(id);};@@ -183,7 +218,7 @@ export class FileActionImpl {if (!item?.agentId) return;dispatchChatUploadFileList({ id, type: 'removeFile' });- await this.uploadChatFiles([item.file], item.agentId);+ await this.uploadChatFiles([item.file], item.agentId, { shareId: item.shareId });};startAsyncTask = async (@@ -224,8 +259,13 @@ export class FileActionImpl {}};- uploadChatFiles = async (rawFiles: File[], agentId: string): Promise<void> => {+ uploadChatFiles = async (+ rawFiles: File[],+ agentId: string,+ options: ChatUploadOptions = {},+ ): Promise<void> => {const { dispatchChatUploadFileList } = this.#get();+ const { shareId } = options;// 0. skip file in blacklistconst filteredFiles = rawFiles.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));@@ -235,10 +275,16 @@ export class FileActionImpl {// whitelist must not apply there. We key off the conversation's own agent id rather// than the global current agent, because the chat input can be scoped to a different// agent than activeAgentId (e.g. another desktop tab). See lobehub/lobehub#15770.+ //+ // A share VISITOR never has the creator's agent in their agent store, so+ // the selectors below would always say "plain chat" by accident. Make it+ // explicit: share uploads are parsed on the creator's account, so only the+ // parseable whitelist is ever accepted there.const agentState = getAgentStoreState();const enforceFileTypeWhitelist =- !agentByIdSelectors.getAgentEnableModeById(agentId)(agentState) &&- !agentByIdSelectors.isAgentHeterogeneousById(agentId)(agentState);+ !!shareId ||+ (!agentByIdSelectors.getAgentEnableModeById(agentId)(agentState) &&+ !agentByIdSelectors.isAgentHeterogeneousById(agentId)(agentState));const { supportedFiles, unsupportedFiles } = enforceFileTypeWhitelist? filterSupportedChatUploadFiles(filteredFiles)@@ -253,11 +299,27 @@ export class FileActionImpl {);}- if (supportedFiles.length === 0) return;+ // Share uploads land on the creator's storage: bounded per file, and+ // rejected here rather than after the bytes were already pushed.+ const tooLarge = shareId ? supportedFiles.filter((file) => isShareFileTooLarge(file)) : [];+ if (tooLarge.length > 0) {+ toast.error(+ t('share.visitor.upload.fileTooLarge', {+ max: formatShareUploadLimit(),+ ns: 'agent',+ }),+ );+ }+ const admittedFiles =+ tooLarge.length > 0+ ? supportedFiles.filter((file) => !tooLarge.includes(file))+ : supportedFiles;++ if (admittedFiles.length === 0) return;// 1. compress images and add files with base64const files = await Promise.all(- supportedFiles.map((file) =>+ admittedFiles.map((file) =>COMPRESSIBLE_IMAGE_TYPES.has(file.type) ? compressImageFile(file) : file,),);@@ -283,6 +345,7 @@ export class FileActionImpl {file,id: file.name,previewUrl,+ shareId,status: 'pending',} as UploadFileItem;}),@@ -295,10 +358,16 @@ export class FileActionImpl {let fileResult: { id: string; url: string } | undefined;try {- fileResult = await this.#get().uploadWithProgress({- file,- onStatusUpdate: dispatchChatUploadFileList,- });+ fileResult = shareId+ ? await uploadShareVisitorFile({+ file,+ onStatusUpdate: dispatchChatUploadFileList,+ shareId,+ })+ : await this.#get().uploadWithProgress({+ file,+ onStatusUpdate: dispatchChatUploadFileList,+ });} catch (error) {if (getErrorMessage(error) === 'UNAUTHORIZED') {dispatchChatUploadFileList({ id: file.name, type: 'removeFile' });@@ -320,6 +389,10 @@ export class FileActionImpl {// image don't need to be chunked and embeddingif (isChunkingUnsupported(file.type)) return;+ // A share file is creator-owned, so the visitor cannot pre-parse it; the+ // run parses it on the creator's account when the turn is set up.+ if (shareId) return;+await ragService.parseFileContent(fileResult.id);});diff --git a/src/store/file/slices/chat/shareVisitorUpload.ts b/src/store/file/slices/chat/shareVisitorUpload.tsnew file mode 100644index 00000000000..12023c53312--- /dev/null+++ b/src/store/file/slices/chat/shareVisitorUpload.ts@@ -0,0 +1,111 @@+import { SHARE_UPLOAD_STORAGE_BLOCK_PREFIX, SHARE_VISITOR_MAX_FILE_SIZE } from '@lobechat/const';++import { shareChatService } from '@/services/shareChat';+import { uploadService } from '@/services/upload';+import type { UploadFileItem } from '@/types/files';+import { getAudioDuration } from '@/utils/client/audioDuration';+import { getImageDimensions } from '@/utils/client/imageDimensions';++import { normalizeUploadedFileType } from '../upload/action';+import { audioMimeFromExtension } from './uploadGuard';++type OnStatusUpdate = (data: {+ id: string;+ type: 'updateFile';+ value: Partial<UploadFileItem>;+}) => void;++/** Storage refused the bytes — the share's upload cap or the creator's quota (`shareChat.createUploadUrl`). */+export const isShareStorageBlockError = (error: unknown) =>+ error instanceof Error && error.message.startsWith(SHARE_UPLOAD_STORAGE_BLOCK_PREFIX);++export const isShareFileTooLarge = (file: File) => file.size > SHARE_VISITOR_MAX_FILE_SIZE;++/**+ * Upload one chat attachment as an agent-share VISITOR.+ *+ * The share counterpart of `uploadWithProgress`: same client-side prep+ * (type sniffing, image dimensions, audio duration) so the attachment renders+ * exactly like an owner upload, but the storage reservation, the file row and+ * any cleanup go through the share-scoped endpoints — the file lands under the+ * CREATOR's account and quota, which the visitor's own `upload.*` / `file.*`+ * procedures could never write to.+ *+ * Deliberately no content hash: no `checkFileHash` dedup (that lookup is the+ * visitor's own global-file view, and a share file must always be a fresh+ * creator-owned row with share provenance) and none sent to the server either+ * — `shareChat.createFile` keeps share rows out of the hash-keyed global-file+ * graph so each upload's object is deleted with its row.+ */+export const uploadShareVisitorFile = async ({+ abortController,+ file,+ onStatusUpdate,+ shareId,+}: {+ abortController?: AbortController;+ file: File;+ onStatusUpdate?: OnStatusUpdate;+ shareId: string;+}): Promise<{ id: string; url: string }> => {+ const statusId = file.name;+ const { detectedMimeType, file: normalizedFile } = await normalizeUploadedFileType(file);+ const extensionAudioMime = audioMimeFromExtension(normalizedFile.name);++ let fileType = normalizedFile.type || detectedMimeType || 'text/plain';+ if (extensionAudioMime && !fileType.startsWith('audio/')) fileType = extensionAudioMime;++ const [dimensions, durationMs] = await Promise.all([+ getImageDimensions(normalizedFile),+ fileType.startsWith('audio/')+ ? getAudioDuration(normalizedFile).catch(() => undefined)+ : undefined,+ ]);++ const { pathname, url } = await shareChatService.createUploadUrl(shareId, {+ name: normalizedFile.name,+ size: normalizedFile.size,+ });++ try {+ await uploadService.uploadToPresignedUrl(normalizedFile, url, {+ abortController,+ onProgress: (status, uploadState) => {+ onStatusUpdate?.({+ id: statusId,+ type: 'updateFile',+ value: { status: status === 'success' ? 'processing' : status, uploadState },+ });+ },+ });++ const data = await shareChatService.createFile({+ fileType,+ metadata: {+ ...dimensions,+ ...(durationMs === undefined ? {} : { durationMs }),+ },+ name: normalizedFile.name,+ pathname,+ shareId,+ size: normalizedFile.size,+ });++ onStatusUpdate?.({+ id: statusId,+ type: 'updateFile',+ value: {+ ...(dimensions && { dimensions }),+ fileUrl: data.url,+ id: data.id,+ status: 'success',+ uploadState: { progress: 100, restTime: 0, speed: 0 },+ },+ });++ return data;+ } catch (error) {+ await shareChatService.abortUpload(shareId, pathname);+ throw error;+ }+};diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.tsindex bce0910bedf..9efdc5dd6ac 100644--- a/src/store/file/slices/upload/action.ts+++ b/src/store/file/slices/upload/action.ts@@ -70,7 +70,7 @@ interface UploadWithProgressResult {url: string;}-const normalizeUploadedFileType = async (+export const normalizeUploadedFileType = async (file: File,): Promise<{ detectedMimeType?: string; file: File }> => {const { fileTypeFromBlob } = await import('file-type');