🤯 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: support workspace agent sharing (#19733)
YuTengjing6bb53eeca214
diff --git a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts b/apps/server/src/routers/lambda/__tests__/agentGroup.test.tsindex 0307c281f35..2c180122f34 100644--- a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts@@ -353,6 +353,30 @@ describe('agentGroupRouter', () => {});});+ describe('transferGroup to another workspace', () => {+ it('maps a shared owned member failure to SharedTransferBlocked', async () => {+ mockCtx.workspaceId = 'ws-1';+ chatGroupModelMock.findById.mockResolvedValue({+ id: 'cg_1',+ userId,+ workspaceId: 'ws-1',+ });+ agentGroupRepoMock.transferToWorkspace.mockRejectedValue(+ new Error(AgentModelModule.AGENT_SHARED_TRANSFER_BLOCKED),+ );++ await expect(+ agentGroupRouter.createCaller(mockCtx).transferGroup({+ groupId: 'cg_1',+ targetWorkspaceId: 'ws-2',+ }),+ ).rejects.toMatchObject({+ cause: { data: { code: 'AGENT_SHARED_TRANSFER_BLOCKED' } },+ code: 'PRECONDITION_FAILED',+ });+ });+ });+describe('getGroup', () => {it('should get a group by id', async () => {const mockGroup = {diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsindex d35bbc5c166..a8f9ade5172 100644--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -39,21 +39,31 @@ vi.mock('@lobechat/business-const', async () => {});const mockCreate = vi.fn();+const mockFindByShareId = vi.fn();+const mockForceDisableWorkspaceShare = vi.fn();const mockGetByAgentId = vi.fn();+const mockListWorkspaceSharesForAudit = vi.fn();const mockUpdateConfig = vi.fn();const mockUpdateSlug = vi.fn();const mockUpdateVisibility = vi.fn();vi.mock('@/database/models/agentShare', () => ({- AgentShareModel: vi.fn(function () {- return {- create: mockCreate,- getByAgentId: mockGetByAgentId,- updateConfig: mockUpdateConfig,- updateSlug: mockUpdateSlug,- updateVisibility: mockUpdateVisibility,- };- }),+ AgentShareModel: Object.assign(+ vi.fn(function () {+ return {+ create: mockCreate,+ getByAgentId: mockGetByAgentId,+ updateConfig: mockUpdateConfig,+ updateSlug: mockUpdateSlug,+ updateVisibility: mockUpdateVisibility,+ };+ }),+ {+ findByShareId: mockFindByShareId,+ forceDisableWorkspaceShare: mockForceDisableWorkspaceShare,+ listWorkspaceSharesForAudit: mockListWorkspaceSharesForAudit,+ },+ ),}));const mockCountShareVisitors = vi.fn();@@ -96,7 +106,18 @@ describe('agentShareRouter', () => {vi.clearAllMocks();mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;mockCreate.mockResolvedValue(share);+ mockFindByShareId.mockResolvedValue({+ ...share,+ ownerId: 'user-1',+ workspaceId: null,+ });+ mockForceDisableWorkspaceShare.mockResolvedValue({+ agentId: 'agent-1',+ shareId: '00000000-0000-4000-8000-000000000001',+ visibility: 'private',+ });mockGetByAgentId.mockResolvedValue(share);+ mockListWorkspaceSharesForAudit.mockResolvedValue([]);mockUpdateConfig.mockResolvedValue(share);mockUpdateSlug.mockResolvedValue({...share,@@ -139,6 +160,36 @@ describe('agentShareRouter', () => {await expect(caller.getShareStatus({ agentId: 'agent-1' })).resolves.toBeNull();});+ it('requires Workspace context for administrator audit operations', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'admin-1' }));++ await expect(caller.getWorkspaceShareAudit({})).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockListWorkspaceSharesForAudit).not.toHaveBeenCalled();+ });++ it('returns the Workspace share audit projection and force-disables by share id', async () => {+ const caller = agentShareRouter.createCaller(+ await createContextInner({ userId: 'admin-1', workspaceId: 'workspace-1' }),+ );+ const shareId = '00000000-0000-4000-8000-000000000001';++ await caller.getWorkspaceShareAudit({ limit: 25, offset: 50 });+ await caller.forceDisableWorkspaceShare({ shareId });++ expect(mockListWorkspaceSharesForAudit).toHaveBeenCalledWith(expect.anything(), 'workspace-1', {+ limit: 25,+ offset: 50,+ });+ expect(mockForceDisableWorkspaceShare).toHaveBeenCalledWith(+ expect.anything(),+ 'workspace-1',+ shareId,+ expect.objectContaining({ authorizeMutation: expect.any(Function) }),+ );+ });+it('forwards an atomic share configuration patch', async () => {const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));const config = { maxTopicsPerVisitor: 10 };@@ -430,6 +481,8 @@ describe('agentShareRouter', () => {expect(mockGetAgentShareMonthlySpend).toHaveBeenCalledWith({agentId: 'agent-1',ownerUserId: 'user-1',+ shareId: 'share-1',+ workspaceId: undefined,});});diff --git a/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.ts b/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.tsindex a80d0927c0a..c736dcd2bef 100644--- a/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.ts+++ b/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.ts@@ -174,15 +174,15 @@ describe('resourceTransferRequestRouter', () => {expect(mockInvalidate).toHaveBeenCalledWith('agent', ['agent-1']);});- it('surfaces PRECONDITION_FAILED (and keeps the request pending) when the agent is still shared', async () => {+ it('keeps the request pending when a share row still exists', async () => {mockFindById.mockResolvedValue(pendingRequest);mockExecuteAcceptedTransfer.mockRejectedValue(new Error(AGENT_SHARED_TRANSFER_BLOCKED));await expect(caller.accept({ requestId: 'req-1' })).rejects.toMatchObject({code: 'PRECONDITION_FAILED',});- // Recoverable: the previous owner can disable sharing and the recipient- // can retry, so the request must NOT be invalidated.+ // A paused share still blocks ownership transfer; keep the request+ // pending so the initiator can cancel it or retry after row removal.expect(mockInvalidate).not.toHaveBeenCalled();expect(mockInvalidateRequest).not.toHaveBeenCalled();});diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex cbde5d7283a..7bb1b5e4fce 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -131,6 +131,7 @@ describe('shareRouter', () => {shareId: 'agent-share-1',userViewCount: 42,visibility: 'link',+ workspaceId: null,};beforeEach(() => {@@ -178,6 +179,7 @@ describe('shareRouter', () => {tags: ['research'],title: 'Research Assistant',},+ billingScope: 'personal',creator: { avatar: 'owner.png', name: 'Owner Person' },isOwner: false,shareId: 'agent-share-1',@@ -202,7 +204,12 @@ describe('shareRouter', () => {expect(result).not.toHaveProperty('userViewCount');// Visitor topics live under the creator's account, so the counter has to// run as the owner rather than the caller.- expect(topicModelConstructor).toHaveBeenCalledWith(expect.anything(), 'owner-user');+ expect(topicModelConstructor).toHaveBeenCalledWith(+ expect.anything(),+ 'owner-user',+ undefined,+ );+ expect(countShareVisitors).toHaveBeenCalledWith({ agentId: 'agent-1' });expect(AgentShareModel.findBySlugOrId).toHaveBeenCalledWith(expect.anything(),'shared-agent',@@ -214,6 +221,24 @@ describe('shareRouter', () => {);});+ it('identifies a Workspace-funded share without exposing its Workspace id', async () => {+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue({+ ...agentShare,+ workspaceId: 'workspace-1',+ } as any);+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ const result = await caller.getSharedAgent({ slugOrId: 'shared-agent' });++ expect(result.billingScope).toBe('workspace');+ expect(result).not.toHaveProperty('workspaceId');+ expect(topicModelConstructor).toHaveBeenCalledWith(+ expect.anything(),+ 'owner-user',+ 'workspace-1',+ );+ });+describe('uploadAbility', () => {const resolve = async () => {const caller = shareRouter.createCaller(@@ -225,12 +250,20 @@ describe('shareRouter', () => {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(agentServiceConstructor).toHaveBeenCalledWith(+ expect.anything(),+ 'owner-user',+ undefined,+ );expect(resolveModelSelectionMock).toHaveBeenCalledWith({model: 'gpt-4o',provider: 'openai',});- expect(aiModelModelConstructor).toHaveBeenCalledWith(expect.anything(), 'owner-user');+ expect(aiModelModelConstructor).toHaveBeenCalledWith(+ expect.anything(),+ 'owner-user',+ undefined,+ );expect(findByIdAndProviderMock).toHaveBeenCalledWith('gpt-4o', 'openai');});diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex 381b11f8702..a054133f864 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -52,10 +52,14 @@ vi.mock('@/server/featureFlags', () => ({}));const mockAccessCheck = vi.fn();+const mockIsRunStillAuthorized = vi.fn();+const mockLockScopedAgentRow = vi.fn();const mockLockUploadAdmission = vi.fn();vi.mock('@/database/models/agentShare', () => ({AgentShareModel: {findByShareIdWithAccessCheck: (...args: any[]) => mockAccessCheck(...args),+ isRunStillAuthorized: (...args: any[]) => mockIsRunStillAuthorized(...args),+ lockScopedAgentRow: (...args: any[]) => mockLockScopedAgentRow(...args),lockUploadAdmission: (...args: any[]) => mockLockUploadAdmission(...args),},}));@@ -220,6 +224,7 @@ const share = {},shareId: 'share-1',visibility: 'link',+ workspaceId: null,};const visitorTopic = {@@ -238,6 +243,8 @@ describe('shareChatRouter', () => {mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });mockAccessCheck.mockResolvedValue(share);+ mockIsRunStillAuthorized.mockResolvedValue(true);+ mockLockScopedAgentRow.mockResolvedValue({ id: share.agentId, workspaceId: null });mockFindById.mockResolvedValue(visitorTopic);mockIsRunningOperationAlive.mockResolvedValue(true);mockCountBySender.mockResolvedValue(0);@@ -392,7 +399,7 @@ describe('shareChatRouter', () => {await caller.execAgent({ fileIds, prompt: 'look', shareId: 'share-1' });- expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined);expect(mockFileFindByIds).toHaveBeenCalledWith(fileIds, {shareId: share.shareId,type: 'agentShare',@@ -670,11 +677,11 @@ describe('shareChatRouter', () => {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(FileUploadModelMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined);expect(mockReserveUpload).toHaveBeenCalledWith(expect.objectContaining({ pathname: result.pathname, size: 10, userId: OWNER }),);- expect(mockReserveUpload.mock.calls[0][0].workspaceId).toBeUndefined();+ expect(mockReserveUpload.mock.calls[0][0].workspaceId).toBeNull();expect(mockCreatePreSignedUrl).toHaveBeenCalledWith(result.pathname, 10);});@@ -774,7 +781,7 @@ describe('shareChatRouter', () => {const result = await caller.createFile(input);expect(result).toEqual({ id: 'file-new', url: 'https://s3/get' });- expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined);expect(mockFileCreate).toHaveBeenCalledWith(expect.objectContaining({fileType: 'image/png',@@ -798,6 +805,34 @@ describe('shareChatRouter', () => {expect(mockUploadSettle).toHaveBeenCalledWith('upload-1', 'file-new', expect.anything());});+ it('serializes settlement with Agent transfer and revalidates the share after the lock', async () => {+ const caller = await createCaller();++ await caller.createFile(input);++ expect(mockLockScopedAgentRow).toHaveBeenCalledWith({ trx: true }, share.agentId, {+ userId: OWNER,+ workspaceId: undefined,+ });+ expect(mockIsRunStillAuthorized).toHaveBeenCalledWith(+ { trx: true },+ { agentId: share.agentId, shareId: share.shareId },+ );+ expect(mockLockScopedAgentRow.mock.invocationCallOrder[0]).toBeLessThan(+ mockUploadFindLatestForUpdate.mock.invocationCallOrder[0],+ );+ });++ it('rejects settlement when hard revocation wins the Agent row lock', async () => {+ mockLockScopedAgentRow.mockResolvedValue(null);+ const caller = await createCaller();++ await expect(caller.createFile(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockFileCreate).not.toHaveBeenCalled();+ expect(mockUploadSettle).not.toHaveBeenCalled();+ });+it('ignores a client-supplied hash instead of registering the object for dedup', async () => {const caller = await createCaller();@@ -872,7 +907,7 @@ describe('shareChatRouter', () => {await caller.abortUpload({ pathname, shareId: 'share-1' });- expect(FileUploadServiceMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(FileUploadServiceMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined);expect(mockUploadRelease).toHaveBeenCalledWith(pathname);});@@ -897,7 +932,7 @@ describe('shareChatRouter', () => {await caller.removeFile({ fileId: 'file-a', shareId: 'share-1' });- expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER);+ expect(FileModelMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined);expect(mockFileFindById).toHaveBeenCalledWith('file-a', {accessScope: {shareId: share.shareId,@@ -1067,8 +1102,8 @@ describe('shareChatRouter', () => {// Topic model is creator-scoped; the query narrows to this visitor's own// topics on this agent. `agent_shares` is 1:1 per agent, so `(agentId,- // senderId)` unambiguously identifies the share conversation without a- // share-instance column on `topics`.+ // senderId)` identifies the share conversation without a share-instance+ // column on `topics`.expect(TopicModelMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined, undefined, {includeShareVisitor: true,});diff --git a/apps/server/src/routers/lambda/__tests__/video.test.ts b/apps/server/src/routers/lambda/__tests__/video.test.tsindex 815c9769b71..d6553143635 100644--- a/apps/server/src/routers/lambda/__tests__/video.test.ts+++ b/apps/server/src/routers/lambda/__tests__/video.test.ts@@ -337,6 +337,25 @@ describe('videoRouter', () => {});describe('createVideo - pre-charge', () => {+ it('forwards the request spend origin to pre-charge', async () => {+ setupMocks();+ const { chargeBeforeGenerate } =+ await import('@/business/server/video-generation/chargeBeforeGenerate');+ const spendOrigin = {+ agentShare: {+ agentId: 'agent-share',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ trigger: 'agent_share',+ };++ const caller = videoRouter.createCaller({ ...mockCtx, spendOrigin });+ await caller.createVideo(defaultInput);++ expect(chargeBeforeGenerate).toHaveBeenCalledWith(expect.objectContaining({ spendOrigin }));+ });+it('should return error batch when pre-charge fails', async () => {setupMocks();const { chargeBeforeGenerate } =diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex cc3cbfb1cfc..4f67bfb78c1 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -1135,7 +1135,9 @@ export const agentRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ {+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),+ },);} catch (error) {if (@@ -1175,7 +1177,8 @@ export const agentRouter = router({throw new TRPCError({cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },code: 'PRECONDITION_FAILED',- message: 'This agent has a share link, so its owner cannot be changed.',+ message:+ 'This agent cannot be transferred while a share link exists, including paused links.',});}throw error;@@ -1319,7 +1322,9 @@ export const agentRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ {+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),+ },);} catch (error) {if (@@ -1357,7 +1362,8 @@ export const agentRouter = router({throw new TRPCError({cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },code: 'PRECONDITION_FAILED',- message: 'One of these agents has a share link, so its owner cannot be changed.',+ message:+ 'These agents cannot be transferred while a share link exists, including paused links.',});}throw error;diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.tsindex f1f2e53d16c..fabaee7dfd4 100644--- a/apps/server/src/routers/lambda/agentGroup.ts+++ b/apps/server/src/routers/lambda/agentGroup.ts@@ -6,7 +6,7 @@ import { startAgentTransferJob } from '@/business/server/agent-transfer/jobRunneimport { notifyResourceTransfer } from '@/business/server/resource-transfer/notify';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';-import { AgentModel } from '@/database/models/agent';+import { AGENT_SHARED_TRANSFER_BLOCKED, AgentModel } from '@/database/models/agent';import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';import {AGENT_TRANSFER_IN_PROGRESS,@@ -937,6 +937,13 @@ export const agentGroupRouter = router({message: "A previous transfer of this group's agents is still migrating history",});}+ if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },+ code: 'PRECONDITION_FAILED',+ message: 'This group contains a shared agent, so its ownership cannot be changed.',+ });+ }throw error;}diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex cd576a2863a..8ebc735553a 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -6,11 +6,16 @@ import { TRPCError } from '@trpc/server';import { z } from 'zod';import { getAgentShareMonthlySpend } from '@/business/server/agent-share/spendGate';+import { withRbacPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentShareModel } from '@/database/models/agentShare';import { FileModel } from '@/database/models/file';+import { RbacModel } from '@/database/models/rbac';import { TopicModel } from '@/database/models/topic';-import { authedProcedure, router } from '@/libs/trpc/lambda';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';import { assertAgentShareCreationEnabled } from './_helpers/agentShareFeatureGate';@@ -79,16 +84,68 @@ export const agentShareConfigPatchSchema = agentShareConfigSchema.refine('Config patch cannot be empty',);-const agentShareProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+const agentShareProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;+ const workspaceId = ctx.workspaceId ?? undefined;return opts.next({ctx: {- agentShareModel: new AgentShareModel(ctx.serverDB, ctx.userId),+ agentShareModel: new AgentShareModel(ctx.serverDB, ctx.userId, workspaceId, {+ authorizeMutation: workspaceId+ ? (db, agentId) =>+ assertCanPerformResourceAction({+ action: 'manage',+ db,+ resourceId: agentId,+ resourceType: 'agent',+ userId: ctx.userId,+ workspaceId,+ })+ : undefined,+ }),},});});+const workspaceAgentShareAdminProcedure = agentShareProcedure+ .use(withRbacPermission('agent:update:all'))+ .use(async (opts) => {+ if (!opts.ctx.workspaceId) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Workspace context required' });+ }++ return opts.next({ ctx: { workspaceId: opts.ctx.workspaceId } });+ });++interface AgentSharePermissionContext {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+ workspacePermissionCodes?: string[];+}++/**+ * Workspace shares are authority over an Agent, not another General Access+ * grade: private Agents stay creator-only, while public Agents are manageable+ * by their creator or a Workspace admin with `agent:update:all`.+ */+const assertCanManageAgentShare = async (+ ctx: AgentSharePermissionContext,+ agentId: string,+): Promise<void> => {+ if (!ctx.workspaceId) return;++ await assertCanPerformResourceAction({+ action: 'manage',+ db: ctx.serverDB,+ grantedPermissions: ctx.workspacePermissionCodes,+ resourceId: agentId,+ resourceType: 'agent',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+};+/** `updateConfig` / `updateVisibility` / `updateSlug` all return `null` when the share (or its owning agent) does not resolve for this caller. */const requireShare = <T>(share: T | null): T => {if (!share) {@@ -106,20 +163,38 @@ export const agentShareRouter = router({* locked out in the meantime — `getSharedAgent` and the runtime's* `isRunStillAuthorized` both require `link`.*/- disableShare: agentShareProcedure- .input(agentIdInput)- .mutation(async ({ input, ctx }) =>- requireShare(await ctx.agentShareModel.updateVisibility(input.agentId, 'private')),- ),+ disableShare: agentShareProcedure.input(agentIdInput).mutation(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);+ return requireShare(await ctx.agentShareModel.updateVisibility(input.agentId, 'private'));+ }),enableShare: agentShareProcedure.input(agentIdInput.extend({ visibility: z.enum(['private', 'link']).optional() }).strict()).mutation(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);await assertAgentShareCreationEnabled(ctx.userId);return ctx.agentShareModel.create(input.agentId, input.visibility);}),+ /**+ * Minimal Workspace-wide audit inventory. `agent:update:all` is held by+ * administrators, while the model projection intentionally omits private+ * Agent configuration and visitor conversation content.+ */+ getWorkspaceShareAudit: workspaceAgentShareAdminProcedure+ .input(+ z+ .object({+ limit: z.number().int().min(1).max(100).default(50),+ offset: z.number().int().nonnegative().default(0),+ })+ .strict(),+ )+ .query(({ input, ctx }) =>+ AgentShareModel.listWorkspaceSharesForAudit(ctx.serverDB, ctx.workspaceId, input),+ ),+/*** Aggregate usage of one share, for its owner only — `getByAgentId` is* ownership-scoped, so a non-owner never gets past the NOT_FOUND below.@@ -134,13 +209,28 @@ export const agentShareRouter = router({* close the share is to its cap, including drafts visitors never sent.*/getShareStats: agentShareProcedure.input(agentIdInput).query(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);const share = requireShare(await ctx.agentShareModel.getByAgentId(input.agentId));+ const resolvedShare = requireShare(await AgentShareModel.findByShareId(ctx.serverDB, share.id));- const topicModel = new TopicModel(ctx.serverDB, ctx.userId);- const fileModel = new FileModel(ctx.serverDB, ctx.userId);+ const topicModel = new TopicModel(+ ctx.serverDB,+ resolvedShare.ownerId,+ resolvedShare.workspaceId ?? undefined,+ );+ const fileModel = new FileModel(+ ctx.serverDB,+ resolvedShare.ownerId,+ resolvedShare.workspaceId ?? undefined,+ );const [visitors, monthlySpend, fileStorageUsed] = await Promise.all([topicModel.countShareVisitors({ agentId: input.agentId }),- getAgentShareMonthlySpend({ agentId: input.agentId, ownerUserId: ctx.userId }),+ getAgentShareMonthlySpend({+ agentId: input.agentId,+ ownerUserId: resolvedShare.ownerId,+ shareId: share.id,+ workspaceId: resolvedShare.workspaceId ?? undefined,+ }),fileModel.countAgentShareUsage(share.id),]);@@ -159,9 +249,40 @@ export const agentShareRouter = router({};}),- getShareStatus: agentShareProcedure- .input(agentIdInput)- .query(async ({ input, ctx }) => ctx.agentShareModel.getByAgentId(input.agentId)),+ getShareStatus: agentShareProcedure.input(agentIdInput).query(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);+ return ctx.agentShareModel.getByAgentId(input.agentId);+ }),++ /**+ * Administrator emergency stop for any share in the active Workspace,+ * including private Agents the administrator cannot otherwise configure.+ */+ forceDisableWorkspaceShare: workspaceAgentShareAdminProcedure+ .input(z.object({ shareId: z.string().uuid() }).strict())+ .mutation(async ({ input, ctx }) =>+ requireShare(+ await AgentShareModel.forceDisableWorkspaceShare(+ ctx.serverDB,+ ctx.workspaceId,+ input.shareId,+ {+ authorizeMutation: async (db) => {+ const allowed = await new RbacModel(db, ctx.userId).hasPermission(+ 'agent:update:all',+ { workspaceId: ctx.workspaceId },+ );+ if (!allowed) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'You do not have permission to perform this action.',+ });+ }+ },+ },+ ),+ ),+ ),updateShareConfig: agentShareProcedure.input(@@ -172,9 +293,10 @@ export const agentShareRouter = router({}).strict(),)- .mutation(async ({ input, ctx }) =>- requireShare(await ctx.agentShareModel.updateConfig(input.agentId, input.config)),- ),+ .mutation(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);+ return requireShare(await ctx.agentShareModel.updateConfig(input.agentId, input.config));+ }),/*** Custom URL slug for this share's public link. Pattern/reserved-word@@ -192,9 +314,10 @@ export const agentShareRouter = router({}).strict(),)- .mutation(async ({ input, ctx }) =>- requireShare(await ctx.agentShareModel.updateSlug(input.agentId, input.slug)),- ),+ .mutation(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);+ return requireShare(await ctx.agentShareModel.updateSlug(input.agentId, input.slug));+ }),updateVisibility: agentShareProcedure.input(@@ -206,6 +329,7 @@ export const agentShareRouter = router({.strict(),).mutation(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);// Flipping to `link` publishes the share, so it is the same capability// as `enableShare`; going back to `private` unpublishes and stays open.if (input.visibility === 'link') await assertAgentShareCreationEnabled(ctx.userId);diff --git a/apps/server/src/routers/lambda/resourceTransferRequest.ts b/apps/server/src/routers/lambda/resourceTransferRequest.tsindex 10fdf2cf64a..c0888bced58 100644--- a/apps/server/src/routers/lambda/resourceTransferRequest.ts+++ b/apps/server/src/routers/lambda/resourceTransferRequest.ts@@ -288,13 +288,14 @@ export const resourceTransferRequestRouter = router({});}if (error.message === AGENT_SHARED_TRANSFER_BLOCKED) {- // Not permanently stale: once the share row is removed (no product- // entry point yet — see the `transferAgents` guard) the recipient- // can retry, so the request stays pending.+ // A share row, including a paused row, blocks ownership transfer.+ // Keep this request pending so it can be canceled or retried only+ // after the share row is actually removed.throw new TRPCError({cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },code: 'PRECONDITION_FAILED',- message: 'This agent has a share link, so its owner cannot be changed.',+ message:+ 'This agent cannot be transferred while a share link exists, including paused links.',});}}diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex 5ad82126f5d..746a1802d47 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -47,21 +47,27 @@ const log = debug('lobe-server:router:share');*/const resolveVisitorUploadAbility = async (db: LobeChatDatabase,- share: { agentModel: string | null; agentProvider: string | null; ownerId: string },+ share: {+ agentModel: string | null;+ agentProvider: string | null;+ ownerId: string;+ workspaceId: string | null;+ },): 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({+ new AgentService(db, share.ownerId, share.workspaceId ?? undefined).resolveModelSelection({model: share.agentModel,provider: share.agentProvider,}),]);- const ownerModel = await new AiModelModel(db, share.ownerId).findByIdAndProvider(- model,- provider,- );+ const ownerModel = await new AiModelModel(+ db,+ share.ownerId,+ share.workspaceId ?? undefined,+ ).findByIdAndProvider(model, provider);const abilities = resolveModelMediaCapabilities({builtinModels,model,@@ -136,7 +142,11 @@ export const shareRouter = router({resolveVisitorUploadAbility(ctx.serverDB, share),(async () => {try {- const topicModel = new TopicModel(ctx.serverDB, share.ownerId);+ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );const counts = await topicModel.countShareVisitors({ agentId: share.agentId });stats = { conversations: counts.topicCount, visitors: counts.visitorCount };} catch (error) {@@ -156,6 +166,7 @@ export const shareRouter = router({tags: share.agentTags ?? [],title: share.agentTitle,},+ billingScope: share.workspaceId ? 'workspace' : 'personal',creator: {avatar: share.ownerAvatar ?? null,name: share.ownerFullName ?? share.ownerUsername ?? null,diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex 2b7edf4b022..da01ad179cf 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -45,26 +45,22 @@ const log = debug('lobe-server:router:shareChat');/*** Visitor-facing execution chain for shared agents (Agent Share).*- * All procedures authenticate the VISITOR (ctx.userId) but operate on- * CREATOR-owned rows: topics/messages of a share conversation carry the- * creator's userId (so runtime, billing, and tool paths behave exactly as a- * creator-owned chat) plus `topics.senderId = visitor` for scoping. Every+ * All procedures authenticate the VISITOR (ctx.userId) but operate on rows in+ * the Agent's owning scope: topics/messages carry the creator's userId plus the+ * Agent's workspaceId when present, and `topics.senderId = visitor` for+ * scoping. Every* read/write here is therefore manually authorized: resolve the share via* {@link resolveLinkShareOrThrow}, then require* `topic.senderId === visitor && topic.agentId === share.agentId`* ({@link findVisitorTopicOrThrow}).*- * There is no share-instance column on `topics`: a visitor topic is tied to- * its share purely through `(agentId, senderId)`, which is unambiguous because- * `agent_shares` is 1:1 per agent. The known consequence is that a visitor's- * own older topics resurface after an owner disables and re-enables the share- * (a pause that keeps the same row, so nothing marks the topics as belonging- * to an earlier run of it). That crosses no identity boundary — it is the same- * visitor's own prior conversation with the same agent — but it does mean the- * per-visitor topic cap counts them.+ * A visitor topic is tied to its share through `(agentId, senderId)`. Turning+ * sharing off and back on keeps the same share row, so that visitor's older+ * conversations remain available and continue counting toward the topic cap.*- * Agent sharing is personal-only (workspace agents cannot be shared), so no- * workspaceId is ever threaded into the creator-scoped models/services.+ * Workspace identity is resolved from the share row, never from visitor+ * headers, and is threaded through every model/service that persists data or+ * invokes the runtime.*/const shareChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {// Visitor access depends on deployment support and share permissions,@@ -190,7 +186,7 @@ const authorizeVisitorRunningOperation = async () => {const share = await resolveLinkShareOrThrow(db, input.shareId, visitorUserId);- const topicModel = new TopicModel(db, share.ownerId, undefined, undefined, {+ const topicModel = new TopicModel(db, share.ownerId, share.workspaceId ?? undefined, undefined, {includeShareVisitor: true,});const topic = await findVisitorTopicOrThrow(topicModel, {@@ -209,6 +205,7 @@ const authorizeVisitorRunningOperation = async (const aiAgentService = new AiAgentService(db, share.ownerId, {includeShareVisitor: true,+ workspaceId: share.workspaceId ?? undefined,});return { aiAgentService, share };@@ -221,8 +218,14 @@ const authorizeVisitorRunningOperation = async (* 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}/`;+const shareUploadPrefix = (share: {+ ownerId: string;+ shareId: string;+ workspaceId: string | null;+}) =>+ share.workspaceId+ ? `files/workspaces/${share.workspaceId}/agent-share/${share.shareId}/`+ : `files/${share.ownerId}/agent-share/${share.shareId}/`;/*** Visitor-facing storage refusal, one shape for two causes: the share's own@@ -267,14 +270,14 @@ const sanitizeUploadName = (name: string) =>*/const assertShareVisitorFiles = async (db: LobeChatDatabase,- share: { ownerId: string; shareId: string },+ share: { ownerId: string; shareId: string; workspaceId: string | null },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(+ const rows = await new FileModel(db, share.ownerId, share.workspaceId ?? undefined).findByIds(uniqueIds,agentShareFileAccessScope({ shareId: share.shareId, visitorUserId }),);@@ -310,11 +313,15 @@ export const shareChatRouter = router({.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))) {+ if (!input.pathname.startsWith(shareUploadPrefix(share))) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });}- const fileUploadService = new FileUploadService(ctx.serverDB, share.ownerId);+ const fileUploadService = new FileUploadService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );const upload = await fileUploadService.findLatest(input.pathname);if (upload?.status === 'active') await fileUploadService.release(input.pathname);@@ -354,12 +361,20 @@ export const shareChatRouter = router({).mutation(async ({ input, ctx }) => {const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- if (!input.pathname.startsWith(shareUploadPrefix(share.ownerId, share.shareId))) {+ if (!input.pathname.startsWith(shareUploadPrefix(share))) {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);+ const fileUploadService = new FileUploadService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );+ const fileService = new FileService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );// No legacy (reservation-less) path here: the share upload flow was born// with reservations, so a pathname without an active session is either@@ -386,6 +401,26 @@ export const shareChatRouter = router({const dirname = parts.join('/');const { id } = await ctx.serverDB.transaction(async (trx) => {+ // Transfer hard revocation locks this same Agent row before it snapshots+ // and deletes share files. Taking the lock first gives the two paths a+ // single order: if settlement wins, transfer sees and removes this+ // file; if transfer wins, the locked recheck below rejects the stale+ // share before a new file row can escape the cleanup snapshot.+ const tx = trx as LobeChatDatabase;+ const lockedAgent = await AgentShareModel.lockScopedAgentRow(tx, share.agentId, {+ userId: share.ownerId,+ workspaceId: share.workspaceId ?? undefined,+ });+ if (+ !lockedAgent ||+ !(await AgentShareModel.isRunStillAuthorized(tx, {+ agentId: share.agentId,+ shareId: share.shareId,+ }))+ ) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' });+ }+const lockedUpload = await fileUploadService.model.findLatestByPathnameForUpdate(input.pathname,trx,@@ -394,7 +429,11 @@ export const shareChatRouter = router({throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });}- const file = await new FileModel(ctx.serverDB, share.ownerId).create(+ const file = await new FileModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ ).create({fileType: input.fileType,metadata: {@@ -460,11 +499,15 @@ export const shareChatRouter = router({throw shareStorageBlocked('share_limit');}- const prefix = shareUploadPrefix(share.ownerId, share.shareId);+ const prefix = shareUploadPrefix(share);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);+ const uploadModel = new FileUploadModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );+ const fileModel = new FileModel(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined);try {await reserveUpload({@@ -488,6 +531,7 @@ export const shareChatRouter = router({size: input.size,storage: s3,userId: share.ownerId,+ workspaceId: share.workspaceId,});} catch (error) {throw toVisitorStorageBlock(error);@@ -496,7 +540,11 @@ export const shareChatRouter = router({try {return { pathname, url: await s3.createPreSignedUrl(pathname, input.size) };} catch (error) {- await new FileUploadService(ctx.serverDB, share.ownerId).releaseBestEffort(pathname);+ await new FileUploadService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ ).releaseBestEffort(pathname);throw error;}}),@@ -548,6 +596,7 @@ export const shareChatRouter = router({ownerUserId: share.ownerId,shareId: share.shareId,visitorUserId: ctx.userId,+ workspaceId: share.workspaceId ?? undefined,});if (!spendGate.allowed) {throw new TRPCError({@@ -569,12 +618,20 @@ export const shareChatRouter = router({share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR;const maxTurnsPerTopic =share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;- const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {- includeShareVisitor: true,- });- const messageModel = new MessageModel(ctx.serverDB, share.ownerId, undefined, undefined, {- includeShareVisitor: true,- });+ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ const messageModel = new MessageModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );// Fast, UX-only pre-check for both caps: reject an obviously-over-cap// request BEFORE paying for agent-config/tool resolution, instead of only@@ -630,12 +687,14 @@ export const shareChatRouter = router({// Creator's Market access token, mirroring aiAgentProcedure — the// server-side tool runtime authenticates against the Market API with it.let marketAccessToken: string | undefined;- try {- const userModel = new UserModel(ctx.serverDB, share.ownerId);- const settings = await userModel.getUserSettings();- marketAccessToken = (settings?.market as any)?.accessToken;- } catch {- // non-fatal — MarketService falls back to trustedClientToken+ if (!share.workspaceId) {+ try {+ const userModel = new UserModel(ctx.serverDB, share.ownerId);+ const settings = await userModel.getUserSettings();+ marketAccessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal — MarketService falls back to trustedClientToken+ }}const aiAgentService = new AiAgentService(ctx.serverDB, share.ownerId, {@@ -645,6 +704,7 @@ export const shareChatRouter = router({// `topics.senderId <> NULL` rows aren't filtered out.includeShareVisitor: true,marketAccessToken,+ workspaceId: share.workspaceId ?? undefined,});log('execAgent: share=%s visitor=%s topic=%s', input.shareId, ctx.userId, input.topicId);@@ -724,19 +784,31 @@ export const shareChatRouter = router({getMessages: shareChatProcedure.input(ShareTopicScopeSchema).query(async ({ input, ctx }) => {const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {- includeShareVisitor: true,- });+ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );await findVisitorTopicOrThrow(topicModel, {agentId: share.agentId,topicId: input.topicId,visitorUserId: ctx.userId,});- const messageModel = new MessageModel(ctx.serverDB, share.ownerId, undefined, undefined, {- includeShareVisitor: true,- });- const fileService = new FileService(ctx.serverDB, share.ownerId);+ const messageModel = new MessageModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ const fileService = new FileService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );// queryForVisitor strips the creator's `sender` identity, and — unless the// share opts in via `showModelInfo` / `showErrorDetails` — the spend/model@@ -769,9 +841,13 @@ export const shareChatRouter = router({// what a visitor already created. Tying the page size to it would hide// those older conversations with no pagination or deep link to reach// them, so the model applies its own fixed, generous list bound instead.- const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {- includeShareVisitor: true,- });+ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );return topicModel.queryBySender({agentId: share.agentId,senderId: ctx.userId,@@ -890,9 +966,13 @@ export const shareChatRouter = router({.query(async ({ input, ctx }) => {const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {- includeShareVisitor: true,- });+ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );const topic = await findVisitorTopicOrThrow(topicModel, {agentId: share.agentId,topicId: input.topicId,@@ -934,7 +1014,7 @@ export const shareChatRouter = router({.mutation(async ({ input, ctx }) => {const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- const fileModel = new FileModel(ctx.serverDB, share.ownerId);+ const fileModel = new FileModel(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined);const accessScope = agentShareFileAccessScope({shareId: share.shareId,visitorUserId: ctx.userId,@@ -950,7 +1030,9 @@ export const shareChatRouter = router({});if (!file) return;- await new FileService(ctx.serverDB, share.ownerId).deleteFile(file.url!);+ await new FileService(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined).deleteFile(+ file.url!,+ );}),});diff --git a/apps/server/src/routers/lambda/video/index.ts b/apps/server/src/routers/lambda/video/index.tsindex 6555605abc1..59ff5f88d65 100644--- a/apps/server/src/routers/lambda/video/index.ts+++ b/apps/server/src/routers/lambda/video/index.ts@@ -175,6 +175,7 @@ export const videoRouter = router({model,params,provider,+ spendOrigin: ctx.spendOrigin,userId,workspaceId: wsId,});diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex be448351a1e..c77708daf51 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -528,9 +528,7 @@ export const setupTurn = async (// `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,// `queryRecent`, `rank`) filter out via `notShareVisitorTopic()`, and// what lets shareChat scope reads per visitor (`queryBySender` /- // `countBySender`). There is no share-instance column — a visitor- // topic is tied to its share purely through `(agentId, senderId)`,- // which is unambiguous because `agent_shares` is 1:1 per agent.+ // `countBySender`).senderId: shareGate?.visitorUserId,title:title !== undefineddiff --git a/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts b/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.tsindex 1fbc944694c..53970299370 100644--- a/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts+++ b/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts@@ -2,19 +2,19 @@ import type { LobeChatDatabase } from '@lobechat/database';import type { CreateMessageParams, DBMessageItem } from '@lobechat/types';import { ChatErrorType } from '@lobechat/types';import { TRPCError } from '@trpc/server';-import { eq } from 'drizzle-orm';+import { and, eq, isNull } from 'drizzle-orm';import { AgentShareModel } from '@/database/models/agentShare';import { MessageModel } from '@/database/models/message';import type { CreateTopicParams } from '@/database/models/topic';import { TopicModel } from '@/database/models/topic';import type { TopicItem } from '@/database/schemas';-import { agentShares } from '@/database/schemas';+import { agents, agentShares } from '@/database/schemas';/*** Re-validate the share is still the SAME live `link` share this request was* authorized against, from INSIDE the same `agents.id FOR UPDATE` transaction- * `AgentShareModel.lockOwnedAgentRow` just took.+ * `AgentShareModel.lockScopedAgentRow` just took.** WHY this must run BEFORE the topic/message INSERT the two guard functions* below perform, not only later: an owner who makes the link private while a@@ -32,11 +32,19 @@ const assertShareStillAuthorized = async (tx: LobeChatDatabase,agentId: string,expectedShareId: string,+ workspaceId?: string,): Promise<void> => {const [share] = await tx.select({ id: agentShares.id, visibility: agentShares.visibility }).from(agentShares)- .where(eq(agentShares.agentId, agentId));+ .innerJoin(agents, eq(agentShares.agentId, agents.id))+ .where(+ and(+ eq(agentShares.agentId, agentId),+ eq(agentShares.id, expectedShareId),+ workspaceId ? eq(agents.workspaceId, workspaceId) : isNull(agents.workspaceId),+ ),+ );if (!share || share.visibility !== 'link' || share.id !== expectedShareId) {throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });@@ -55,7 +63,7 @@ const assertShareStillAuthorized = async (* serializing them. Concurrent new-topic requests from the same visitor can* all observe the same pre-insert count and all insert.*- * `AgentShareModel.lockOwnedAgentRow` takes `FOR UPDATE` on the SAME+ * `AgentShareModel.lockScopedAgentRow` takes `FOR UPDATE` on the SAME* `agents.id` row every other share-mutation path locks (`create`,* `updateConfig`, `updateVisibility`, `deleteByAgentId`). The recount and the* INSERT both run inside that one locked transaction, so whichever of two@@ -93,14 +101,17 @@ export const reserveShareVisitorTopicOrThrow = async (params: {// Fail closed: a deleted/transferred/no-longer-owned agent never gets a// new visitor topic, same as every other share-mutation path locking this- // row — see `lockOwnedAgentRow`'s JSDoc.- const locked = await AgentShareModel.lockOwnedAgentRow(tx, agentId, ownerId);+ // row — see `lockScopedAgentRow`'s JSDoc.+ const locked = await AgentShareModel.lockScopedAgentRow(tx, agentId, {+ userId: ownerId,+ workspaceId,+ });if (!locked) {throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });}// Fail closed BEFORE any row is written.- await assertShareStillAuthorized(tx, agentId, expectedShareId);+ await assertShareStillAuthorized(tx, agentId, expectedShareId, workspaceId);// Fresh read under the lock, not a caller-supplied value — see this// function's JSDoc for the stale-cap flood this closes.@@ -156,7 +167,7 @@ export const reserveShareVisitorTopic = (* burst of concurrent sends to the SAME topic can all pass the pre-check and* all insert.*- * Locked via `AgentShareModel.lockOwnedAgentRow` — the SAME `agents.id FOR+ * Locked via `AgentShareModel.lockScopedAgentRow` — the SAME `agents.id FOR* UPDATE` row {@link reserveShareVisitorTopicOrThrow} and every other* share-mutation path lock, not a topic-scoped lock, so the cap read below* also conflicts with a concurrent `updateConfig`. The trade-off is coarser@@ -180,13 +191,16 @@ export const reserveShareVisitorTurnOrThrow = async (params: {const tx = trx as unknown as LobeChatDatabase;// Fail closed: same ownership/existence check as the topic guard.- const locked = await AgentShareModel.lockOwnedAgentRow(tx, agentId, ownerId);+ const locked = await AgentShareModel.lockScopedAgentRow(tx, agentId, {+ userId: ownerId,+ workspaceId,+ });if (!locked) {throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });}// Fail closed BEFORE any row is written.- await assertShareStillAuthorized(tx, agentId, expectedShareId);+ await assertShareStillAuthorized(tx, agentId, expectedShareId, workspaceId);// Fresh read under the lock, not a caller-supplied value.const { maxTurnsPerTopic } = await AgentShareModel.readCurrentVisitorCaps(tx, agentId);diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex dfaf8d84564..5b54f767dc0 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -311,6 +311,7 @@"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.maxFileStorageWorkspaceHint": "Files visitors attach are stored in the Workspace. 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",@@ -318,6 +319,7 @@"share.settings.limits.monthlySpendLimit": "Monthly spend cap (M credits)","share.settings.limits.monthlySpendLimitHint": "Visitor runs stop once this month’s spend on this Agent reaches the cap. Resets on the 1st of each month (UTC).","share.settings.limits.title": "Limits",+ "share.settings.limits.workspaceDesc": "Every visitor run is billed to the Workspace budget, not to the visitor or any member quota. These per-Agent caps always apply — you can change the numbers, but not turn them off.","share.settings.link.copied": "Link copied","share.settings.link.copy": "Copy link","share.settings.link.desc": "Anyone signed in who has the link can chat with this Agent. Runs execute on your account.",@@ -335,8 +337,11 @@"share.settings.link.slugSaved": "Custom link updated","share.settings.link.title": "Share link","share.settings.link.viewCount": "{{views}} views",+ "share.settings.link.workspaceDesc": "Anyone signed in who has the link can chat with this Agent. Runs execute in the Workspace and are charged to its budget.","share.settings.notice.desc": "Visitors don’t just read this Agent — they run it. Every reply is generated on your account and charged to your balance, and the Agent acts with whatever access you grant below.","share.settings.notice.title": "Visitors run this Agent on your account",+ "share.settings.notice.workspaceDesc": "Visitors don’t just read this Agent — they run it. Every reply is generated in the Workspace and charged to its shared budget, without consuming the creator’s or another member’s quota. The Agent only acts with the visitor access you grant below.",+ "share.settings.notice.workspaceTitle": "Visitors run this Agent on the Workspace budget","share.settings.permissions.allowCreatorViewSessions": "Let me read visitor conversations","share.settings.permissions.allowCreatorViewSessionsHint": "Off by default: visitor conversations stay private to the visitor.","share.settings.permissions.allowReadMemory": "Allow reading my memory",@@ -396,11 +401,13 @@"share.visitor.input.send": "Send","share.visitor.input.stop": "Stop","share.visitor.privacyNotice": "This conversation runs on the owner’s account and may be visible to them. Avoid sharing sensitive information.",+ "share.visitor.privacyNoticeWorkspace": "This conversation is paid for by the Workspace and may be visible to the Agent creator. Avoid sharing sensitive information.","share.visitor.profile.about": "About","share.visitor.profile.createdBy": "Created by {{creator}}","share.visitor.profile.cta": "Start a conversation","share.visitor.profile.ctaSignIn": "Sign in to start","share.visitor.profile.freeNote": "Free · paid for by the creator",+ "share.visitor.profile.freeNoteWorkspace": "Free · paid for by the Workspace","share.visitor.profile.metrics.conversations": "Conversations","share.visitor.profile.metrics.conversationsCaption": "started so far","share.visitor.profile.metrics.tools": "Open tools",@@ -414,6 +421,7 @@"share.visitor.profile.starters.desc": "Pick one and it goes straight into the composer.","share.visitor.profile.starters.title": "Not sure where to start?","share.visitor.profile.terms.account": "It runs on the creator’s account, and every reply is paid for by them.",+ "share.visitor.profile.terms.accountWorkspace": "It runs in the owner Workspace, and every reply is paid from the Workspace budget.","share.visitor.profile.terms.desc": "Today these rules only show up as errors once you hit them. Here they are up front.","share.visitor.profile.terms.title": "Before you start","share.visitor.profile.terms.tools_one": "{{count}} tool is open to visitors.",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e914166f4d3..acf8515c3d5 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1341,6 +1341,7 @@"pageSelection.lines": "Lines {{start}}-{{end}}","pageSelection.reference": "Selected Text","permission.configAccess.agentChatOnly": "You can only use this Agent, not configure it. You were returned to chat.",+ "permission.configAccess.agentManageRestricted": "Only the Agent creator or a workspace admin can manage external sharing. You were returned to chat.","permission.configAccess.agentRoleRestricted": "Your workspace role cannot configure Agents. You were returned to chat.","permission.configAccess.groupChatOnly": "You can only use this Agent Group, not configure it. You were returned to chat.","permission.configAccess.groupRoleRestricted": "Your workspace role cannot configure Agent Groups. You were returned to chat.",diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 2d6246314b5..5811d0e35c8 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -130,7 +130,7 @@"transfer.ownerOnly": "Only workspace owners can transfer resources created by other members.","transfer.resourceNotFound": "This resource no longer exists or you no longer have access. Refresh and try again.","transfer.sameWorkspace": "This resource is already in the selected workspace. Choose another target.",- "transfer.sharedTransferBlocked": "This agent has a share link, so its owner cannot be changed.",+ "transfer.sharedTransferBlocked": "This agent has a share link and cannot be transferred, even while sharing is paused.","transfer.targetIsCurrentOwner": "This agent already belongs to that member. Pick someone else.","transfer.targetNoWriteAccess": "You need Member or Owner access to move resources into the target workspace.","transfer.targetNotWorkspaceMember": "The selected recipient is not an active member of this workspace. Refresh the member list and try again.",diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex 4700e427621..17ca714a68c 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -70,6 +70,26 @@"comparePlans": "View Plans","createSubscriptionError": "Failed to create subscription","creditUsageReminder.title": "{{percent}} of the subscription credits included in this billing cycle have been used",+ "credits.agentShareBudget.audit.agent": "Agent {{id}}",+ "credits.agentShareBudget.audit.desc": "Admins can audit and pause external links without opening private Agent configuration or visitor conversations.",+ "credits.agentShareBudget.audit.disable": "Pause link",+ "credits.agentShareBudget.audit.disableError": "Failed to pause the share link",+ "credits.agentShareBudget.audit.disableSuccess": "Share link paused",+ "credits.agentShareBudget.audit.empty": "No Workspace Agent has been shared externally.",+ "credits.agentShareBudget.audit.owner": "Owner",+ "credits.agentShareBudget.audit.ownerUnavailable": "Unknown member",+ "credits.agentShareBudget.audit.statusActive": "Active",+ "credits.agentShareBudget.audit.statusPaused": "Paused",+ "credits.agentShareBudget.audit.title": "Workspace share audit",+ "credits.agentShareBudget.audit.views": "{{views}} views",+ "credits.agentShareBudget.desc": "Set one monthly safety cap across all externally shared Workspace Agents",+ "credits.agentShareBudget.limit": "Workspace monthly cap",+ "credits.agentShareBudget.limitHint": "Leave blank for no Workspace-wide cap. Set 0 to pause all visitor runs. These charges use Workspace credits and never consume a member quota.",+ "credits.agentShareBudget.save": "Save",+ "credits.agentShareBudget.saveError": "Failed to save the Agent Share budget policy",+ "credits.agentShareBudget.saveSuccess": "Agent Share budget policy saved",+ "credits.agentShareBudget.title": "External Agent sharing",+ "credits.agentShareBudget.unlimited": "No Workspace-wide cap","credits.autoTopUp.cardBindingGiftHint": "🎁 Add your first payment method and get 1M credits free","credits.autoTopUp.currentBalance": "Current Balance","credits.autoTopUp.desc": "Ensure your credits never run out",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex e9792123e77..8c90c69f958 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -311,6 +311,7 @@"share.settings.limits.desc": "访客的每次运行都记在你的账户上,这些上限是分享链接不会跑出高额账单的唯一保障。上限始终生效,你可以调整数值,但不能关闭。","share.settings.limits.maxFileStorage": "文件存储上限(MB)","share.settings.limits.maxFileStorageHint": "访客上传的文件会存放在你的账号里。累计达到这个总量后就不能再上传;填 0 表示关闭附件功能。",+ "share.settings.limits.maxFileStorageWorkspaceHint": "访客上传的文件会存放在工作区内。累计达到这个总量后就不能再上传;填 0 表示关闭附件功能。","share.settings.limits.maxTopicsPerVisitor": "每位访客的会话数","share.settings.limits.maxTopicsPerVisitorHint": "每位已登录访客最多能发起多少个独立会话。","share.settings.limits.maxTurnsPerTopic": "每个会话的轮次",@@ -318,6 +319,7 @@"share.settings.limits.monthlySpendLimit": "每月消耗上限(M 积分)","share.settings.limits.monthlySpendLimitHint": "本月该助手的消耗达到上限后,访客将无法继续运行。按自然月统计,每月 1 日(UTC)重置。","share.settings.limits.title": "使用限制",+ "share.settings.limits.workspaceDesc": "访客的每次运行都会从工作区预算扣费,不会扣访客余额,也不占用创建者或其他成员的个人额度。每个智能体的这些上限始终生效,你可以调整数值,但不能关闭。","share.settings.link.copied": "链接已复制","share.settings.link.copy": "复制链接","share.settings.link.desc": "任何拿到链接并已登录的人都能和这个助手对话,运行都发生在你的账户上。",@@ -335,8 +337,11 @@"share.settings.link.slugSaved": "自定义链接已更新","share.settings.link.title": "分享链接","share.settings.link.viewCount": "被浏览 {{views}} 次",+ "share.settings.link.workspaceDesc": "任何拿到链接并已登录的人都能和这个助手对话,运行发生在工作区内,并从工作区预算扣费。","share.settings.notice.desc": "访客不只是查看这个助手,而是真的在运行它。每一次回复都由你的账户生成并扣你的余额,助手也会带着你在下面授予的权限行动。","share.settings.notice.title": "访客将在你的账户上运行此助手",+ "share.settings.notice.workspaceDesc": "访客不只是查看这个助手,而是真的在运行它。每一次回复都在工作区内生成并从工作区共享预算扣费,不占用创建者或其他成员的个人额度。助手只会使用你在下面授予访客的权限。",+ "share.settings.notice.workspaceTitle": "访客将使用工作区预算运行此助手","share.settings.permissions.allowCreatorViewSessions": "允许我查看访客会话","share.settings.permissions.allowCreatorViewSessionsHint": "默认关闭:访客的会话内容只有访客自己能看到。","share.settings.permissions.allowReadMemory": "允许读取我的记忆",@@ -396,11 +401,13 @@"share.visitor.input.send": "发送","share.visitor.input.stop": "停止","share.visitor.privacyNotice": "本次会话运行在创建者的账号下,内容可能对创建者可见,请勿发送敏感信息。",+ "share.visitor.privacyNoticeWorkspace": "本次会话由工作区付费,内容可能对智能体创建者可见,请勿发送敏感信息。","share.visitor.profile.about": "简介","share.visitor.profile.createdBy": "由 {{creator}} 创建","share.visitor.profile.cta": "开始对话","share.visitor.profile.ctaSignIn": "登录后开始","share.visitor.profile.freeNote": "免费 · 由创建者付费",+ "share.visitor.profile.freeNoteWorkspace": "免费 · 由工作区付费","share.visitor.profile.metrics.conversations": "累计对话","share.visitor.profile.metrics.conversationsCaption": "次会话","share.visitor.profile.metrics.tools": "开放工具",@@ -414,6 +421,7 @@"share.visitor.profile.starters.desc": "点一条,它会直接带进输入框。","share.visitor.profile.starters.title": "不知道从哪开始?","share.visitor.profile.terms.account": "它运行在创建者的账号上,每一次回复都由创建者付费。",+ "share.visitor.profile.terms.accountWorkspace": "它运行在所属工作区内,每一次回复都从工作区预算扣费。","share.visitor.profile.terms.desc": "这几条规则今天只在你撞上时以报错的形式出现,这里把它们提前讲清楚。","share.visitor.profile.terms.title": "开始之前","share.visitor.profile.terms.tools_one": "{{count}} 个工具对访客开放。",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7feeb77f449..b80e46d9fcc 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1341,6 +1341,7 @@"pageSelection.lines": "第 {{start}}-{{end}} 行","pageSelection.reference": "选中文本","permission.configAccess.agentChatOnly": "您对此代理只有使用权限,无法配置。您已返回到聊天界面。",+ "permission.configAccess.agentManageRestricted": "只有代理创建者或工作区管理员可以管理外部分享。您已返回到聊天界面。","permission.configAccess.agentRoleRestricted": "您的工作区角色无法配置代理。您已返回到聊天界面。","permission.configAccess.groupChatOnly": "您对此代理组只有使用权限,无法配置。您已返回到聊天界面。","permission.configAccess.groupRoleRestricted": "您的工作区角色无法配置代理组。您已返回到聊天界面。",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex b8c23368c89..55b7da71f70 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -130,7 +130,7 @@"transfer.ownerOnly": "只有工作区所有者可以转移其他成员创建的资源。","transfer.resourceNotFound": "此资源已不存在或您已无法访问。请刷新后重试。","transfer.sameWorkspace": "此资源已在选定的工作区中。请选择其他目标。",- "transfer.sharedTransferBlocked": "该 Agent 已创建过分享链接,暂不能变更所有者。",+ "transfer.sharedTransferBlocked": "该 Agent 已创建分享链接,暂不支持转移;暂停分享后仍不可转移。","transfer.targetIsCurrentOwner": "该 Agent 已属于这位成员,请选择其他人。","transfer.targetNoWriteAccess": "您需要成员或所有者权限才能将资源移动到目标工作区。","transfer.targetNotWorkspaceMember": "所选接收人不是该工作区的有效成员。请刷新成员列表后重试。",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex d1fedbb041d..2751a44728d 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -70,6 +70,26 @@"comparePlans": "查看套餐","createSubscriptionError": "创建订阅失败","creditUsageReminder.title": "当前计费周期包含的订阅积分已使用 {{percent}}",+ "credits.agentShareBudget.audit.agent": "智能体 {{id}}",+ "credits.agentShareBudget.audit.desc": "管理员可以审计和暂停对外链接,但不能借此打开私有智能体配置或访客会话正文。",+ "credits.agentShareBudget.audit.disable": "暂停链接",+ "credits.agentShareBudget.audit.disableError": "分享链接暂停失败",+ "credits.agentShareBudget.audit.disableSuccess": "分享链接已暂停",+ "credits.agentShareBudget.audit.empty": "当前没有对外分享的工作区智能体。",+ "credits.agentShareBudget.audit.owner": "所有者",+ "credits.agentShareBudget.audit.ownerUnavailable": "未知成员",+ "credits.agentShareBudget.audit.statusActive": "已启用",+ "credits.agentShareBudget.audit.statusPaused": "已暂停",+ "credits.agentShareBudget.audit.title": "工作区分享审计",+ "credits.agentShareBudget.audit.views": "{{views}} 次浏览",+ "credits.agentShareBudget.desc": "为工作区内所有对外分享的智能体设置统一的月度安全上限",+ "credits.agentShareBudget.limit": "工作区月度上限",+ "credits.agentShareBudget.limitHint": "留空表示不设置工作区总上限;填 0 会暂停所有访客运行。相关费用只从工作区积分扣除,不占用任何成员额度。",+ "credits.agentShareBudget.save": "保存",+ "credits.agentShareBudget.saveError": "智能体分享预算策略保存失败",+ "credits.agentShareBudget.saveSuccess": "智能体分享预算策略已保存",+ "credits.agentShareBudget.title": "智能体对外分享",+ "credits.agentShareBudget.unlimited": "不设置工作区总上限","credits.autoTopUp.cardBindingGiftHint": "🎁 首次添加支付方式,即送 1M 积分","credits.autoTopUp.currentBalance": "当前总余额","credits.autoTopUp.desc": "确保你的积分不会用光",diff --git a/packages/business-server/src/agent-share/spendGate.ts b/packages/business-server/src/agent-share/spendGate.tsindex e2669ff8f61..cb2193fb805 100644--- a/packages/business-server/src/agent-share/spendGate.ts+++ b/packages/business-server/src/agent-share/spendGate.ts@@ -1,10 +1,9 @@/*** Optional business hook for deployments that meter shared-agent usage.*- * A shared agent runs under its CREATOR's identity, so every visitor turn is- * billed to the creator. `AgentShareConfig.monthlySpendLimit` lets the creator- * bound that exposure; this slot is where a deployment that actually tracks- * spend decides whether the next visitor run may start.+ * A shared agent runs under its owning billing scope. Personal shares charge+ * the creator; Workspace shares charge the Workspace without consuming a+ * member quota. `AgentShareConfig.monthlySpendLimit` bounds that exposure.** The slot is a pure admission check called BEFORE any topic/message row is* created — the caller is responsible for turning a denial into a@@ -25,6 +24,8 @@ export interface AgentShareSpendGateParams {shareId: string;/** The signed-in visitor asking to run the agent. */visitorUserId: string;+ /** Owning Workspace for a Workspace share; absent for a personal share. */+ workspaceId?: string;}export interface AgentShareSpendGateResult {@@ -56,6 +57,8 @@ export async function checkAgentShareSpendAllowance(export async function getAgentShareMonthlySpend(_params: {agentId: string;ownerUserId: string;+ shareId: string;+ workspaceId?: string;}): Promise<number | null> {return null;}diff --git a/packages/business-server/src/video-generation/chargeBeforeGenerate.ts b/packages/business-server/src/video-generation/chargeBeforeGenerate.tsindex 9db076d6c2e..5f87d801ae9 100644--- a/packages/business-server/src/video-generation/chargeBeforeGenerate.ts+++ b/packages/business-server/src/video-generation/chargeBeforeGenerate.ts@@ -1,3 +1,5 @@+import type { SpendOrigin } from '@lobechat/types';+import type { NewGeneration, NewGenerationBatch } from '@/database/schemas';import type { CreateVideoServicePayload } from '@/server/routers/lambda/video';@@ -6,6 +8,8 @@ interface ChargeParams {model: string;params: CreateVideoServicePayload['params'];provider: string;+ /** Origin of the request, preserved for deferred video spend attribution. */+ spendOrigin?: SpendOrigin;userId: string;workspaceId?: string;}diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex db121e9e2c2..a17196ba01f 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -1,10 +1,10 @@// @vitest-environment nodeimport { eq, sql } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';import type { AgentShareConfig } from '../../schemas';-import { agents, agentShares, users, workspaces } from '../../schemas';+import { agents, agentShares, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentShareModel } from '../agentShare';@@ -16,21 +16,32 @@ const agentId = 'agent-share-test-agent';const otherAgentId = 'agent-share-test-other-agent';const workspaceAgentId = 'agent-share-test-workspace-agent';const workspaceId = 'agent-share-test-workspace';+const otherWorkspaceId = 'agent-share-test-other-workspace';const agentShareModel = new AgentShareModel(serverDB, userId);const otherAgentShareModel = new AgentShareModel(serverDB, otherUserId);+const workspaceAgentShareModel = new AgentShareModel(serverDB, userId, workspaceId);+const otherWorkspaceAgentShareModel = new AgentShareModel(serverDB, userId, otherWorkspaceId);describe('AgentShareModel', () => {beforeEach(async () => {await serverDB.delete(users);await serverDB.transaction(async (tx) => {await tx.insert(users).values([{ id: userId }, { id: otherUserId }]);- await tx.insert(workspaces).values({- id: workspaceId,- name: 'Agent Share Test Workspace',- primaryOwnerId: userId,- slug: 'agent-share-test-workspace',- });+ await tx.insert(workspaces).values([+ {+ id: workspaceId,+ name: 'Agent Share Test Workspace',+ primaryOwnerId: userId,+ slug: 'agent-share-test-workspace',+ },+ {+ id: otherWorkspaceId,+ name: 'Other Agent Share Test Workspace',+ primaryOwnerId: userId,+ slug: 'agent-share-test-other-workspace',+ },+ ]);await tx.insert(agents).values([{avatar: '🤯',@@ -151,7 +162,7 @@ describe('AgentShareModel', () => {});});- it('rejects missing, foreign, and workspace agents', async () => {+ it('rejects missing, foreign, and workspace agents from personal scope', async () => {await expect(agentShareModel.create('missing-agent')).rejects.toMatchObject({code: 'FORBIDDEN',});@@ -162,6 +173,165 @@ describe('AgentShareModel', () => {code: 'FORBIDDEN',});});++ it('creates a share scoped to the workspace', async () => {+ const share = await workspaceAgentShareModel.create(workspaceAgentId, 'link');++ expect(share).toMatchObject({+ agentId: workspaceAgentId,+ visibility: 'link',+ });+ await expect(+ otherWorkspaceAgentShareModel.getByAgentId(workspaceAgentId),+ ).resolves.toBeNull();+ });+ });++ describe('Agent-derived workspace scope', () => {+ it('resolves runtime identity and limits without a duplicated share scope', async () => {+ const [share] = await serverDB+ .insert(agentShares)+ .values({+ agentId: workspaceAgentId,+ shareConfig: { maxTopicsPerVisitor: 3, monthlySpendLimit: 2.5 },+ visibility: 'link',+ })+ .returning();++ await expect(AgentShareModel.findByShareId(serverDB, share.id)).resolves.toMatchObject({+ agentId: workspaceAgentId,+ ownerId: userId,+ shareId: share.id,+ workspaceId,+ });+ await expect(+ AgentShareModel.readCurrentVisitorCaps(serverDB, workspaceAgentId),+ ).resolves.toMatchObject({+ maxTopicsPerVisitor: 3,+ monthlySpendLimit: 2.5,+ shareId: share.id,+ workspaceId,+ });+ await expect(+ AgentShareModel.isRunStillAuthorized(serverDB, {+ agentId: workspaceAgentId,+ shareId: share.id,+ }),+ ).resolves.toBe(true);+ });++ it('scopes owner mutations and administrator pause through the Agent', async () => {+ const [share] = await serverDB+ .insert(agentShares)+ .values({+ agentId: workspaceAgentId,+ visibility: 'link',+ })+ .returning();++ await expect(+ otherWorkspaceAgentShareModel.updateVisibility(workspaceAgentId, 'private'),+ ).resolves.toBeNull();+ await expect(agentShareModel.getByAgentId(workspaceAgentId)).resolves.toBeNull();+ await expect(+ otherWorkspaceAgentShareModel.deleteByAgentId(workspaceAgentId),+ ).resolves.toBeNull();+ await expect(+ AgentShareModel.forceDisableWorkspaceShare(serverDB, otherWorkspaceId, share.id),+ ).resolves.toBeNull();+ await expect(+ workspaceAgentShareModel.updateConfig(workspaceAgentId, { maxTopicsPerVisitor: 4 }),+ ).resolves.toMatchObject({+ id: share.id,+ shareConfig: { maxTopicsPerVisitor: 4 },+ visibility: 'link',+ });+ await expect(+ AgentShareModel.listWorkspaceSharesForAudit(serverDB, workspaceId, {+ limit: 50,+ offset: 0,+ }),+ ).resolves.toEqual([+ expect.objectContaining({ agentId: workspaceAgentId, shareId: share.id }),+ ]);+ await expect(+ AgentShareModel.listWorkspaceSharesForAudit(serverDB, otherWorkspaceId, {+ limit: 50,+ offset: 0,+ }),+ ).resolves.toEqual([]);+ await expect(+ AgentShareModel.forceDisableWorkspaceShare(serverDB, workspaceId, share.id),+ ).resolves.toMatchObject({+ shareId: share.id,+ visibility: 'private',+ });+ });+ });++ describe('workspace administrator operations', () => {+ it('rechecks Workspace mutation authority after taking the Agent lock', async () => {+ const authorizeMutation = vi.fn().mockRejectedValue(new Error('stale-authority'));+ const model = new AgentShareModel(serverDB, userId, workspaceId, { authorizeMutation });++ await expect(model.create(workspaceAgentId, 'link')).rejects.toThrow('stale-authority');+ expect(authorizeMutation).toHaveBeenCalledWith(expect.anything(), workspaceAgentId);+ await expect(model.getByAgentId(workspaceAgentId)).resolves.toBeNull();+ });++ it('lists only minimal audit metadata and force-disables within the workspace', async () => {+ const workspaceShare = await workspaceAgentShareModel.create(workspaceAgentId, 'link');+ await workspaceAgentShareModel.updateConfig(workspaceAgentId, {+ allowCreatorViewSessions: true,+ toolGrants: [{ identifier: 'private-tool' }],+ });+ await agentShareModel.create(agentId, 'link');++ const auditRows = await AgentShareModel.listWorkspaceSharesForAudit(serverDB, workspaceId, {+ limit: 50,+ offset: 0,+ });++ expect(auditRows).toHaveLength(1);+ expect(auditRows[0]).toMatchObject({+ agentId: workspaceAgentId,+ ownerId: userId,+ shareId: workspaceShare.id,+ shareVisibility: 'link',+ userViewCount: 0,+ });+ expect(auditRows[0]).not.toHaveProperty('shareConfig');+ expect(auditRows[0]).not.toHaveProperty('agentTitle');++ await expect(+ AgentShareModel.forceDisableWorkspaceShare(serverDB, otherWorkspaceId, workspaceShare.id),+ ).resolves.toBeNull();+ await expect(+ AgentShareModel.forceDisableWorkspaceShare(serverDB, workspaceId, workspaceShare.id),+ ).resolves.toMatchObject({+ agentId: workspaceAgentId,+ shareId: workspaceShare.id,+ visibility: 'private',+ });+ await expect(workspaceAgentShareModel.getByAgentId(workspaceAgentId)).resolves.toMatchObject({+ visibility: 'private',+ });+ });++ it('rechecks administrator authority after taking the Agent lock', async () => {+ const workspaceShare = await workspaceAgentShareModel.create(workspaceAgentId, 'link');+ const authorizeMutation = vi.fn().mockRejectedValue(new Error('stale-admin-authority'));++ await expect(+ AgentShareModel.forceDisableWorkspaceShare(serverDB, workspaceId, workspaceShare.id, {+ authorizeMutation,+ }),+ ).rejects.toThrow('stale-admin-authority');+ expect(authorizeMutation).toHaveBeenCalledWith(expect.anything(), workspaceAgentId);+ await expect(workspaceAgentShareModel.getByAgentId(workspaceAgentId)).resolves.toMatchObject({+ visibility: 'link',+ });+ });});describe('owner operations', () => {@@ -251,8 +421,14 @@ describe('AgentShareModel', () => {// `deleteByAgentId` is the hard-teardown path, deliberately NOT what the// disable flow uses (see the cycle test below).- it('updates visibility, and hard-deletes the share on demand', async () => {+ it('updates visibility and deletes only the share when explicitly requested', async () => {const created = await agentShareModel.create(agentId);+ await serverDB.insert(topics).values({+ agentId,+ id: 'agent-share-legacy-visitor-topic',+ senderId: otherUserId,+ userId,+ });const updated = await agentShareModel.updateVisibility(agentId, 'link');expect(updated?.visibility).toBe('link');@@ -260,6 +436,12 @@ describe('AgentShareModel', () => {const deleted = await agentShareModel.deleteByAgentId(agentId);expect(deleted?.id).toBe(created?.id);expect(await AgentShareModel.findByShareId(serverDB, created!.id)).toBeNull();+ expect(+ await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'agent-share-legacy-visitor-topic')),+ ).toHaveLength(1);});it('returns null for missing shares', async () => {@@ -448,17 +630,15 @@ describe('AgentShareModel', () => {});});- it('does not expose a workspace agent even if a share row exists', async () => {- const [share] = await serverDB- .insert(agentShares)- .values({- agentId: workspaceAgentId,- shareConfig: { maxTopicsPerVisitor: 5, maxTurnsPerTopic: 20 },- visibility: 'link',- })- .returning();+ it('resolves a workspace share with its billing scope', async () => {+ const created = await workspaceAgentShareModel.create(workspaceAgentId, 'link');- expect(await AgentShareModel.findByShareId(serverDB, share.id)).toBeNull();+ expect(await AgentShareModel.findByShareId(serverDB, created.id)).toMatchObject({+ agentId: workspaceAgentId,+ ownerId: userId,+ shareId: created.id,+ workspaceId,+ });});it('returns null for an unknown UUID', async () => {@@ -530,6 +710,17 @@ describe('AgentShareModel', () => {).toBe(true);});+ it('authorizes a live link share on a workspace agent', async () => {+ const created = await workspaceAgentShareModel.create(workspaceAgentId, 'link');++ expect(+ await AgentShareModel.isRunStillAuthorized(serverDB, {+ agentId: workspaceAgentId,+ shareId: created.id,+ }),+ ).toBe(true);+ });+it('revokes once the share is paused or replaced', async () => {const created = await agentShareModel.create(agentId, 'link');@@ -546,17 +737,6 @@ describe('AgentShareModel', () => {}),).toBe(false);});-- // `transferAgent` does not touch `agent_shares`; the per-step check must- // notice the agent left personal scope on its own, like `findByShareId`.- it('revokes an in-flight run once the agent is moved into a workspace', async () => {- const created = await agentShareModel.create(agentId, 'link');- await serverDB.update(agents).set({ workspaceId }).where(eq(agents.id, agentId));-- expect(- await AgentShareModel.isRunStillAuthorized(serverDB, { agentId, shareId: created!.id }),- ).toBe(false);- });});describe('readCurrentVisitorCaps', () => {@@ -573,6 +753,7 @@ describe('AgentShareModel', () => {maxTurnsPerTopic: 8,monthlySpendLimit: 2.5,shareId: created!.id,+ workspaceId: null,});});@@ -582,6 +763,7 @@ describe('AgentShareModel', () => {maxTurnsPerTopic: 20,monthlySpendLimit: 10,shareId: null,+ workspaceId: null,});});});diff --git a/packages/database/src/models/__tests__/agentTransfer.test.ts b/packages/database/src/models/__tests__/agentTransfer.test.tsindex b4a44556955..6101bbe0b97 100644--- a/packages/database/src/models/__tests__/agentTransfer.test.ts+++ b/packages/database/src/models/__tests__/agentTransfer.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { eq, inArray } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';import {@@ -68,6 +68,7 @@ beforeEach(async () => {});afterEach(async () => {+ vi.restoreAllMocks();await serverDB.delete(users);});@@ -1068,54 +1069,82 @@ describe('AgentModel.transferAgent', () => {);});- // Regression: a share carries the previous owner's tool grants, custom- // slug, and (in Cloud) monthly spend cap, and its visitor conversations are- // stored under (agentId, senderId) within that owner's scope — an ownership- // transfer must be REFUSED while the share row exists. See- // `AgentModel.transferAgents` step 1d and the `isRunStillAuthorized` doc in- // `agentShare.ts`.- it('should reject the transfer when the agent still carries a share row', async () => {- const model = new AgentModel(serverDB, userId);- const agent = await model.create({ title: 'Shared Agent', slug: 'shared-agent' });+ it.each([+ { source: null, target: null, recipient: targetUserId, visibility: 'link' },+ { source: null, target: wsId1, recipient: userId, visibility: 'link' },+ { source: wsId1, target: null, recipient: userId, visibility: 'link' },+ { source: wsId1, target: wsId2, recipient: userId, visibility: 'link' },+ { source: wsId1, target: wsId1, recipient: targetUserId, visibility: 'link' },+ { source: null, target: wsId1, recipient: userId, visibility: 'private' },+ { source: wsId1, target: wsId2, recipient: userId, visibility: 'private' },+ { source: wsId1, target: wsId1, recipient: targetUserId, visibility: 'private' },+ ] as const)(+ 'rejects a $visibility share transfer from $source to $target for $recipient without changing data',+ async ({ source, target, recipient, visibility }) => {+ const model = new AgentModel(serverDB, userId, source ?? undefined);+ const agent = await model.create({ title: 'Shared Agent', slug: 'shared-agent' });+ const [share] = await serverDB+ .insert(agentShares)+ .values({+ agentId: agent.id,+ shareConfig: { monthlySpendLimit: 5 },+ visibility,+ })+ .returning();+ const [topic] = await serverDB+ .insert(topics)+ .values({+ agentId: agent.id,+ id: 'shared-agent-visitor-topic',+ senderId: targetUserId,+ userId,+ workspaceId: source,+ })+ .returning();+ const [file] = await serverDB+ .insert(files)+ .values({+ fileType: 'image/png',+ metadata: { agentShare: { shareId: share.id, visitorUserId: targetUserId } },+ name: 'visitor.png',+ size: 42,+ url: `agent-shares/${share.id}/visitor.png`,+ userId,+ workspaceId: source,+ })+ .returning();++ await expect(model.transferAgent(agent.id, target, recipient)).rejects.toThrow(+ AGENT_SHARED_TRANSFER_BLOCKED,+ );++ expect(await serverDB.select().from(agents).where(eq(agents.id, agent.id))).toEqual([agent]);+ expect(await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id))).toEqual(+ [share],+ );+ expect(await serverDB.select().from(topics).where(eq(topics.id, topic.id))).toEqual([topic]);+ expect(await serverDB.select().from(files).where(eq(files.id, file.id))).toEqual([file]);+ },+ );- await serverDB- .insert(agentShares)- .values({ agentId: agent.id, shareConfig: { monthlySpendLimit: 5 }, visibility: 'link' });+ it('rejects an entire batch when one agent has a paused share', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const ordinary = await model.create({ title: 'Ordinary Agent' });+ const shared = await model.create({ title: 'Shared Agent' });+ await serverDB.insert(agentShares).values({+ agentId: shared.id,+ visibility: 'private',+ });- await expect(model.transferAgent(agent.id, null, targetUserId)).rejects.toThrow(+ await expect(model.transferAgents([ordinary.id, shared.id], wsId2, userId)).rejects.toThrow(AGENT_SHARED_TRANSFER_BLOCKED,);- // Agent stays with the original owner: batch guard fires before any- // mutation, so neither `agents.userId` nor the share row change.- const [row] = await serverDB.select().from(agents).where(eq(agents.id, agent.id));- expect(row.userId).toBe(userId);- const remaining = await serverDB+ const rows = await serverDB.select()- .from(agentShares)- .where(eq(agentShares.agentId, agent.id));- expect(remaining).toHaveLength(1);- });-- it('should keep the share row on a same-owner personal ↔ workspace round-trip', async () => {- const model = new AgentModel(serverDB, userId);- const agent = await model.create({ title: 'Roundtrip Agent', slug: 'roundtrip-agent' });-- await serverDB- .insert(agentShares)- .values({ agentId: agent.id, shareConfig: { monthlySpendLimit: 5 }, visibility: 'link' });-- // Personal → workspace (owner unchanged, share paused via workspaceId join).- await model.transferAgent(agent.id, wsId1, userId);- let rows = await serverDB.select().from(agentShares).where(eq(agentShares.agentId, agent.id));- expect(rows).toHaveLength(1);-- // Workspace → personal, same owner: share resumes.- const wsModel = new AgentModel(serverDB, userId, wsId1);- await wsModel.transferAgent(agent.id, null, userId);- rows = await serverDB.select().from(agentShares).where(eq(agentShares.agentId, agent.id));- expect(rows).toHaveLength(1);- expect(rows[0].visibility).toBe('link');+ .from(agents)+ .where(inArray(agents.id, [ordinary.id, shared.id]));+ expect(rows).toEqual(expect.arrayContaining([ordinary, shared]));});});diff --git a/packages/database/src/models/__tests__/agentTransferOwnership.test.ts b/packages/database/src/models/__tests__/agentTransferOwnership.test.tsindex 916e66c49cd..1381909f0df 100644--- a/packages/database/src/models/__tests__/agentTransferOwnership.test.ts+++ b/packages/database/src/models/__tests__/agentTransferOwnership.test.ts@@ -71,24 +71,33 @@ afterEach(async () => {});describe('AgentModel.transferAgentOwnership', () => {- it('rejects the handover while the agent still carries a share row', async () => {- const agent = await ownerModel.create({ slug: 'shared-handover', title: 'Shared Handover' });- await serverDB- .insert(agentShares)- .values({ agentId: agent.id, shareConfig: { monthlySpendLimit: 5 }, visibility: 'link' });-- await expect(- handover({ agentId: agent.id, fromUserId: ownerId, toUserId: recipientId }),- ).rejects.toThrow(AGENT_SHARED_TRANSFER_BLOCKED);-- // Guard fires before any mutation: the agent stays with the previous- // owner and the share row is untouched. The block lifts only once the- // share row itself is removed (no product entry point yet).- const [row] = await serverDB.select().from(agents).where(eq(agents.id, agent.id));- expect(row.userId).toBe(ownerId);- const rows = await serverDB.select().from(agentShares).where(eq(agentShares.agentId, agent.id));- expect(rows).toHaveLength(1);- });+ it.each(['link', 'private'] as const)(+ 'rejects ownership handover with a %s share without changing the agent or share',+ async (visibility) => {+ const agent = await ownerModel.create({+ slug: 'shared-handover',+ title: 'Shared Handover',+ visibility: 'public',+ });+ const [share] = await serverDB+ .insert(agentShares)+ .values({+ agentId: agent.id,+ shareConfig: { allowReadMemory: true, monthlySpendLimit: 5 },+ visibility,+ })+ .returning();++ await expect(+ handover({ agentId: agent.id, fromUserId: ownerId, toUserId: recipientId }),+ ).rejects.toThrow(AGENT_SHARED_TRANSFER_BLOCKED);++ expect(await serverDB.select().from(agents).where(eq(agents.id, agent.id))).toEqual([agent]);+ expect(await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id))).toEqual(+ [share],+ );+ },+ );it('flips only the agent owner; scope, slug and visibility stay put', async () => {const agent = await ownerModel.create({diff --git a/packages/database/src/models/__tests__/chatGroupTransferOwnership.test.ts b/packages/database/src/models/__tests__/chatGroupTransferOwnership.test.tsindex adf42fe4437..895ed349df7 100644--- a/packages/database/src/models/__tests__/chatGroupTransferOwnership.test.ts+++ b/packages/database/src/models/__tests__/chatGroupTransferOwnership.test.ts@@ -4,7 +4,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';import {+ agentHistoryJobs,agents,+ agentShares,agentsKnowledgeBases,chatGroups,chatGroupsAgents,@@ -14,6 +16,7 @@ import {workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { AGENT_SHARED_TRANSFER_BLOCKED } from '../agent';import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';import {CHAT_GROUP_OWNERSHIP_STALE,@@ -78,10 +81,46 @@ beforeEach(async () => {});afterEach(async () => {+ /** Transfer jobs intentionally survive user deletion and need explicit fixture cleanup. */+ await serverDB.delete(agentHistoryJobs).where(eq(agentHistoryJobs.sourceUserId, ownerId));await serverDB.delete(users);});describe('ChatGroupModel.transferGroupOwnership', () => {+ it.each(['link', 'private'] as const)(+ 'rejects handover when an owned member has a %s share without changing the group',+ async (visibility) => {+ const { group, supervisor } = await seedGroupWithRoster();+ const [share] = await serverDB+ .insert(agentShares)+ .values({ agentId: supervisor.id, visibility })+ .returning();++ const [groupBefore] = await serverDB+ .select()+ .from(chatGroups)+ .where(eq(chatGroups.id, group.id));+ const [agentBefore] = await serverDB+ .select()+ .from(agents)+ .where(eq(agents.id, supervisor.id));++ await expect(+ handover({ fromUserId: ownerId, groupId: group.id, toUserId: recipientId }),+ ).rejects.toThrow(AGENT_SHARED_TRANSFER_BLOCKED);++ expect(await serverDB.select().from(chatGroups).where(eq(chatGroups.id, group.id))).toEqual([+ groupBefore,+ ]);+ expect(await serverDB.select().from(agents).where(eq(agents.id, supervisor.id))).toEqual([+ agentBefore,+ ]);+ expect(await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id))).toEqual(+ [share],+ );+ },+ );+it('flips the group, junction rows and owned members; scope and visibility stay put', async () => {const { group, supervisor } = await seedGroupWithRoster();@@ -106,11 +145,18 @@ describe('ChatGroupModel.transferGroupOwnership', () => {it('leaves referenced standalone members with their own owners', async () => {const { group, referenced } = await seedGroupWithRoster();+ const [share] = await serverDB+ .insert(agentShares)+ .values({ agentId: referenced.id, visibility: 'link' })+ .returning();await handover({ fromUserId: ownerId, groupId: group.id, toUserId: recipientId });const [standalone] = await serverDB.select().from(agents).where(eq(agents.id, referenced.id));expect(standalone.userId).toBe(teammateId);+ expect(await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id))).toEqual([+ share,+ ]);});it('keeps everyone’s group conversations untouched', async () => {diff --git a/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts b/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.tsindex c2114072a04..3187fcfbe52 100644--- a/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts+++ b/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts@@ -7,7 +7,7 @@ import {} from '@/server/services/aiAgent/shareVisitorAbuseGuards';import { getTestDB } from '../../core/getTestDB';-import { agents, messages, topics, users } from '../../schemas';+import { agents, agentShares, messages, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentShareModel } from '../agentShare';@@ -35,6 +35,8 @@ import { AgentShareModel } from '../agentShare';const ownerId = 'share-abuse-guard-race-owner';const visitorUserId = 'share-abuse-guard-race-visitor';+const workspaceId = 'share-abuse-guard-race-workspace';+const otherWorkspaceId = 'share-abuse-guard-race-other-workspace';const serverDB: LobeChatDatabase = await getTestDB();const cleanup = async () => {@@ -175,6 +177,60 @@ describe('shareVisitorAbuseGuards — revoked share authorization', () => {afterAll(cleanup);+ it('derives workspace scope from the Agent when the share row has no workspaceId', async () => {+ const agentId = 'workspace-share-guard-scope';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Workspace share guard scope',+ primaryOwnerId: ownerId,+ slug: 'workspace-share-guard-scope',+ });+ await serverDB.insert(agents).values({+ id: agentId,+ model: 'gpt-4o',+ userId: ownerId,+ workspaceId,+ });+ const [share] = await serverDB+ .insert(agentShares)+ .values({ agentId, visibility: 'link' })+ .returning();++ await expect(+ reserveShareVisitorTopic(+ {+ agentId,+ db: serverDB,+ expectedShareId: share.id,+ ownerId,+ visitorUserId,+ workspaceId,+ },+ { agentId, senderId: visitorUserId, title: 'workspace-scoped topic' },+ ),+ ).resolves.toMatchObject({ agentId, workspaceId });++ await expect(+ reserveShareVisitorTopic(+ {+ agentId,+ db: serverDB,+ expectedShareId: share.id,+ ownerId,+ visitorUserId,+ workspaceId: otherWorkspaceId,+ },+ { agentId, senderId: visitorUserId, title: 'wrong-workspace topic' },+ ),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ const inserted = await serverDB+ .select({ title: topics.title })+ .from(topics)+ .where(eq(topics.agentId, agentId));+ expect(inserted).toEqual([{ title: 'workspace-scoped topic' }]);+ });+it('rejects a new-topic reservation once the owner made the link private, and inserts nothing', async () => {const agentId = 'revoked-share-topic-private';await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex ee05b5ef7c1..678eb3bcce0 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -208,21 +208,9 @@ export const AGENT_OWNED_BY_GROUP = 'AGENT_OWNED_BY_GROUP';export const AGENT_OWNERSHIP_STALE = 'AGENT_OWNERSHIP_STALE';/**- * Ownership transfer refused: the agent still carries an `agent_shares` row.- *- * The share row is bound to the ORIGINAL owner — it carries their grants and- * (in Cloud) their spend cap linked to their budget, and every visitor- * conversation reached through the link is stored under (agentId, senderId)- * within THAT owner's scope. Handing the agent to someone else would either- * silently republish the previous owner's grants under a new identity, or- * strand the visitor conversations under a user that no longer owns the- * agent. Neither is a valid product state, so ownership transfer of a shared- * agent is refused until the owner disables sharing AND deletes the share- * row (`AgentShareModel.deleteByAgentId`).- *- * Same-owner personal ↔ workspace moves are unaffected: the share row is- * paused via `isRunStillAuthorized`'s `agents.workspaceId IS NULL` join and- * resumes on the round-trip. Only a change of `agents.userId` is blocked.+ * A share binds its grants, billing scope and visitor history to the current+ * agent owner and workspace. Transfers remain unsupported while any share row+ * exists, including paused shares; disabling a link must not bypass the guard.*/export const AGENT_SHARED_TRANSFER_BLOCKED = 'AGENT_SHARED_TRANSFER_BLOCKED';@@ -239,6 +227,10 @@ export class AgentOwnedByGroupError extends Error {}}+interface AgentTransferOptions {+ rejectForeignTopicCommentAuthors?: boolean;+}+export class AgentModel {private userId: string;private db: LobeChatDatabase;@@ -2065,7 +2057,7 @@ export class AgentModel {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: { rejectForeignTopicCommentAuthors?: boolean } = {},+ options: AgentTransferOptions = {},): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }> => {const [result] = await this.transferAgents([agentId],@@ -2088,7 +2080,7 @@ export class AgentModel {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: { rejectForeignTopicCommentAuthors?: boolean } = {},+ options: AgentTransferOptions = {},): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }[]> => {if (agentIds.length === 0) return [];@@ -2138,30 +2130,15 @@ export class AgentModel {const ownedGroups = await this.findOwnedGroupMemberships(trx, agentIds);if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);- // 1d. Refuse to change the owner of an agent that still carries an- // `agent_shares` row. The share is bound to the previous owner: it- // holds their tool grants and spend cap, and every visitor conversation- // opened through the link is stored under (agentId, senderId) within- // THAT owner's scope. Handing the agent over would either silently- // republish the previous owner's grants under a new identity, or leave- // the visitor threads dangling under a user that no longer owns them.- // Disabling sharing keeps the row as `private`, so this is a hard stop- // until the row is removed (`AgentShareModel.deleteByAgentId`, which has- // no product entry point yet — a deliberate follow-up). A same-owner- // personal ↔ workspace move keeps the row (it is paused via the- // workspaceId join in `isRunStillAuthorized`). Fail the whole batch,- // consistent with the guards above.- const sharedAgentIds = foundAgents- .filter((agent) => agent.userId !== targetUserId)- .map((agent) => agent.id);- if (sharedAgentIds.length > 0) {- const sharedRows = await trx- .select({ agentId: agentShares.agentId })- .from(agentShares)- .where(inArray(agentShares.agentId, sharedAgentIds))- .limit(1);- if (sharedRows.length > 0) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);- }+ // 1d. Keep the share owner and tenancy stable. Check paused shares too:+ // disabling a link retains its grants and visitor history. The Agent row+ // lock also serializes this guard with AgentShareModel.create.+ const [existingShare] = await trx+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(inArray(agentShares.agentId, agentIds))+ .limit(1);+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);// 2. Resolve slug conflicts in the target scope with a single query:// fetch every existing slug that could collide (exact match or@@ -2639,13 +2616,7 @@ export class AgentModel {const ownedGroups = await this.findOwnedGroupMemberships(trx, [agentId]);if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);- // Mirror of transferAgents step 1d: refuse the handover if the agent- // still carries an `agent_shares` row. The share is bound to the previous- // owner's grants / spend cap, and every visitor conversation reached- // through the link is stored under (agentId, senderId) within THAT- // owner's scope. The previous owner must turn sharing off and delete the- // share row before their agent can change hands. Checked BEFORE any- // mutation below so the refusal leaves the agent untouched.+ /** Reject before mutation so the transfer request and share remain unchanged. */const [existingShare] = await trx.select({ id: agentShares.id }).from(agentShares)diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex 73ba6589e3b..ee2c341480d 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -60,11 +60,17 @@ export type AgentShareData = NonNullable<Awaited<ReturnType<(typeof AgentShareModel)['findByShareId']>>>;-/** Minimal locked-row snapshot returned by {@link AgentShareModel.lockOwnedAgentRow}. */+/** Minimal locked-row snapshot returned by {@link AgentShareModel.lockScopedAgentRow}. */interface LockedAgentSnapshot {id: string;/** The agent's own profile slug (`agents.slug`), unique per owner only. */slug: string | null;+ workspaceId: string | null;+}++interface AgentShareModelOptions {+ /** Re-check Workspace share authority after the Agent row lock is acquired. */+ authorizeMutation?: (tx: LobeChatDatabase, agentId: string) => Promise<void>;}/**@@ -82,26 +88,41 @@ const getShareSlugRejection = (};export class AgentShareModel {+ private authorizeMutation?: AgentShareModelOptions['authorizeMutation'];private db: LobeChatDatabase;private userId: string;+ private workspaceId?: string;- constructor(db: LobeChatDatabase, userId: string) {+ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ options: AgentShareModelOptions = {},+ ) {+ this.authorizeMutation = options.authorizeMutation;this.db = db;this.userId = userId;+ this.workspaceId = workspaceId;}- /** Agent sharing is personal-only; workspace agents fail this predicate. */- private ownership = () =>+ /**+ * Scope a share to the Agent's current tenancy. In personal mode the caller+ * must still own the Agent; Workspace authorization is enforced by the+ * resource-permission service before this model is called.+ */+ private scope = () =>exists(this.db.select({ id: agents.id }).from(agents).where(- and(- eq(agents.id, agentShares.agentId),- eq(agents.userId, this.userId),- isNull(agents.workspaceId),- ),+ this.workspaceId+ ? and(eq(agents.id, agentShares.agentId), eq(agents.workspaceId, this.workspaceId))+ : and(+ eq(agents.id, agentShares.agentId),+ eq(agents.userId, this.userId),+ isNull(agents.workspaceId),+ ),),);@@ -112,19 +133,28 @@ export class AgentShareModel {* `updateSlug`) serializes on this same physical row, so two concurrent* writes on the same agent's share can never interleave.*- * Returns `null` (never locks) when the agent does not exist, is not- * personally owned by `ownerId`, or is workspace-scoped — callers must fail- * closed on `null`.+ * Returns `null` (never locks) when the agent does not exist in the requested+ * scope. Personal scope additionally requires ownership. Workspace callers+ * are checked once by the router and again through `authorizeMutation` after+ * this lock, closing the owner-handover race between authorization and write.*/- static lockOwnedAgentRow = async (+ static lockScopedAgentRow = async (tx: LobeChatDatabase,agentId: string,- ownerId: string,+ params: { userId: string; workspaceId?: string },): Promise<LockedAgentSnapshot | null> => {const [agent] = await tx- .select({ id: agents.id, slug: agents.slug })+ .select({ id: agents.id, slug: agents.slug, workspaceId: agents.workspaceId }).from(agents)- .where(and(eq(agents.id, agentId), eq(agents.userId, ownerId), isNull(agents.workspaceId)))+ .where(+ params.workspaceId+ ? and(eq(agents.id, agentId), eq(agents.workspaceId, params.workspaceId))+ : and(+ eq(agents.id, agentId),+ eq(agents.userId, params.userId),+ isNull(agents.workspaceId),+ ),+ ).for('update');return agent ?? null;@@ -186,21 +216,25 @@ export class AgentShareModel {return updated ?? share;};- private withOwnedPersonalAgentLock = async <T>(+ private withScopedAgentLock = async <T>(agentId: string,mutation: (tx: LobeChatDatabase, agent: LockedAgentSnapshot) => Promise<T>,): Promise<T | null> =>this.db.transaction(async (transaction) => {const tx = transaction as LobeChatDatabase;- const agent = await AgentShareModel.lockOwnedAgentRow(tx, agentId, this.userId);+ const agent = await AgentShareModel.lockScopedAgentRow(tx, agentId, {+ userId: this.userId,+ workspaceId: this.workspaceId,+ });if (!agent) return null;+ await this.authorizeMutation?.(tx, agentId);return mutation(tx, agent);});/** Create a private share by default, or return the existing share for the agent. */create = async (agentId: string, visibility: ShareVisibility = 'private') => {- const share = await this.withOwnedPersonalAgentLock(agentId, async (tx, agent) => {+ const share = await this.withScopedAgentLock(agentId, async (tx, agent) => {// One row per agent, forever: `onConflictDoNothing` on `agentId` makes a// re-enable fall back to the SELECT below, returning the existing row// untouched. That is what keeps a share's id and custom slug — i.e. the@@ -208,7 +242,11 @@ export class AgentShareModel {// since disabling only flips `visibility` to `private`.const [created] = await tx.insert(agentShares)- .values({ agentId, shareConfig: DEFAULT_AGENT_SHARE_CONFIG, visibility })+ .values({+ agentId,+ shareConfig: DEFAULT_AGENT_SHARE_CONFIG,+ visibility,+ }).onConflictDoNothing({ target: agentShares.agentId }).returning();@@ -227,7 +265,7 @@ export class AgentShareModel {if (!share) {throw new TRPCError({code: 'FORBIDDEN',- message: 'Agent sharing is only available to personal agent owners',+ message: 'Agent sharing is not available in this scope',});}@@ -239,7 +277,7 @@ export class AgentShareModel {const [share] = await this.db.select().from(agentShares)- .where(and(eq(agentShares.agentId, agentId), this.ownership()))+ .where(and(eq(agentShares.agentId, agentId), this.scope())).limit(1);if (!share) return null;@@ -247,6 +285,80 @@ export class AgentShareModel {return { ...share, shareConfig: normalizeAgentShareConfig(share.shareConfig) };};+ /**+ * Minimal Workspace-wide share inventory for administrators. Deliberately+ * excludes `shareConfig` and Agent profile fields: an administrator may+ * audit and stop external exposure without gaining read access to a private+ * Agent's instructions, tools, credentials, or visitor conversations.+ */+ static listWorkspaceSharesForAudit = async (+ db: LobeChatDatabase,+ workspaceId: string,+ options: { limit: number; offset: number },+ ) =>+ db+ .select({+ agentId: agentShares.agentId,+ agentVisibility: agents.visibility,+ createdAt: agentShares.createdAt,+ ownerId: agents.userId,+ shareId: agentShares.id,+ shareVisibility: agentShares.visibility,+ updatedAt: agentShares.updatedAt,+ userViewCount: agentShares.userViewCount,+ })+ .from(agentShares)+ .innerJoin(agents, eq(agentShares.agentId, agents.id))+ .where(eq(agents.workspaceId, workspaceId))+ .orderBy(sql`${agentShares.updatedAt} DESC, ${agentShares.id} DESC`)+ .limit(options.limit)+ .offset(options.offset);++ /**+ * Administrative emergency stop for one Workspace share. This is a pause,+ * not an irreversible revoke: it keeps the row and URL so the Agent owner+ * may inspect the state and explicitly republish later.+ */+ static forceDisableWorkspaceShare = async (+ db: LobeChatDatabase,+ workspaceId: string,+ shareId: string,+ options: AgentShareModelOptions = {},+ ) =>+ db.transaction(async (transaction) => {+ const tx = transaction as LobeChatDatabase;+ const [share] = await tx+ .select({ agentId: agentShares.agentId })+ .from(agentShares)+ .innerJoin(agents, eq(agentShares.agentId, agents.id))+ .where(and(eq(agentShares.id, shareId), eq(agents.workspaceId, workspaceId)))+ .limit(1);+ if (!share) return null;++ // Serialize against owner-side enable/disable/config mutations, all of+ // which lock this same Agent row before touching the share.+ const agent = await AgentShareModel.lockScopedAgentRow(tx, share.agentId, {+ userId: '',+ workspaceId,+ });+ if (!agent) return null;+ // The administrator may lose membership or `agent:update:all` while waiting for this lock.+ // Recheck inside the transaction so a revocation that won the race also wins the mutation.+ await options.authorizeMutation?.(tx, share.agentId);++ const [updated] = await tx+ .update(agentShares)+ .set({ updatedAt: new Date(), visibility: 'private' })+ .where(and(eq(agentShares.id, shareId), eq(agentShares.agentId, agent.id)))+ .returning({+ agentId: agentShares.agentId,+ shareId: agentShares.id,+ visibility: agentShares.visibility,+ });++ return updated ?? null;+ });+/*** Atomically merge client-owned fields into the existing config, preserving* sibling keys that were not part of this patch. A flat top-level jsonb@@ -261,7 +373,7 @@ export class AgentShareModel {agentId: string,config: AgentShareConfigPatch,): Promise<NormalizedAgentShareItem | null> =>- this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ this.withScopedAgentLock(agentId, async (tx) => {const { slug: _slug, ...patch } = config as AgentShareConfigPatch & { slug?: unknown };const setEntries = Object.entries(patch).filter(([, v]) => v !== undefined);@@ -285,7 +397,7 @@ export class AgentShareModel {});/**- * Update share visibility for a personally owned agent. This is also the+ * Update share visibility for an Agent in the model's owning scope. This is also the* "turn sharing off" path (`private`): the row, its id and its custom slug* are all preserved, so flipping back to `link` republishes the exact same* URL the owner already handed out.@@ -294,7 +406,7 @@ export class AgentShareModel {agentId: string,visibility: ShareVisibility,): Promise<NormalizedAgentShareItem | null> =>- this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ this.withScopedAgentLock(agentId, async (tx) => {const [updated] = await tx.update(agentShares).set({ updatedAt: new Date(), visibility })@@ -325,7 +437,7 @@ export class AgentShareModel {slug: string | null,): Promise<NormalizedAgentShareItem | null> => {if (slug === null) {- return this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ return this.withScopedAgentLock(agentId, async (tx) => {const [updated] = await tx.update(agentShares).set({@@ -346,7 +458,7 @@ export class AgentShareModel {throw new TRPCError({ code: 'BAD_REQUEST', message: rejection });}- return this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ return this.withScopedAgentLock(agentId, async (tx) => {if (await AgentShareModel.isShareSlugTaken(tx, slug, agentId)) {throw new TRPCError({ code: 'CONFLICT', message: 'SHARE_SLUG_TAKEN' });}@@ -377,7 +489,7 @@ export class AgentShareModel {* `isRunStillAuthorized` guards against).*/deleteByAgentId = async (agentId: string): Promise<AgentShareItem | null> =>- this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ this.withScopedAgentLock(agentId, async (tx) => {const [deleted] = await tx.delete(agentShares).where(eq(agentShares.agentId, agentId))@@ -407,11 +519,17 @@ export class AgentShareModel {Pick<AgentShareConfig, 'maxTopicsPerVisitor' | 'maxTurnsPerTopic' | 'monthlySpendLimit'>> & {shareId: string | null;+ workspaceId: string | null;}> => {const [row] = await db- .select({ id: agentShares.id, shareConfig: agentShares.shareConfig })+ .select({+ id: agentShares.id,+ shareConfig: agentShares.shareConfig,+ workspaceId: agents.workspaceId,+ }).from(agentShares)+ .innerJoin(agents, eq(agentShares.agentId, agents.id)).where(eq(agentShares.agentId, agentId));const normalized = normalizeAgentShareConfig(row?.shareConfig ?? null);@@ -420,6 +538,7 @@ export class AgentShareModel {maxTurnsPerTopic: normalized.maxTurnsPerTopic!,monthlySpendLimit: normalized.monthlySpendLimit!,shareId: row?.id ?? null,+ workspaceId: row?.workspaceId ?? null,};};@@ -452,21 +571,8 @@ export class AgentShareModel {* comes back as a different instance — a hard delete (`deleteByAgentId`) or* the agent being deleted and recreated under the same id.*- * The agent must ALSO still be personal (`agents.workspaceId IS NULL`) —- * the same condition `findByShareId` resolves through. Sharing is- * personal-only, so a creator moving the agent into a workspace mid-run- * leaves the share row intact while every entry point stops resolving it;- * without this join the in-flight run would keep spending under the creator- * after the share was effectively paused. Same-owner personal ↔ workspace- * moves preserve the row deliberately, so returning the agent to personal- * scope resumes the same link. An OWNERSHIP TRANSFER is different:- * `AgentModel.transferAgents` / `transferAgentOwnership` REFUSE to change- * `agents.userId` while this row exists (`AGENT_SHARED_TRANSFER_BLOCKED`)- * — the share carries the previous owner's grants and spend cap, and- * visitor conversations reached through the link live under (agentId,- * senderId) within that owner's scope. Disabling sharing keeps the row- * (`private`), so the block lifts only once the row itself is removed;- * a product entry point for that is a follow-up, not part of this model.+ * The Agent is the sole source of ownership and Workspace scope. Transfers+ * are blocked while a share row exists, including paused shares.** Deliberately cheap (one indexed lookup + a primary-key join): it runs once* per runtime step. Returns `false` — never throws — for an ordinary@@ -481,18 +587,15 @@ export class AgentShareModel {.select({ id: agentShares.id, visibility: agentShares.visibility }).from(agentShares).innerJoin(agents, eq(agentShares.agentId, agents.id))- .where(and(eq(agentShares.agentId, params.agentId), isNull(agents.workspaceId)))+ .where(eq(agentShares.agentId, params.agentId)).limit(1);return !!share && share.id === params.shareId && share.visibility === 'link';};/**- * Resolve the public metadata required by an agent share page. Workspace- * agents never resolve here — `agentShares` rows only exist for personal- * agents (see `create`'s ownership check), but the `isNull` guard is kept- * as defense in depth against a row surviving some future write path that- * does not go through this model.+ * Resolve public share metadata and derive ownership and billing scope from+ * the Agent. Sharing prevents transfers, so no separate tenancy snapshot is needed.*/static findByShareId = async (db: LobeChatDatabase, shareId: string) => {if (!isUuid(shareId)) return null;@@ -514,8 +617,7 @@ export class AgentShareModel {agentTitle: agents.title,// Creator identity for the visitor-facing profile. Left-joined on the// owner rather than read through a second query: the share page needs- // it on its only round trip, and the row is already joined for the- // personal-scope guard below.+ // it on its only round trip alongside the Agent's Workspace scope.ownerAvatar: users.avatar,ownerFullName: users.fullName,ownerId: agents.userId,@@ -524,11 +626,12 @@ export class AgentShareModel {shareId: agentShares.id,userViewCount: agentShares.userViewCount,visibility: agentShares.visibility,+ workspaceId: agents.workspaceId,}).from(agentShares).innerJoin(agents, eq(agentShares.agentId, agents.id)).leftJoin(users, eq(agents.userId, users.id))- .where(and(eq(agentShares.id, shareId), isNull(agents.workspaceId)))+ .where(eq(agentShares.id, shareId)).limit(1);if (!share) return null;diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.tsindex 08ff1bbec80..639f716026b 100644--- a/packages/database/src/models/chatGroup.ts+++ b/packages/database/src/models/chatGroup.ts@@ -12,6 +12,7 @@ import {agentBotProviders,agentCronJobs,agents,+ agentShares,chatGroups,chatGroupsAgents,projectAgents,@@ -38,6 +39,7 @@ import {} from '../utils/groupMembership';import { normalizeInboxAgentAvatar } from '../utils/inboxAgent';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { AGENT_SHARED_TRANSFER_BLOCKED } from './agent';import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from './agentTransferJob';@@ -901,6 +903,18 @@ export class ChatGroupModel {.for('update');}+ // A share row keeps the agent bound to its current owner and workspace,+ // including when the share is paused. Check only owned members: referenced+ // standalone agents remain with their owner and do not move with the group.+ if (ownedAgentIds.length > 0) {+ const [existingShare] = await trx+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(inArray(agentShares.agentId, ownedAgentIds))+ .limit(1);+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);+ }+// A REFERENCED member that is private to someone other than the recipient// would silently vanish from the roster for the group's new owner (every// roster read applies member-agent visibility). Refuse instead — samediff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 687fa4165e4..57a9e78aa73 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -427,7 +427,7 @@ export class TopicModel {* Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store for* both {@link ownership} and {@link mine}, and the escape hatch for methods* that must see visitor rows independent of the instance flag- * ({@link queryBySender} / {@link countBySender} / {@link countVisitors}).+ * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors}).*/private workspaceScope = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics);@@ -442,7 +442,7 @@ export class TopicModel {** `mine()` deliberately does NOT AND {@link notShareVisitor} — it is the* per-user variant of {@link workspaceScope} and the share-scoped methods- * ({@link queryBySender} / {@link countBySender} / {@link countVisitors})+ * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors})* layer their own `senderId` predicate on top of it. Creator-facing* destructive sweeps that reach for `mine()` still get the visitor* exclusion by AND-ing {@link notShareVisitor} themselves.diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.tsindex 799771c7bb1..2a75a57b972 100644--- a/packages/database/src/repositories/agentGroup/index.test.ts+++ b/packages/database/src/repositories/agentGroup/index.test.ts@@ -4,6 +4,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { AGENT_SHARED_TRANSFER_BLOCKED } from '../../models/agent';import { AGENT_TRANSFER_IN_PROGRESS } from '../../models/agentTransferJob';import { ChatGroupModel } from '../../models/chatGroup';import {@@ -13,6 +14,7 @@ import {} from '../../models/topicComment';import { agents } from '../../schemas/agent';import { agentHistoryJobAgents, agentHistoryJobs } from '../../schemas/agentHistoryJob';+import { agentShares } from '../../schemas/agentShare';import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';import { messagePlugins, messages } from '../../schemas/message';import { threads, topics } from '../../schemas/topic';@@ -1565,6 +1567,10 @@ describe('AgentGroupRepository', () => {workspaceId,},]);+ const [referencedShare] = await serverDB+ .insert(agentShares)+ .values({ agentId: 'transfer-member', visibility: 'link' })+ .returning();await serverDB.insert(chatGroupsAgents).values([{agentId: 'transfer-supervisor',@@ -1645,6 +1651,9 @@ describe('AgentGroupRepository', () => {where: (a, { eq }) => eq(a.id, 'transfer-member'),});expect(referencedMember!.workspaceId).toBe(workspaceId);+ expect(+ await serverDB.select().from(agentShares).where(eq(agentShares.id, referencedShare.id)),+ ).toEqual([referencedShare]);const junctions = await serverDB.query.chatGroupsAgents.findMany({where: (cga, { eq }) => eq(cga.chatGroupId, 'transfer-group'),@@ -1695,6 +1704,75 @@ describe('AgentGroupRepository', () => {expect(mention.workspaceId).toBe(targetWorkspaceId);});+ it.each(['link', 'private'] as const)(+ 'rejects the whole group transfer when an owned member has a %s share',+ async (visibility) => {+ const targetWorkspaceId = `agent-group-blocked-target-${visibility}`;+ await serverDB.insert(workspaces).values({+ id: targetWorkspaceId,+ name: 'Blocked Target Workspace',+ primaryOwnerId: userId,+ slug: targetWorkspaceId,+ });++ const [group] = await serverDB+ .insert(chatGroups)+ .values({+ id: `blocked-group-${visibility}`,+ title: 'Blocked Group',+ userId,+ workspaceId,+ })+ .returning();+ const [ownedAgent] = await serverDB+ .insert(agents)+ .values({+ id: `blocked-supervisor-${visibility}`,+ title: 'Blocked Supervisor',+ userId,+ virtual: true,+ workspaceId,+ })+ .returning();+ const [share] = await serverDB+ .insert(agentShares)+ .values({ agentId: ownedAgent.id, visibility })+ .returning();+ const [junction] = await serverDB+ .insert(chatGroupsAgents)+ .values({+ agentId: ownedAgent.id,+ chatGroupId: group.id,+ role: 'supervisor',+ userId,+ workspaceId,+ })+ .returning();++ const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);++ await expect(+ wsRepo.transferToWorkspace(group.id, targetWorkspaceId, userId),+ ).rejects.toThrow(AGENT_SHARED_TRANSFER_BLOCKED);++ expect(await serverDB.select().from(chatGroups).where(eq(chatGroups.id, group.id))).toEqual(+ [group],+ );+ expect(await serverDB.select().from(agents).where(eq(agents.id, ownedAgent.id))).toEqual([+ ownedAgent,+ ]);+ expect(+ await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id)),+ ).toEqual([share]);+ expect(+ await serverDB+ .select()+ .from(chatGroupsAgents)+ .where(eq(chatGroupsAgents.agentId, ownedAgent.id)),+ ).toEqual([junction]);+ },+ );+it('aborts when the group leaves the source scope before the lock is taken', async () => {// The scope check runs outside the transaction. A racing transfer small// enough to take the fast path leaves no pending job behind, so thediff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsindex 2e2575feaf3..876ba43fe1b 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -3,6 +3,7 @@ import type { AgentGroupDetail, AgentGroupMember, AgentPluginEntry } from '@lobeimport { cleanObject } from '@lobechat/utils';import { and, asc, count, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';+import { AGENT_SHARED_TRANSFER_BLOCKED } from '../../models/agent';import {AGENT_COPY_IN_PROGRESS,AgentCopyJobModel,@@ -32,6 +33,7 @@ import type {import {agentLabelAssignments,agents,+ agentShares,chatGroups,chatGroupsAgents,messages,@@ -1124,6 +1126,18 @@ export class AgentGroupRepository {.for('update');}+ // A share row keeps the agent bound to its current owner and workspace,+ // including when the share is paused. Check only owned members: referenced+ // standalone agents remain with their owner and do not move with the group.+ if (ownedAgentIds.length > 0) {+ const [existingShare] = await trx+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(inArray(agentShares.agentId, ownedAgentIds))+ .limit(1);+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);+ }+// `memberRows` is read RAW — the partition above must see every member,// including ones hidden from this caller. But a referenced member is// about to be CLONED into the target scope, systemRole and config anddiff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex 224ee3ce21c..782cda95a46 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -17,8 +17,8 @@ export interface AgentShareConfig {*/allowReadMemory?: boolean;/**- * Total bytes this share's visitor uploads may occupy on the creator's- * account (settled files plus in-flight reservations). Mandatory like+ * Total bytes this share's visitor uploads may occupy in the Agent's owning+ * scope (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`.*/@@ -28,11 +28,11 @@ export interface AgentShareConfig {/** Maximum number of message turns allowed in each shared topic. */maxTurnsPerTopic?: number;/**- * Creator's monthly spend cap for this shared agent, in USD credits.+ * Per-Agent monthly spend cap for this share, in USD credits.** Mandatory: `normalizeAgentShareConfig` fills a default for any row that* lacks one, so every read path through `AgentShareModel` sees a number —- * see {@link NormalizedAgentShareConfig}. The creator can move the number+ * see {@link NormalizedAgentShareConfig}. A share manager can move the number* but can never clear it. A cap of `0` is a real lower bound meaning "stop* all visitor runs", never "unlimited".*diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 189a90d8371..ec07b8350eb 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -399,6 +399,8 @@ export default {'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.maxFileStorageWorkspaceHint':+ 'Files visitors attach are stored in the Workspace. 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.',@@ -409,6 +411,8 @@ export default {'share.settings.limits.monthlySpendLimitHint':'Visitor runs stop once this month’s spend on this Agent reaches the cap. Resets on the 1st of each month (UTC).','share.settings.limits.title': 'Limits',+ 'share.settings.limits.workspaceDesc':+ 'Every visitor run is billed to the Workspace budget, not to the visitor or any member quota. These per-Agent caps always apply — you can change the numbers, but not turn them off.','share.settings.link.copied': 'Link copied','share.settings.link.copy': 'Copy link','share.settings.link.desc':@@ -432,9 +436,14 @@ export default {'share.settings.link.slugSaved': 'Custom link updated','share.settings.link.title': 'Share link','share.settings.link.viewCount': '{{views}} views',+ 'share.settings.link.workspaceDesc':+ 'Anyone signed in who has the link can chat with this Agent. Runs execute in the Workspace and are charged to its budget.','share.settings.notice.desc':'Visitors don’t just read this Agent — they run it. Every reply is generated on your account and charged to your balance, and the Agent acts with whatever access you grant below.','share.settings.notice.title': 'Visitors run this Agent on your account',+ 'share.settings.notice.workspaceDesc':+ 'Visitors don’t just read this Agent — they run it. Every reply is generated in the Workspace and charged to its shared budget, without consuming the creator’s or another member’s quota. The Agent only acts with the visitor access you grant below.',+ 'share.settings.notice.workspaceTitle': 'Visitors run this Agent on the Workspace budget','share.settings.permissions.allowCreatorViewSessions': 'Let me read visitor conversations','share.settings.permissions.allowCreatorViewSessionsHint':'Off by default: visitor conversations stay private to the visitor.',@@ -517,11 +526,14 @@ export default {'share.visitor.input.stop': 'Stop','share.visitor.privacyNotice':'This conversation runs on the owner’s account and may be visible to them. Avoid sharing sensitive information.',+ 'share.visitor.privacyNoticeWorkspace':+ 'This conversation is paid for by the Workspace and may be visible to the Agent creator. Avoid sharing sensitive information.','share.visitor.profile.about': 'About','share.visitor.profile.createdBy': 'Created by {{creator}}','share.visitor.profile.cta': 'Start a conversation','share.visitor.profile.ctaSignIn': 'Sign in to start','share.visitor.profile.freeNote': 'Free · paid for by the creator',+ 'share.visitor.profile.freeNoteWorkspace': 'Free · paid for by the Workspace','share.visitor.profile.metrics.conversations': 'Conversations','share.visitor.profile.metrics.conversationsCaption': 'started so far','share.visitor.profile.metrics.tools': 'Open tools',@@ -536,6 +548,8 @@ export default {'share.visitor.profile.starters.title': 'Not sure where to start?','share.visitor.profile.terms.account':'It runs on the creator’s account, and every reply is paid for by them.',+ 'share.visitor.profile.terms.accountWorkspace':+ 'It runs in the owner Workspace, and every reply is paid from the Workspace budget.','share.visitor.profile.terms.desc':'Today these rules only show up as errors once you hit them. Here they are up front.','share.visitor.profile.terms.title': 'Before you start',diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex d7695053c86..181bb14146e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -83,6 +83,8 @@ export default {'This agent does not exist or is no longer accessible — it may have been deleted or set to private by its owner.','permission.configAccess.agentChatOnly':'You can only use this Agent, not configure it. You were returned to chat.',+ 'permission.configAccess.agentManageRestricted':+ 'Only the Agent creator or a workspace admin can manage external sharing. You were returned to chat.','permission.configAccess.agentRoleRestricted':'Your workspace role cannot configure Agents. You were returned to chat.','permission.configAccess.groupChatOnly':diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex 1fb988f2156..d6d782757bf 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -254,7 +254,8 @@ export default {'A previous copy of this agent is still duplicating its history. Try again once it finishes.','transfer.transferInProgress':'A previous move of this resource is still migrating its history. Try again once it finishes.',- 'transfer.sharedTransferBlocked': 'This agent has a share link, so its owner cannot be changed.',+ 'transfer.sharedTransferBlocked':+ 'This agent has a share link and cannot be transferred, even while sharing is paused.','transfer.sameWorkspace':'This resource is already in the selected workspace. Choose another target.','transfer.targetIsCurrentOwner': 'This agent already belongs to that member. Pick someone else.',diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex 649ac7959b9..ea0b9ed6f6a 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -144,6 +144,29 @@ export default {'credits.autoTopUp.upgradeHint': 'Subscribe to a paid plan to enable auto top-up','credits.autoTopUp.validation.targetMustExceedThreshold':'Target balance must be greater than threshold',+ 'credits.agentShareBudget.desc':+ 'Set one monthly safety cap across all externally shared Workspace Agents',+ 'credits.agentShareBudget.audit.agent': 'Agent {{id}}',+ 'credits.agentShareBudget.audit.desc':+ 'Admins can audit and pause external links without opening private Agent configuration or visitor conversations.',+ 'credits.agentShareBudget.audit.disable': 'Pause link',+ 'credits.agentShareBudget.audit.disableError': 'Failed to pause the share link',+ 'credits.agentShareBudget.audit.disableSuccess': 'Share link paused',+ 'credits.agentShareBudget.audit.empty': 'No Workspace Agent has been shared externally.',+ 'credits.agentShareBudget.audit.owner': 'Owner',+ 'credits.agentShareBudget.audit.ownerUnavailable': 'Unknown member',+ 'credits.agentShareBudget.audit.views': '{{views}} views',+ 'credits.agentShareBudget.audit.statusActive': 'Active',+ 'credits.agentShareBudget.audit.statusPaused': 'Paused',+ 'credits.agentShareBudget.audit.title': 'Workspace share audit',+ 'credits.agentShareBudget.limit': 'Workspace monthly cap',+ 'credits.agentShareBudget.limitHint':+ 'Leave blank for no Workspace-wide cap. Set 0 to pause all visitor runs. These charges use Workspace credits and never consume a member quota.',+ 'credits.agentShareBudget.save': 'Save',+ 'credits.agentShareBudget.saveError': 'Failed to save the Agent Share budget policy',+ 'credits.agentShareBudget.saveSuccess': 'Agent Share budget policy saved',+ 'credits.agentShareBudget.title': 'External Agent sharing',+ 'credits.agentShareBudget.unlimited': 'No Workspace-wide cap','credits.dedicatedBudget.actions.add': 'Dedicated budget','credits.dedicatedBudget.actions.create': 'Create','credits.dedicatedBudget.actions.edit': 'Edit dedicated budget',diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.tsindex bd140035628..dc0ae6d4446 100644--- a/packages/types/src/agent/share.ts+++ b/packages/types/src/agent/share.ts@@ -54,6 +54,8 @@ export interface SharedAgentData {tags: string[];title: string | null;};+ /** Who funds visitor execution, without exposing the owning Workspace id. */+ billingScope: 'personal' | 'workspace';/*** Who published this share. In a market of user-made agents the creator is* the quality signal a visitor has before any usage number exists.diff --git a/src/features/AgentProfileTabs/index.tsx b/src/features/AgentProfileTabs/index.tsxindex 68ba76dfa9a..56214ab7fe3 100644--- a/src/features/AgentProfileTabs/index.tsx+++ b/src/features/AgentProfileTabs/index.tsx@@ -62,10 +62,15 @@ const AgentProfileTabs = memo<AgentProfileTabsProps>(({ active, agentId }) => {agentSelectors.currentAgentHeterogeneousProviderType,);const { allowed: canEditContent } = usePermission('edit_own_content');- const { canEditResource, isAccessResolved } = useResourceAccess('agent', agentId);+ const { canEditResource, canManageResource, isAccessResolved } = useResourceAccess(+ 'agent',+ agentId,+ );const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);const canConfigure = !!isAgentEditable && isAccessResolved && canEditContent && canEditResource;+ const canManageShare =+ !!isAgentEditable && isAccessResolved && canEditContent && canManageResource;const channelsSupported = supportsMessageChannels(heterogeneousProviderType);const { visible: shareVisible } = useAgentShareSupported(agentId);@@ -84,9 +89,9 @@ const AgentProfileTabs = memo<AgentProfileTabsProps>(({ active, agentId }) => {share: t('share', { ns: 'common' }),statistics: t('usageStats.title', { ns: 'spend' }),},- shareSupported: shareVisible === true,+ shareSupported: shareVisible === true && canManageShare,}),- [active, canConfigure, channelsSupported, shareVisible, t],+ [active, canConfigure, canManageShare, channelsSupported, shareVisible, t],);// A lone segment is a label, not a switcher.diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsxindex 19a2fb950c1..5b0a48f7288 100644--- a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({accessResolved: true,canEditContent: true,canEditResource: false,+ canManageResource: false,navigate: vi.fn(),toastInfo: vi.fn(),}));@@ -38,17 +39,23 @@ vi.mock('./useResourceAccess', () => ({useResourceAccess: () => ({accessError: undefined,canEditResource: mocks.canEditResource,+ canManageResource: mocks.canManageResource,isAccessResolved: mocks.accessResolved,isLoading: false,retryAccess: vi.fn(),}),}));-const renderGate = (resourceType: 'agent' | 'agentGroup' = 'agent', loading?: ReactNode) =>+const renderGate = (+ resourceType: 'agent' | 'agentGroup' = 'agent',+ loading?: ReactNode,+ requiredAccess: 'edit' | 'manage' = 'edit',+) =>render(<ResourceConfigAccessGateloading={loading}redirectPath="/agent/agent-1"+ requiredAccess={requiredAccess}resourceId="agent-1"resourceType={resourceType}>@@ -61,6 +68,7 @@ describe('ResourceConfigAccessGate', () => {vi.clearAllMocks();mocks.canEditContent = true;mocks.canEditResource = false;+ mocks.canManageResource = false;mocks.accessResolved = true;});@@ -105,6 +113,16 @@ describe('ResourceConfigAccessGate', () => {});});+ it('explains when Agent sharing requires creator or admin access', async () => {+ mocks.canEditResource = true;++ renderGate('agent', undefined, 'manage');++ await waitFor(() => {+ expect(mocks.toastInfo).toHaveBeenCalledWith('permission.configAccess.agentManageRestricted');+ });+ });+it('uses the surface-specific loading state while access is resolving', () => {mocks.accessResolved = false;diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.tsxindex ae432ca9b69..d6072f2165d 100644--- a/src/features/ResourcePermission/ResourceConfigAccessGate.tsx+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.tsx@@ -15,21 +15,31 @@ interface ResourceConfigAccessGateProps {children: ReactNode;loading?: ReactNode;redirectPath: string;+ requiredAccess?: 'edit' | 'manage';resourceId?: string;resourceType: 'agent' | 'agentGroup';}const ResourceConfigAccessGate = memo<ResourceConfigAccessGateProps>(- ({ children, loading, redirectPath, resourceId, resourceType }) => {+ ({ children, loading, redirectPath, requiredAccess = 'edit', resourceId, resourceType }) => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();const hasRedirected = useRef(false);const { allowed: canEditContent } = usePermission('edit_own_content');- const { accessError, canEditResource, isAccessResolved, isLoading, retryAccess } =- useResourceAccess(resourceType, resourceId);+ const {+ accessError,+ canEditResource,+ canManageResource,+ isAccessResolved,+ isLoading,+ retryAccess,+ } = useResourceAccess(resourceType, resourceId);const accessReady = !!resourceId && isAccessResolved && !isLoading;- const canConfigure = accessReady && canEditContent && canEditResource;+ const canConfigure =+ accessReady &&+ canEditContent &&+ (requiredAccess === 'manage' ? canManageResource : canEditResource);useEffect(() => {if (!accessReady || accessError || canConfigure || hasRedirected.current) return;@@ -40,11 +50,15 @@ const ResourceConfigAccessGate = memo<ResourceConfigAccessGateProps>(// resource, and conflating them made authors think their own Agent had// rejected them.const isRoleRestricted = !canEditContent;+ const isManagementRestricted =+ requiredAccess === 'manage' && canEditResource && !canManageResource;const messageKey =resourceType === 'agent'? isRoleRestricted? 'permission.configAccess.agentRoleRestricted'- : 'permission.configAccess.agentChatOnly'+ : isManagementRestricted+ ? 'permission.configAccess.agentManageRestricted'+ : 'permission.configAccess.agentChatOnly': isRoleRestricted? 'permission.configAccess.groupRoleRestricted': 'permission.configAccess.groupChatOnly';@@ -55,8 +69,11 @@ const ResourceConfigAccessGate = memo<ResourceConfigAccessGateProps>(accessReady,canConfigure,canEditContent,+ canEditResource,+ canManageResource,navigate,redirectPath,+ requiredAccess,resourceType,t,]);diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsxindex 86cf73ebb31..4e198ff11f1 100644--- a/src/routes/(main)/agent/profile/features/Header/index.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx@@ -252,7 +252,9 @@ const Header = memo(() => {);const { visible: shareVisible } = useAgentShareSupported(activeAgentId);- const canShareAgent = shareVisible === true && canConfigure;+ // External sharing is stronger than General Access `edit`: only the Agent+ // creator or a Workspace admin (`canManageResource`) may manage the link.+ const canShareAgent = shareVisible === true && canManage;const showMarketSubmission = !!config && !isBuiltinAgent && !isHeterogeneous;const canSubmitToMarket = showMarketSubmission && canManage && !lockedByOther && !lockPending;diff --git a/src/routes/(main)/agent/share/index.tsx b/src/routes/(main)/agent/share/index.tsxindex a4f91a16443..0b576398b63 100644--- a/src/routes/(main)/agent/share/index.tsx+++ b/src/routes/(main)/agent/share/index.tsx@@ -14,11 +14,12 @@ const AgentSharePage = memo(() => {return (<Suspense fallback={skeleton}>- {/* Sharing exposes real execution on the creator's account — a- configuration action, gated exactly like Agent Profile / Channels. */}+ {/* Sharing exposes real execution in the Agent's owning billing scope —+ only resource managers may configure the external link. */}<ResourceConfigAccessGateloading={skeleton}redirectPath={`/agent/${aid ?? ''}`}+ requiredAccess="manage"resourceId={aid}resourceType="agent">diff --git a/src/services/agentShare.ts b/src/services/agentShare.tsindex 1f869238079..1f18162a691 100644--- a/src/services/agentShare.ts+++ b/src/services/agentShare.ts@@ -22,6 +22,11 @@ class AgentShareService {return lambdaClient.agentShare.getShareStatus.query({ agentId });}+ /** Workspace administrator inventory; intentionally excludes private Agent configuration. */+ async getWorkspaceShareAudit(input: { limit?: number; offset?: number } = {}) {+ return lambdaClient.agentShare.getWorkspaceShareAudit.query(input);+ }+/** Resolve a share's visitor-facing metadata, by its custom slug or its raw share id. */async getSharedAgent(slugOrId: string) {// The visitor page renders its own login prompt on UNAUTHORIZED; opt out of@@ -47,6 +52,10 @@ class AgentShareService {async updateVisibility(agentId: string, visibility: 'link' | 'private') {return lambdaClient.agentShare.updateVisibility.mutate({ agentId, visibility });}++ async forceDisableWorkspaceShare(shareId: string) {+ return lambdaClient.agentShare.forceDisableWorkspaceShare.mutate({ shareId });+ }}export const agentShareService = new AgentShareService();