Skip to content

🤯 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.

✨ feat(chat-input): nudge sandbox users to switch to local (#16520)

YuTengjinge20b0757bcf8
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index c459e87bb53..fbc603e38b5 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -234,7 +234,10 @@ jobs:
test-server:
needs: check-duplicate-run
if: needs.check-duplicate-run.outputs.should_skip != 'true'
- name: Test Server
+ strategy:
+ matrix:
+ shard: [1, 2]
+ name: Test Server (shard ${{ matrix.shard }}/2)
runs-on: ubuntu-latest
@@ -256,7 +259,49 @@ jobs:
run: pnpm install
- name: Test Server Coverage
- run: bunx vitest --coverage --silent='passed-only' --reporter=default --coverage.reportsDirectory=./apps/server/coverage --dir apps/server
+ run: bunx vitest --coverage --silent='passed-only' --reporter=default --reporter=blob --coverage.reportsDirectory=./apps/server/coverage --dir apps/server --shard=${{ matrix.shard }}/2
+
+ - name: Upload blob report
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v6
+ with:
+ name: server-blob-report-${{ matrix.shard }}
+ path: .vitest-reports
+ include-hidden-files: true
+ retention-days: 1
+
+ # Merge sharded test reports and upload coverage
+ merge-server-coverage:
+ needs: test-server
+ if: ${{ !cancelled() && needs.test-server.result == 'success' }}
+ name: Merge and Upload Server Coverage
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ env:
+ REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
+ REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ run: |
+ git init .
+ git remote add origin "https://github.com/${REPOSITORY}.git"
+ git fetch --no-tags --depth=1 origin "${REF_SHA}"
+ git checkout --force FETCH_HEAD
+
+ - name: Setup environment
+ uses: ./.github/actions/setup-env
+
+ - name: Install deps
+ run: pnpm install
+
+ - name: Download blob reports
+ uses: actions/download-artifact@v7
+ with:
+ path: .vitest-reports
+ pattern: server-blob-report-*
+ merge-multiple: true
+
+ - name: Merge reports
+ run: bunx vitest --merge-reports --reporter=default --coverage --coverage.reportsDirectory=./apps/server/coverage
- name: Upload Server coverage to Codecov
uses: codecov/codecov-action@v5
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 3634249f85b..b9271193c8c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -328,10 +328,12 @@
"input.inputCompletionError.title": "Input suggestions paused",
"input.modelUnavailable": "The current model is no longer available. Choose another model to continue.",
"input.more": "More",
+ "input.sandboxModeNotice": "Running in a temporary Cloud Sandbox. Local runs are faster and can access your files.",
"input.send": "Send",
"input.sendWithCmdEnter": "Press <key/> to send",
"input.sendWithEnter": "Press <key/> to send",
"input.stop": "Stop",
+ "input.switchToLocal": "Use local machine",
"input.warp": "New Line",
"input.warpWithKey": "Press <key/> to insert a line break",
"inputQueue.delete": "Delete",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index ffe4fe9dd54..ef19fc0897d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -328,10 +328,12 @@
"input.inputCompletionError.title": "输入补全已暂停",
"input.modelUnavailable": "当前模型已下线。请选择其他模型后继续使用。",
"input.more": "更多",
+ "input.sandboxModeNotice": "正在使用临时云端沙箱,本机运行更快且可访问本地文件。",
"input.send": "发送",
"input.sendWithCmdEnter": "按 <key/> 发送",
"input.sendWithEnter": "按 <key/> 发送",
"input.stop": "停止",
+ "input.switchToLocal": "切换到本机",
"input.warp": "换行",
"input.warpWithKey": "按 <key/> 换行",
"inputQueue.delete": "删除",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 76cce5f2fa1..b61beeed9b8 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -265,10 +265,13 @@ export default {
'input.modelUnavailable':
'The current model is no longer available. Choose another model to continue.',
'input.more': 'More',
+ 'input.sandboxModeNotice':
+ 'Running in a temporary Cloud Sandbox. Local runs are faster and can access your files.',
'input.send': 'Send',
'input.sendWithCmdEnter': 'Press <key/> to send',
'input.sendWithEnter': 'Press <key/> to send',
'input.stop': 'Stop',
+ 'input.switchToLocal': 'Use local machine',
'input.warp': 'New Line',
'input.warpWithKey': 'Press <key/> to insert a line break',
'inputQueue.delete': 'Delete',
diff --git a/src/features/ChatInput/ChatInputNotice/index.tsx b/src/features/ChatInput/ChatInputNotice/index.tsx
new file mode 100644
index 00000000000..4a865d7ca2f
--- /dev/null
+++ b/src/features/ChatInput/ChatInputNotice/index.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+import { Alert } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
+
+import { useChatInputNotice } from './useChatInputNotice';
+
+const styles = createStaticStyles(({ css }) => ({
+ alert: css`
+ /* @lobehub/ui's root style sets align-items: flex-start, top-aligning the
+ * action button against the (shorter) icon+text row instead of centering
+ * it. */
+ align-items: center !important;
+
+ /* Antd's alert section defaults to flex: 1, stretching to fill all
+ * leftover width and pushing the action button to the far edge. Shrink
+ * it to content so the action sits right next to the message. */
+ .ant-alert-section {
+ flex: 0 1 auto !important;
+ }
+
+ /* The rendered title class is .ant-alert-title (not .ant-alert-message,
+ * which this version of antd no longer emits) — matching line-height to
+ * the icon's forced height keeps them vertically aligned. */
+ .ant-alert-title {
+ font-size: 12px;
+ line-height: 18px !important;
+ }
+
+ .ant-alert-icon {
+ height: 18px !important;
+ }
+ `,
+}));
+
+const SwitchToLocalAction = memo(() => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const selectExecutionTarget = useSelectExecutionTarget(agentId);
+ const [loading, setLoading] = useState(false);
+
+ const handleClick = async () => {
+ setLoading(true);
+ try {
+ await selectExecutionTarget('local');
+ } finally {
+ // The notice unmounts once the target switches; guard in case it doesn't
+ // (e.g. a hetero agent with no resolvable local device).
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Button loading={loading} size={'small'} type={'primary'} onClick={handleClick}>
+ {t('input.switchToLocal')}
+ </Button>
+ );
+});
+
+SwitchToLocalAction.displayName = 'SwitchToLocalAction';
+
+const ChatInputNotice = memo(() => {
+ const { t } = useTranslation('chat');
+ const notice = useChatInputNotice();
+
+ if (!notice) return null;
+
+ return (
+ <Alert
+ action={notice.action === 'switchToLocal' ? <SwitchToLocalAction /> : undefined}
+ classNames={{ alert: cx(styles.alert) }}
+ style={{ fontSize: 12 }}
+ title={t(notice.key)}
+ type={notice.type}
+ variant={'borderless'}
+ />
+ );
+});
+
+ChatInputNotice.displayName = 'ChatInputNotice';
+
+export default ChatInputNotice;
diff --git a/src/features/ChatInput/CurrentModelNotice/useCurrentModelNotice.test.tsx b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
similarity index 51%
rename from src/features/ChatInput/CurrentModelNotice/useCurrentModelNotice.test.tsx
rename to src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
index 068266f2d60..67bb89ee3b2 100644
--- a/src/features/ChatInput/CurrentModelNotice/useCurrentModelNotice.test.tsx
+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
@@ -1,7 +1,7 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useCurrentModelNotice } from './useCurrentModelNotice';
+import { useChatInputNotice } from './useChatInputNotice';
interface TestModel {
abilities?: {
@@ -17,7 +17,8 @@ interface TestProviderWithModels {
const testState = vi.hoisted(() => ({
agent: {
- agencyConfig: undefined as { heterogeneousProvider?: { type: string } } | undefined,
+ agencyConfig: undefined as
+ { executionTarget?: string; heterogeneousProvider?: { type: string } } | undefined,
model: 'gpt-4o',
provider: 'openai',
},
@@ -25,10 +26,17 @@ const testState = vi.hoisted(() => ({
enabledChatModelList: [] as TestProviderWithModels[],
isInitAiProviderRuntimeState: false,
},
+ isDesktop: false,
}));
type StoreSelector<T = unknown, S = Record<PropertyKey, unknown>> = (state: S) => T;
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return testState.isDesktop;
+ },
+}));
+
vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({
useAgentId: () => 'agent-id',
}));
@@ -44,6 +52,7 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/agent/selectors', () => ({
agentByIdSelectors: {
+ getAgencyConfigById: () => (s: typeof testState.agent) => s.agencyConfig,
getAgentModelById: () => (s: typeof testState.agent) => s.model,
getAgentModelProviderById: () => (s: typeof testState.agent) => s.provider,
isAgentHeterogeneousById: () => (s: typeof testState.agent) =>
@@ -59,17 +68,18 @@ vi.mock('@/store/aiInfra', () => ({
selector(testState.aiInfra),
}));
-describe('useCurrentModelNotice', () => {
+describe('useChatInputNotice', () => {
beforeEach(() => {
testState.agent.agencyConfig = undefined;
testState.agent.model = 'gpt-4o';
testState.agent.provider = 'openai';
testState.aiInfra.enabledChatModelList = [];
testState.aiInfra.isInitAiProviderRuntimeState = false;
+ testState.isDesktop = false;
});
it('does not return a notice before the model runtime config is ready', () => {
- const { result } = renderHook(() => useCurrentModelNotice());
+ const { result } = renderHook(() => useChatInputNotice());
expect(result.current).toBeUndefined();
});
@@ -77,9 +87,9 @@ describe('useCurrentModelNotice', () => {
it('returns unavailable model copy when the ready model config no longer contains the selected model', () => {
testState.aiInfra.isInitAiProviderRuntimeState = true;
- const { result } = renderHook(() => useCurrentModelNotice());
+ const { result } = renderHook(() => useChatInputNotice());
- expect(result.current).toBe('input.modelUnavailable');
+ expect(result.current).toEqual({ key: 'input.modelUnavailable', type: 'warning' });
});
it('does not return unsupported tool-use copy when the selected model exists but lacks tool calls', () => {
@@ -88,7 +98,7 @@ describe('useCurrentModelNotice', () => {
{ children: [{ abilities: { functionCall: false }, id: 'gpt-4o' }], id: 'openai' },
];
- const { result } = renderHook(() => useCurrentModelNotice());
+ const { result } = renderHook(() => useChatInputNotice());
expect(result.current).toBeUndefined();
});
@@ -99,9 +109,9 @@ describe('useCurrentModelNotice', () => {
{ children: [{ abilities: { functionCall: true }, id: 'gpt-image-1' }], id: 'openai' },
];
- const { result } = renderHook(() => useCurrentModelNotice());
+ const { result } = renderHook(() => useChatInputNotice());
- expect(result.current).toBe('input.modelUnavailable');
+ expect(result.current).toEqual({ key: 'input.modelUnavailable', type: 'warning' });
});
it('does not return a notice when the ready model supports tool use', () => {
@@ -110,17 +120,75 @@ describe('useCurrentModelNotice', () => {
{ children: [{ abilities: { functionCall: true }, id: 'gpt-4o' }], id: 'openai' },
];
- const { result } = renderHook(() => useCurrentModelNotice());
+ const { result } = renderHook(() => useChatInputNotice());
expect(result.current).toBeUndefined();
});
- it('does not return a notice for heterogeneous agents', () => {
+ it('does not return a model notice for heterogeneous agents', () => {
testState.agent.agencyConfig = { heterogeneousProvider: { type: 'codex' } };
testState.aiInfra.isInitAiProviderRuntimeState = true;
- const { result } = renderHook(() => useCurrentModelNotice());
+ const { result } = renderHook(() => useChatInputNotice());
+
+ expect(result.current).toBeUndefined();
+ });
+
+ it('returns the sandbox tip on desktop when the cloud sandbox is selected', () => {
+ testState.isDesktop = true;
+ testState.agent.agencyConfig = { executionTarget: 'sandbox' };
+ testState.aiInfra.isInitAiProviderRuntimeState = true;
+ testState.aiInfra.enabledChatModelList = [
+ { children: [{ abilities: { functionCall: true }, id: 'gpt-4o' }], id: 'openai' },
+ ];
+
+ const { result } = renderHook(() => useChatInputNotice());
+
+ expect(result.current).toEqual({
+ action: 'switchToLocal',
+ key: 'input.sandboxModeNotice',
+ type: 'info',
+ });
+ });
+
+ it('does not return the sandbox tip off desktop even when the sandbox is selected', () => {
+ testState.isDesktop = false;
+ testState.agent.agencyConfig = { executionTarget: 'sandbox' };
+ testState.aiInfra.isInitAiProviderRuntimeState = true;
+ testState.aiInfra.enabledChatModelList = [
+ { children: [{ abilities: { functionCall: true }, id: 'gpt-4o' }], id: 'openai' },
+ ];
+
+ const { result } = renderHook(() => useChatInputNotice());
expect(result.current).toBeUndefined();
});
+
+ it('shows the sandbox tip for heterogeneous agents that selected the sandbox', () => {
+ testState.isDesktop = true;
+ testState.agent.agencyConfig = {
+ executionTarget: 'sandbox',
+ heterogeneousProvider: { type: 'codex' },
+ };
+ testState.aiInfra.isInitAiProviderRuntimeState = true;
+
+ const { result } = renderHook(() => useChatInputNotice());
+
+ expect(result.current).toEqual({
+ action: 'switchToLocal',
+ key: 'input.sandboxModeNotice',
+ type: 'info',
+ });
+ });
+
+ it('prioritizes the model warning over the sandbox tip when both apply', () => {
+ testState.isDesktop = true;
+ testState.agent.agencyConfig = { executionTarget: 'sandbox' };
+ testState.aiInfra.isInitAiProviderRuntimeState = true;
+ // selected model absent from the chat selector → modelUnavailable
+
+ const { result } = renderHook(() => useChatInputNotice());
+
+ expect(result.current).toEqual({ key: 'input.modelUnavailable', type: 'warning' });
+ });
});
diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts
new file mode 100644
index 00000000000..b48e4467116
--- /dev/null
+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts
@@ -0,0 +1,90 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { type EnabledProviderWithModels } from '@/types/aiProvider';
+
+interface ResolveChatInputNoticeParams {
+ currentChatModel?: unknown;
+ isHeterogeneousAgent: boolean;
+ isModelConfigReady: boolean;
+ /** Desktop has selected the ephemeral cloud sandbox as the execution target. */
+ isSandboxTarget: boolean;
+}
+
+const findEnabledChatModel = (
+ enabledChatModelList: EnabledProviderWithModels[],
+ model: string,
+ provider: string,
+) => {
+ return enabledChatModelList
+ .find((item) => item.id === provider)
+ ?.children.find((item) => item.id === model);
+};
+
+export const resolveChatInputNotice = ({
+ currentChatModel,
+ isHeterogeneousAgent,
+ isModelConfigReady,
+ isSandboxTarget,
+}: ResolveChatInputNoticeParams) => {
+ // Model-config notices (warning) take priority over the sandbox tip (info):
+ // an unusable model blocks the send, the sandbox is only a softer suggestion.
+ // They don't apply to heterogeneous agents (own toolchain) or before the
+ // model runtime config is ready.
+ if (
+ !isHeterogeneousAgent &&
+ isModelConfigReady && // Example: an agent still references `gpt-4-32k`, or a model reclassified to
+ // image/video; once absent from the chat selector, it should read as unavailable.
+ !currentChatModel
+ )
+ return { action: undefined, key: 'input.modelUnavailable', type: 'warning' } as const;
+
+ // Sandbox is an ephemeral environment; nudge desktop users toward a device
+ // (e.g. local) for a better experience. Applies to hetero agents too, so it
+ // sits outside the model-notice guard above. `action: 'switchToLocal'`
+ // re-targets execution to this machine.
+ if (isSandboxTarget)
+ return { action: 'switchToLocal', key: 'input.sandboxModeNotice', type: 'info' } as const;
+};
+
+/** Union of every notice shape `resolveChatInputNotice` can return. */
+export type ChatInputNotice = NonNullable<ReturnType<typeof resolveChatInputNotice>>;
+
+export const useChatInputNotice = (): ChatInputNotice | undefined => {
+ const agentId = useAgentId();
+
+ const [isHeterogeneousAgent, model, provider, agencyConfig] = useAgentStore((s) => [
+ agentByIdSelectors.isAgentHeterogeneousById(agentId)(s),
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ agentByIdSelectors.getAgencyConfigById(agentId)(s),
+ ]);
+
+ const enabledChatModelList = useEnabledChatModels();
+ const isModelConfigReady = useAiInfraStore((s) =>
+ aiProviderSelectors.isInitAiProviderRuntimeState(s),
+ );
+ const currentChatModel = findEnabledChatModel(enabledChatModelList, model, provider);
+
+ // The sandbox suggestion only makes sense on desktop, where `local` is the
+ // recommended alternative. `clientExecutionAvailable: isDesktop` matches how
+ // HeteroDeviceSwitcher resolves the effective target for the chip.
+ const isSandboxTarget =
+ isDesktop &&
+ resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ isHetero: isHeterogeneousAgent,
+ }) === 'sandbox';
+
+ return resolveChatInputNotice({
+ currentChatModel,
+ isHeterogeneousAgent,
+ isModelConfigReady,
+ isSandboxTarget,
+ });
+};
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 2608dd06100..906bd7832ee 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -23,10 +23,10 @@ import {
import { memo, type ReactNode, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { lambdaQuery } from '@/libs/trpc/client';
-import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useElectronStore } from '@/store/electron';
@@ -342,7 +342,6 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const navigate = useWorkspaceAwareNavigate();
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
// Workspace-scoped agent: every workspace member runs through one device pool,
// so personal devices (only reachable by their registering user) must be
// suppressed from the picker. The server enforces the same rule on writes.
@@ -377,34 +376,13 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
clientExecutionAvailable: isDesktop,
});
+ const selectExecutionTarget = useSelectExecutionTarget(agentId);
const handleSelect = useCallback(
async (target: DeviceExecutionTarget, deviceId?: string) => {
setOpen(false);
-
- // `executionTarget` is the single source of truth — the server tool
- // gate + client `getRuntimeModeById` derive `runtimeMode` from it.
- let nextBoundDeviceId = target === 'device' ? deviceId : boundDeviceId;
- if (target === 'local') {
- nextBoundDeviceId = currentDeviceId;
- if (!nextBoundDeviceId) {
- try {
- nextBoundDeviceId = (await gatewayConnectionService.getDeviceInfo())?.deviceId;
- } catch {
- nextBoundDeviceId = undefined;
- }
- }
- if (isHetero && !nextBoundDeviceId) return;
- }
-
- await updateAgentConfigById(agentId, {
- agencyConfig: {
- ...agencyConfig,
- executionTarget: target,
- ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),
- },
- });
+ await selectExecutionTarget(target, deviceId);
},
- [agentId, agencyConfig, boundDeviceId, currentDeviceId, isHetero, updateAgentConfigById],
+ [selectExecutionTarget],
);
// Don't render for remote hetero agents — they use RemoteAgentConfigCard in profile.
diff --git a/src/features/ChatInput/CurrentModelNotice/index.tsx b/src/features/ChatInput/CurrentModelNotice/index.tsx
deleted file mode 100644
index b8d3330ec7b..00000000000
--- a/src/features/ChatInput/CurrentModelNotice/index.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-'use client';
-
-import { Alert } from '@lobehub/ui';
-import { createStaticStyles, cx } from 'antd-style';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useCurrentModelNotice } from './useCurrentModelNotice';
-
-const styles = createStaticStyles(({ css }) => ({
- alert: css`
- .ant-alert-message {
- font-size: 12px;
- line-height: 18px !important;
- }
-
- .ant-alert-icon {
- height: 18px !important;
- }
- `,
-}));
-
-const CurrentModelNotice = memo(() => {
- const { t } = useTranslation('chat');
- const noticeKey = useCurrentModelNotice();
-
- if (!noticeKey) return null;
-
- return (
- <Alert
- classNames={{ alert: cx(styles.alert) }}
- style={{ fontSize: 12 }}
- title={t(noticeKey)}
- type={'warning'}
- variant={'borderless'}
- />
- );
-});
-
-CurrentModelNotice.displayName = 'CurrentModelNotice';
-
-export default CurrentModelNotice;
diff --git a/src/features/ChatInput/CurrentModelNotice/useCurrentModelNotice.ts b/src/features/ChatInput/CurrentModelNotice/useCurrentModelNotice.ts
deleted file mode 100644
index abc42e55d6d..00000000000
--- a/src/features/ChatInput/CurrentModelNotice/useCurrentModelNotice.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
-import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
-import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
-import { type EnabledProviderWithModels } from '@/types/aiProvider';
-
-interface ResolveCurrentModelNoticeKeyParams {
- currentChatModel?: unknown;
- isHeterogeneousAgent: boolean;
- isModelConfigReady: boolean;
-}
-
-const findEnabledChatModel = (
- enabledChatModelList: EnabledProviderWithModels[],
- model: string,
- provider: string,
-) => {
- return enabledChatModelList
- .find((item) => item.id === provider)
- ?.children.find((item) => item.id === model);
-};
-
-export const resolveCurrentModelNoticeKey = ({
- currentChatModel,
- isHeterogeneousAgent,
- isModelConfigReady,
-}: ResolveCurrentModelNoticeKeyParams) => {
- if (isHeterogeneousAgent || !isModelConfigReady) return;
-
- // Example: an agent still references `gpt-4-32k`, or a model reclassified to
- // image/video; once absent from the chat selector, it should read as unavailable.
- if (!currentChatModel) return 'input.modelUnavailable';
-};
-
-export const useCurrentModelNotice = () => {
- const agentId = useAgentId();
-
- const [isHeterogeneousAgent, model, provider] = useAgentStore((s) => [
- agentByIdSelectors.isAgentHeterogeneousById(agentId)(s),
- agentByIdSelectors.getAgentModelById(agentId)(s),
- agentByIdSelectors.getAgentModelProviderById(agentId)(s),
- ]);
-
- const enabledChatModelList = useEnabledChatModels();
- const isModelConfigReady = useAiInfraStore((s) =>
- aiProviderSelectors.isInitAiProviderRuntimeState(s),
- );
- const currentChatModel = findEnabledChatModel(enabledChatModelList, model, provider);
-
- return resolveCurrentModelNoticeKey({
- currentChatModel,
- isHeterogeneousAgent,
- isModelConfigReady,
- });
-};
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index 3a152be3640..889d686dfcc 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -9,7 +9,7 @@ import { memo, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
-import CurrentModelNotice from '@/features/ChatInput/CurrentModelNotice';
+import ChatInputNotice from '@/features/ChatInput/ChatInputNotice';
import { useChatInputStore } from '@/features/ChatInput/store';
import { LayoutContainerContext } from '@/routes/(main)/_layout/DesktopLayoutContainer/LayoutContainerContext';
import { useChatStore } from '@/store/chat';
@@ -166,7 +166,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
onDragOver={skillDrop.onDragOver}
onDrop={skillDrop.onDrop}
>
- {!isConfigLoading && <CurrentModelNotice />}
+ {!isConfigLoading && <ChatInputNotice />}
<ChatInput
data-testid="chat-input"
defaultHeight={chatInputHeight || 32}
diff --git a/src/features/ChatInput/Mobile/index.tsx b/src/features/ChatInput/Mobile/index.tsx
index f152901e6dc..787975bd2b4 100644
--- a/src/features/ChatInput/Mobile/index.tsx
+++ b/src/features/ChatInput/Mobile/index.tsx
@@ -5,7 +5,7 @@ import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { memo } from 'react';
-import CurrentModelNotice from '@/features/ChatInput/CurrentModelNotice';
+import ChatInputNotice from '@/features/ChatInput/ChatInputNotice';
import { useChatInputStore } from '@/features/ChatInput/store';
import dynamic from '@/libs/next/dynamic';
@@ -45,7 +45,7 @@ const DesktopChatInput = memo(() => {
paddingBlock={'0 12px'}
paddingInline={12}
>
- <CurrentModelNotice />
+ <ChatInputNotice />
<ChatInput
fullscreen={expand}
header={<ChatInputActionBar left={<ActionBar />} />}
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
new file mode 100644
index 00000000000..7f83825fa89
--- /dev/null
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -0,0 +1,131 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useSelectExecutionTarget } from './useSelectExecutionTarget';
+
+const testState = vi.hoisted(() => ({
+ agent: {
+ agencyConfig: undefined as
+ | {
+ boundDeviceId?: string;
+ executionTarget?: string;
+ heterogeneousProvider?: { type: string };
+ }
+ | undefined,
+ isHetero: false,
+ updateAgentConfigById: vi.fn(),
+ },
+ electron: {
+ gatewayDeviceInfo: undefined as { deviceId?: string } | undefined,
+ },
+ getDeviceInfo: vi.fn(),
+ isDesktop: false,
+}));
+
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return testState.isDesktop;
+ },
+}));
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: {
+ getDeviceInfo: () => testState.getDeviceInfo(),
+ },
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: typeof testState.agent) => unknown) => selector(testState.agent),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => (s: typeof testState.agent) => s.agencyConfig,
+ isAgentHeterogeneousById: () => (s: typeof testState.agent) => s.isHetero,
+ },
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (s: typeof testState.electron) => unknown) =>
+ selector(testState.electron),
+}));
+
+describe('useSelectExecutionTarget', () => {
+ beforeEach(() => {
+ testState.agent.agencyConfig = undefined;
+ testState.agent.isHetero = false;
+ testState.agent.updateAgentConfigById = vi.fn();
+ testState.electron.gatewayDeviceInfo = undefined;
+ testState.getDeviceInfo = vi.fn();
+ testState.isDesktop = false;
+ });
+
+ it('persists the target as-is when switching to sandbox, keeping any existing boundDeviceId', async () => {
+ testState.agent.agencyConfig = { boundDeviceId: 'device-1', executionTarget: 'local' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { boundDeviceId: 'device-1', executionTarget: 'sandbox' },
+ });
+ });
+
+ it('pins the given deviceId when switching to a specific device', async () => {
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('device', 'device-2');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { boundDeviceId: 'device-2', executionTarget: 'device' },
+ });
+ });
+
+ it('reuses this desktop machine gateway deviceId when switching to local', async () => {
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.getDeviceInfo).not.toHaveBeenCalled();
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ });
+ });
+
+ it('falls back to the gateway connection service when no gateway deviceId is cached yet', async () => {
+ testState.isDesktop = true;
+ testState.getDeviceInfo.mockResolvedValue({ deviceId: 'resolved-device' });
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.getDeviceInfo).toHaveBeenCalled();
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { boundDeviceId: 'resolved-device', executionTarget: 'local' },
+ });
+ });
+
+ it('keeps the previous boundDeviceId when the local device cannot be resolved for a non-hetero agent', async () => {
+ testState.agent.agencyConfig = { boundDeviceId: 'stale-device', executionTarget: 'sandbox' };
+ testState.getDeviceInfo.mockRejectedValue(new Error('no gateway'));
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { boundDeviceId: 'stale-device', executionTarget: 'local' },
+ });
+ });
+
+ it('does not switch a heterogeneous agent to local when no device can be resolved', async () => {
+ testState.agent.isHetero = true;
+ testState.getDeviceInfo.mockRejectedValue(new Error('no gateway'));
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
new file mode 100644
index 00000000000..bf94b275ac2
--- /dev/null
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -0,0 +1,58 @@
+'use client';
+
+import { isDesktop } from '@lobechat/const';
+import type { DeviceExecutionTarget } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useElectronStore } from '@/store/electron';
+
+/**
+ * Persist an execution-target selection for an agent. Shared by the device
+ * switcher and the sandbox notice so the `local` device-id resolution (which
+ * has to find this machine's gateway `deviceId`) lives in one place.
+ *
+ * `executionTarget` is the single source of truth — the server tool gate +
+ * client `getRuntimeModeById` derive `runtimeMode` from it.
+ */
+export const useSelectExecutionTarget = (agentId: string) => {
+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+
+ // The current machine's own gateway deviceId (desktop only); used to pin a
+ // `local` selection to this device.
+ const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);
+ const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;
+
+ return useCallback(
+ async (target: DeviceExecutionTarget, deviceId?: string) => {
+ const boundDeviceId = agencyConfig?.boundDeviceId;
+ let nextBoundDeviceId = target === 'device' ? deviceId : boundDeviceId;
+ if (target === 'local') {
+ nextBoundDeviceId = currentDeviceId;
+ if (!nextBoundDeviceId) {
+ try {
+ nextBoundDeviceId = (await gatewayConnectionService.getDeviceInfo())?.deviceId;
+ } catch {
+ nextBoundDeviceId = undefined;
+ }
+ }
+ // Hetero agents must execute somewhere; without a resolvable local
+ // device there is nothing to pin `local` to, so don't switch.
+ if (isHetero && !nextBoundDeviceId) return;
+ }
+
+ await updateAgentConfigById(agentId, {
+ agencyConfig: {
+ ...agencyConfig,
+ executionTarget: target,
+ ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),
+ },
+ });
+ },
+ [agentId, agencyConfig, currentDeviceId, isHetero, updateAgentConfigById],
+ );
+};
diff --git a/src/store/chat/slices/message/reducer.ts b/src/store/chat/slices/message/reducer.ts
index c167f9a4b49..7e142cb6a3f 100644
--- a/src/store/chat/slices/message/reducer.ts
+++ b/src/store/chat/slices/message/reducer.ts
@@ -7,7 +7,7 @@ import {
} from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import i18n from 'i18next';
-import { produce } from 'immer';
+import { current, produce } from 'immer';
import { merge } from '@/utils/merge';
@@ -152,7 +152,10 @@ export const messagesReducer = (
newState = merge(message.pluginState, { [key]: value });
}
- if (isEqual(message.pluginState, newState)) return;
+ // Compare against a plain snapshot, not the raw draft proxy — fast-deep-equal's
+ // traversal of an Immer draft is an implementation detail that can change between
+ // immer patch releases (e.g. immer 11.1.9 broke this exact comparison vs 11.1.8).
+ if (message.pluginState && isEqual(current(message.pluginState), newState)) return;
message.pluginState = newState;
message.updatedAt = Date.now();
diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.ts
index 091dcb2fd2c..eb41f148840 100644
--- a/src/store/chat/slices/topic/reducer.ts
+++ b/src/store/chat/slices/topic/reducer.ts
@@ -1,5 +1,5 @@
import isEqual from 'fast-deep-equal';
-import { produce } from 'immer';
+import { current, produce } from 'immer';
import { type ChatTopic, type CreateTopicParams } from '@/types/topic';
@@ -39,10 +39,7 @@ type ReplaceChatTopicIdAction = ChatTopicScope & {
};
export type ChatTopicDispatch =
- | AddChatTopicAction
- | UpdateChatTopicAction
- | DeleteChatTopicAction
- | ReplaceChatTopicIdAction;
+ AddChatTopicAction | UpdateChatTopicAction | DeleteChatTopicAction | ReplaceChatTopicIdAction;
export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch): ChatTopic[] => {
switch (payload.type) {
@@ -70,9 +67,9 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
const currentTopic = draftState[topicIndex];
const mergedTopic = { ...currentTopic, ...value };
- // Only update if the merged value is different from current (excluding updatedAt)
-
- if (!isEqual(currentTopic, mergedTopic)) {
+ // Only update if the merged value is different from current (excluding updatedAt).
+ // Compare against a plain snapshot, not the raw draft proxy — see message/reducer.ts.
+ if (!isEqual(current(currentTopic), mergedTopic)) {
// TODO: updatedAt type needs to be changed to Date later
// @ts-ignore
draftState[topicIndex] = { ...mergedTopic, updatedAt: new Date() };