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
fix(llm): block sending when the selected model isn't available
Elian Doran4d717283501b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b0f7877839..96c32d1042 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3148,7 +3148,7 @@"feature_not_enabled": "Enable the LLM experimental feature in Settings → Advanced → Experimental features to use AI integrations.","add_provider": "Add Provider","add_provider_title": "Add AI Provider",- "edit_provider_title": "Edit {{name}}",+ "edit_provider_title": "Edit {{- name}}","edit_provider": "Edit","save": "Save","select_models": "Select models",@@ -3176,7 +3176,7 @@"base_url_description": "Optional. Reaches the same API through a proxy or gateway. To run a model yourself, add an Ollama or LM Studio provider instead.","base_url_invalid": "Base URL must be a valid http:// or https:// URL","claude_agent_description": "Uses your Claude Pro/Max subscription through Claude Code, so no API key is needed. Claude Code must be installed on the machine running Trilium (the server when self-hosting, or this computer on desktop); sign in once by running \"claude /login\" there.",- "add_provider_title_named": "Add {{name}}",+ "add_provider_title_named": "Add {{- name}}","provider_group_cloud": "Cloud providers","provider_group_cloud_description": "Pay per use with an API key, billed separately from any subscription you already have. Your notes are sent to the provider's servers.","provider_group_subscription": "Subscription",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex e99be52641..d35056d69c 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -19,7 +19,7 @@ import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdenimport { editorHtmlToMarkdown } from "./chat_input_markdown.js";import { SafeImage } from "./retry_image.js";import { useChatAttachments } from "./useChatAttachments.js";-import type { ModelOption, UseLlmChatReturn } from "./useLlmChat.js";+import { type ModelOption, resolveSelectedModel, type UseLlmChatReturn } from "./useLlmChat.js";const READ_ONLY_LOCK = "llm-chat-streaming";@@ -115,13 +115,14 @@ export default function ChatInputBar({// the draft state) avoids the React-render / CKEditor-change-event race that left// the editor visually populated after submit.const handleSubmit = useCallback((e: Event) => {- const willSubmit = (chat.hasInputText || chat.pendingAttachments.length > 0) && !chat.isStreaming;+ const hasResolvedModel = !!resolveSelectedModel(chat.availableModels, chat.selectedModel, chat.selectedProvider, chat.selectedProviderId);+ const willSubmit = (chat.hasInputText || chat.pendingAttachments.length > 0) && !chat.isStreaming && hasResolvedModel;baseSubmit(e);if (willSubmit) {editorApiRef.current?.setText("");editorApiRef.current?.focus();}- }, [baseSubmit, chat.hasInputText, chat.isStreaming, chat.pendingAttachments.length]);+ }, [baseSubmit, chat.hasInputText, chat.isStreaming, chat.pendingAttachments.length, chat.availableModels, chat.selectedModel, chat.selectedProvider, chat.selectedProviderId]);submitRef.current = handleSubmit;// Expose the reply-input editor to the chat hook so timeline actions (e.g. quoting a selection)@@ -200,15 +201,9 @@ export default function ChatInputBar({const isNoteContextEnabled = !!chat.contextNoteId && !!activeNoteId;- // Several providers can expose the same model ID (e.g. an Anthropic API key- // and a Claude subscription both offering "claude-sonnet-5", or two- // OpenAI-compatible endpoints), so identify the active model by its provider- // config too. Mirror the sender's resolution: prefer the recorded provider- // id/type, else fall back to the first ID match (pre-existing chats).- const currentModel = chat.availableModels.find(m =>- m.id === chat.selectedModel- && (!chat.selectedProvider || m.provider === chat.selectedProvider)- && (!chat.selectedProviderId || m.providerId === chat.selectedProviderId));+ // Identify the active model; mirrors the sender's resolution so what the UI+ // shows as selected is exactly what will be sent (see resolveSelectedModel).+ const currentModel = resolveSelectedModel(chat.availableModels, chat.selectedModel, chat.selectedProvider, chat.selectedProviderId);const isSelectedModel = (m: ModelOption) => m === currentModel;// 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@@ -473,9 +468,11 @@ export default function ChatInputBar({/><ActionButtonicon={chat.isStreaming ? "bx bx-stop" : "bx bx-send"}- text={chat.isStreaming ? t("llm_chat.stop") : t("llm_chat.send")}+ text={chat.isStreaming+ ? t("llm_chat.stop")+ : !currentModel ? t("llm_chat.no_model_selected") : t("llm_chat.send")}onClick={chat.isStreaming ? chat.stopStreaming : handleSubmit}- disabled={!chat.isStreaming && !chat.hasInputText && chat.pendingAttachments.length === 0}+ disabled={!chat.isStreaming && (!currentModel || (!chat.hasInputText && chat.pendingAttachments.length === 0))}className={`llm-chat-send-btn ${chat.isStreaming ? "llm-chat-stop-btn" : ""}`}/></div>diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex f3102cbc72..7670fd78bc 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,27 @@ export interface ModelOption extends LlmModelInfo {costDescription?: string;}+/**+ * Resolve the active model from the available list. Several providers can expose+ * the same model ID (e.g. an Anthropic API key and a Claude subscription, or two+ * OpenAI-compatible endpoints), so the recorded provider type/config id narrow+ * the match; when they're absent (chats saved before they existed) we fall back+ * to the first ID match. Returns undefined when nothing matches — e.g. a saved+ * model ID that has since been deselected — which callers treat as "no model".+ */+export function resolveSelectedModel(+ availableModels: ModelOption[],+ selectedModel: string,+ selectedProvider: string | undefined,+ selectedProviderId: string | undefined+): ModelOption | undefined {+ if (!selectedModel) return undefined;+ return availableModels.find(m =>+ m.id === selectedModel+ && (!selectedProvider || m.provider === selectedProvider)+ && (!selectedProviderId || m.providerId === selectedProviderId));+}+/** A configured provider and the models the user selected for it (possibly none). */export interface ModelProviderGroup {/** Provider config id — stable group key. */@@ -238,6 +259,8 @@ export function useLlmChat(// Refs to get fresh values in getContent (avoids stale closures)const messagesRef = useRef(messages);messagesRef.current = messages;+ const availableModelsRef = useRef(availableModels);+ availableModelsRef.current = availableModels;const selectedModelRef = useRef(selectedModel);selectedModelRef.current = selectedModel;const selectedProviderRef = useRef(selectedProvider);@@ -808,6 +831,14 @@ export function useLlmChat(const handleSubmit = useCallback(async (e: Event) => {e.preventDefault();if (isStreaming) return;+ // The picked model must resolve to one the provider actually offers.+ // A bare `selectedModel` truthiness check isn't enough: a saved chat can+ // restore a model ID that has since been deselected (so it's absent from+ // availableModels). Sending it anyway would let the server silently fall+ // back to some default, so block until an available model is chosen.+ if (!resolveSelectedModel(availableModelsRef.current, selectedModelRef.current, selectedProviderRef.current, selectedProviderIdRef.current)) {+ return;+ }const trimmedInput = inputRef.current.trim();const attachments = pendingAttachmentsRef.current;if (!trimmedInput && attachments.length === 0) return;