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: add model selection guard hooks (#17186)

YuTengjing6dc50309abfb
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index cb1eb887d59..68dafb4dd55 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -536,3 +536,24 @@ be hidden/disabled for users who will always be rejected).
as the blocked role and screenshot the rejection state (and the allowed role's
success state) in addition to API probes. If the rejection renders as a raw or
missing error message, report that as a finding instead of leaving it undiscovered.
+
+---
+
+## Case 21 — Turning a feature verification into an unbounded dev-environment repair
+
+**Wrong approach**: after the normal product surface fails to boot, repeatedly modify
+shared dev configuration, reinstall the entire workspace, and investigate unrelated
+dependency/context problems before running any assertion for the feature under test.
+
+**Why it's wrong**: environment readiness is a gate, not the test goal. A workaround
+that changes shared configuration can also make the verification less representative,
+while an open-ended repair loop produces no feature evidence.
+
+**What it breaks**: the user waits through a long sequence of setup experiments, the
+working tree gains unrelated edits, and the run still has no reportable test result.
+
+**Correct approach**: follow only recovery paths already documented by this skill. If the
+observed failure mode is not covered, stop the test immediately, revert any experimental
+changes, summarize the exact checks and evidence collected, and ask the user for help before
+continuing. Do not repair the environment, switch surfaces, or invent a fallback without user
+direction.
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 23cc1a84492..29b8d8dccc1 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -1267,3 +1267,19 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
IDENTICALLY whether the gate is broken or the session is missing. Always establish that the
session is live (a 200 from an authed procedure) BEFORE concluding the gate is wrong —
otherwise you publish a false bug against your own change.
+
+### E23. In zsh, a loop variable named `path` overwrites the command search path
+
+- **Situation**: parsing a Netscape cookie jar with `while read ... path ...` and then invoking
+ browser commands inside the loop. The first iteration succeeds at assigning the fields, but the
+ next executable fails with `command not found`.
+- **Cause**: zsh exposes `path` as a special array tied to `PATH`; assigning the cookie path field
+ (usually `/`) replaces the process command search path.
+- **Works**: name the field `cookie_path` (and similarly avoid other zsh special parameter names),
+ then pass it to the cookie command. This is a shell failure, not an auth or browser failure.
+
+### E24. Vite throws `EMFILE` — terminate Agent Testing and ask the user for help
+
+- **Situation**: an isolated frontend-only Vite surface exits at startup with `EMFILE: too many open files, watch`, while the intended port is free and the shell can successfully create thousands of `fs.watch` handles in a control process.
+- **Likely causes (not established)**: multiple LobeHub Cloud worktrees or clones are running file watchers; or a previously used workspace still has watchers owned by a surviving terminal process or a VS Code window, even after its visible terminal was closed.
+- **Required action**: immediately terminate Agent Testing, report the observed `EMFILE`, and ask the user to inspect and clean up other worktrees, terminal processes, or VS Code windows. Do not kill user-owned processes, close editor windows, change Vite watch mode, fall back to a one-shot static build, or publish a Verify report from a degraded surface.
diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.json
index a03474f35bc..ac92b10d6c1 100644
--- a/locales/en-US/subscription.json
+++ b/locales/en-US/subscription.json
@@ -57,6 +57,7 @@
"compareAllPlans": "View All Plans",
"comparePlans": "View Plans",
"createSubscriptionError": "Failed to create subscription",
+ "creditUsageReminder.title": "{{percent}} of the subscription credits included in this billing cycle have been used",
"credits.autoTopUp.cardBindingGiftHint": "🎁 Add your first payment method and get 1M credits free",
"credits.autoTopUp.currentBalance": "Current Balance",
"credits.autoTopUp.desc": "Ensure your credits never run out",
@@ -280,6 +281,11 @@
"modelPricing.button": "View Pricing Documentation",
"modelPricing.desc": "{{name}} uses Credits to measure AI model usage. The table below shows credits per 1M Tokens.",
"modelPricing.title": "Text Model Pricing",
+ "modelSelection.confirm.continue": "Continue using",
+ "modelSelection.confirm.description": "{{model}} can incur higher usage costs. Review its current rates before continuing.",
+ "modelSelection.confirm.inputPrice": "Input",
+ "modelSelection.confirm.outputPrice": "Output",
+ "modelSelection.confirm.title": "Use {{model}}?",
"models.input": "Input",
"models.intro": "Introduction",
"models.link": "View",
diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.json
index f934a2028ba..f501c21d527 100644
--- a/locales/zh-CN/subscription.json
+++ b/locales/zh-CN/subscription.json
@@ -57,6 +57,7 @@
"compareAllPlans": "查看所有套餐",
"comparePlans": "查看套餐",
"createSubscriptionError": "创建订阅失败",
+ "creditUsageReminder.title": "当前计费周期包含的订阅积分已使用 {{percent}}",
"credits.autoTopUp.cardBindingGiftHint": "🎁 首次添加支付方式,即送 1M 积分",
"credits.autoTopUp.currentBalance": "当前总余额",
"credits.autoTopUp.desc": "确保你的积分不会用光",
@@ -280,6 +281,11 @@
"modelPricing.button": "查看价格文档",
"modelPricing.desc": "{{name}} 使用积分衡量 AI 模型使用量。下表显示每百万 Token 所需计算积分。",
"modelPricing.title": "文本模型价格",
+ "modelSelection.confirm.continue": "继续使用",
+ "modelSelection.confirm.description": "{{model}} 可能产生较高的使用成本,请确认当前价格后继续。",
+ "modelSelection.confirm.inputPrice": "输入",
+ "modelSelection.confirm.outputPrice": "输出",
+ "modelSelection.confirm.title": "使用 {{model}}?",
"models.input": "输入",
"models.intro": "简介",
"models.link": "查看",
diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.ts
index 2332c93fb20..3526407209e 100644
--- a/packages/locales/src/default/subscription.ts
+++ b/packages/locales/src/default/subscription.ts
@@ -64,6 +64,8 @@ export default {
'Does not include monthly credits, you need to configure your own model API',
'compare.monthlyCredit': 'Monthly Credits',
'compare.title': 'Plan Comparison',
+ 'creditUsageReminder.title':
+ '{{percent}} of the subscription credits included in this billing cycle have been used',
'compareAllPlans': 'View All Plans',
'comparePlans': 'View Plans',
'createSubscriptionError': 'Failed to create subscription',
@@ -81,6 +83,12 @@ export default {
'discount.maxOff': 'Up to {{percent}}% off',
'discount.off': '{{percent}}% off',
'discount.save': 'Save',
+ 'modelSelection.confirm.continue': 'Continue using',
+ 'modelSelection.confirm.description':
+ '{{model}} can incur higher usage costs. Review its current rates before continuing.',
+ 'modelSelection.confirm.inputPrice': 'Input',
+ 'modelSelection.confirm.outputPrice': 'Output',
+ 'modelSelection.confirm.title': 'Use {{model}}?',
'downgradePlans.alert':
'You will still enjoy the benefits until the current plan expires ({{date}}). The new plan will take effect after the current plan expires.',
'downgradePlans.desc': 'The plan change will take effect after the current plan expires.',
diff --git a/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx b/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
index ef5187fffa3..7ae48f81f24 100644
--- a/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
+++ b/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
@@ -1,7 +1,13 @@
import type { ReactNode } from 'react';
+// The cloud implementation calls hooks while the OSS fallback intentionally does not.
+// eslint-disable-next-line @eslint-react/no-unnecessary-use-prefix
export const useBusinessChatInputCostEstimateAlert = (): ReactNode => null;
+// The cloud implementation calls hooks while the OSS fallback intentionally does not.
+// eslint-disable-next-line @eslint-react/no-unnecessary-use-prefix
+export const useBusinessChatInputAlerts = (): ReactNode => null;
+
export const getBusinessChatInputSendAreaPrefix = (sendAreaPrefix?: ReactNode): ReactNode =>
sendAreaPrefix;
diff --git a/src/business/client/hooks/useBusinessModelListGuard.ts b/src/business/client/hooks/useBusinessModelListGuard.ts
index b4b3e50956c..7be474feb0a 100644
--- a/src/business/client/hooks/useBusinessModelListGuard.ts
+++ b/src/business/client/hooks/useBusinessModelListGuard.ts
@@ -1,6 +1,8 @@
export interface BusinessModelListGuard {
isModelRestricted?: (modelId: string, providerId: string) => boolean;
+ onBeforeModelSelect?: (modelId: string, providerId: string) => boolean | Promise<boolean>;
onRestrictedModelClick?: () => void;
+ sortModelLast?: (modelId: string, providerId: string) => boolean;
}
export const useBusinessModelListGuard = (): BusinessModelListGuard => {
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 9d1bfc164d9..88b46902200 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -11,7 +11,7 @@ import { Link } from 'react-router';
import {
getBusinessChatInputSendAreaPrefix,
- useBusinessChatInputCostEstimateAlert,
+ useBusinessChatInputAlerts,
} from '@/business/client/hooks/useBusinessChatInputSendAreaPrefix';
import { useBusinessInputCompletionErrorAlert } from '@/business/client/hooks/useBusinessInputCompletionErrorAlert';
import type { ActionKeys, ChatInputFeature } from '@/features/ChatInput';
@@ -330,7 +330,7 @@ const ChatInput = memo<ChatInputProps>(
const disabled =
isInputEmpty || isUploadingFiles || (!!disableQueue && isInputQueueBlocked) || !!disableSend;
const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;
- const businessCostEstimateAlert = useBusinessChatInputCostEstimateAlert();
+ const businessAlerts = useBusinessChatInputAlerts();
const businessSendAreaPrefix = getBusinessChatInputSendAreaPrefix(sendAreaPrefix);
// Send handler - gets message, clears editor immediately, then sends
@@ -427,7 +427,7 @@ const ChatInput = memo<ChatInputProps>(
</Flexbox>
)}
<InputCompletionErrorAlert />
- {businessCostEstimateAlert}
+ {businessAlerts}
<Flexbox
paddingInline={12}
ref={overlayRef}
diff --git a/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx b/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx
index 55b8847763d..bcd47679f14 100644
--- a/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx
+++ b/src/features/ModelSwitchPanel/components/List/ListItemRenderer.tsx
@@ -35,6 +35,7 @@ interface ListItemRendererProps {
isModelRestricted?: (modelId: string, providerId: string) => boolean;
item: ListItem;
newLabel: string;
+ onBeforeModelSelect?: (modelId: string, providerId: string) => boolean | Promise<boolean>;
onClose: () => void;
onModelChange: (modelId: string, providerId: string) => void;
onRestrictedModelClick?: () => void;
@@ -48,6 +49,7 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
isModelRestricted,
item,
newLabel,
+ onBeforeModelSelect,
onModelChange,
onClose,
onRestrictedModelClick,
@@ -60,6 +62,13 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
const [detailOpen, setDetailOpen] = useState(false);
+ const selectModel = async (modelId: string, providerId: string) => {
+ onClose();
+ if ((await onBeforeModelSelect?.(modelId, providerId)) === false) return;
+
+ onModelChange(modelId, providerId);
+ };
+
useEffect(() => {
return subscribeScroll?.(() => setDetailOpen(false));
}, [subscribeScroll]);
@@ -161,8 +170,7 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
onClose();
return;
}
- onClose();
- onModelChange(item.model.id, item.provider.id);
+ void selectModel(item.model.id, item.provider.id);
}}
>
<ModelItemRender
@@ -205,8 +213,7 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
onClose();
return;
}
- onClose();
- onModelChange(item.data.model.id, singleProvider.id);
+ void selectModel(item.data.model.id, singleProvider.id);
}}
>
<SingleProviderModelItem
@@ -238,6 +245,7 @@ export const ListItemRenderer = memo<ListItemRendererProps>(
newLabel={newLabel}
proLabel={proLabel}
showInfoTag={isDevMode}
+ onBeforeModelSelect={onBeforeModelSelect}
onClose={onClose}
onModelChange={onModelChange}
onRestrictedModelClick={onRestrictedModelClick}
diff --git a/src/features/ModelSwitchPanel/components/List/MultipleProvidersModelItem.tsx b/src/features/ModelSwitchPanel/components/List/MultipleProvidersModelItem.tsx
index 34905b8388f..c293c7a7de2 100644
--- a/src/features/ModelSwitchPanel/components/List/MultipleProvidersModelItem.tsx
+++ b/src/features/ModelSwitchPanel/components/List/MultipleProvidersModelItem.tsx
@@ -31,6 +31,7 @@ interface MultipleProvidersModelItemProps {
defaultProviderId?: string;
isModelRestricted?: (modelId: string, providerId: string) => boolean;
newLabel: string;
+ onBeforeModelSelect?: (modelId: string, providerId: string) => boolean | Promise<boolean>;
onClose: () => void;
onModelChange: (modelId: string, providerId: string) => void;
onRestrictedModelClick?: () => void;
@@ -44,6 +45,7 @@ export const MultipleProvidersModelItem = memo<MultipleProvidersModelItemProps>(
data,
isModelRestricted,
newLabel,
+ onBeforeModelSelect,
onModelChange,
onClose,
onRestrictedModelClick,
@@ -65,6 +67,14 @@ export const MultipleProvidersModelItem = memo<MultipleProvidersModelItemProps>(
data.providers.length > 0 &&
data.providers.every((p) => isModelRestricted(data.model.id, p.id));
+ const selectModel = async (providerId: string) => {
+ setSubmenuOpen(false);
+ onClose();
+ if ((await onBeforeModelSelect?.(data.model.id, providerId)) === false) return;
+
+ onModelChange(data.model.id, providerId);
+ };
+
return (
<DropdownMenuSubmenuRoot
open={submenuOpen}
@@ -86,9 +96,7 @@ export const MultipleProvidersModelItem = memo<MultipleProvidersModelItemProps>(
onClose();
return;
}
- setSubmenuOpen(false);
- onModelChange(data.model.id, defaultProvider.id);
- onClose();
+ void selectModel(defaultProvider.id);
}}
>
<ModelItemRender
@@ -124,9 +132,7 @@ export const MultipleProvidersModelItem = memo<MultipleProvidersModelItemProps>(
onClose();
return;
}
- setSubmenuOpen(false);
- onClose();
- onModelChange(data.model.id, p.id);
+ void selectModel(p.id);
}}
>
<DropdownMenuItemIcon>
diff --git a/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx b/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx
index 86e47534c98..b50e1ab0f7a 100644
--- a/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx
+++ b/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx
@@ -135,4 +135,33 @@ describe('MultipleProvidersModelItem', () => {
expect(onModelChange).not.toHaveBeenCalled();
expect(screen.getByTestId('model-pro-badge')).toHaveTextContent('pro');
});
+
+ it('should only change the model when the before-select guard approves', async () => {
+ const onModelChange = vi.fn();
+ const onBeforeModelSelect = vi.fn().mockResolvedValue(false);
+
+ render(
+ <MultipleProvidersModelItem
+ activeKey=""
+ newLabel="new"
+ data={{
+ displayName: 'Claude Opus 4.8',
+ model: {
+ abilities: {},
+ displayName: 'Claude Opus 4.8',
+ id: 'claude-opus-4-8',
+ } as any,
+ providers: [{ id: 'lobehub', name: 'LobeHub' }],
+ }}
+ onBeforeModelSelect={onBeforeModelSelect}
+ onClose={vi.fn()}
+ onModelChange={onModelChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('Claude Opus 4.8'));
+
+ expect(onBeforeModelSelect).toHaveBeenCalledWith('claude-opus-4-8', 'lobehub');
+ await vi.waitFor(() => expect(onModelChange).not.toHaveBeenCalled());
+ });
});
diff --git a/src/features/ModelSwitchPanel/components/List/index.tsx b/src/features/ModelSwitchPanel/components/List/index.tsx
index 992b9f2e651..f655d5303d1 100644
--- a/src/features/ModelSwitchPanel/components/List/index.tsx
+++ b/src/features/ModelSwitchPanel/components/List/index.tsx
@@ -43,7 +43,8 @@ export const List: FC<ListProps> = ({
}) => {
const { t: tCommon } = useTranslation('common');
const newLabel = tCommon('new');
- const { isModelRestricted, onRestrictedModelClick } = useBusinessModelListGuard();
+ const { isModelRestricted, onBeforeModelSelect, onRestrictedModelClick, sortModelLast } =
+ useBusinessModelListGuard();
const proLabel = isModelRestricted ? tCommon('pro') : undefined;
const chatEnabledList = useEnabledChatModels();
@@ -53,7 +54,7 @@ export const List: FC<ListProps> = ({
onModelChange: onModelChangeProp,
onOpenChange,
});
- const listItems = useBuildListItems(enabledList, groupMode, searchKeyword);
+ const listItems = useBuildListItems(enabledList, groupMode, searchKeyword, sortModelLast);
const panelHeight = useMemo(
() =>
@@ -148,6 +149,7 @@ export const List: FC<ListProps> = ({
newLabel={newLabel}
proLabel={proLabel}
subscribeScroll={subscribeScroll}
+ onBeforeModelSelect={onBeforeModelSelect}
onClose={handleClose}
onModelChange={handleModelChange}
onRestrictedModelClick={onRestrictedModelClick}
diff --git a/src/features/ModelSwitchPanel/hooks/useBuildListItems.test.ts b/src/features/ModelSwitchPanel/hooks/useBuildListItems.test.ts
new file mode 100644
index 00000000000..0f6345289c9
--- /dev/null
+++ b/src/features/ModelSwitchPanel/hooks/useBuildListItems.test.ts
@@ -0,0 +1,52 @@
+import type { AiModelForSelect } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import type { EnabledProviderWithModels } from '@/types/aiProvider';
+
+import { buildListItems } from './useBuildListItems';
+
+const model = (id: string, displayName = id) =>
+ ({ abilities: {}, displayName, id }) satisfies AiModelForSelect;
+
+const provider = (id: string, children: AiModelForSelect[]): EnabledProviderWithModels => ({
+ children,
+ id,
+ name: id,
+ source: 'builtin',
+});
+
+const getProviderModelIds = (items: ReturnType<typeof buildListItems>) =>
+ items.flatMap((item) => (item.type === 'provider-model-item' ? [item.model.id] : []));
+
+describe('buildListItems', () => {
+ it('should stably move matching models after other models within a provider', () => {
+ const items = buildListItems(
+ [provider('lobehub', [model('pro-a'), model('normal-a'), model('pro-b'), model('normal-b')])],
+ 'byProvider',
+ '',
+ (modelId, providerId) => providerId === 'lobehub' && modelId.startsWith('pro-'),
+ );
+
+ expect(getProviderModelIds(items)).toEqual(['normal-a', 'normal-b', 'pro-a', 'pro-b']);
+ });
+
+ it('should not move a by-model row when another provider remains available', () => {
+ const items = buildListItems(
+ [
+ provider('lobehub', [model('mixed-pro', 'Mixed'), model('lobehub-pro'), model('normal')]),
+ provider('openai', [model('mixed-pro', 'Mixed')]),
+ ],
+ 'byModel',
+ '',
+ (modelId, providerId) => providerId === 'lobehub' && modelId.includes('pro'),
+ );
+
+ expect(
+ items.flatMap((item) =>
+ item.type === 'model-item-single' || item.type === 'model-item-multiple'
+ ? [item.data.model.id]
+ : [],
+ ),
+ ).toEqual(['mixed-pro', 'normal', 'lobehub-pro']);
+ });
+});
diff --git a/src/features/ModelSwitchPanel/hooks/useBuildListItems.ts b/src/features/ModelSwitchPanel/hooks/useBuildListItems.ts
index c82843b5258..305f40a3613 100644
--- a/src/features/ModelSwitchPanel/hooks/useBuildListItems.ts
+++ b/src/features/ModelSwitchPanel/hooks/useBuildListItems.ts
@@ -4,107 +4,132 @@ import { type EnabledProviderWithModels } from '@/types/aiProvider';
import { type GroupMode, type ListItem, type ModelWithProviders } from '../types';
-export const useBuildListItems = (
+export const buildListItems = (
enabledList: EnabledProviderWithModels[],
groupMode: GroupMode,
searchKeyword: string = '',
+ sortModelLast?: (modelId: string, providerId: string) => boolean,
): ListItem[] => {
- return useMemo(() => {
- if (enabledList.length === 0) {
- return [{ type: 'no-provider' }] as ListItem[];
- }
-
- const matchesSearch = (text: string): boolean => {
- if (!searchKeyword.trim()) return true;
- const keyword = searchKeyword.toLowerCase().trim();
- return text.toLowerCase().includes(keyword);
- };
-
- // lobehub first, then others
- const sortedProviders = [...enabledList].sort((a, b) => {
- const aIsLobehub = a.id === 'lobehub';
- const bIsLobehub = b.id === 'lobehub';
- if (aIsLobehub && !bIsLobehub) return -1;
- if (!aIsLobehub && bIsLobehub) return 1;
- return 0;
- });
-
- if (groupMode === 'byModel') {
- const modelMap = new Map<string, ModelWithProviders>();
-
- for (const providerItem of sortedProviders) {
- for (const modelItem of providerItem.children) {
- const displayName = modelItem.displayName || modelItem.id;
-
- if (!matchesSearch(displayName) && !matchesSearch(providerItem.name)) {
- continue;
- }
-
- if (!modelMap.has(displayName)) {
- modelMap.set(displayName, {
- displayName,
- model: modelItem,
- providers: [],
- });
- }
+ if (enabledList.length === 0) {
+ return [{ type: 'no-provider' }] as ListItem[];
+ }
+
+ const matchesSearch = (text: string): boolean => {
+ if (!searchKeyword.trim()) return true;
+ const keyword = searchKeyword.toLowerCase().trim();
+ return text.toLowerCase().includes(keyword);
+ };
+
+ // lobehub first, then others
+ const sortedProviders = [...enabledList].sort((a, b) => {
+ const aIsLobehub = a.id === 'lobehub';
+ const bIsLobehub = b.id === 'lobehub';
+ if (aIsLobehub && !bIsLobehub) return -1;
+ if (!aIsLobehub && bIsLobehub) return 1;
+ return 0;
+ });
+
+ if (groupMode === 'byModel') {
+ const modelMap = new Map<string, ModelWithProviders>();
+
+ for (const providerItem of sortedProviders) {
+ for (const modelItem of providerItem.children) {
+ const displayName = modelItem.displayName || modelItem.id;
+
+ if (!matchesSearch(displayName) && !matchesSearch(providerItem.name)) {
+ continue;
+ }
- const entry = modelMap.get(displayName)!;
- entry.providers.push({
- id: providerItem.id,
- logo: providerItem.logo,
- name: providerItem.name,
- source: providerItem.source,
+ if (!modelMap.has(displayName)) {
+ modelMap.set(displayName, {
+ displayName,
+ model: modelItem,
+ providers: [],
});
}
- }
- // lobehub first
- const modelArray = Array.from(modelMap.values());
- for (const model of modelArray) {
- model.providers.sort((a, b) => {
- const aIsLobehub = a.id === 'lobehub';
- const bIsLobehub = b.id === 'lobehub';
- if (aIsLobehub && !bIsLobehub) return -1;
- if (!aIsLobehub && bIsLobehub) return 1;
- return 0;
+ const entry = modelMap.get(displayName)!;
+ entry.providers.push({
+ id: providerItem.id,
+ logo: providerItem.logo,
+ name: providerItem.name,
+ source: providerItem.source,
});
}
+ }
- return modelArray.map((data) => ({
- data,
- type:
- data.providers.length === 1
- ? ('model-item-single' as const)
- : ('model-item-multiple' as const),
- }));
- } else {
- const items: ListItem[] = [];
-
- for (const providerItem of sortedProviders) {
- const filteredModels = providerItem.children.filter(
- (modelItem) =>
- matchesSearch(modelItem.displayName || modelItem.id) ||
- matchesSearch(providerItem.name),
- );
-
- if (filteredModels.length > 0 || !searchKeyword.trim()) {
- items.push({ provider: providerItem, type: 'group-header' });
-
- if (filteredModels.length === 0) {
- items.push({ provider: providerItem, type: 'empty-model' });
- } else {
- for (const modelItem of filteredModels) {
- items.push({
- model: modelItem,
- provider: providerItem,
- type: 'provider-model-item',
- });
- }
+ // lobehub first
+ const modelArray = Array.from(modelMap.values());
+ for (const model of modelArray) {
+ model.providers.sort((a, b) => {
+ const aIsLobehub = a.id === 'lobehub';
+ const bIsLobehub = b.id === 'lobehub';
+ if (aIsLobehub && !bIsLobehub) return -1;
+ if (!aIsLobehub && bIsLobehub) return 1;
+ return 0;
+ });
+ }
+
+ const sortedModels = sortModelLast
+ ? modelArray.toSorted((a, b) => {
+ const aLast = a.providers.every((provider) => sortModelLast(a.model.id, provider.id));
+ const bLast = b.providers.every((provider) => sortModelLast(b.model.id, provider.id));
+
+ return Number(aLast) - Number(bLast);
+ })
+ : modelArray;
+
+ return sortedModels.map((data) => ({
+ data,
+ type:
+ data.providers.length === 1
+ ? ('model-item-single' as const)
+ : ('model-item-multiple' as const),
+ }));
+ } else {
+ const items: ListItem[] = [];
+
+ for (const providerItem of sortedProviders) {
+ const filteredModels = providerItem.children.filter(
+ (modelItem) =>
+ matchesSearch(modelItem.displayName || modelItem.id) || matchesSearch(providerItem.name),
+ );
+ const sortedModels = sortModelLast
+ ? filteredModels.toSorted(
+ (a, b) =>
+ Number(sortModelLast(a.id, providerItem.id)) -
+ Number(sortModelLast(b.id, providerItem.id)),
+ )
+ : filteredModels;
+
+ if (sortedModels.length > 0 || !searchKeyword.trim()) {
+ items.push({ provider: providerItem, type: 'group-header' });
+
+ if (sortedModels.length === 0) {
+ items.push({ provider: providerItem, type: 'empty-model' });
+ } else {
+ for (const modelItem of sortedModels) {
+ items.push({
+ model: modelItem,
+ provider: providerItem,
+ type: 'provider-model-item',
+ });
}
}
}
-
- return items;
}
- }, [enabledList, groupMode, searchKeyword]);
+
+ return items;
+ }
};
+
+export const useBuildListItems = (
+ enabledList: EnabledProviderWithModels[],
+ groupMode: GroupMode,
+ searchKeyword: string = '',
+ sortModelLast?: (modelId: string, providerId: string) => boolean,
+): ListItem[] =>
+ useMemo(
+ () => buildListItems(enabledList, groupMode, searchKeyword, sortModelLast),
+ [enabledList, groupMode, searchKeyword, sortModelLast],
+ );