🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: enforce shared agent provider restrictions (#19827)
YuTengjingd322793048ee
diff --git a/.agents/skills/ux/SKILL.md b/.agents/skills/ux/SKILL.mdindex b373b0274cb..e7a34157d98 100644--- a/.agents/skills/ux/SKILL.md+++ b/.agents/skills/ux/SKILL.md@@ -77,6 +77,10 @@ surface uses (grep `NavItem`, `Accordion`) and compose it; fall to raw elementsgenuinely novel row. See **[Read §1.10](references/read.md)** for the full pattern; the**react** component-priority rule covers the mechanics.+### Review messages in page context・Certainty++Distinguish routine explanations from action-blocking states; do not stack equally prominent warning banners for different roles. Restriction copy must name the current condition and the next action, using precise product entities (for example, distinguish a model from its provider). Verify the whole page, not just the changed component.+## Checklist modulesGrouped by **interaction type** — the kind of thing the user is doing. Jump to the modulediff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsindex a8f9ade5172..e0e5d96c73b 100644--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -38,6 +38,20 @@ vi.mock('@lobechat/business-const', async () => {};});+const mockAssertShareModelAllowed = vi.fn();+vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn(function () {+ return {+ prepareShareModel: mockAssertShareModelAllowed,+ withShareModelLock: (_id: string, action: (service: unknown, shares: unknown) => unknown) =>+ action(+ { prepareShareModel: mockAssertShareModelAllowed },+ { create: mockCreate, updateVisibility: mockUpdateVisibility },+ ),+ };+ }),+}));+const mockCreate = vi.fn();const mockFindByShareId = vi.fn();const mockForceDisableWorkspaceShare = vi.fn();@@ -104,6 +118,7 @@ const share = {describe('agentShareRouter', () => {beforeEach(() => {vi.clearAllMocks();+ mockAssertShareModelAllowed.mockReset().mockResolvedValue(undefined);mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;mockCreate.mockResolvedValue(share);mockFindByShareId.mockResolvedValue({@@ -153,6 +168,29 @@ describe('agentShareRouter', () => {expect(mockCreate).toHaveBeenCalledWith('agent-1', 'link');});+ it.each(['enableShare', 'updateVisibility'] as const)(+ 'rejects unsupported providers through %s before publishing',+ async (method) => {+ mockAssertShareModelAllowed.mockRejectedValue(+ new TRPCError({ code: 'BAD_REQUEST', message: 'Unsupported share provider' }),+ );+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ await expect(+ caller[method]({ agentId: 'agent-1', visibility: 'link' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockCreate).not.toHaveBeenCalled();+ expect(mockUpdateVisibility).not.toHaveBeenCalled();+ },+ );++ it('allows disabling a share with an unsupported provider', async () => {+ mockAssertShareModelAllowed.mockRejectedValue(new Error('Unsupported share provider'));+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ await expect(+ caller.updateVisibility({ agentId: 'agent-1', visibility: 'private' }),+ ).resolves.toEqual(share);+ });+it('returns null when a personal agent has no share', async () => {mockGetByAgentId.mockResolvedValue(null);const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex 8ebc735553a..b7c99a37c79 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -15,6 +15,7 @@ import { TopicModel } from '@/database/models/topic';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { AgentService } from '@/server/services/agent';import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';import { assertAgentShareCreationEnabled } from './_helpers/agentShareFeatureGate';@@ -90,6 +91,7 @@ const agentShareProcedure = wsCompatProcedure.use(serverDatabase).use(async (optreturn opts.next({ctx: {+ agentService: new AgentService(ctx.serverDB, ctx.userId, workspaceId),agentShareModel: new AgentShareModel(ctx.serverDB, ctx.userId, workspaceId, {authorizeMutation: workspaceId? (db, agentId) =>@@ -174,6 +176,13 @@ export const agentShareRouter = router({await assertCanManageAgentShare(ctx, input.agentId);await assertAgentShareCreationEnabled(ctx.userId);+ if (input.visibility === 'link') {+ return ctx.agentService.withShareModelLock(input.agentId, async (service, shares) => {+ await service.prepareShareModel(input.agentId);+ return shares.create(input.agentId, 'link');+ });+ }+return ctx.agentShareModel.create(input.agentId, input.visibility);}),@@ -332,7 +341,13 @@ export const agentShareRouter = router({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);+ if (input.visibility === 'link') {+ await assertAgentShareCreationEnabled(ctx.userId);+ return ctx.agentService.withShareModelLock(input.agentId, async (service, shares) => {+ await service.prepareShareModel(input.agentId);+ return requireShare(await shares.updateVisibility(input.agentId, 'link'));+ });+ }return requireShare(await ctx.agentShareModel.updateVisibility(input.agentId, input.visibility),diff --git a/apps/server/src/services/agent/index.test.ts b/apps/server/src/services/agent/index.test.tsindex 103f14badb2..9508be526cc 100644--- a/apps/server/src/services/agent/index.test.ts+++ b/apps/server/src/services/agent/index.test.ts@@ -4,14 +4,24 @@ import { DEFAULT_AGENT_CONFIG, DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE } fromimport { beforeEach, describe, expect, it, vi } from 'vitest';import { AgentModel } from '@/database/models/agent';+import { AgentShareModel } from '@/database/models/agentShare';import { SessionModel } from '@/database/models/session';import { UserModel } from '@/database/models/user';import type * as RedisModule from '@/libs/redis';import { initializeRedisWithPrefix, isRedisEnabled, RedisKeys } from '@/libs/redis';import { parseAgentConfig } from '@/server/globalConfig/parseDefaultAgent';+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';import { AgentService } from './index';+vi.mock('@/server/services/resourcePermission', () => ({+ assertCanPerformResourceAction: vi.fn(),+}));++vi.mock('@/business/agent-share', () => ({+ AGENT_SHARE_ALLOWED_PROVIDERS: ['lobehub'],+}));+vi.mock('@/envs/app', () => ({appEnv: {DEFAULT_AGENT_CONFIG: 'model=gpt-4;temperature=0.7',@@ -33,6 +43,10 @@ vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(),}));+vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: Object.assign(vi.fn(), { lockScopedAgentRow: vi.fn() }),+}));+vi.mock('@/database/models/user', () => ({UserModel: vi.fn(),}));@@ -825,6 +839,159 @@ describe('AgentService', () => {});});+ describe('share provider restrictions', () => {+ const storedAgent = { id: 'agent-1', model: 'gpt-4', provider: 'lobehub' };+ let agent: Omit<typeof storedAgent, 'provider'> & { provider: string | null };+ let visibility: string;++ beforeEach(() => {+ agent = { ...storedAgent };+ visibility = 'link';+ mockDb.transaction = vi.fn(async (action) => action(mockDb));+ vi.mocked(AgentShareModel.lockScopedAgentRow).mockResolvedValue({+ id: 'agent-1',+ slug: null,+ workspaceId: null,+ });+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValue({});+ vi.mocked(parseAgentConfig).mockReturnValue({ provider: 'lobehub' });+ vi.mocked(AgentModel).mockImplementation(function () {+ return {+ getAgentConfigById: vi.fn(async () => agent),+ updateConfig: vi.fn(async (_id, patch) => {+ agent = { ...agent, ...patch };+ }),+ } as unknown as AgentModel;+ });+ vi.mocked(AgentShareModel).mockImplementation(function () {+ return { getByAgentId: vi.fn(async () => ({ visibility })) } as unknown as AgentShareModel;+ });+ vi.mocked(isRedisEnabled).mockReturnValue(false);+ service = new AgentService(mockDb, mockUserId);+ });++ it('preserves workspace scope and rechecks management permission under the lock', async () => {+ const workspaceService = new AgentService(mockDb, mockUserId, 'workspace-1');+ await workspaceService.withShareModelLock('agent-1', async () => undefined);+ expect(AgentShareModel.lockScopedAgentRow).toHaveBeenCalledWith(mockDb, 'agent-1', {+ userId: mockUserId,+ workspaceId: 'workspace-1',+ });+ expect(assertCanPerformResourceAction).toHaveBeenCalledWith(+ expect.objectContaining({+ action: 'manage',+ db: mockDb,+ resourceId: 'agent-1',+ workspaceId: 'workspace-1',+ }),+ );+ expect(AgentShareModel).toHaveBeenCalledWith(mockDb, mockUserId, 'workspace-1');+ });++ it('rechecks visibility after acquiring the publication lock', async () => {+ visibility = 'private';+ vi.mocked(AgentShareModel.lockScopedAgentRow).mockImplementationOnce(async () => {+ visibility = 'link';+ return { id: 'agent-1', slug: null, workspaceId: null };+ });+ await expect(+ service.updateAgentConfig('agent-1', { provider: 'openai' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.provider).toBe('lobehub');+ });++ it('validates the provider after an earlier configuration writer releases the lock', async () => {+ vi.mocked(AgentShareModel.lockScopedAgentRow).mockImplementationOnce(async () => {+ agent.provider = 'openai';+ return { id: 'agent-1', slug: null, workspaceId: null };+ });+ const publish = vi.fn();+ await expect(+ service.withShareModelLock('agent-1', async (lockedService) => {+ await lockedService.prepareShareModel('agent-1');+ publish();+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(publish).not.toHaveBeenCalled();+ });++ it('rejects changing a shared agent to a third-party provider without saving it', async () => {+ await expect(+ service.updateAgentConfig('agent-1', { provider: 'supergrok' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.provider).toBe('lobehub');+ });++ it('allows changing the model within the supported provider', async () => {+ await expect(service.updateAgentConfig('agent-1', { model: 'gpt-5' })).resolves.toMatchObject(+ { success: true },+ );+ expect(agent.model).toBe('gpt-5');+ });++ it('allows third-party providers when there is no share', async () => {+ vi.mocked(AgentShareModel).mockImplementation(function () {+ return { getByAgentId: vi.fn(async () => null) } as unknown as AgentShareModel;+ });+ await expect(+ service.updateAgentConfig('agent-1', { provider: 'openai' }),+ ).resolves.toMatchObject({ success: true });+ expect(agent.provider).toBe('openai');+ });++ it('allows third-party providers after sharing is disabled', async () => {+ visibility = 'private';+ await expect(+ service.updateAgentConfig('agent-1', { provider: 'supergrok' }),+ ).resolves.toMatchObject({ success: true });+ expect(agent.provider).toBe('supergrok');+ });++ it('does not block unrelated edits to legacy shared agents', async () => {+ agent.provider = 'supergrok';+ await expect(+ service.updateAgentConfig('agent-1', { title: 'Updated title' }),+ ).resolves.toMatchObject({ success: true });+ });++ it('rejects publishing a third-party model', async () => {+ agent.provider = 'supergrok';+ await expect(service.assertShareModelAllowed('agent-1')).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it('pins inherited defaults when publishing before account defaults change', async () => {+ agent.provider = null;+ await service.prepareShareModel('agent-1');+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValue({+ config: { provider: 'openai' },+ });+ expect(agent.provider).toBe('lobehub');+ await expect(service.assertShareModelAllowed('agent-1')).resolves.toMatchObject({+ provider: 'lobehub',+ });+ });++ it('pins an inherited provider when clearing a shared selection', async () => {+ await service.updateAgentConfig('agent-1', { provider: null });+ expect(agent.provider).toBe('lobehub');+ });++ it('resolves inherited providers before publishing', async () => {+ agent.provider = null;+ await expect(service.assertShareModelAllowed('agent-1')).resolves.toMatchObject({+ provider: 'lobehub',+ });+ mockUserModel.getUserSettingsDefaultAgentConfig.mockResolvedValue({+ config: { provider: 'openai' },+ });+ await expect(service.assertShareModelAllowed('agent-1')).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });+ });+describe('updateAgentConfig', () => {it('should throw when the updated agent cannot be read back', async () => {const mockAgentModel = {diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.tsindex e161bf1a0b3..df268253063 100644--- a/apps/server/src/services/agent/index.ts+++ b/apps/server/src/services/agent/index.ts@@ -9,7 +9,9 @@ import { TRPCError } from '@trpc/server';import debug from 'debug';import { type PartialDeep } from 'type-fest';+import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';import { AgentModel } from '@/database/models/agent';+import { AgentShareModel } from '@/database/models/agentShare';import { SessionModel } from '@/database/models/session';import { UserModel } from '@/database/models/user';import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '@/database/utils/inboxAgent';@@ -22,6 +24,7 @@ import {RedisKeys,} from '@/libs/redis';import { getServerDefaultAgentConfig } from '@/server/globalConfig';+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';import { type UpdateAgentResult } from './type';@@ -67,6 +70,65 @@ export class AgentService {this.userModel = new UserModel(db, userId);}+ /** Validate the effective selection at configuration boundaries, including inherited defaults. */+ async assertShareModelAllowed(agentId: string, patch: PartialDeep<AgentItem> = {}) {+ if (!AGENT_SHARE_ALLOWED_PROVIDERS) return;++ const agent = await this.agentModel.getAgentConfigById(agentId);+ if (!agent) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });++ const selection = await this.resolveModelSelection({ ...agent, ...patch });+ const { provider } = selection;+ if (!AGENT_SHARE_ALLOWED_PROVIDERS.includes(provider)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Shared agents only support models from: ${AGENT_SHARE_ALLOWED_PROVIDERS.join(', ')}. Switch providers or turn off sharing first.`,+ });+ }+ return selection;+ }++ /** Serialize provider changes and publication on the existing shared-agent row lock. */+ async withShareModelLock<T>(+ agentId: string,+ action: (service: AgentService, shares: AgentShareModel) => Promise<T>,+ ): Promise<T> {+ if (!AGENT_SHARE_ALLOWED_PROVIDERS) {+ return action(this, new AgentShareModel(this.db, this.userId, this.workspaceId));+ }+ return this.db.transaction(async (transaction) => {+ const tx = transaction as LobeChatDatabase;+ if (+ !(await AgentShareModel.lockScopedAgentRow(tx, agentId, {+ userId: this.userId,+ workspaceId: this.workspaceId,+ }))+ ) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });+ }+ if (this.workspaceId) {+ await assertCanPerformResourceAction({+ action: 'manage',+ db: tx,+ resourceId: agentId,+ resourceType: 'agent',+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ }+ return action(+ new AgentService(tx, this.userId, this.workspaceId),+ new AgentShareModel(tx, this.userId, this.workspaceId),+ );+ });+ }++ /** Pin inherited defaults so later account changes cannot alter a published model. */+ async prepareShareModel(agentId: string) {+ const selection = await this.assertShareModelAllowed(agentId);+ if (selection) await this.agentModel.updateConfig(agentId, selection);+ }+async createInbox() {const sessionModel = new SessionModel(this.db, this.userId, this.workspaceId);const defaultAgentConfig = getServerDefaultAgentConfig();@@ -275,6 +337,30 @@ export class AgentService {agentId: string,value: PartialDeep<AgentItem>,): Promise<UpdateAgentResult> {+ if (+ AGENT_SHARE_ALLOWED_PROVIDERS &&+ !this.workspaceId &&+ ('model' in value || 'provider' in value)+ ) {+ return this.withShareModelLock(agentId, (service) => service.saveAgentConfig(agentId, value));+ }+ return this.saveAgentConfig(agentId, value);+ }++ private async saveAgentConfig(+ agentId: string,+ value: PartialDeep<AgentItem>,+ ): Promise<UpdateAgentResult> {+ if (AGENT_SHARE_ALLOWED_PROVIDERS && ('model' in value || 'provider' in value)) {+ const share = await new AgentShareModel(this.db, this.userId, this.workspaceId).getByAgentId(+ agentId,+ );+ if (share?.visibility === 'link') {+ const selection = await this.assertShareModelAllowed(agentId, value);+ value = { ...value, ...selection };+ }+ }+// 1. Execute update// `AgentItem` here is the `@lobechat/types` domain shape (plugins:// AgentPluginEntry[]); `agentModel.updateConfig` takes the DB-layerdiff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.tsindex 431176b7ce1..1cf378c8576 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts@@ -12,6 +12,7 @@ const {mockGetAiProviderModelList,mockGetHiddenBuiltinModelsForUser,mockUpdateAgent,+ mockServiceUpdateConfig,mockUpdateConfig,} = vi.hoisted(() => ({mockCreatePlugin: vi.fn(),@@ -21,6 +22,7 @@ const {mockGetAiProviderModelList: vi.fn(),mockGetHiddenBuiltinModelsForUser: vi.fn(),mockUpdateAgent: vi.fn(),+ mockServiceUpdateConfig: vi.fn(),mockUpdateConfig: vi.fn(),}));@@ -29,6 +31,12 @@ vi.mock('@/business/server/aiProvider', () => ({getModelRedirects: vi.fn(async () => ({})),}));+vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn(function () {+ return { updateAgentConfig: mockServiceUpdateConfig };+ }),+}));+vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(function () {return {@@ -83,9 +91,22 @@ const createWorkspaceRuntime = () =>describe('agentBuilderRuntime', () => {beforeEach(() => {vi.clearAllMocks();+ mockServiceUpdateConfig.mockImplementation((...args) => mockUpdateConfig(...args));mockGetHiddenBuiltinModelsForUser.mockResolvedValue(undefined);});+ it('does not persist a model change rejected by the shared-agent policy', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', provider: 'lobehub' });+ mockServiceUpdateConfig.mockRejectedValueOnce(new Error('Shared agent provider is restricted'));+ const result = await createRuntime().updateConfig(+ { config: { model: 'gpt-4o', provider: 'openai' } },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );+ expect(result.success).toBe(false);+ expect(result.content).toContain('Shared agent provider is restricted');+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });+describe('getAvailableModels', () => {it('does not query or expose models when access cannot be resolved', async () => {mockGetAiProviderList.mockResolvedValue([{ enabled: true, id: 'lobehub', name: 'LobeHub' }]);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.tsindex c4819d79fd8..9205b7c8d89 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts@@ -11,6 +11,7 @@ const {mockGetAssistantList,mockQueryAgents,mockGetAgentConfigById,+ mockServiceUpdateConfig,mockUpdateConfig,mockFindById,mockCreatePlugin,@@ -21,9 +22,16 @@ const {mockGetAgentConfigById: vi.fn(),mockGetAssistantList: vi.fn(),mockQueryAgents: vi.fn(),+ mockServiceUpdateConfig: vi.fn(),mockUpdateConfig: vi.fn(),}));+vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn(function () {+ return { updateAgentConfig: mockServiceUpdateConfig };+ }),+}));+vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(function () {return {@@ -79,6 +87,19 @@ const makeAgents = (count: number, startIndex = 0) =>describe('agentManagementRuntime', () => {beforeEach(() => {vi.clearAllMocks();+ mockServiceUpdateConfig.mockImplementation((...args) => mockUpdateConfig(...args));+ });++ it('does not persist a model change rejected by the shared-agent policy', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', provider: 'lobehub' });+ mockServiceUpdateConfig.mockRejectedValueOnce(new Error('Shared agent provider is restricted'));+ const result = await createRuntime().updateAgent({+ agentId: 'agent-1',+ config: { model: 'gpt-4o', provider: 'openai' },+ });+ expect(result.success).toBe(false);+ expect(result.content).toContain('Shared agent provider is restricted');+ expect(mockUpdateConfig).not.toHaveBeenCalled();});it('declares the agent management runtime identifier', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.tsindex 10047d386b6..bb1b59f4a61 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts@@ -16,6 +16,7 @@ import { getHiddenBuiltinModelsForUser } from '@/business/server/aiProvider';import { AgentModel } from '@/database/models/agent';import { PluginModel } from '@/database/models/plugin';import { AiInfraRepos } from '@/database/repositories/aiInfra';+import { AgentService } from '@/server/services/agent';import { DiscoverService } from '@/server/services/discover';import { filterHiddenProviderModels } from '@/utils/aiProvider';@@ -37,6 +38,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {const userId = context.userId;const agentModel = new AgentModel(context.serverDB, userId, context.workspaceId);+ const agentService = new AgentService(context.serverDB, userId, context.workspaceId);const pluginModel = new PluginModel(context.serverDB, userId, context.workspaceId);const aiInfraRepos = new AiInfraRepos(context.serverDB, userId, {}, context.workspaceId);/**@@ -224,12 +226,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {}if (Object.keys(finalConfig).length > 0) {- // Domain tool plugins support structured entries, while the DB- // model's JSONB column still carries its legacy string[] annotation.- await agentModel.updateConfig(- agentId,- finalConfig as unknown as Parameters<typeof agentModel.updateConfig>[1],- );+ await agentService.updateAgentConfig(agentId, finalConfig);const nonPluginFields = Object.keys(finalConfig).filter((f) => f !== 'plugins');if (nonPluginFields.length > 0) {updatedParts.push(`config fields: ${nonPluginFields.join(', ')}`);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.tsindex 8e1b10b2038..2fcb5df6ad2 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts@@ -20,6 +20,7 @@ import {import { AgentModel } from '@/database/models/agent';import { PluginModel } from '@/database/models/plugin';+import { AgentService } from '@/server/services/agent';import { DiscoverService } from '@/server/services/discover';import { type ToolExecutionContext, type ToolExecutionResult } from '../types';@@ -40,6 +41,7 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {}const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);+ const agentService = new AgentService(context.serverDB, context.userId, context.workspaceId);const pluginModel = new PluginModel(context.serverDB, context.userId, context.workspaceId);// Same identity requirement as the Agent Builder runtime: built without an// identity, DiscoverService sends no credentials and every market read fails@@ -386,7 +388,7 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {const updatedParts: string[] = [];if (config && Object.keys(config).length > 0) {- await agentModel.updateConfig(agentId, config as Record<string, unknown>);+ await agentService.updateAgentConfig(agentId, config);updatedParts.push(`config: ${Object.keys(config).join(', ')}`);}diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 5b54f767dc0..c23734a4f8a 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -320,12 +320,15 @@"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.changeModel": "Change model","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.","share.settings.link.disableConfirmContent": "Visitors lose access to the link right away. The link itself is kept, so turning sharing back on later republishes the exact same URL.","share.settings.link.disableConfirmOk": "Turn off sharing","share.settings.link.disableConfirmTitle": "Turn off sharing?",+ "share.settings.link.modelDisabled": "Your current model uses another provider. Choose a model provided by LobeHub, then turn on sharing.",+ "share.settings.link.modelDisabledTitle": "Switch model providers to enable sharing","share.settings.link.offHint": "Sharing is off. Turn it on to get a link you can hand out — turning it off again only pauses it, and the same link resumes whenever you turn it back on.","share.settings.link.publishDisabled": "Sharing is not available on your account yet. You can still turn off a share you already published.","share.settings.link.slugError.invalid": "Use lowercase letters, numbers and hyphens only, and don’t start or end with a hyphen.",@@ -338,10 +341,12 @@"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.modelRestriction.description": "To choose a model from another provider, turn off sharing first.",+ "share.settings.modelRestriction.title": "Sharing is on: models are limited to the LobeHub provider",+ "share.settings.notice.desc": "Visitors can use the tools and data you allow below. Review permissions and the monthly spend cap before sharing.",+ "share.settings.notice.title": "You pay for visitor usage.","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",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 8c90c69f958..6e2183bb038 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -320,12 +320,15 @@"share.settings.limits.monthlySpendLimitHint": "本月该助手的消耗达到上限后,访客将无法继续运行。按自然月统计,每月 1 日(UTC)重置。","share.settings.limits.title": "使用限制","share.settings.limits.workspaceDesc": "访客的每次运行都会从工作区预算扣费,不会扣访客余额,也不占用创建者或其他成员的个人额度。每个智能体的这些上限始终生效,你可以调整数值,但不能关闭。",+ "share.settings.link.changeModel": "更换模型","share.settings.link.copied": "链接已复制","share.settings.link.copy": "复制链接","share.settings.link.desc": "任何拿到链接并已登录的人都能和这个助手对话,运行都发生在你的账户上。","share.settings.link.disableConfirmContent": "访客会立即无法访问。链接本身会保留,之后重新开启分享时仍然是同一个链接。","share.settings.link.disableConfirmOk": "关闭分享","share.settings.link.disableConfirmTitle": "要关闭分享吗?",+ "share.settings.link.modelDisabled": "当前模型由其他服务商提供,暂不支持分享。请切换到由 LobeHub 提供的模型,再开启分享。",+ "share.settings.link.modelDisabledTitle": "切换模型服务商后即可分享","share.settings.link.offHint": "分享已关闭。开启后会生成一条可以分发的链接;再次关闭只是暂停访问,重新开启时链接保持不变。","share.settings.link.publishDisabled": "分享功能暂未对你的账号开放。已经分享出去的链接仍然可以关闭。","share.settings.link.slugError.invalid": "只能使用小写字母、数字和连字符,且不能以连字符开头或结尾。",@@ -338,10 +341,12 @@"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.modelRestriction.description": "如需选择其他服务商提供的模型,请先关闭分享。",+ "share.settings.modelRestriction.title": "分享已开启,模型服务商限定为 LobeHub",+ "share.settings.notice.desc": "访客可使用你在下方授权的工具和数据。开启分享前,请确认权限与每月消耗上限。",+ "share.settings.notice.title": "访客使用产生的费用由你承担。","share.settings.permissions.allowCreatorViewSessions": "允许我查看访客会话","share.settings.permissions.allowCreatorViewSessionsHint": "默认关闭:访客的会话内容只有访客自己能看到。","share.settings.permissions.allowReadMemory": "允许读取我的记忆",diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex ec07b8350eb..3c83384aa97 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -425,6 +425,14 @@ export default {'Sharing is off. Turn it on to get a link you can hand out — turning it off again only pauses it, and the same link resumes whenever you turn it back on.','share.settings.link.publishDisabled':'Sharing is not available on your account yet. You can still turn off a share you already published.',+ 'share.settings.link.modelDisabledTitle': 'Switch model providers to enable sharing',+ 'share.settings.link.changeModel': 'Change model',+ 'share.settings.modelRestriction.title':+ 'Sharing is on: models are limited to the LobeHub provider',+ 'share.settings.modelRestriction.description':+ 'To choose a model from another provider, turn off sharing first.',+ 'share.settings.link.modelDisabled':+ 'Your current model uses another provider. Choose a model provided by LobeHub, then turn on sharing.','share.settings.link.slugError.invalid':'Use lowercase letters, numbers and hyphens only, and don’t start or end with a hyphen.','share.settings.link.slugError.reserved': 'This word is reserved. Please pick another one.',@@ -439,8 +447,8 @@ export default {'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',+ 'Visitors can use the tools and data you allow below. Review permissions and the monthly spend cap before sharing.',+ 'share.settings.notice.title': 'You pay for visitor usage.','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',diff --git a/src/business/agent-share.ts b/src/business/agent-share.tsnew file mode 100644index 00000000000..49440f78988--- /dev/null+++ b/src/business/agent-share.ts@@ -0,0 +1,2 @@+/** Optional provider restriction for shared agents. */+export const AGENT_SHARE_ALLOWED_PROVIDERS: readonly string[] | undefined = undefined;diff --git a/src/business/client/useAgentShareSupported.ts b/src/business/client/useAgentShareSupported.tsindex 7872298a731..0385e590407 100644--- a/src/business/client/useAgentShareSupported.ts+++ b/src/business/client/useAgentShareSupported.ts@@ -8,8 +8,12 @@*/export interface AgentShareSupport {+ /** Whether this agent currently has an active link share. */+ isShared: boolean | undefined;/** Whether a *new* share may be published right now. */publishable: boolean;+ /** Whether the agent's effective model provider may be shared. */+ shareModelAllowed: boolean;/** Whether the share management surface applies to this agent at all. */supported: boolean;/**@@ -19,6 +23,12 @@ export interface AgentShareSupport {visible: boolean | undefined;}-const UNSUPPORTED: AgentShareSupport = { publishable: false, supported: false, visible: false };+const UNSUPPORTED: AgentShareSupport = {+ isShared: false,+ publishable: false,+ shareModelAllowed: true,+ supported: false,+ visible: false,+};export const useAgentShareSupported = (_agentId?: null | string): AgentShareSupport => UNSUPPORTED;diff --git a/src/features/ChatInput/ActionBar/Model/SelectorMenu.tsx b/src/features/ChatInput/ActionBar/Model/SelectorMenu.tsxindex ff763c95e1b..40a86ebe3e2 100644--- a/src/features/ChatInput/ActionBar/Model/SelectorMenu.tsx+++ b/src/features/ChatInput/ActionBar/Model/SelectorMenu.tsx@@ -20,6 +20,7 @@ import { useTranslation } from 'react-i18next';import { ModelIcon } from '@/components/LobeIcons';import { ModelSwitchSubmenuPopup } from '@/features/ModelSwitchPanel';+import type { EnabledProviderWithModels } from '@/types/aiProvider';import type { SelectorSubmenuItem } from '../../components/buildSelectorSubmenu';import { buildSelectorSubmenu } from '../../components/buildSelectorSubmenu';@@ -74,7 +75,9 @@ interface SelectorMenuProps {children: ReactNode;displayName: string;effort: ReasoningEffortControl;+ enabledList?: EnabledProviderWithModels[];model: string;+ modelNotice?: ReactNode;onModelChange: (params: { model: string; provider: string }) => Promise<void>;openOnHover?: boolean;placement?: DropdownPlacement;@@ -93,7 +96,9 @@ const SelectorMenu = memo<SelectorMenuProps>(children,displayName,effort,+ enabledList,model,+ modelNotice,onModelChange,openOnHover = false,placement = 'topLeft',@@ -177,7 +182,9 @@ const SelectorMenu = memo<SelectorMenuProps>(</DropdownMenuItemContent></DropdownMenuSubmenuTrigger><ModelSwitchSubmenuPopup+ enabledList={enabledList}model={model}+ notice={modelNotice}provider={provider}onModelChange={onModelChange}onOpenChange={handleModelPanelOpenChange}diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsxindex 584862d3326..19e3c96255f 100644--- a/src/features/ChatInput/ActionBar/Model/index.tsx+++ b/src/features/ChatInput/ActionBar/Model/index.tsx@@ -1,8 +1,12 @@import { Tooltip } from '@lobehub/ui';+import { Alert } from '@lobehub/ui/base-ui';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';+import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';import ModelSwitchPanel from '@/features/ModelSwitchPanel';+import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/slices/topic/selectors';@@ -16,7 +20,7 @@ import { useActionBarContext } from '../context';import SelectorMenu from './SelectorMenu';const ModelSwitch = memo(() => {- const { t } = useTranslation('chat');+ const { t } = useTranslation(['chat', 'agent']);const { dropdownPlacement } = useActionBarContext();const agentId = useAgentId();const {@@ -32,6 +36,20 @@ const ModelSwitch = memo(() => {// default; a switch pins to the active topic, otherwise updates the agent// (via selectModel, which honors workspace member overrides).const activeTopicId = useChatStore((s) => s.activeTopicId);+ const { isShared } = useAgentShareSupported(agentId);+ const chatModels = useEnabledChatModels();+ const enabledList =+ !activeTopicId && isShared && AGENT_SHARE_ALLOWED_PROVIDERS+ ? chatModels.filter((item) => AGENT_SHARE_ALLOWED_PROVIDERS?.includes(item.id))+ : undefined;+ const modelNotice = enabledList ? (+ <Alert+ showIcon+ description={t('share.settings.modelRestriction.description', { ns: 'agent' })}+ title={t('share.settings.modelRestriction.title', { ns: 'agent' })}+ type={'info'}+ />+ ) : undefined;const topicModel = useChatStore(topicSelectors.activeTopicModel);const updateTopicModel = useChatStore((s) => s.updateTopicModel);const model = topicModel?.model ?? agentModel;@@ -85,7 +103,9 @@ const ModelSwitch = memo(() => {canSelectModel={canSelectModel}displayName={displayName}effort={effort}+ enabledList={enabledList}model={model}+ modelNotice={modelNotice}placement={dropdownPlacement ?? 'topRight'}provider={provider}onModelChange={handleModelChange}@@ -100,7 +120,9 @@ const ModelSwitch = memo(() => {return (<ModelSwitchPanel+ enabledList={enabledList}model={model}+ notice={modelNotice}openOnHover={false}placement={dropdownPlacement ?? 'topRight'}provider={provider}diff --git a/src/features/ModelSwitchPanel/SubmenuPopup.tsx b/src/features/ModelSwitchPanel/SubmenuPopup.tsxindex 423a75eb157..38d7c59bc01 100644--- a/src/features/ModelSwitchPanel/SubmenuPopup.tsx+++ b/src/features/ModelSwitchPanel/SubmenuPopup.tsx@@ -4,13 +4,17 @@ import {DropdownMenuPositioner,stopPropagation,} from '@lobehub/ui';-import { memo } from 'react';+import { memo, type ReactNode } from 'react';++import type { EnabledProviderWithModels } from '@/types/aiProvider';import { PanelContent } from './components/PanelContent';import { styles } from './styles';interface ModelSwitchSubmenuPopupProps {+ enabledList?: EnabledProviderWithModels[];model?: string;+ notice?: ReactNode;onModelChange?: (params: { model: string; provider: string }) => Promise<void>;/** Called with `false` once a row is picked, so the host can close its whole menu. */onOpenChange?: (open: boolean) => void;@@ -23,12 +27,14 @@ interface ModelSwitchSubmenuPopupProps {* The caller supplies the `DropdownMenuSubmenuRoot` and its trigger row.*/export const ModelSwitchSubmenuPopup = memo<ModelSwitchSubmenuPopupProps>(- ({ model, onModelChange, onOpenChange, provider }) => (+ ({ enabledList, model, notice, onModelChange, onOpenChange, provider }) => (<DropdownMenuPortal><DropdownMenuPositioner alignOffset={-4} anchor={null} placement="right" sideOffset={8}><DropdownMenuPopup className={styles.container} onKeyDown={stopPropagation}><PanelContent+ enabledList={enabledList}model={model}+ notice={notice}provider={provider}onModelChange={onModelChange}onOpenChange={onOpenChange}diff --git a/src/features/ModelSwitchPanel/components/PanelContent.tsx b/src/features/ModelSwitchPanel/components/PanelContent.tsxindex 9e1242400af..c838ef75d0a 100644--- a/src/features/ModelSwitchPanel/components/PanelContent.tsx+++ b/src/features/ModelSwitchPanel/components/PanelContent.tsx@@ -1,5 +1,5 @@import { Flexbox } from '@lobehub/ui';-import { type ComponentType, type FC } from 'react';+import { type ComponentType, type FC, type ReactNode } from 'react';import { useState } from 'react';import { Rnd } from 'react-rnd';@@ -20,6 +20,7 @@ interface PanelContentProps {enabledList?: EnabledProviderWithModels[];model?: string;ModelItemComponent?: ComponentType<any>;+ notice?: ReactNode;onModelChange?: (params: { model: string; provider: string }) => Promise<void>;onOpenChange?: (open: boolean) => void;pricingMode?: PricingMode;@@ -30,6 +31,7 @@ export const PanelContent: FC<PanelContentProps> = ({ModelItemComponent,enabledList: enabledListProp,model: modelProp,+ notice,onModelChange: onModelChangeProp,onOpenChange,pricingMode,@@ -46,6 +48,11 @@ export const PanelContent: FC<PanelContentProps> = ({const content = (<>+ {notice && (+ <Flexbox padding={8} style={{ flexShrink: 0 }}>+ {notice}+ </Flexbox>+ )}<ToolbarshowGroupModeSwitchgroupMode={groupMode}diff --git a/src/features/ModelSwitchPanel/index.tsx b/src/features/ModelSwitchPanel/index.tsxindex 45b932fc18d..5a7e91cc6df 100644--- a/src/features/ModelSwitchPanel/index.tsx+++ b/src/features/ModelSwitchPanel/index.tsx@@ -19,6 +19,7 @@ const ModelSwitchPanel = memo<ModelSwitchPanelProps>(children,enabledList,model: modelProp,+ notice,onModelChange,onOpenChange,open,@@ -51,6 +52,7 @@ const ModelSwitchPanel = memo<ModelSwitchPanelProps>(ModelItemComponent={ModelItemComponent}enabledList={enabledList}model={modelProp}+ notice={notice}pricingMode={pricingMode}provider={providerProp}onModelChange={onModelChange}diff --git a/src/features/ModelSwitchPanel/types.ts b/src/features/ModelSwitchPanel/types.tsindex ae065029425..e4ba7df01a4 100644--- a/src/features/ModelSwitchPanel/types.ts+++ b/src/features/ModelSwitchPanel/types.ts@@ -61,6 +61,8 @@ export interface ModelSwitchPanelProps {* Optional row component for generation UIs (e.g. ImageModelItem). Requires `enabledList` + `pricingMode`.*/ModelItemComponent?: ComponentType<any>;+ /** Explanation of any restrictions applied by the host. */+ notice?: React.ReactNode;/*** Callback when model changes. If not provided, uses updateAgentConfig from store.*/diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 3dfe6dcd8dc..e197554e8ad 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -9,22 +9,27 @@ import {import type { HeterogeneousApiConfig, HeterogeneousAuthMode } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import type { TabsItem } from '@lobehub/ui/base-ui';-import { Tabs } from '@lobehub/ui/base-ui';+import { Alert, Button, Tabs } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';-import { Wrench } from 'lucide-react';+import { ChevronDown, Wrench } from 'lucide-react';import React, { memo } from 'react';import { useTranslation } from 'react-i18next';+import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';+import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';+import { ModelIcon } from '@/components/LobeIcons';import { resolveServerDefaultAgentModels } from '@/features/HeterogeneousAgent/modelPicker';-import ModelSelect from '@/features/ModelSelect';import ReasoningEffortSelect from '@/features/ModelSelect/ReasoningEffortSelect';+import ModelSwitchPanel from '@/features/ModelSwitchPanel';import RunPriorityHint from '@/features/ProfileEditor/AgentUserTools/RunPriorityHint';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import EditorCanvas from '../EditorCanvas';import AgentHeader from './AgentHeader';@@ -58,10 +63,19 @@ const styles = createStaticStyles(({ css }) => ({}));const ProfileEditor = memo(() => {- const { t } = useTranslation('setting');+ const { t } = useTranslation(['setting', 'agent']);const { allowed: canEdit } = usePermission('edit_own_content');const agentId = useAgentStore((s) => s.activeAgentId || '');const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);+ const { isShared } = useAgentShareSupported(agentId);+ const chatModels = useEnabledChatModels();+ const enabledList =+ isShared && AGENT_SHARE_ALLOWED_PROVIDERS+ ? chatModels.filter((provider) => AGENT_SHARE_ALLOWED_PROVIDERS?.includes(provider.id))+ : undefined;+ const selectedModel = useAiInfraStore(+ aiModelSelectors.getEnabledModelById(config?.model ?? '', config?.provider ?? ''),+ );const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);@@ -257,20 +271,35 @@ const ProfileEditor = memo(() => {<RunPriorityHint agentId={agentId} /></Flexbox><Flexbox horizontal align={'center'} gap={12} justify={'flex-start'} wrap={'wrap'}>- <ModelSelect- initialWidth- disabled={!canEdit}- popupWidth={400}- value={{- model: config?.model,- provider: config?.provider,- }}- onChange={(value) => {- if (!canEdit) return;-- void updateAgentConfigById(agentId, value);+ <ModelSwitchPanel+ enabledList={enabledList}+ model={config?.model}+ open={canEdit ? undefined : false}+ openOnHover={false}+ placement={'bottomLeft'}+ provider={config?.provider}+ notice={+ enabledList && (+ <Alert+ showIcon+ title={t('share.settings.modelRestriction.title', { ns: 'agent' })}+ type={'info'}+ description={t('share.settings.modelRestriction.description', {+ ns: 'agent',+ })}+ />+ )+ }+ onModelChange={async (value) => {+ if (canEdit) await updateAgentConfigById(agentId, value);}}- />+ >+ <Button disabled={!canEdit}>+ <ModelIcon model={config?.model} size={20} />+ {selectedModel?.displayName || config?.model}+ <ChevronDown size={14} />+ </Button>+ </ModelSwitchPanel>{config?.model && config.provider && (<ReasoningEffortSelectdisabled={!canEdit}