Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(llm): keep empty provider groups in the model dropdown
Elian Doran870b8c52fc8f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex bf903b0b3f..8ceeeca8d6 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2157,6 +2157,7 @@"extended_thinking": "Extended thinking","legacy_models": "Legacy models","model_cost_included": "Subscription",+ "no_models_selected": "No models selected, edit this provider in settings","thinking": "Thinking...","thought_process": "Thought process","tool_calls": "{{count}} tool call(s)",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex ff707d7d5f..4131666d2a 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -14,7 +14,7 @@ import CKEditor, { type CKEditorApi } from "../../react/CKEditor.js";import Dropdown from "../../react/Dropdown.js";import { FormDropdownDivider, FormListHeader, FormListItem, FormListToggleableItem } from "../../react/FormList.js";import { useLegacyImperativeHandlers } from "../../react/hooks.js";-import AddProviderModal, { type LlmProviderConfig, PROVIDER_TYPES } from "../options/llm/AddProviderModal.js";+import AddProviderModal, { type LlmProviderConfig } from "../options/llm/AddProviderModal.js";import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";import { editorHtmlToMarkdown } from "./chat_input_markdown.js";import { SafeImage } from "./retry_image.js";@@ -188,9 +188,6 @@ export default function ChatInputBar({&& (!chat.selectedProvider || m.provider === chat.selectedProvider)&& (!chat.selectedProviderId || m.providerId === chat.selectedProviderId));const isSelectedModel = (m: ModelOption) => m === currentModel;- // The dropdown shows exactly the models the user selected per provider (in- // provider settings). Legacy demotion happens there now, not here.- const currentModelGroups = groupModelsByProvider(chat.availableModels);// Gemini 2.x cannot combine googleSearch with function tools in a single// request. When note tools are enabled on a Gemini model we silently drop// web search server-side; reflect that here by disabling the toggle so the@@ -357,10 +354,10 @@ export default function ChatInputBar({portalToBody={inSidebar}dropdownOptions={inSidebar ? { popperConfig: { strategy: "fixed" } } : undefined}>- {currentModelGroups.map(group => (- <Fragment key={group.key}>- {group.providerName && <FormListHeader text={group.providerName} />}- {group.models.map(model => (+ {chat.modelGroups.map(group => (+ <Fragment key={group.id}>+ <FormListHeader text={group.name} />+ {group.models.length > 0 ? group.models.map(model => (<FormListItemkey={`${model.providerId ?? model.provider}:${model.id}`}onClick={() => handleModelSelect(model)}@@ -368,7 +365,13 @@ export default function ChatInputBar({>{model.name}{model.costDescription && <> <small>({model.costDescription})</small></>}</FormListItem>- ))}+ )) : (+ // Provider configured before model selection existed (or with+ // everything deselected): keep the group visible with a hint.+ <FormListItem disabled onClick={() => {}}>+ <small>{t("llm_chat.no_models_selected")}</small>+ </FormListItem>+ )}</Fragment>))}<FormDropdownDivider />@@ -443,42 +446,3 @@ export default function ChatInputBar({);}-interface ProviderModelGroup {- /** Stable key for the group (the provider config id, falling back to the type). */- key: string;- /** Group header: the user-given config name, or the provider type's friendly name. */- providerName: string;- models: ModelOption[];-}--/**- * Groups models by their owning provider config, preserving the order in which each config- * first appears — so two configs of the same type (e.g. OpenAI and a self-hosted Ollama)- * get separate groups. The user-given config name heads each group, falling back to the- * provider type's friendly name (from {@link PROVIDER_TYPES}) for older servers that don't- * report it.- */-function groupModelsByProvider(models: ModelOption[]): ProviderModelGroup[] {- const groups: ProviderModelGroup[] = [];- const byProvider = new Map<string, ProviderModelGroup>();-- for (const model of models) {- const key = model.providerId ?? model.provider ?? "";- let group = byProvider.get(key);- if (!group) {- group = {- key,- providerName: model.providerName- ?? PROVIDER_TYPES.find(p => p.id === model.provider)?.name- ?? model.provider- ?? "",- models: []- };- byProvider.set(key, group);- groups.push(group);- }- group.models.push(model);- }-- return groups;-}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsxindex 014678ff2b..cd9266aa10 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx@@ -109,6 +109,24 @@ describe("useLlmChat", () => {expect(costById.get("mini")).toBeUndefined(); // baseline cost — no annotation});+ it("groups models per provider, keeping a provider with no selected models as an empty group", async () => {+ // A config migrated from before selection existed: no selectedModels.+ optionsGetJsonMock.mockReturnValue([+ { id: "a_1", name: "Anthropic", provider: "anthropic", selectedModels: [{ id: "opus", name: "Opus" }] },+ { id: "legacy_1", name: "My OpenAI", provider: "openai" }+ ]);+ await mountChat();++ expect(api().modelGroups.map(g => [g.id, g.models.length])).toEqual([+ ["a_1", 1],+ ["legacy_1", 0] // still present so the dropdown can prompt the user to configure it+ ]);+ // A configured-but-empty provider still counts as "has provider".+ expect(api().hasProvider).toBe(true);+ // The empty group contributes no selectable models.+ expect(api().availableModels.map(m => m.id)).toEqual(["opus"]);+ });+it("sends with the provider recorded at model selection", async () => {await mountChat();await act(async () => {diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex 0977b03f09..a2a58549b8 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -78,6 +78,18 @@ export interface ModelOption extends LlmModelInfo {costDescription?: string;}+/** A configured provider and the models the user selected for it (possibly none). */+export interface ModelProviderGroup {+ /** Provider config id — stable group key. */+ id: string;+ /** User-given provider name, shown as the group header. */+ name: string;+ /** Provider type (e.g. "openai"). */+ provider: string;+ /** Selected models for this provider; empty for configs migrated from before selection existed. */+ models: ModelOption[];+}+export interface LlmChatOptions {/** Default value for enableNoteTools */defaultEnableNoteTools?: boolean;@@ -103,6 +115,8 @@ export interface UseLlmChatReturn {/** Images or files the user has attached but not yet sent. */pendingAttachments: AttachmentBlock[];availableModels: ModelOption[];+ /** Per-provider groups (including providers with no models selected yet). */+ modelGroups: ModelProviderGroup[];selectedModel: string;/** Provider type owning {@link selectedModel}; undefined until a model is picked or in pre-existing chats. */selectedProvider: string | undefined;@@ -193,6 +207,7 @@ export function useLlmChat(const [pendingCitations, setPendingCitations] = useState<LlmCitation[]>([]);const [pendingAttachments, setPendingAttachments] = useState<AttachmentBlock[]>([]);const [availableModels, setAvailableModels] = useState<ModelOption[]>([]);+ const [modelGroups, setModelGroups] = useState<ModelProviderGroup[]>([]);const [selectedModel, setSelectedModel] = useState<string>("");const [selectedProvider, setSelectedProvider] = useState<string | undefined>(undefined);const [selectedProviderId, setSelectedProviderId] = useState<string | undefined>(undefined);@@ -289,8 +304,9 @@ export function useLlmChat(// picked (with full metadata) when the provider was configured; dynamic// listing only runs in the provider-settings model picker.const refreshModels = useCallback(() => {- const { models, hasProvider } = readSelectedModels();+ const { models, groups, hasProvider } = readSelectedModels();setAvailableModels(models);+ setModelGroups(groups);setHasProvider(hasProvider);setIsCheckingProvider(false);if (!selectedModel) {@@ -884,6 +900,7 @@ export function useLlmChat(pendingCitations,pendingAttachments,availableModels,+ modelGroups,selectedModel,selectedProvider,selectedProviderId,@@ -939,26 +956,30 @@ interface StoredProviderConfig {}/**- * Flatten the user's selected models across all configured providers, tagging- * each with its owning config (provider type, id, name) and a cost description.- * `hasProvider` reflects whether any provider is configured at all, independent- * of whether it has models selected.+ * Read the user's selected models per configured provider. Returns:+ * - `groups`: one entry per configured provider (in config order), each with its+ * selected models — the group is kept even when it has none, so a provider+ * migrated from before selection existed still shows up with an empty group.+ * - `models`: the flattened list across all groups (for default selection and+ * the active-model lookup).+ * - `hasProvider`: whether any provider is configured at all.*/-function readSelectedModels(): { models: ModelOption[]; hasProvider: boolean } {+function readSelectedModels(): { models: ModelOption[]; groups: ModelProviderGroup[]; hasProvider: boolean } {const configs = (options.getJson("llmProviders") as StoredProviderConfig[] | null) ?? [];- const models: ModelOption[] = [];- for (const config of configs) {- for (const model of config.selectedModels ?? []) {- models.push({- ...model,- provider: config.provider,- providerId: config.id,- providerName: config.name,- costDescription: model.isSubscription- ? t("llm_chat.model_cost_included")- : model.costMultiplier ? `${model.costMultiplier}x` : undefined- });- }- }- return { models, hasProvider: configs.length > 0 };+ const groups: ModelProviderGroup[] = configs.map(config => ({+ id: config.id,+ name: config.name,+ provider: config.provider,+ models: (config.selectedModels ?? []).map(model => ({+ ...model,+ provider: config.provider,+ providerId: config.id,+ providerName: config.name,+ costDescription: model.isSubscription+ ? t("llm_chat.model_cost_included")+ : model.costMultiplier ? `${model.costMultiplier}x` : undefined+ }))+ }));+ const models = groups.flatMap(g => g.models);+ return { models, groups, hasProvider: configs.length > 0 };}