π€― 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(agent-share): exempt Claude Code / Codex from share model limit (#23372)
YuTengjing0e5d44329085
diff --git a/apps/server/src/services/agent/index.test.ts b/apps/server/src/services/agent/index.test.tsindex fae771a5f5d..efb32b27857 100644--- a/apps/server/src/services/agent/index.test.ts+++ b/apps/server/src/services/agent/index.test.ts@@ -841,7 +841,10 @@ 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 agent: Omit<typeof storedAgent, 'provider'> & {+ agencyConfig?: { heterogeneousProvider?: { command?: string; type: string } | null };+ provider: string | null;+ };let visibility: string;beforeEach(() => {@@ -978,6 +981,108 @@ describe('AgentService', () => {expect(agent.provider).toBe('lobehub');});+ it('allows switching a shared agent to Claude Code, which runs no provider model', async () => {+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: { command: 'claude', type: 'claude-code' } },+ provider: 'claude-code',+ } as any),+ ).resolves.toMatchObject({ success: true });+ expect(agent.provider).toBe('claude-code');+ });++ it('allows the clear-then-write step of switching between two heterogeneous drivers', async () => {+ agent.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ agent.provider = 'claude-code';+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: null },+ } as any),+ ).resolves.toMatchObject({ success: true });+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: { command: 'codex', type: 'codex' } },+ provider: 'codex',+ } as any),+ ).resolves.toMatchObject({ success: true });+ expect(agent.provider).toBe('codex');+ });++ it('publishes a heterogeneous agent without pinning a harness model over its stamp', async () => {+ agent.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ agent.provider = 'claude-code';+ await service.prepareShareModel('agent-1');+ expect(agent.provider).toBe('claude-code');+ expect(agent.model).toBe('gpt-4');+ });++ it('keeps a shared agent on a runtime visitors cannot run under the restriction', async () => {+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: { type: 'openclaw' } },+ provider: 'openclaw',+ } as any),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.provider).toBe('lobehub');+ });++ it('checks a patch that clears the whole agencyConfig of a shared Claude Code agent', async () => {+ agent.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ agent.provider = 'claude-code';+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: null,+ model: 'gpt-5',+ provider: 'openai',+ } as any),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.provider).toBe('claude-code');+ });++ it('keeps the driver type when a shared Claude Code agent edits only its env', async () => {+ agent.agencyConfig = { heterogeneousProvider: { command: 'claude', type: 'claude-code' } };+ agent.provider = 'claude-code';+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: { env: { FOO: 'bar' } } },+ } as any),+ ).resolves.toMatchObject({ success: true });+ });++ it('rejects saving a third-party model next to a shared Claude Code driver', async () => {+ agent.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ agent.provider = 'claude-code';+ await expect(+ service.updateAgentConfig('agent-1', { model: 'gpt-5', provider: 'openai' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.provider).toBe('claude-code');+ });++ it('rejects clearing a Claude Code driver that would leave a third-party model', async () => {+ agent.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ agent.provider = 'openai';+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: null },+ } as any),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.agencyConfig).toEqual({ heterogeneousProvider: { type: 'claude-code' } });+ expect(AgentShareModel.lockScopedAgentRow).toHaveBeenCalled();+ });++ it('still rejects switching a shared heterogeneous agent back to a third-party model', async () => {+ agent.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ agent.provider = 'claude-code';+ await expect(+ service.updateAgentConfig('agent-1', {+ agencyConfig: { heterogeneousProvider: null },+ model: 'gpt-5',+ provider: 'openai',+ } as any),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(agent.provider).toBe('claude-code');+ });+it('resolves inherited providers before publishing', async () => {agent.provider = null;await expect(service.assertShareModelAllowed('agent-1')).resolves.toMatchObject({diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.tsindex 7185fe02879..11c646a81d7 100644--- a/apps/server/src/services/agent/index.ts+++ b/apps/server/src/services/agent/index.ts@@ -1,7 +1,7 @@import { type BuiltinAgentSlug } from '@lobechat/builtin-agents';import { BUILTIN_AGENTS } from '@lobechat/builtin-agents';import { DEFAULT_PROVIDER } from '@lobechat/business-const';-import { DEFAULT_MODEL } from '@lobechat/const';+import { DEFAULT_MODEL, isAgentShareModelRestrictionExempt } from '@lobechat/const';import { type LobeChatDatabase } from '@lobechat/database';import {type AgentItem,@@ -32,11 +32,23 @@ import {RedisKeys,} from '@/server/modules/Redis';import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';+import { merge } from '@/utils/merge';import { type UpdateAgentResult } from './type';const log = debug('lobe-agent:service');+/**+ * Whether a config patch can change what a shared agent's model restriction sees: the model+ * selection itself, or the driver that exempts it. Clearing a Claude Code driver turns the+ * stored selection back into a native one, so it is checked under the same lock.+ */+const touchesShareModel = (value: PartialDeep<AgentItem>): boolean =>+ 'model' in value ||+ 'provider' in value ||+ value.agencyConfig === null ||+ (!!value.agencyConfig && 'heterogeneousProvider' in value.agencyConfig);+/*** Agent config with required id field.* Used when returning agent config from database (id is always present).@@ -112,16 +124,48 @@ export class AgentService {return { agentId: agent.id };}- /** Validate the effective selection at configuration boundaries, including inherited defaults. */+ /**+ * Validate the effective selection at configuration boundaries, including inherited defaults.+ *+ * Returns the resolved selection to pin, or `undefined` when there is nothing to check.+ * A Claude Code / Codex agent is exempt (`isAgentShareModelRestrictionExempt`): it runs on the+ * creator's device and calls none of `provider`'s models. The decision reads the effective+ * driver, the stored one merged with the patch, so switching back to LobeHub+ * (`heterogeneousProvider: null`) is checked as usual, and a real provider saved next to the+ * driver is checked too, since clearing the driver would make it the native selection.+ */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' });+ // Same deep merge as `AgentModel.updateConfig`, so a partial driver edit (`env` only) keeps+ // the stored `type`. `agencyConfig: null` clears the whole block and must not fall back to it.+ const effectiveAgencyConfig =+ 'agencyConfig' in patch+ ? patch.agencyConfig === null+ ? null+ : merge(agent.agencyConfig ?? {}, patch.agencyConfig)+ : agent.agencyConfig;+ const provider = 'provider' in patch ? patch.provider : agent.provider;+ if (+ isAgentShareModelRestrictionExempt({+ agencyConfig: effectiveAgencyConfig as AgentItem['agencyConfig'],+ provider,+ })+ )+ return;+ // Moving between two heterogeneous drivers clears the old one first and writes the new+ // one second. The cleared row keeps only the runtime stamp, which names no chat provider.+ if (+ !effectiveAgencyConfig?.heterogeneousProvider &&+ isAgentShareModelRestrictionExempt({ agencyConfig: agent.agencyConfig, provider })+ )+ return;+const selection = await this.resolveModelSelection({ ...agent, ...patch });- const { provider } = selection;- if (!AGENT_SHARE_ALLOWED_PROVIDERS.includes(provider)) {+ if (!AGENT_SHARE_ALLOWED_PROVIDERS.includes(selection.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.`,@@ -371,11 +415,7 @@ export class AgentService {value: PartialDeep<AgentItem>,replaceWorkingDirDeviceIds?: string[],): Promise<UpdateAgentResult> {- if (- AGENT_SHARE_ALLOWED_PROVIDERS &&- !this.workspaceId &&- ('model' in value || 'provider' in value)- ) {+ if (AGENT_SHARE_ALLOWED_PROVIDERS && !this.workspaceId && touchesShareModel(value)) {return this.withShareModelLock(agentId, (service) =>service.saveAgentConfig(agentId, value, replaceWorkingDirDeviceIds),);@@ -388,7 +428,7 @@ export class AgentService {value: PartialDeep<AgentItem>,replaceWorkingDirDeviceIds?: string[],): Promise<UpdateAgentResult> {- if (AGENT_SHARE_ALLOWED_PROVIDERS && ('model' in value || 'provider' in value)) {+ if (AGENT_SHARE_ALLOWED_PROVIDERS && touchesShareModel(value)) {const share = await new AgentShareModel(this.db, this.userId, this.workspaceId).getByAgentId(agentId,);diff --git a/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.ts b/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.tsindex f334c175c75..1adcf485638 100644--- a/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.ts+++ b/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.ts@@ -1,4 +1,4 @@-import { isHeterogeneousAgentModelId } from '@lobechat/const';+import { isAgentShareVisitorHeteroType, isHeterogeneousAgentModelId } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import type { LobeAgentAgencyConfig, RequestTrigger } from '@lobechat/types';import { ChatErrorType } from '@lobechat/types';@@ -9,13 +9,6 @@ import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDeimport type { AgentShareGate } from '../shareGate';-/**- * Heterogeneous runtimes a share visitor may run, on a device the share grants- * them. Both run as a local CLI on that device; platform agents (OpenClaw /- * Hermes) and the other CLIs have no visitor-scoped dispatch.- */-const SHARE_VISITOR_HETERO_TYPES = new Set<string>(['claude-code', 'codex']);-export interface AssertShareHeteroAllowedParams {agencyConfig?: LobeAgentAgencyConfig;db: LobeChatDatabase;@@ -61,7 +54,7 @@ export const assertShareHeteroAllowed = async ({if (!shareGate) return;const type = heterogeneousType ?? (isHeterogeneousAgentModelId(model) ? model : undefined);if (!type) return;- if (!shareGate.canUseDevice || !SHARE_VISITOR_HETERO_TYPES.has(type))+ if (!shareGate.canUseDevice || !isAgentShareVisitorHeteroType(type))throw new TRPCError({code: 'FORBIDDEN',message: ChatErrorType.ShareHeterogeneousAgentUnsupported,diff --git a/packages/const/src/agentShare.test.ts b/packages/const/src/agentShare.test.tsindex f6ea6b8ea9e..747ab728475 100644--- a/packages/const/src/agentShare.test.ts+++ b/packages/const/src/agentShare.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {hasShareToolGrant,+ isAgentShareModelRestrictionExempt,isShareToolApiGranted,resolveShareAllowedSkillIds,resolveShareToolGrants,@@ -110,3 +111,47 @@ describe('resolveShareAllowedSkillIds', () => {expect(resolveShareAllowedSkillIds(['pdf-report'], {})).toEqual([]);});});++describe('isAgentShareModelRestrictionExempt', () => {+ const driver = (type: string) => ({ heterogeneousProvider: { type } });++ it('exempts Claude Code and Codex agents, which run no provider model', () => {+ expect(+ isAgentShareModelRestrictionExempt({+ agencyConfig: driver('claude-code'),+ provider: 'claude-code',+ }),+ ).toBe(true);+ expect(+ isAgentShareModelRestrictionExempt({ agencyConfig: driver('codex'), provider: 'codex' }),+ ).toBe(true);+ });++ it('keeps LobeHub agents and runtimes a visitor cannot run restricted', () => {+ expect(isAgentShareModelRestrictionExempt(undefined)).toBe(false);+ expect(isAgentShareModelRestrictionExempt({ agencyConfig: null, provider: 'lobehub' })).toBe(+ false,+ );+ expect(+ isAgentShareModelRestrictionExempt({+ agencyConfig: { heterogeneousProvider: null },+ provider: 'claude-code',+ }),+ ).toBe(false);+ expect(+ isAgentShareModelRestrictionExempt({+ agencyConfig: driver('openclaw'),+ provider: 'openclaw',+ }),+ ).toBe(false);+ });++ it('checks a real provider saved next to a Claude Code driver', () => {+ expect(+ isAgentShareModelRestrictionExempt({+ agencyConfig: driver('claude-code'),+ provider: 'openai',+ }),+ ).toBe(false);+ });+});diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.tsindex 41e0c05f8cd..f125a61ade2 100644--- a/packages/const/src/agentShare.ts+++ b/packages/const/src/agentShare.ts@@ -242,3 +242,36 @@ export const isShareToolApiGranted = (* over the creator's machine, so it is meant for a handful of trusted people.*/export const AGENT_SHARE_DEVICE_ALLOW_USERS_LIMIT = 100;++/**+ * Heterogeneous runtimes a share visitor may run, on a device the share grants+ * them. Both run as a local CLI on that device; platform agents (OpenClaw /+ * Hermes) and the other CLIs have no visitor-scoped dispatch.+ */+export const AGENT_SHARE_VISITOR_HETERO_TYPES: readonly string[] = ['claude-code', 'codex'];++/** Whether a share visitor may run this heterogeneous runtime type. */+export const isAgentShareVisitorHeteroType = (type?: string | null): boolean =>+ !!type && AGENT_SHARE_VISITOR_HETERO_TYPES.includes(type);++/**+ * Whether an agent's effective config is exempt from the shared-agent model+ * provider restriction (`AGENT_SHARE_ALLOWED_PROVIDERS`).+ *+ * The restriction keeps visitors from spending the creator's third-party model+ * quota. A Claude Code / Codex agent runs its own CLI on the creator's device and+ * calls none of `provider`'s models β `provider` only stamps the runtime type β so+ * it is exempt. Every other driver, including heterogeneous runtimes a visitor+ * cannot run, stays restricted. Server save/publish checks and every client hint+ * must use this one predicate so they never disagree.+ *+ * `provider` must still be a runtime stamp: a real provider saved next to the driver+ * would become the agent's native model the moment the driver is cleared, so it is+ * checked like any other selection.+ */+export const isAgentShareModelRestrictionExempt = (config?: {+ agencyConfig?: { heterogeneousProvider?: { type?: string } | null } | null;+ provider?: string | null;+}): boolean =>+ isAgentShareVisitorHeteroType(config?.agencyConfig?.heterogeneousProvider?.type) &&+ isAgentShareVisitorHeteroType(config?.provider);diff --git a/src/features/AgentDriver/index.tsx b/src/features/AgentDriver/index.tsxindex f1886909fd3..42fa5d60a4f 100644--- a/src/features/AgentDriver/index.tsx+++ b/src/features/AgentDriver/index.tsx@@ -7,13 +7,21 @@ import { SparklesIcon } from 'lucide-react';import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';+import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';+import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';import { CONNECTABLE_PROVIDERS, getConnectableProvider } from '@/features/ConnectAgent/providers';+import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';-import { type DriverTarget, planDriverRollback, planDriverSwitch } from './switchPlan';+import {+ type DriverTarget,+ planDriverSwitch,+ resolveHarnessModel,+ runDriverSwitch,+} from './switchPlan';const HARNESS = 'lobehub';@@ -80,6 +88,8 @@ const AgentDriverSelect = memo<AgentDriverSelectProps>(({ agentId, canEdit }) =>);const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const defaults = useUserStore(settingsSelectors.defaultAgentConfig);+ const { isShared } = useAgentShareSupported(agentId);+ const enabledChatModels = useEnabledChatModels();const harnessName = t('settingAgent.driver.harness');const current = heterogeneousProvider?.type ?? HARNESS;@@ -101,10 +111,15 @@ const AgentDriverSelect = memo<AgentDriverSelectProps>(({ agentId, canEdit }) =>onOk: async () => {const plan = planDriverSwitch({currentlyHeterogeneous: !!heterogeneousProvider,- defaults: {- model: defaults.model ?? DEFAULT_MODEL,- provider: defaults.provider ?? DEFAULT_PROVIDER,- },+ defaults: resolveHarnessModel({+ allowedProviders: isShared ? AGENT_SHARE_ALLOWED_PROVIDERS : undefined,+ defaults: {+ model: defaults.model ?? DEFAULT_MODEL,+ provider: defaults.provider ?? DEFAULT_PROVIDER,+ },+ enabledChatModels,+ fallback: { model: DEFAULT_MODEL, provider: DEFAULT_PROVIDER },+ }),target,});@@ -115,23 +130,14 @@ const AgentDriverSelect = memo<AgentDriverSelectProps>(({ agentId, canEdit }) =>provider: before?.provider,};- try {- // Sequential on purpose: the second write must merge into the cleared block.- for (const patch of plan) await updateAgentConfigById(agentId, patch);- toast.success(t('settingAgent.driver.switched', { name }));- } catch {- // Switching between two external drivers is clear-then-write. If the write fails after- // the clear, put the previous driver back rather than leave the agent on LobeHub with a- // stale provider stamp.- if (plan.length > 1 && previous.heterogeneousProvider) {- try {- await updateAgentConfigById(agentId, planDriverRollback(previous));- } catch {- // The failure toast below still tells the person the switch did not happen.- }- }- toast.error(t('settingAgent.driver.switchFailed'));- }+ const result = await runDriverSwitch({+ agentId,+ plan,+ previous,+ write: updateAgentConfigById,+ });+ if (result === 'switched') toast.success(t('settingAgent.driver.switched', { name }));+ else if (result === 'failed') toast.error(t('settingAgent.driver.switchFailed'));},});};diff --git a/src/features/AgentDriver/switchPlan.test.ts b/src/features/AgentDriver/switchPlan.test.tsindex 821f1138996..e8c5536bdf0 100644--- a/src/features/AgentDriver/switchPlan.test.ts+++ b/src/features/AgentDriver/switchPlan.test.ts@@ -1,6 +1,11 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { planDriverRollback, planDriverSwitch } from './switchPlan';+import {+ planDriverRollback,+ planDriverSwitch,+ resolveHarnessModel,+ runDriverSwitch,+} from './switchPlan';const defaults = { model: 'gpt-5.5', provider: 'openai' };@@ -57,3 +62,138 @@ describe('planDriverRollback', () => {});});});++describe('runDriverSwitch', () => {+ /**+ * Mirrors `updateAgentConfigById`: a rejected save is toasted by the store and swallowed+ * unless the caller passes `rethrow`, and the store's toast is skipped with+ * `showErrorMessage: false`.+ */+ const storeWriter = (rejectAt: Set<number>) => {+ const storeToasts: string[] = [];+ let call = 0;+ const write = vi.fn(+ async (+ _id: string,+ _patch: unknown,+ options?: { rethrow?: boolean; showErrorMessage?: boolean },+ ) => {+ const index = call++;+ if (!rejectAt.has(index)) return;+ if (options?.showErrorMessage !== false) storeToasts.push('saveAgentConfigFail');+ if (options?.rethrow) throw new Error('Shared agents only support models from: lobehub.');+ },+ );+ return { storeToasts, write };+ };++ const toCodex = planDriverSwitch({+ currentlyHeterogeneous: true,+ defaults,+ target: { command: 'codex', kind: 'hetero', type: 'codex' },+ });+ const previous = {+ heterogeneousProvider: { command: 'claude', type: 'claude-code' },+ provider: 'claude-code',+ };++ it('reports a rejected save as failed, with no store toast on top of the caller one', async () => {+ const { storeToasts, write } = storeWriter(new Set([0]));+ const plan = planDriverSwitch({+ currentlyHeterogeneous: false,+ defaults,+ target: { command: 'claude', kind: 'hetero', type: 'claude-code' },+ });++ await expect(+ runDriverSwitch({+ agentId: 'a',+ plan,+ previous: { heterogeneousProvider: undefined },+ write,+ }),+ ).resolves.toBe('failed');+ expect(storeToasts).toEqual([]);+ });++ it('rolls a clear-then-write switch back when the second write is rejected', async () => {+ const { write } = storeWriter(new Set([1]));++ await expect(runDriverSwitch({ agentId: 'a', plan: toCodex, previous, write })).resolves.toBe(+ 'failed',+ );+ expect(write).toHaveBeenCalledTimes(3);+ expect(write.mock.calls[2][1]).toEqual(planDriverRollback(previous));+ });++ it('reports switched only when every write is saved', async () => {+ const { write } = storeWriter(new Set());++ await expect(runDriverSwitch({ agentId: 'a', plan: toCodex, previous, write })).resolves.toBe(+ 'switched',+ );+ expect(write).toHaveBeenCalledTimes(2);+ });++ it('leaves the outcome to a newer write that aborted this one', async () => {+ const abort = Object.assign(new Error('aborted'), { name: 'AbortError' });+ const write = vi.fn().mockRejectedValueOnce(abort);++ await expect(runDriverSwitch({ agentId: 'a', plan: toCodex, previous, write })).resolves.toBe(+ 'superseded',+ );+ expect(write).toHaveBeenCalledTimes(1);+ });+});++describe('resolveHarnessModel', () => {+ const fallback = { model: 'lobe-flash', provider: 'lobehub' };+ const enabledChatModels = [+ { children: [{ id: 'gpt-5.5' }], id: 'openai' },+ { children: [{ id: 'lobe-pro' }, { id: 'lobe-flash' }], id: 'lobehub' },+ ];++ it('keeps the account default when sharing restricts nothing', () => {+ expect(resolveHarnessModel({ defaults, enabledChatModels, fallback })).toEqual(defaults);+ });++ it('keeps an account default that sharing allows', () => {+ const lobeDefault = { model: 'lobe-pro', provider: 'lobehub' };+ expect(+ resolveHarnessModel({+ allowedProviders: ['lobehub'],+ defaults: lobeDefault,+ enabledChatModels,+ fallback,+ }),+ ).toEqual(lobeDefault);+ });++ it('moves a shared agent onto the deployment default instead of a third-party default', () => {+ expect(+ resolveHarnessModel({ allowedProviders: ['lobehub'], defaults, enabledChatModels, fallback }),+ ).toEqual(fallback);+ });++ it('falls back to the first allowed model when the deployment default is not enabled', () => {+ expect(+ resolveHarnessModel({+ allowedProviders: ['lobehub'],+ defaults,+ enabledChatModels: [{ children: [{ id: 'lobe-pro' }], id: 'lobehub' }],+ fallback,+ }),+ ).toEqual({ model: 'lobe-pro', provider: 'lobehub' });+ });++ it('keeps the account default when no allowed model is enabled, so the server reports it', () => {+ expect(+ resolveHarnessModel({+ allowedProviders: ['lobehub'],+ defaults,+ enabledChatModels: [{ children: [{ id: 'gpt-5.5' }], id: 'openai' }],+ fallback,+ }),+ ).toEqual(defaults);+ });+});diff --git a/src/features/AgentDriver/switchPlan.ts b/src/features/AgentDriver/switchPlan.tsindex 6df49bdce21..dd060c86637 100644--- a/src/features/AgentDriver/switchPlan.ts+++ b/src/features/AgentDriver/switchPlan.ts@@ -12,6 +12,50 @@ interface DefaultChatModel {provider: string;}+/**+ * The chat model a shared agent lands on when it moves back to the LobeHub harness.+ *+ * Moving back writes the account's default model, but a shared agent may only use models from+ * the providers sharing allows: the server rejects anything else, and the person would be told+ * to change a global setting on another page before they could switch. So when the default is+ * not allowed, pick an allowed model instead β the deployment default when it is one, then a+ * model with the same id, then the first allowed model. With no allowed model available the+ * account default is kept and the server's rejection is reported as a failed switch.+ */+export const resolveHarnessModel = ({+ allowedProviders,+ defaults,+ enabledChatModels,+ fallback,+}: {+ /** Providers a shared agent may use; `undefined` when sharing restricts none. */+ allowedProviders?: readonly string[];+ defaults: DefaultChatModel;+ enabledChatModels: { children: { id: string }[]; id: string }[];+ /** The deployment's default chat model. */+ fallback: DefaultChatModel;+}): DefaultChatModel => {+ if (!allowedProviders || allowedProviders.includes(defaults.provider)) return defaults;++ const allowed = enabledChatModels.filter(+ (provider) => allowedProviders.includes(provider.id) && provider.children.length > 0,+ );+ const find = (model: string, provider?: string) =>+ allowed.find(+ (item) =>+ (!provider || item.id === provider) && item.children.some((child) => child.id === model),+ );++ const fallbackProvider = find(fallback.model, fallback.provider);+ if (fallbackProvider) return fallback;++ const sameModel = find(defaults.model);+ if (sameModel) return { model: defaults.model, provider: sameModel.id };++ const first = allowed[0];+ return first ? { model: first.children[0].id, provider: first.id } : defaults;+};+/*** The config writes that move an agent to another driver, in the order they must land.*@@ -73,3 +117,63 @@ export const planDriverRollback = ({agencyConfig: { heterogeneousProvider },provider,}) as unknown as PartialDeep<LobeAgentConfig>;++interface DriverWriteOptions {+ rethrow: true;+ showErrorMessage: false;+}++/**+ * The store's config writer: by default it reports a failed save with its own toast and resolves,+ * so a caller cannot tell success from failure. A driver switch needs the failure to roll back and+ * to replace the success toast, so every write here asks for the error and keeps the store quiet.+ */+type DriverConfigWriter = (+ agentId: string,+ patch: PartialDeep<LobeAgentConfig>,+ options: DriverWriteOptions,+) => Promise<void>;++const DRIVER_WRITE_OPTIONS: DriverWriteOptions = { rethrow: true, showErrorMessage: false };++const isAbortError = (error: unknown) =>+ error instanceof Error && (error.name === 'AbortError' || error.message.includes('aborted'));++/**+ * Land a driver switch plan and say how it ended, so the caller shows exactly one outcome.+ *+ * - `switched`: every write was saved.+ * - `failed`: a write was rejected; a clear-then-write switch has been rolled back to `previous`.+ * - `superseded`: a newer config write for this agent aborted ours, and that write owns the outcome.+ */+export const runDriverSwitch = async ({+ agentId,+ plan,+ previous,+ write,+}: {+ agentId: string;+ plan: PartialDeep<LobeAgentConfig>[];+ previous: { heterogeneousProvider: unknown; provider?: string };+ write: DriverConfigWriter;+}): Promise<'failed' | 'superseded' | 'switched'> => {+ try {+ // Sequential on purpose: the second write must merge into the cleared block.+ for (const patch of plan) await write(agentId, patch, DRIVER_WRITE_OPTIONS);+ return 'switched';+ } catch (error) {+ if (isAbortError(error)) return 'superseded';++ // Switching between two external drivers is clear-then-write. If the write fails after the+ // clear, put the previous driver back rather than leave the agent on LobeHub with a stale+ // provider stamp.+ if (plan.length > 1 && previous.heterogeneousProvider) {+ try {+ await write(agentId, planDriverRollback(previous), DRIVER_WRITE_OPTIONS);+ } catch {+ // The caller's failure message still tells the person the switch did not happen.+ }+ }+ return 'failed';+ }+};diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsxindex abadb6cfecd..2cd3429d151 100644--- a/src/features/ChatInput/ActionBar/Model/index.tsx+++ b/src/features/ChatInput/ActionBar/Model/index.tsx@@ -6,6 +6,8 @@ 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 { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import SelectorTrigger from '../../components/SelectorTrigger';@@ -32,9 +34,12 @@ const ModelSwitch = memo(() => {topicId,} = useTopicModelSwitch(selection);const { isShared } = useAgentShareSupported(agentId);+ const shareModelExempt = useAgentStore(+ agentByIdSelectors.isAgentShareModelRestrictionExemptById(agentId),+ );const chatModels = useEnabledChatModels();const enabledList =- !topicId && isShared && AGENT_SHARE_ALLOWED_PROVIDERS+ !topicId && isShared && AGENT_SHARE_ALLOWED_PROVIDERS && !shareModelExempt? chatModels.filter((item) => AGENT_SHARE_ALLOWED_PROVIDERS?.includes(item.id)): undefined;const modelNotice = enabledList ? (diff --git a/src/routes/(main)/agent/profile/features/EngineEditor/index.tsx b/src/routes/(main)/agent/profile/features/EngineEditor/index.tsxindex be62033749a..3af13b891b9 100644--- a/src/routes/(main)/agent/profile/features/EngineEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/EngineEditor/index.tsx@@ -37,9 +37,12 @@ const EngineEditor = memo(() => {const agentId = useAgentStore((s) => s.activeAgentId || '');const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);const { isShared } = useAgentShareSupported(agentId);+ const shareModelExempt = useAgentStore(+ agentByIdSelectors.isAgentShareModelRestrictionExemptById(agentId),+ );const chatModels = useEnabledChatModels();const enabledList =- isShared && AGENT_SHARE_ALLOWED_PROVIDERS+ isShared && AGENT_SHARE_ALLOWED_PROVIDERS && !shareModelExempt? chatModels.filter((provider) => AGENT_SHARE_ALLOWED_PROVIDERS?.includes(provider.id)): undefined;const selectedModel = useAiInfraStore(diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.tsindex 17d2c88acf6..0a4c23d31f4 100644--- a/src/store/agent/selectors/agentByIdSelectors.ts+++ b/src/store/agent/selectors/agentByIdSelectors.ts@@ -1,5 +1,10 @@import { DEFAULT_PROVIDER } from '@lobechat/business-const';-import { DEFAULT_MODEL, DEFAUTT_AGENT_TTS_CONFIG, isDesktop } from '@lobechat/const';+import {+ DEFAULT_MODEL,+ DEFAUTT_AGENT_TTS_CONFIG,+ isAgentShareModelRestrictionExempt,+ isDesktop,+} from '@lobechat/const';import { type AgentBuilderContext } from '@lobechat/context-engine';import {type AgentMode,@@ -206,6 +211,18 @@ const isAgentHeterogeneousById =(s: AgentStoreState): boolean =>!!getAgencyConfigById(agentId)(s)?.heterogeneousProvider;+/**+ * Whether a shared agent is exempt from the share model-provider restriction+ * (a Claude Code / Codex agent) β by agentId. Mirrors the server check.+ */+const isAgentShareModelRestrictionExemptById =+ (agentId: string) =>+ (s: AgentStoreState): boolean =>+ isAgentShareModelRestrictionExempt({+ agencyConfig: getAgencyConfigById(agentId)(s),+ provider: agentSelectors.getAgentConfigById(agentId)(s)?.provider,+ });+/*** Get full agent data by agentId* Returns the complete agent object including metadata fields like updatedAt@@ -244,5 +261,6 @@ export const agentByIdSelectors = {isAgentConfigLoadingById,isAgentHeterogeneousById,isAgentNotFoundById,+ isAgentShareModelRestrictionExemptById,isWorkspaceAgentById,};