Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): user-curated model selection per provider

Elian Dorana85b1a405105
diff --git a/apps/client/src/services/llm_chat.spec.ts b/apps/client/src/services/llm_chat.spec.ts
index fd4666df95..02e8216c9a 100644
--- a/apps/client/src/services/llm_chat.spec.ts
+++ b/apps/client/src/services/llm_chat.spec.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { LlmChatConfig, LlmMessage } from "@triliumnext/commons";
-import { getAvailableModels, streamChatCompletion, type StreamCallbacks } from "./llm_chat.js";
+import { fetchProviderModels, streamChatCompletion, type StreamCallbacks } from "./llm_chat.js";
import server from "./server.js";
/**
@@ -48,17 +48,18 @@ function makeCallbacks(): Record<keyof StreamCallbacks, ReturnType<typeof vi.fn>
const messages: LlmMessage[] = [{ role: "user", content: "hi" }];
const config = {} as LlmChatConfig;
-describe("getAvailableModels", () => {
- it("returns the models array from the server response", async () => {
- const models = [{ name: "gpt", provider: "openai" }];
- server.get = vi.fn(async () => ({ models })) as typeof server.get;
- await expect(getAvailableModels()).resolves.toBe(models);
- expect(server.get).toHaveBeenCalledWith("llm-chat/models");
+describe("fetchProviderModels", () => {
+ it("posts the provider credentials and returns the models array", async () => {
+ const models = [{ id: "gpt-4.1", name: "gpt", provider: "openai" }];
+ server.post = vi.fn(async () => ({ models })) as typeof server.post;
+ const query = { provider: "openai", apiKey: "sk-test", baseURL: "http://localhost:11434/v1" };
+ await expect(fetchProviderModels(query)).resolves.toBe(models);
+ expect(server.post).toHaveBeenCalledWith("llm-chat/provider-models", query);
});
it("defaults to an empty array when models is absent", async () => {
- server.get = vi.fn(async () => ({})) as typeof server.get;
- await expect(getAvailableModels()).resolves.toEqual([]);
+ server.post = vi.fn(async () => ({})) as typeof server.post;
+ await expect(fetchProviderModels({ provider: "openai" })).resolves.toEqual([]);
});
});
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.ts
index e5f48094fd..7c6b4a03d0 100644
--- a/apps/client/src/services/llm_chat.ts
+++ b/apps/client/src/services/llm_chat.ts
@@ -2,11 +2,20 @@ import type { LlmChatConfig, LlmCitation, LlmMessage, LlmModelInfo,LlmUsage } fr
import server from "./server.js";
+/** Credentials describing a provider whose live model list should be fetched. */
+export interface ProviderModelsQuery {
+ provider: string;
+ apiKey?: string;
+ baseURL?: string;
+}
+
/**
- * Fetch available models from all configured providers.
+ * Fetch the live model list for a provider from its credentials. Used by the
+ * model-selection screen while adding or editing a provider — the config need
+ * not be saved yet.
*/
-export async function getAvailableModels(): Promise<LlmModelInfo[]> {
- const response = await server.get<{ models?: LlmModelInfo[] }>("llm-chat/models");
+export async function fetchProviderModels(query: ProviderModelsQuery): Promise<LlmModelInfo[]> {
+ const response = await server.post<{ models?: LlmModelInfo[] }>("llm-chat/provider-models", query);
return response.models ?? [];
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index a5cadce4eb..bf903b0b3f 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3136,6 +3136,20 @@
"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 AI Provider",
+ "edit_provider": "Edit",
+ "next": "Next",
+ "back": "Back",
+ "save": "Save",
+ "select_models": "Select models",
+ "models_loading": "Loading models…",
+ "models_load_failed": "Could not load models: {{error}}",
+ "models_none_available": "This provider returned no models.",
+ "models_selected_count": "{{count}} of {{total}} selected",
+ "models_select_all": "Select all",
+ "models_select_none": "Select none",
+ "provider_model_count_one": "{{count}} model",
+ "provider_model_count_other": "{{count}} models",
"configured_providers": "Configured Providers",
"no_providers_configured": "No providers configured yet.",
"provider_name": "Name",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index 225f094937..ff707d7d5f 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -12,7 +12,7 @@ import ActionButton from "../../react/ActionButton.js";
import Button from "../../react/Button.js";
import CKEditor, { type CKEditorApi } from "../../react/CKEditor.js";
import Dropdown from "../../react/Dropdown.js";
-import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem, FormListToggleableItem } from "../../react/FormList.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 { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";
@@ -188,10 +188,9 @@ export default function ChatInputBar({
&& (!chat.selectedProvider || m.provider === chat.selectedProvider)
&& (!chat.selectedProviderId || m.providerId === chat.selectedProviderId));
const isSelectedModel = (m: ModelOption) => m === currentModel;
- const currentModels = chat.availableModels.filter(m => !m.isLegacy);
- const currentModelGroups = groupModelsByProvider(currentModels);
- const legacyModels = chat.availableModels.filter(m => m.isLegacy);
- const legacyModelGroups = groupModelsByProvider(legacyModels);
+ // 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
@@ -372,31 +371,6 @@ export default function ChatInputBar({
))}
</Fragment>
))}
- {legacyModels.length > 0 && (
- <>
- <FormDropdownDivider />
- <FormDropdownSubmenu
- icon="bx bx-history"
- title={t("llm_chat.legacy_models")}
- dropStart={inSidebar}
- >
- {legacyModelGroups.map(group => (
- <Fragment key={group.key}>
- {group.providerName && <FormListHeader text={group.providerName} />}
- {group.models.map(model => (
- <FormListItem
- key={`${model.providerId ?? model.provider}:${model.id}`}
- onClick={() => handleModelSelect(model)}
- checked={isSelectedModel(model)}
- >
- {model.name}{model.costDescription && <> <small>({model.costDescription})</small></>}
- </FormListItem>
- ))}
- </Fragment>
- ))}
- </FormDropdownSubmenu>
- </>
- )}
<FormDropdownDivider />
<FormListToggleableItem
icon="bx bx-globe"
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.tsx
index e1765010ee..014678ff2b 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
@@ -2,13 +2,18 @@ import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const getAvailableModelsMock = vi.hoisted(() => vi.fn());
const streamChatCompletionMock = vi.hoisted(() => vi.fn());
vi.mock("../../../services/llm_chat.js", () => ({
- getAvailableModels: getAvailableModelsMock,
streamChatCompletion: streamChatCompletionMock
}));
+// The chat picker now reads the user's selected models straight from the
+// `llmProviders` option (no server fetch), so stub that service.
+const optionsGetJsonMock = vi.hoisted(() => vi.fn());
+vi.mock("../../../services/options.js", () => ({
+ default: { getJson: optionsGetJsonMock }
+}));
+
// useTriliumEvent subscribes to the app-wide event bus; stub it so the hook
// renders without the full app context.
vi.mock("../../react/hooks.js", async (importOriginal) => ({
@@ -27,10 +32,18 @@ import { useLlmChat } from "./useLlmChat.js";
type LlmChatApi = ReturnType<typeof useLlmChat>;
type LlmChatOptions = Parameters<typeof useLlmChat>[1];
-const MODELS = [
- { id: "sonnet", name: "Sonnet", provider: "claude-agent", providerId: "ca_1", isDefault: true, isSubscription: true },
- { id: "opus", name: "Opus", provider: "anthropic", providerId: "a_1", costMultiplier: 5 },
- { id: "mini", name: "Mini", provider: "openai", providerId: "o_1" }
+// Provider configs as stored in the llmProviders option; provider/providerId/
+// providerName are applied from the config when the hook flattens selectedModels.
+const PROVIDERS = [
+ { id: "ca_1", name: "Claude Code", provider: "claude-agent", selectedModels: [
+ { id: "sonnet", name: "Sonnet", isDefault: true, isSubscription: true }
+ ] },
+ { id: "a_1", name: "Anthropic", provider: "anthropic", selectedModels: [
+ { id: "opus", name: "Opus", costMultiplier: 5 }
+ ] },
+ { id: "o_1", name: "OpenAI", provider: "openai", selectedModels: [
+ { id: "mini", name: "Mini" }
+ ] }
];
describe("useLlmChat", () => {
@@ -62,7 +75,7 @@ describe("useLlmChat", () => {
}
beforeEach(() => {
- getAvailableModelsMock.mockResolvedValue(MODELS);
+ optionsGetJsonMock.mockReturnValue(PROVIDERS);
// Minimal successful stream: finish immediately with no content.
streamChatCompletionMock.mockImplementation(async (_messages, _options, callbacks) => {
callbacks.onDone();
@@ -76,7 +89,7 @@ describe("useLlmChat", () => {
host = undefined;
}
captured = undefined;
- getAvailableModelsMock.mockReset();
+ optionsGetJsonMock.mockReset();
streamChatCompletionMock.mockReset();
});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index 216674f2e5..0977b03f09 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -3,7 +3,8 @@ import { RefObject } from "preact";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
-import { getAvailableModels, streamChatCompletion } from "../../../services/llm_chat.js";
+import { streamChatCompletion } from "../../../services/llm_chat.js";
+import options from "../../../services/options.js";
import { randomString } from "../../../services/utils.js";
import { useTriliumEvent } from "../../react/hooks.js";
import { stripQuoteSources } from "./chat_quote.js";
@@ -283,30 +284,21 @@ export function useLlmChat(
setSelectedProviderId(providerId);
}, []);
- // Fetch available models on mount
+ // Read the user's selected models straight from the synced `llmProviders`
+ // option — no server round-trip, no live provider fetch. The models were
+ // picked (with full metadata) when the provider was configured; dynamic
+ // listing only runs in the provider-settings model picker.
const refreshModels = useCallback(() => {
- setIsCheckingProvider(true);
- getAvailableModels().then(models => {
- const modelsWithDescription = models.map(m => ({
- ...m,
- costDescription: m.isSubscription
- ? t("llm_chat.model_cost_included")
- : m.costMultiplier ? `${m.costMultiplier}x` : undefined
- }));
- setAvailableModels(modelsWithDescription);
- setHasProvider(models.length > 0);
- setIsCheckingProvider(false);
- if (!selectedModel) {
- const defaultModel = models.find(m => m.isDefault) || models[0];
- if (defaultModel) {
- selectModel(defaultModel.id, defaultModel.provider, defaultModel.providerId);
- }
+ const { models, hasProvider } = readSelectedModels();
+ setAvailableModels(models);
+ setHasProvider(hasProvider);
+ setIsCheckingProvider(false);
+ if (!selectedModel) {
+ const defaultModel = models.find(m => m.isDefault) || models[0];
+ if (defaultModel) {
+ selectModel(defaultModel.id, defaultModel.provider, defaultModel.providerId);
}
- }).catch(err => {
- console.error("Failed to fetch available models:", err);
- setHasProvider(false);
- setIsCheckingProvider(false);
- });
+ }
}, [selectedModel, selectModel]);
useEffect(() => {
@@ -937,3 +929,36 @@ export function useLlmChat(
regenerateLastReply
};
}
+
+/** Minimal shape of a provider config as stored in the `llmProviders` option. */
+interface StoredProviderConfig {
+ id: string;
+ name: string;
+ provider: string;
+ selectedModels?: LlmModelInfo[];
+}
+
+/**
+ * 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.
+ */
+function readSelectedModels(): { models: ModelOption[]; 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 };
+}
diff --git a/apps/client/src/widgets/type_widgets/options/llm.tsx b/apps/client/src/widgets/type_widgets/options/llm.tsx
index 749ef4544a..f5ae22082c 100644
--- a/apps/client/src/widgets/type_widgets/options/llm.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm.tsx
@@ -72,10 +72,23 @@ function ProviderSettings() {
const setProviders = useCallback((newProviders: LlmProviderConfig[]) => {
setProvidersJson(JSON.stringify(newProviders));
}, [setProvidersJson]);
- const [showAddModal, setShowAddModal] = useState(false);
-
- const handleAddProvider = useCallback((newProvider: LlmProviderConfig) => {
- setProviders([...providers, newProvider]);
+ // `undefined` while closed; the edited provider (or a fresh marker) while open.
+ // The bumping token keys the modal so it re-initializes its wizard on every open.
+ const [modalProvider, setModalProvider] = useState<LlmProviderConfig | undefined>();
+ const [modalOpen, setModalOpen] = useState(false);
+ const [openToken, setOpenToken] = useState(0);
+
+ const openModal = useCallback((provider?: LlmProviderConfig) => {
+ setModalProvider(provider);
+ setOpenToken(token => token + 1);
+ setModalOpen(true);
+ }, []);
+
+ // Upsert: editing replaces the config with the matching id, adding appends.
+ const handleSaveProvider = useCallback((saved: LlmProviderConfig) => {
+ setProviders(providers.some(p => p.id === saved.id)
+ ? providers.map(p => (p.id === saved.id ? saved : p))
+ : [...providers, saved]);
}, [providers, setProviders]);
const handleDeleteProvider = useCallback(async (providerId: string, providerName: string) => {
@@ -89,6 +102,7 @@ function ProviderSettings() {
<OptionsSection title={t("llm.configured_providers")}>
<ProviderList
providers={providers}
+ onEdit={openModal}
onDelete={handleDeleteProvider}
/>
@@ -97,14 +111,16 @@ function ProviderSettings() {
name="add-llm-provider-button"
size="micro" icon="bx bx-plus"
text={t("llm.add_provider")}
- onClick={() => setShowAddModal(true)}
+ onClick={() => openModal()}
/>
</OptionsRow>
<AddProviderModal
- show={showAddModal}
- onHidden={() => setShowAddModal(false)}
- onSave={handleAddProvider}
+ key={openToken}
+ show={modalOpen}
+ existingProvider={modalProvider}
+ onHidden={() => setModalOpen(false)}
+ onSave={handleSaveProvider}
/>
</OptionsSection>
);
@@ -150,10 +166,11 @@ function McpSettings() {
interface ProviderListProps {
providers: LlmProviderConfig[];
+ onEdit: (provider: LlmProviderConfig) => void;
onDelete: (providerId: string, providerName: string) => Promise<void>;
}
-function ProviderList({ providers, onDelete }: ProviderListProps) {
+function ProviderList({ providers, onEdit, onDelete }: ProviderListProps) {
if (!providers.length) {
return <NoItems icon="bx bx-bot" text={t("llm.no_providers_configured")} />;
}
@@ -161,6 +178,7 @@ function ProviderList({ providers, onDelete }: ProviderListProps) {
return <>
{providers.map((provider) => {
const providerType = PROVIDER_TYPES.find(p => p.id === provider.provider);
+ const modelCount = provider.selectedModels?.length ?? 0;
return (
<OptionsRow
key={provider.id}
@@ -171,13 +189,22 @@ function ProviderList({ providers, onDelete }: ProviderListProps) {
{provider.name}
</span>
}
- description={providerType?.name || provider.provider}
+ description={modelCount > 0
+ ? t("llm.provider_model_count", { count: modelCount })
+ : providerType?.name || provider.provider}
>
- <ActionButton
- icon="bx bx-trash"
- text={t("llm.delete_provider")}
- onClick={() => onDelete(provider.id, provider.name)}
- />
+ <>
+ <ActionButton
+ icon="bx bx-edit"
+ text={t("llm.edit_provider")}
+ onClick={() => onEdit(provider)}
+ />
+ <ActionButton
+ icon="bx bx-trash"
+ text={t("llm.delete_provider")}
+ onClick={() => onDelete(provider.id, provider.name)}
+ />
+ </>
</OptionsRow>
);
})}
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
index b9191b301f..ec87aa5e25 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
@@ -1,5 +1,6 @@
import "./AddProviderModal.css";
+import type { LlmModelInfo } from "@triliumnext/commons";
import { createPortal } from "preact/compat";
import { useMemo, useRef, useState } from "preact/hooks";
@@ -14,6 +15,7 @@ import anthropicIcon from "./icons/anthropic.svg?url";
import claudeAgentIcon from "./icons/claude-ai.svg?url";
import geminiIcon from "./icons/gemini.svg?url";
import openaiIcon from "./icons/openai.svg?url";
+import ModelSelection from "./ModelSelection";
export interface LlmProviderConfig {
id: string;
@@ -21,6 +23,8 @@ export interface LlmProviderConfig {
provider: string;
apiKey: string;
baseURL?: string;
+ /** Models the user selected for this provider, with full metadata for offline rendering. */
+ selectedModels?: LlmModelInfo[];
}
export interface ProviderType {
@@ -63,12 +67,18 @@ interface AddProviderModalProps {
show: boolean;
onHidden: () => void;
onSave: (provider: LlmProviderConfig) => void;
+ /** When provided, the modal edits this provider in place instead of adding a new one. */
+ existingProvider?: LlmProviderConfig;
}
-export default function AddProviderModal({ show, onHidden, onSave }: AddProviderModalProps) {
- const [selectedProvider, setSelectedProvider] = useState(PROVIDER_TYPES[0].id);
- const [apiKey, setApiKey] = useState("");
- const [baseUrl, setBaseUrl] = useState("");
+export default function AddProviderModal({ show, onHidden, onSave, existingProvider }: AddProviderModalProps) {
+ const isEdit = !!existingProvider;
+ // Connection details first, then model selection. Editing keeps the same two steps.
+ const [step, setStep] = useState<1 | 2>(1);
+ const [selectedProvider, setSelectedProvider] = useState(existingProvider?.provider ?? PROVIDER_TYPES[0].id);
+ const [apiKey, setApiKey] = useState(existingProvider?.apiKey ?? "");
+ const [baseUrl, setBaseUrl] = useState(existingProvider?.baseURL ?? "");
+ const [selectedModels, setSelectedModels] = useState<LlmModelInfo[]>(existingProvider?.selectedModels ?? []);
const formRef = useRef<HTMLFormElement>(null);
const providerType = useMemo(
@@ -76,38 +86,56 @@ export default function AddProviderModal({ show, onHidden, onSave }: AddProvider
[selectedProvider]
);
const usesApiKey = providerType?.usesApiKey !== false;
+ const trimmedApiKey = apiKey.trim();
const trimmedBaseUrl = baseUrl.trim();
const baseUrlIsValid = isValidBaseUrl(trimmedBaseUrl);
- const canSubmit = usesApiKey ? !!apiKey.trim() && baseUrlIsValid : true;
+ const connectionValid = usesApiKey ? !!trimmedApiKey && baseUrlIsValid : true;
+
+ const modelQuery = useMemo(
+ () => ({ provider: selectedProvider, apiKey: trimmedApiKey, baseURL: trimmedBaseUrl || undefined }),
+ [selectedProvider, trimmedApiKey, trimmedBaseUrl]
+ );
+
+ function reset() {
+ setStep(1);
+ setSelectedProvider(existingProvider?.provider ?? PROVIDER_TYPES[0].id);
+ setApiKey(existingProvider?.apiKey ?? "");
+ setBaseUrl(existingProvider?.baseURL ?? "");
+ setSelectedModels(existingProvider?.selectedModels ?? []);
+ }
+
+ function handleCancel() {
+ reset();
+ onHidden();
+ }
function handleSubmit() {
- if (!canSubmit) {
+ if (step === 1) {
+ if (connectionValid) {
+ setStep(2);
+ }
return;
}
- const newProvider: LlmProviderConfig = {
- id: `${selectedProvider}_${Date.now()}`,
+ const saved: LlmProviderConfig = {
+ id: existingProvider?.id ?? `${selectedProvider}_${Date.now()}`,
name: providerType?.name || selectedProvider,
provider: selectedProvider,
- apiKey: usesApiKey ? apiKey.trim() : "",
- ...(usesApiKey && trimmedBaseUrl && { baseURL: trimmedBaseUrl })
+ apiKey: usesApiKey ? trimmedApiKey : "",
+ ...(usesApiKey && trimmedBaseUrl && { baseURL: trimmedBaseUrl }),
+ selectedModels
};
- onSave(newProvider);
- resetForm();
+ onSave(saved);
+ reset();
onHidden();
}
- function resetForm() {
- setSelectedProvider(PROVIDER_TYPES[0].id);
- setApiKey("");
- setBaseUrl("");
- }
-
- function handleCancel() {
- resetForm();
- onHidden();
- }
+ const title = isEdit ? t("llm.edit_provider_title") : t("llm.add_provider_title");
+ const primaryLabel = step === 1
+ ? t("llm.next")
+ : isEdit ? t("llm.save") : t("llm.add_provider");
+ const primaryDisabled = step === 1 ? !connectionValid : selectedModels.length === 0;
return createPortal(
<Modal
@@ -115,78 +143,95 @@ export default function AddProviderModal({ show, onHidden, onSave }: AddProvider
onHidden={handleCancel}
onSubmit={handleSubmit}
formRef={formRef}
- title={t("llm.add_provider_title")}
+ title={title}
className="add-provider-modal"
size="md"
maxWidth={600}
stackable
footer={
<>
- <button type="button" className="btn btn-secondary" onClick={handleCancel}>
- {t("llm.cancel")}
+ <button type="button" className="btn btn-secondary" onClick={step === 2 ? () => setStep(1) : handleCancel}>
+ {step === 2 ? t("llm.back") : t("llm.cancel")}
</button>
- <button type="submit" className="btn btn-primary" disabled={!canSubmit}>
- {t("llm.add_provider")}
+ <button type="submit" className="btn btn-primary" disabled={primaryDisabled}>
+ {primaryLabel}
</button>
</>
}
>
- <Card heading={t("llm.provider_type")}>
- <CardSection>
- <SelectableCardGrid columns={2}>
- {PROVIDER_TYPES.map((provider) => (
- <SelectableCard
- key={provider.id}
- iconUrl={provider.iconUrl}
- title={provider.beta
- ? <span className="add-provider-card-heading">{provider.name}<Badge text={t("llm.beta")} className="add-provider-beta-badge" outline /></span>
- : provider.name}
- description={provider.description}
- selected={selectedProvider === provider.id}
- onSelect={() => setSelectedProvider(provider.id)}
- />
- ))}
- </SelectableCardGrid>
- </CardSection>
- </Card>
-
- <Card heading={t("llm.connection_details")}>
- <CardSection>
- {usesApiKey ? (
- <FormGroup name="api-key" label={t("llm.api_key")}>
- <FormTextBox
- type="password"
- currentValue={apiKey}
- onChange={setApiKey}
- placeholder={t("llm.api_key_placeholder")}
- autoFocus
- />
- </FormGroup>
- ) : (
- <p>{t("llm.claude_agent_description")}</p>
+ {step === 1 ? (
+ <>
+ {!isEdit && (
+ <Card heading={t("llm.provider_type")}>
+ <CardSection>
+ <SelectableCardGrid columns={2}>
+ {PROVIDER_TYPES.map((provider) => (
+ <SelectableCard
+ key={provider.id}
+ iconUrl={provider.iconUrl}
+ title={provider.beta
+ ? <span className="add-provider-card-heading">{provider.name}<Badge text={t("llm.beta")} className="add-provider-beta-badge" outline /></span>
+ : provider.name}
+ description={provider.description}
+ selected={selectedProvider === provider.id}
+ onSelect={() => setSelectedProvider(provider.id)}
+ />
+ ))}
+ </SelectableCardGrid>
+ </CardSection>
+ </Card>
)}
- </CardSection>
- </Card>
- {usesApiKey && (
- <Card heading={t("llm.advanced_options")}>
+ <Card heading={t("llm.connection_details")}>
+ <CardSection>
+ {usesApiKey ? (
+ <FormGroup name="api-key" label={t("llm.api_key")}>
+ <FormTextBox
+ type="password"
+ currentValue={apiKey}
+ onChange={setApiKey}
+ placeholder={t("llm.api_key_placeholder")}
+ autoFocus
+ />
+ </FormGroup>
+ ) : (
+ <p>{t("llm.claude_agent_description")}</p>
+ )}
+ </CardSection>
+ </Card>
+
+ {usesApiKey && (
+ <Card heading={t("llm.advanced_options")}>
+ <CardSection>
+ <FormGroup
+ name="base-url"
+ label={t("llm.base_url")}
+ description={
+ !baseUrlIsValid
+ ? <span className="text-danger">{t("llm.base_url_invalid")}</span>
+ : t("llm.base_url_description")
+ }
+ >
+ <FormTextBox
+ type="text"
+ currentValue={baseUrl}
+ onChange={setBaseUrl}
+ placeholder={providerType?.defaultBaseUrl}
+ />
+ </FormGroup>
+ </CardSection>
+ </Card>
+ )}
+ </>
+ ) : (
+ <Card heading={t("llm.select_models")}>
<CardSection>
- <FormGroup
- name="base-url"
- label={t("llm.base_url")}
- description={
- !baseUrlIsValid
- ? <span className="text-danger">{t("llm.base_url_invalid")}</span>
- : t("llm.base_url_description")
- }
- >
- <FormTextBox
- type="text"
- currentValue={baseUrl}
- onChange={setBaseUrl}
- placeholder={providerType?.defaultBaseUrl}
- />
- </FormGroup>
+ <ModelSelection
+ query={modelQuery}
+ selected={selectedModels}
+ onChange={setSelectedModels}
+ autoSelectDefaults
+ />
</CardSection>
</Card>
)}
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css
new file mode 100644
index 0000000000..8cb31b1cb6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css
@@ -0,0 +1,40 @@
+.model-selection-status {
+ padding: 1em;
+ text-align: center;
+ color: var(--muted-text-color);
+}
+
+.model-selection-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.5em;
+ margin-bottom: 0.5em;
+}
+
+.model-selection-count {
+ color: var(--muted-text-color);
+ font-size: 0.9em;
+}
+
+.model-selection-list {
+ max-height: 40vh;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0.25em;
+}
+
+.model-selection-label {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+}
+
+.model-selection-cost {
+ color: var(--muted-text-color);
+}
+
+.model-selection-legacy-badge {
+ --color: var(--muted-text-color);
+}
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
new file mode 100644
index 0000000000..8cfea478a2
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
@@ -0,0 +1,108 @@
+import type { LlmModelInfo } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fetchProviderModelsMock = vi.hoisted(() => vi.fn());
+vi.mock("../../../../services/llm_chat", () => ({
+ fetchProviderModels: fetchProviderModelsMock
+}));
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// A lightweight checkbox that records its onChange so we can toggle it directly.
+const checkboxHandlers = new Map<string, (checked: boolean) => void>();
+vi.mock("../../../react/FormCheckbox", () => ({
+ default: ({ name, currentValue, onChange }: { name?: string; currentValue: boolean; onChange: (c: boolean) => void }) => {
+ checkboxHandlers.set(name ?? "", onChange);
+ return <div className="checkbox-stub" data-name={name} data-checked={String(currentValue)} />;
+ }
+}));
+
+import ModelSelection from "./ModelSelection";
+
+const MODELS: LlmModelInfo[] = [
+ { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true, costMultiplier: 1 },
+ { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, isLegacy: true, costMultiplier: 1.2 },
+ { id: "custom", name: "Custom" }
+];
+
+let container: HTMLDivElement | undefined;
+
+async function renderSelection(props: Parameters<typeof ModelSelection>[0]) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ const target = container;
+ await act(async () => { render(<ModelSelection {...props} />, target); });
+ // Flush the fetch promise + the state updates it schedules.
+ await act(async () => {});
+}
+
+describe("ModelSelection", () => {
+ beforeEach(() => {
+ fetchProviderModelsMock.mockResolvedValue(MODELS);
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ checkboxHandlers.clear();
+ fetchProviderModelsMock.mockReset();
+ });
+
+ it("fetches the provider's models and renders one checkbox per model", async () => {
+ const query = { provider: "openai", apiKey: "sk-test", baseURL: "http://x/v1" };
+ await renderSelection({ query, selected: MODELS, onChange: vi.fn() });
+
+ expect(fetchProviderModelsMock).toHaveBeenCalledWith(query);
+ const names = [...container!.querySelectorAll(".checkbox-stub")].map(el => el.getAttribute("data-name"));
+ expect(names).toEqual(["model-gpt-4.1", "model-gpt-4o", "model-custom"]);
+ });
+
+ it("auto-selects only non-legacy models when nothing is selected yet", async () => {
+ const onChange = vi.fn();
+ await renderSelection({ query: { provider: "openai" }, selected: [], onChange, autoSelectDefaults: true });
+ expect(onChange).toHaveBeenCalledWith([MODELS[0], MODELS[2]]); // gpt-4o (legacy) excluded
+ });
+
+ it("does not auto-select when a selection already exists", async () => {
+ const onChange = vi.fn();
+ await renderSelection({ query: { provider: "openai" }, selected: [MODELS[0]], onChange, autoSelectDefaults: true });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("toggling a checkbox adds or removes that model", async () => {
+ const onChange = vi.fn();
+ await renderSelection({ query: { provider: "openai" }, selected: [MODELS[0]], onChange });
+
+ act(() => checkboxHandlers.get("model-custom")?.(true));
+ expect(onChange).toHaveBeenLastCalledWith([MODELS[0], MODELS[2]]);
+
+ act(() => checkboxHandlers.get("model-gpt-4.1")?.(false));
+ expect(onChange).toHaveBeenLastCalledWith([]);
+ });
+
+ it("select-all / select-none toggles the whole list", async () => {
+ const onChange = vi.fn();
+ await renderSelection({ query: { provider: "openai" }, selected: [], onChange });
+
+ const button = container!.querySelector("button") as HTMLButtonElement;
+ act(() => button.click());
+ expect(onChange).toHaveBeenLastCalledWith(MODELS);
+ });
+
+ it("renders an error state when the fetch fails", async () => {
+ fetchProviderModelsMock.mockRejectedValue(new Error("bad key"));
+ await renderSelection({ query: { provider: "openai" }, selected: [], onChange: vi.fn() });
+ expect(container!.textContent).toContain("llm.models_load_failed");
+ });
+
+ it("renders an empty state when the provider returns no models", async () => {
+ fetchProviderModelsMock.mockResolvedValue([]);
+ await renderSelection({ query: { provider: "openai" }, selected: [], onChange: vi.fn() });
+ expect(container!.textContent).toContain("llm.models_none_available");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
new file mode 100644
index 0000000000..ce2e142905
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
@@ -0,0 +1,116 @@
+import "./ModelSelection.css";
+
+import type { LlmModelInfo } from "@triliumnext/commons";
+import { useCallback, useEffect, useState } from "preact/hooks";
+
+import { t } from "../../../../services/i18n";
+import { fetchProviderModels, type ProviderModelsQuery } from "../../../../services/llm_chat";
+import { Badge } from "../../../react/Badge";
+import FormCheckbox from "../../../react/FormCheckbox";
+import NoItems from "../../../react/NoItems";
+
+interface ModelSelectionProps {
+ /** Credentials describing the provider whose models should be listed. */
+ query: ProviderModelsQuery;
+ /** Currently selected models (full metadata), controlled by the parent. */
+ selected: LlmModelInfo[];
+ onChange: (selected: LlmModelInfo[]) => void;
+ /**
+ * When true, pre-select the non-legacy models on the first successful fetch
+ * if nothing is selected yet — seeds a sensible default for a fresh provider.
+ */
+ autoSelectDefaults?: boolean;
+}
+
+/**
+ * Fetches a provider's live model list and lets the user pick which models to
+ * keep. The picked set (with full metadata) is what the chat picker later shows,
+ * so no live fetch is needed during normal chatting.
+ */
+export default function ModelSelection({ query, selected, onChange, autoSelectDefaults }: ModelSelectionProps) {
+ const [models, setModels] = useState<LlmModelInfo[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | undefined>();
+
+ // Refetch whenever the provider credentials change. A stale-guard flag drops
+ // the result of a superseded request so a slow earlier fetch can't overwrite
+ // a newer one.
+ useEffect(() => {
+ let active = true;
+ setLoading(true);
+ setError(undefined);
+ fetchProviderModels(query)
+ .then(fetched => {
+ if (!active) return;
+ setModels(fetched);
+ setLoading(false);
+ if (autoSelectDefaults && selected.length === 0 && fetched.length > 0) {
+ onChange(fetched.filter(m => !m.isLegacy));
+ }
+ })
+ .catch(err => {
+ if (!active) return;
+ setError(err instanceof Error ? err.message : String(err));
+ setLoading(false);
+ });
+ return () => { active = false; };
+ // selected/onChange intentionally excluded: refetch tracks credentials only.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [query.provider, query.apiKey, query.baseURL]);
+
+ const isSelected = useCallback((model: LlmModelInfo) => selected.some(s => s.id === model.id), [selected]);
+
+ const toggle = useCallback((model: LlmModelInfo, checked: boolean) => {
+ onChange(checked
+ ? [...selected, model]
+ : selected.filter(s => s.id !== model.id));
+ }, [selected, onChange]);
+
+ if (loading) {
+ return <div className="model-selection-status">{t("llm.models_loading")}</div>;
+ }
+ if (error) {
+ return <NoItems icon="bx bx-error-circle" text={t("llm.models_load_failed", { error })} />;
+ }
+ if (models.length === 0) {
+ return <NoItems icon="bx bx-bot" text={t("llm.models_none_available")} />;
+ }
+
+ const allSelected = models.every(isSelected);
+
+ return (
+ <div className="model-selection">
+ <div className="model-selection-toolbar">
+ <span className="model-selection-count">{t("llm.models_selected_count", { count: selected.length, total: models.length })}</span>
+ <button type="button" className="btn btn-sm btn-secondary" onClick={() => onChange(allSelected ? [] : [...models])}>
+ {allSelected ? t("llm.models_select_none") : t("llm.models_select_all")}
+ </button>
+ </div>
+ <div className="model-selection-list">
+ {models.map(model => (
+ <FormCheckbox
+ key={model.id}
+ name={`model-${model.id}`}
+ currentValue={isSelected(model)}
+ onChange={checked => toggle(model, checked)}
+ label={<ModelLabel model={model} />}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** Row label: model name plus curated hints (cost, legacy) when available. */
+function ModelLabel({ model }: { model: LlmModelInfo }) {
+ const cost = model.isSubscription
+ ? t("llm_chat.model_cost_included")
+ : model.costMultiplier ? `${model.costMultiplier}x` : undefined;
+ return (
+ <span className="model-selection-label">
+ <span className="model-selection-name">{model.name}</span>
+ {cost && <small className="model-selection-cost">({cost})</small>}
+ {model.isLegacy && <Badge text={t("llm_chat.legacy_models")} className="model-selection-legacy-badge" outline />}
+ </span>
+ );
+}
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
index 319f08f928..ce564c0462 100644
--- a/apps/server/src/routes/api/llm_chat.spec.ts
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -13,7 +13,9 @@ const state = vi.hoisted(() => ({
chunkSignal: undefined as AbortSignal | undefined,
// Records how streamChat resolved the provider.
providerIdRequested: undefined as string | undefined,
- providerTypeRequested: undefined as string | undefined
+ providerTypeRequested: undefined as string | undefined,
+ // Records the credentials passed to listProviderModels by the provider-models route.
+ providerModelsArgs: undefined as unknown[] | undefined
}));
vi.mock("../../services/llm/index.js", () => {
@@ -30,7 +32,8 @@ vi.mock("../../services/llm/index.js", () => {
});
return {
hasConfiguredProviders: () => state.configured,
- getAllModels: async () => state.models,
+ listProviderModels: async (...args: unknown[]) => { state.providerModelsArgs = args; return state.models; },
+ getSelectedModel: () => undefined,
getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
};
@@ -83,20 +86,29 @@ describe("LLM chat API", () => {
chunkNative: false,
chunkSignal: undefined,
providerIdRequested: undefined,
- providerTypeRequested: undefined
+ providerTypeRequested: undefined,
+ providerModelsArgs: undefined
});
generateChatTitle.mockClear();
});
- describe("getModels", () => {
- it("returns no models when no provider is configured", async () => {
- state.configured = false;
- await expect(llmChatRoute.getModels({} as Request, {} as Response)).resolves.toEqual({ models: [] });
+ describe("getProviderModels", () => {
+ it("lists models for the credentials in the request body", async () => {
+ state.models = [{ id: "m1" }];
+ const req = { body: { provider: "openai", apiKey: "sk-test", baseURL: "http://localhost:11434/v1" } } as unknown as Request;
+ await expect(llmChatRoute.getProviderModels(req, {} as Response)).resolves.toEqual({ models: [{ id: "m1" }] });
+ expect(state.providerModelsArgs).toEqual(["openai", "sk-test", "http://localhost:11434/v1"]);
});
- it("returns all models when configured", async () => {
- state.models = [{ id: "m1" }];
- await expect(llmChatRoute.getModels({} as Request, {} as Response)).resolves.toEqual({ models: [{ id: "m1" }] });
+ it("throws when no provider is given", async () => {
+ const req = { body: {} } as unknown as Request;
+ await expect(llmChatRoute.getProviderModels(req, {} as Response)).rejects.toThrow(/provider is required/);
+ });
+
+ it("defaults a missing apiKey to an empty string", async () => {
+ const req = { body: { provider: "claude-agent" } } as unknown as Request;
+ await llmChatRoute.getProviderModels(req, {} as Response);
+ expect(state.providerModelsArgs).toEqual(["claude-agent", "", undefined]);
});
});
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index 8264e245a4..ab9b1c5995 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -3,7 +3,7 @@ import { getLog } from "@triliumnext/core";
import type { Request, Response } from "express";
import { generateChatTitle } from "../../services/llm/chat_title.js";
-import { getAllModels, getProvider, getProviderByType, hasConfiguredProviders, type LlmProviderConfig } from "../../services/llm/index.js";
+import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, listProviderModels, type LlmProviderConfig } from "../../services/llm/index.js";
import { streamToChunks } from "../../services/llm/stream.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";
@@ -64,8 +64,14 @@ async function streamChat(req: Request, res: Response) {
return;
}
- const pricing = provider.getModelPricing(modelId);
- const modelDisplayName = provider.getAvailableModels().find(m => m.id === modelId)?.name || modelId;
+ // Prefer the config's stored selection for name/pricing — it carries the
+ // denormalized metadata even for dynamically discovered models the curated
+ // list doesn't know. Fall back to the provider's curated list, then the id.
+ const selectedModel = getSelectedModel(config.providerId, modelId);
+ const pricing = selectedModel?.pricing ?? provider.getModelPricing(modelId);
+ const modelDisplayName = selectedModel?.name
+ ?? provider.getAvailableModels().find(m => m.id === modelId)?.name
+ ?? modelId;
let chunks: AsyncIterable<LlmStreamChunk>;
if (provider.chatChunks) {
@@ -116,20 +122,26 @@ async function streamChat(req: Request, res: Response) {
}
}
+interface ProviderModelsRequest {
+ provider: string;
+ apiKey?: string;
+ baseURL?: string;
+}
+
/**
- * Get available models from all configured providers. Providers that support
- * dynamic listing are queried live (with server-side caching); the rest report
- * their curated list.
+ * List the live models for a provider described by raw credentials. Used by the
+ * model-selection screen while adding or editing a provider — the config need
+ * not be saved yet, so credentials come in the request body rather than by id.
*/
-async function getModels(_req: Request, _res: Response) {
- if (!hasConfiguredProviders()) {
- return { models: [] };
+async function getProviderModels(req: Request, _res: Response) {
+ const { provider, apiKey, baseURL } = req.body as ProviderModelsRequest;
+ if (!provider) {
+ throw new Error("provider is required");
}
-
- return { models: await getAllModels() };
+ return { models: await listProviderModels(provider, apiKey ?? "", baseURL) };
}
export default {
streamChat,
- getModels
+ getProviderModels
};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index b10608f149..94fd376788 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -173,7 +173,7 @@ function register(app: express.Application) {
// LLM chat endpoints
asyncRoute(PST, "/api/llm-chat/stream", [auth.checkApiAuthOrElectron, csrfMiddleware], llmChatRoute.streamChat, null);
- asyncApiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);
+ asyncApiRoute(PST, "/api/llm-chat/provider-models", llmChatRoute.getProviderModels);
// no CSRF since this is called from android app
asyncRoute(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.ts
index be515ea1b2..fb07fb1237 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@ -34,10 +34,11 @@ vi.mock("./providers/claude_agent.js", () => ({ ClaudeAgentProvider: makeProvide
import {
clearProviderCache,
- getAllModels,
getProvider,
getProviderByType,
- hasConfiguredProviders
+ getSelectedModel,
+ hasConfiguredProviders,
+ listProviderModels
} from "./index.js";
function setProviders(configs: unknown) {
@@ -149,52 +150,33 @@ describe("llm/index provider registry", () => {
});
});
- describe("getAllModels", () => {
- it("aggregates models across providers, tagged with type and config id/name", async () => {
- setProviders(TWO);
- const models = await getAllModels();
- expect(models).toEqual([
- { id: "anthropic-model", name: "anthropic Model", provider: "anthropic", providerId: "a1", providerName: "My Claude" },
- { id: "openai-model", name: "openai Model", provider: "openai", providerId: "o1", providerName: "My GPT" }
- ]);
+ describe("listProviderModels", () => {
+ it("lists models for ad-hoc credentials, falling back to the curated list", async () => {
+ // No saved config needed — the add/edit flow passes raw credentials.
+ const models = await listProviderModels("openai", "sk-test", "http://localhost:11434/v1");
+ expect(models).toEqual([{ id: "openai-model", name: "openai Model" }]);
});
- it("lists every config separately, even two of the same type", async () => {
- // e.g. a real OpenAI key plus a self-hosted Ollama endpoint.
- setProviders([
- { id: "o1", name: "OpenAI", provider: "openai", apiKey: "k1" },
- { id: "o2", name: "My Ollama", provider: "openai", apiKey: "k2", baseURL: "http://localhost:11434/v1" }
- ]);
- const models = await getAllModels();
- expect(models.map(m => [m.providerId, m.providerName])).toEqual([
- ["o1", "OpenAI"],
- ["o2", "My Ollama"]
- ]);
+ it("throws for an unknown provider type", async () => {
+ await expect(listProviderModels("mystery", "k")).rejects.toThrow(/Unknown LLM provider type: mystery/);
});
+ });
- it("prefers dynamic listModels() when the provider implements it", async () => {
- setProviders(TWO);
- const provider = getProvider("a1") as { listModels?: () => Promise<unknown> };
- provider.listModels = vi.fn().mockResolvedValue([{ id: "dyn-model", name: "Dynamic Model" }]);
- const models = await getAllModels();
- expect(models[0]).toEqual({
- id: "dyn-model",
- name: "Dynamic Model",
- provider: "anthropic",
- providerId: "a1",
- providerName: "My Claude"
- });
- });
-
- it("skips and logs a provider whose model lookup throws, keeping the rest", async () => {
+ describe("getSelectedModel", () => {
+ it("finds a stored selected model by config id and model id", () => {
setProviders([
- { id: "x", name: "X", provider: "mystery", apiKey: "k" },
- { id: "o1", name: "My GPT", provider: "openai", apiKey: "k2" }
+ { id: "o1", name: "My GPT", provider: "openai", apiKey: "k", selectedModels: [
+ { id: "gpt-9", name: "GPT-9", pricing: { input: 1, output: 2 } }
+ ] }
]);
- // Unknown type → getProvider throws inside getAllModels and is caught.
- const models = await getAllModels();
- expect(models.map(m => m.providerId)).toEqual(["o1"]);
- expect(errorMock).toHaveBeenCalled();
+ expect(getSelectedModel("o1", "gpt-9")).toMatchObject({ name: "GPT-9", pricing: { input: 1, output: 2 } });
+ });
+
+ it("returns undefined for a missing provider, model, or providerId", () => {
+ setProviders([{ id: "o1", name: "My GPT", provider: "openai", apiKey: "k", selectedModels: [{ id: "gpt-9", name: "GPT-9" }] }]);
+ expect(getSelectedModel("o1", "absent")).toBeUndefined();
+ expect(getSelectedModel("nope", "gpt-9")).toBeUndefined();
+ expect(getSelectedModel(undefined, "gpt-9")).toBeUndefined();
});
});
});
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index 895a759a78..00f71721f8 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -17,6 +17,12 @@ export interface LlmProviderSetup {
apiKey: string;
/** Optional override for the SDK's default API endpoint (e.g. for self-hosted Ollama, vLLM, or proxies). */
baseURL?: string;
+ /**
+ * Models the user selected for this provider, with full metadata denormalized
+ * so the chat picker renders them without a live fetch. Absent in configs
+ * saved before model selection existed.
+ */
+ selectedModels?: ModelInfo[];
}
/** Factory functions for creating provider instances */
@@ -117,33 +123,33 @@ export function hasConfiguredProviders(): boolean {
}
/**
- * Get all models from every configured provider instance, tagged with the
- * provider type and the owning config's id/name. Each config is listed
- * separately (not deduped by type) so e.g. a real OpenAI key and a self-hosted
- * Ollama endpoint each contribute their own models. Providers that support
- * dynamic listing are queried live (in parallel); the rest — and any provider
- * whose lookup fails — contribute their curated list or are skipped.
+ * List the models available for a provider described by raw credentials —
+ * used by the model-selection screen during the add/edit flow, where the
+ * provider config isn't necessarily persisted yet. Instantiates the provider
+ * ad-hoc (bypassing the config cache) and queries it live, falling back to its
+ * curated list when it doesn't support dynamic listing.
*/
-export async function getAllModels(): Promise<ModelInfo[]> {
- const configs = getConfiguredProviders();
-
- const modelsPerConfig = await Promise.all(configs.map(async config => {
- try {
- const provider = getProvider(config.id);
- const models = await (provider.listModels?.() ?? provider.getAvailableModels());
- return models.map(model => ({
- ...model,
- provider: config.provider,
- providerId: config.id,
- providerName: config.name
- }));
- } catch (e) {
- getLog().error(`Failed to get models from provider ${config.provider} (${config.id}): ${e}`);
- return [];
- }
- }));
+export async function listProviderModels(provider: string, apiKey: string, baseURL?: string): Promise<ModelInfo[]> {
+ const factory = providerFactories[provider];
+ if (!factory) {
+ throw new Error(`Unknown LLM provider type: ${provider}. Available: ${Object.keys(providerFactories).join(", ")}`);
+ }
+ const instance = factory(apiKey, baseURL);
+ return await (instance.listModels?.() ?? instance.getAvailableModels());
+}
- return modelsPerConfig.flat();
+/**
+ * Find the model a chat is targeting within its provider config's stored
+ * selection — the denormalized source of display name and pricing for the
+ * response's usage/cost, working even for dynamically discovered models the
+ * curated list doesn't know. Returns undefined when the model isn't stored.
+ */
+export function getSelectedModel(providerId: string | undefined, modelId: string): ModelInfo | undefined {
+ if (!providerId) {
+ return undefined;
+ }
+ const config = getConfiguredProviders().find(c => c.id === providerId);
+ return config?.selectedModels?.find(m => m.id === modelId);
}
/**