Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): generalize the Ollama provider to any self-hosted endpoint

Elian Doran0cf3536ee79b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 187cce48c5..2163ce2463 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3175,6 +3175,16 @@
"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.",
"provider_desc_ollama": "Local models via an Ollama instance. No API key needed — just the instance URL.",
+ "provider_desc_lmstudio": "Local models via LM Studio's built-in server. No API key needed — just the server URL.",
+ "provider_openai_compatible": "OpenAI-compatible",
+ "provider_desc_openai_compatible": "Any self-hosted endpoint speaking the OpenAI API — llama.cpp, vLLM, LocalAI, Jan, LiteLLM and others.",
+ "api_key_optional_description": "Optional. Only needed if your endpoint is behind an authenticating proxy or gateway.",
+ "setup_hint_ollama": "Ollama must be running on this address — start it with <Code>ollama serve</Code> if it isn't.",
+ "setup_hint_lmstudio": "Start the server in LM Studio under the Developer tab, then check the port shown there matches this address.",
+ "setup_hint_openai_compatible": "The address of your server's OpenAI-compatible API, usually ending in <Code>/v1</Code>.",
+ "troubleshoot_server_running": "Is the server running on the machine you expect?",
+ "troubleshoot_port": "Does the port in the URL match the one the server reports?",
+ "troubleshoot_remote": "If the server is on another machine, is it configured to accept connections from the network rather than localhost only?",
"cancel": "Cancel",
"mcp_title": "MCP (Model Context Protocol)",
"mcp_enabled": "MCP server",
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
new file mode 100644
index 0000000000..eb2a70ab21
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+import { prefilledBaseUrl, PROVIDER_TYPES } from "./AddProviderModal";
+
+/** Card ids are persisted in the llmProviders option, so they double as an API. */
+const SELF_HOSTED = ["ollama", "lmstudio", "openai-compatible"];
+
+describe("AddProviderModal provider cards", () => {
+ it("prefills an endpoint for self-hosted providers only", () => {
+ // The port is the one detail a self-hosted user must get right, and it
+ // differs per runtime — whereas prefilling a vendor endpoint would store
+ // a redundant override on every provider the user adds.
+ expect(prefilledBaseUrl("ollama")).toBe("http://localhost:11434");
+ expect(prefilledBaseUrl("lmstudio")).toBe("http://localhost:1234/v1");
+ expect(prefilledBaseUrl("openai")).toBe("");
+ expect(prefilledBaseUrl("anthropic")).toBe("");
+ expect(prefilledBaseUrl("claude-agent")).toBe("");
+ // The generic card has no single sensible endpoint to guess.
+ expect(prefilledBaseUrl("openai-compatible")).toBe("");
+ expect(prefilledBaseUrl("unknown")).toBe("");
+ });
+
+ it("declares an endpoint and a setup hint for every self-hosted card", () => {
+ for (const id of SELF_HOSTED) {
+ const card = PROVIDER_TYPES.find(p => p.id === id);
+ expect(card, `missing card: ${id}`).toBeDefined();
+ expect(card?.baseUrl).toBe("required");
+ expect(card?.setupHintKey).toBeTruthy();
+ expect(card?.defaultBaseUrl).toBeTruthy();
+ }
+ });
+
+ it("keeps vendor cards on a required key and an advanced endpoint override", () => {
+ for (const id of ["anthropic", "openai", "google"]) {
+ const card = PROVIDER_TYPES.find(p => p.id === id);
+ // Both default, so neither is set explicitly.
+ expect(card?.apiKey ?? "required").toBe("required");
+ expect(card?.baseUrl ?? "advanced").toBe("advanced");
+ }
+ });
+
+ it("asks for no key from local runtimes and an optional one from arbitrary endpoints", () => {
+ const byId = new Map(PROVIDER_TYPES.map(p => [p.id, p]));
+ expect(byId.get("ollama")?.apiKey).toBe("none");
+ expect(byId.get("lmstudio")?.apiKey).toBe("none");
+ // A generic endpoint may sit behind an authenticating proxy (vLLM, LiteLLM).
+ expect(byId.get("openai-compatible")?.apiKey).toBe("optional");
+ // Subscription auth belongs to Claude Code itself.
+ expect(byId.get("claude-agent")?.apiKey).toBe("none");
+ expect(byId.get("claude-agent")?.baseUrl).toBe("none");
+ });
+
+ it("gives every card an icon of some kind", () => {
+ for (const card of PROVIDER_TYPES) {
+ expect(card.iconUrl ?? card.icon, `no icon for ${card.id}`).toBeTruthy();
+ }
+ });
+});
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 9f5b242cf5..af24505fde 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
@@ -3,6 +3,7 @@ import "./AddProviderModal.css";
import type { LlmModelInfo } from "@triliumnext/commons";
import { createPortal } from "preact/compat";
import { useMemo, useRef, useState } from "preact/hooks";
+import { Trans } from "react-i18next";
import { t } from "../../../../services/i18n";
import { Badge } from "../../../react/Badge";
@@ -31,29 +32,63 @@ export interface LlmProviderConfig {
export interface ProviderType {
id: string;
name: string;
+ /** Shown as the endpoint field's placeholder, and prefilled into it when {@link prefillBaseUrl} is set. */
defaultBaseUrl: string;
+ /**
+ * Write {@link defaultBaseUrl} into the field when the card is picked. Set for
+ * self-hosted providers, where the port is the one detail the user must get
+ * right and differs per runtime; vendor providers keep it as a hint only, so
+ * that an unedited field stores no endpoint override.
+ */
+ prefillBaseUrl?: boolean;
/** URL of the provider's logo (an imported `*.svg?url`), rendered monochrome via a CSS mask. */
- iconUrl: string;
+ iconUrl?: string;
+ /** Boxicons class shown when the provider has no logo of its own. */
+ icon?: string;
/** Short blurb shown under the provider name on its selectable card. */
description: string;
+ /** One-line setup reminder shown under the endpoint field (i18n key, rendered via `<Trans>`). */
+ setupHintKey?: string;
/** Marks the provider as beta, shown as a badge next to its name. */
beta?: boolean;
- /** When false, the provider needs no API key or base URL (e.g. subscription-based auth). */
- usesApiKey?: boolean;
- /** When true (with usesApiKey: false), the base URL is the primary connection detail (e.g. Ollama). */
- usesBaseUrl?: boolean;
+ /**
+ * How the provider authenticates: a key it requires (vendor APIs), one it may
+ * take (self-hosted endpoints that sit behind a proxy or gateway), or none at
+ * all (subscription auth). Defaults to `"required"`.
+ */
+ apiKey?: "required" | "optional" | "none";
+ /**
+ * Where the endpoint URL belongs: the primary connection detail (self-hosted),
+ * an advanced override (vendor APIs), or not applicable. Defaults to `"advanced"`.
+ */
+ baseUrl?: "required" | "advanced" | "none";
}
// The two Claude-powered providers lead the list so they sit together on the top row,
-// making the subscription-vs-API-key choice easy to spot.
+// making the subscription-vs-API-key choice easy to spot; the self-hosted ones close it.
export const PROVIDER_TYPES: ProviderType[] = [
{ id: "anthropic", name: "Anthropic", defaultBaseUrl: "https://api.anthropic.com/v1", iconUrl: anthropicIcon, description: t("llm.provider_desc_anthropic") },
// Uses the Claude Agent SDK on the server; auth belongs to Claude Code (`claude /login`).
- { id: "claude-agent", name: "Claude Code", defaultBaseUrl: "", iconUrl: claudeAgentIcon, description: t("llm.provider_desc_claude_agent"), beta: true, usesApiKey: false },
+ { id: "claude-agent", name: "Claude Code", defaultBaseUrl: "", iconUrl: claudeAgentIcon, description: t("llm.provider_desc_claude_agent"), beta: true, apiKey: "none", baseUrl: "none" },
{ id: "openai", name: "OpenAI", defaultBaseUrl: "https://api.openai.com/v1", iconUrl: openaiIcon, description: t("llm.provider_desc_openai") },
{ id: "google", name: "Google Gemini", defaultBaseUrl: "https://generativelanguage.googleapis.com/v1beta", iconUrl: geminiIcon, description: t("llm.provider_desc_google") },
- // Local models via Ollama — no API key, only the instance URL.
- { id: "ollama", name: "Ollama", defaultBaseUrl: "http://localhost:11434", iconUrl: ollamaIcon, description: t("llm.provider_desc_ollama"), usesApiKey: false, usesBaseUrl: true }
+ // The three self-hosted cards share one server-side provider; they differ only in
+ // the endpoint they prefill and the setup hint they show.
+ {
+ id: "ollama", name: "Ollama", defaultBaseUrl: "http://localhost:11434", prefillBaseUrl: true,
+ iconUrl: ollamaIcon, description: t("llm.provider_desc_ollama"),
+ setupHintKey: "llm.setup_hint_ollama", apiKey: "none", baseUrl: "required"
+ },
+ {
+ id: "lmstudio", name: "LM Studio", defaultBaseUrl: "http://localhost:1234/v1", prefillBaseUrl: true,
+ icon: "bx bx-desktop", description: t("llm.provider_desc_lmstudio"),
+ setupHintKey: "llm.setup_hint_lmstudio", apiKey: "none", baseUrl: "required"
+ },
+ {
+ id: "openai-compatible", name: t("llm.provider_openai_compatible"), defaultBaseUrl: "http://localhost:8080/v1",
+ icon: "bx bx-server", description: t("llm.provider_desc_openai_compatible"),
+ setupHintKey: "llm.setup_hint_openai_compatible", apiKey: "optional", baseUrl: "required"
+ }
];
function isValidBaseUrl(value: string): boolean {
@@ -84,7 +119,7 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
const [step, setStep] = useState<1 | 2>(initialStep);
const [selectedProvider, setSelectedProvider] = useState(existingProvider?.provider ?? PROVIDER_TYPES[0].id);
const [apiKey, setApiKey] = useState(existingProvider?.apiKey ?? "");
- const [baseUrl, setBaseUrl] = useState(existingProvider?.baseURL ?? "");
+ const [baseUrl, setBaseUrl] = useState(existingProvider?.baseURL ?? prefilledBaseUrl(existingProvider?.provider ?? PROVIDER_TYPES[0].id));
const [selectedModels, setSelectedModels] = useState<LlmModelInfo[]>(existingProvider?.selectedModels ?? []);
const formRef = useRef<HTMLFormElement>(null);
@@ -92,14 +127,31 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
() => PROVIDER_TYPES.find(p => p.id === selectedProvider),
[selectedProvider]
);
- const usesApiKey = providerType?.usesApiKey !== false;
- // Providers with an API key can override the base URL as an advanced option;
- // key-less providers (Ollama) can declare it as their primary connection detail.
- const usesBaseUrl = usesApiKey || providerType?.usesBaseUrl === true;
+ const apiKeyMode = providerType?.apiKey ?? "required";
+ // Self-hosted providers show the endpoint as their primary connection detail;
+ // vendor providers keep it tucked away as an advanced override.
+ const baseUrlMode = providerType?.baseUrl ?? "advanced";
+ const usesApiKey = apiKeyMode !== "none";
const trimmedApiKey = apiKey.trim();
const trimmedBaseUrl = baseUrl.trim();
const baseUrlIsValid = isValidBaseUrl(trimmedBaseUrl);
- const connectionValid = (usesApiKey ? !!trimmedApiKey : true) && (usesBaseUrl ? baseUrlIsValid : true);
+ const connectionValid = (apiKeyMode !== "required" || !!trimmedApiKey)
+ && (baseUrlMode === "none" || (baseUrlIsValid && (baseUrlMode !== "required" || !!trimmedBaseUrl)));
+
+ /** Picking a card swaps in that provider's endpoint, so the right port is filled in by default. */
+ function selectProviderType(providerId: string) {
+ setSelectedProvider(providerId);
+ setBaseUrl(prefilledBaseUrl(providerId));
+ }
+
+ // Under the endpoint field: the validation error if any, otherwise the
+ // provider's own setup reminder (how to start its server), falling back to
+ // the generic explanation of what the field overrides.
+ const baseUrlDescription = !baseUrlIsValid
+ ? <span className="text-danger">{t("llm.base_url_invalid")}</span>
+ : providerType?.setupHintKey
+ ? <Trans i18nKey={providerType.setupHintKey} components={{ Code: <code /> }} />
+ : t("llm.base_url_description");
const modelQuery = useMemo(
() => ({ provider: selectedProvider, apiKey: trimmedApiKey, baseURL: trimmedBaseUrl || undefined }),
@@ -115,10 +167,11 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
const seedDefaultModels = !existingProvider?.selectedModels;
function reset() {
+ const initialProvider = existingProvider?.provider ?? PROVIDER_TYPES[0].id;
setStep(initialStep);
- setSelectedProvider(existingProvider?.provider ?? PROVIDER_TYPES[0].id);
+ setSelectedProvider(initialProvider);
setApiKey(existingProvider?.apiKey ?? "");
- setBaseUrl(existingProvider?.baseURL ?? "");
+ setBaseUrl(existingProvider?.baseURL ?? prefilledBaseUrl(initialProvider));
setSelectedModels(existingProvider?.selectedModels ?? []);
}
@@ -140,7 +193,7 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
name: providerType?.name || selectedProvider,
provider: selectedProvider,
apiKey: usesApiKey ? trimmedApiKey : "",
- ...(usesBaseUrl && trimmedBaseUrl && { baseURL: trimmedBaseUrl }),
+ ...(baseUrlMode !== "none" && trimmedBaseUrl && { baseURL: trimmedBaseUrl }),
selectedModels
};
@@ -197,7 +250,7 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
: provider.name}
description={provider.description}
selected={selectedProvider === provider.id}
- onSelect={() => setSelectedProvider(provider.id)}
+ onSelect={() => selectProviderType(provider.id)}
/>
))}
</SelectableCardGrid>
@@ -207,55 +260,44 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
<Card heading={t("llm.connection_details")}>
<CardSection>
- {usesApiKey ? (
- <FormGroup name="api-key" label={t("llm.api_key")}>
+ {/* Self-hosted providers lead with the endpoint — the port is the
+ detail that has to be right — and treat the key as optional. */}
+ {baseUrlMode === "required" && (
+ <FormGroup name="base-url" label={t("llm.base_url")} description={baseUrlDescription}>
<FormTextBox
- type="password"
- currentValue={apiKey}
- onChange={setApiKey}
- placeholder={t("llm.api_key_placeholder")}
+ type="text"
+ currentValue={baseUrl}
+ onChange={setBaseUrl}
+ placeholder={providerType?.defaultBaseUrl}
autoFocus
/>
</FormGroup>
- ) : usesBaseUrl ? (
- // Key-less self-hosted provider (Ollama): the base URL is
- // the primary connection detail, so it is shown here rather
- // than tucked away under the advanced options.
+ )}
+ {usesApiKey && (
<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")
- }
+ name="api-key"
+ label={t("llm.api_key")}
+ description={apiKeyMode === "optional" ? t("llm.api_key_optional_description") : undefined}
>
<FormTextBox
- type="text"
- currentValue={baseUrl}
- onChange={setBaseUrl}
- placeholder={providerType?.defaultBaseUrl}
- autoFocus
+ type="password"
+ currentValue={apiKey}
+ onChange={setApiKey}
+ placeholder={t("llm.api_key_placeholder")}
+ autoFocus={baseUrlMode !== "required"}
/>
</FormGroup>
- ) : (
+ )}
+ {!usesApiKey && baseUrlMode === "none" && (
<p>{t("llm.claude_agent_description")}</p>
)}
</CardSection>
</Card>
- {usesApiKey && (
+ {baseUrlMode === "advanced" && (
<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")
- }
- >
+ <FormGroup name="base-url" label={t("llm.base_url")} description={baseUrlDescription}>
<FormTextBox
type="text"
currentValue={baseUrl}
@@ -275,6 +317,7 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
selected={selectedModels}
onChange={setSelectedModels}
autoSelectDefaults={seedDefaultModels}
+ troubleshooting={providerType?.baseUrl === "required" ? <SelfHostedTroubleshooting /> : undefined}
/>
</CardSection>
</Card>
@@ -283,3 +326,28 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
document.body
);
}
+
+/**
+ * The endpoint a freshly picked provider starts with. Only self-hosted providers
+ * prefill: their port is the one thing the user must get right and it differs per
+ * runtime, whereas a vendor endpoint is a hint the user should leave alone (an
+ * unedited field must not store a redundant override).
+ */
+export function prefilledBaseUrl(providerId: string): string {
+ const providerType = PROVIDER_TYPES.find(p => p.id === providerId);
+ return providerType?.prefillBaseUrl ? providerType.defaultBaseUrl : "";
+}
+
+/**
+ * Shown when a self-hosted endpoint can't be listed — the point at which the
+ * user needs setup instructions, rather than on the way in.
+ */
+function SelfHostedTroubleshooting() {
+ return (
+ <ul className="model-selection-troubleshooting">
+ <li>{t("llm.troubleshoot_server_running")}</li>
+ <li>{t("llm.troubleshoot_port")}</li>
+ <li>{t("llm.troubleshoot_remote")}</li>
+ </ul>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css
index cdc8e832ea..422100dd44 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.css
@@ -39,3 +39,16 @@
.model-selection-cost {
color: var(--muted-text-color);
}
+
+/* Setup checklist shown inside the "couldn't list models" placeholder. */
+.model-selection-troubleshooting {
+ margin: 0.75em 0 0;
+ padding-inline-start: 1.2em;
+ text-align: start;
+ font-size: 0.9em;
+ color: var(--muted-text-color);
+
+ & li {
+ margin-bottom: 0.25em;
+ }
+}
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
index bbfb2b5c16..73193f3581 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.spec.tsx
@@ -130,4 +130,19 @@ describe("ModelSelection", () => {
const el = await renderSelection({ query: { provider: "openai" }, selected: [], onChange: vi.fn() });
expect(el.textContent).toContain("llm.models_none_available");
});
+
+ it("shows the provider's setup guidance when listing fails or comes back empty", async () => {
+ // The failure state is where a self-hosted user needs instructions, so
+ // the caller's checklist rides along with both non-happy paths.
+ const troubleshooting = <span>check the server</span>;
+
+ fetchProviderModelsMock.mockRejectedValue(new Error("ECONNREFUSED"));
+ const failed = await renderSelection({ query: { provider: "ollama" }, selected: [], onChange: vi.fn(), troubleshooting });
+ expect(failed.textContent).toContain("check the server");
+
+ render(null, failed);
+ fetchProviderModelsMock.mockResolvedValue([]);
+ const empty = await renderSelection({ query: { provider: "ollama" }, selected: [], onChange: vi.fn(), troubleshooting });
+ expect(empty.textContent).toContain("check the server");
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
index cd35448890..09f7895fa7 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/ModelSelection.tsx
@@ -1,6 +1,7 @@
import "./ModelSelection.css";
import type { LlmModelInfo } from "@triliumnext/commons";
+import type { ComponentChildren } from "preact";
import { useCallback, useEffect, useState } from "preact/hooks";
import { t } from "../../../../services/i18n";
@@ -20,6 +21,12 @@ interface ModelSelectionProps {
* if nothing is selected yet — seeds a sensible default for a fresh provider.
*/
autoSelectDefaults?: boolean;
+ /**
+ * Setup guidance shown alongside a listing failure. A failed fetch is the
+ * moment the user needs it, so the provider passes its checklist here rather
+ * than crowding the connection form with instructions nobody reads.
+ */
+ troubleshooting?: ComponentChildren;
}
/**
@@ -27,7 +34,7 @@ interface ModelSelectionProps {
* 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) {
+export default function ModelSelection({ query, selected, onChange, autoSelectDefaults, troubleshooting }: ModelSelectionProps) {
const [models, setModels] = useState<LlmModelInfo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | undefined>();
@@ -70,10 +77,14 @@ export default function ModelSelection({ query, selected, onChange, autoSelectDe
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 })} />;
+ return (
+ <NoItems icon="bx bx-error-circle" text={t("llm.models_load_failed", { error })}>
+ {troubleshooting}
+ </NoItems>
+ );
}
if (models.length === 0) {
- return <NoItems icon="bx bx-bot" text={t("llm.models_none_available")} />;
+ return <NoItems icon="bx bx-bot" text={t("llm.models_none_available")}>{troubleshooting}</NoItems>;
}
const allSelected = models.every(isSelected);
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.ts
index 645a78ba30..3dfd3aaa96 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@ -41,7 +41,7 @@ vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock
vi.mock("./providers/openai.js", () => ({ OpenAiProvider: makeProviderMock("openai") }));
vi.mock("./providers/google.js", () => ({ GoogleProvider: makeProviderMock("google") }));
vi.mock("./providers/claude_agent.js", () => ({ ClaudeAgentProvider: makeProviderMock("claude-agent") }));
-vi.mock("./providers/ollama.js", () => ({ OllamaProvider: makeProviderMock("ollama") }));
+vi.mock("./providers/local.js", () => ({ LocalProvider: makeProviderMock("local") }));
import {
clearProviderCache,
@@ -94,15 +94,20 @@ describe("llm/index provider registry", () => {
{ id: "o", name: "O", provider: "openai", apiKey: "ko" },
{ id: "g", name: "G", provider: "google", apiKey: "kg" },
{ id: "c", name: "C", provider: "claude-agent", apiKey: "" },
- { id: "l", name: "L", provider: "ollama", apiKey: "", baseURL: "http://ollama.lan:11434" }
+ { id: "l", name: "L", provider: "ollama", apiKey: "", baseURL: "http://ollama.lan:11434" },
+ { id: "lm", name: "LM", provider: "lmstudio", apiKey: "", baseURL: "http://box:1234/v1" },
+ { id: "oc", name: "OC", provider: "openai-compatible", apiKey: "k", baseURL: "http://box:8080/v1" }
]);
expect((getProvider("a").constructor as any).lastArgs).toEqual(["ka", undefined]);
expect((getProvider("o").constructor as any).lastArgs).toEqual(["ko", undefined]);
expect((getProvider("g").constructor as any).lastArgs).toEqual(["kg", undefined]);
// The subscription provider takes no constructor args — auth is Claude Code's.
expect((getProvider("c").constructor as any).lastArgs).toEqual([]);
- // Ollama needs no key, only the instance URL.
- expect((getProvider("l").constructor as any).lastArgs).toEqual(["", "http://ollama.lan:11434"]);
+ // The three self-hosted cards share one class, which receives the card
+ // id so it knows which endpoint to probe and prefill.
+ expect((getProvider("l").constructor as any).lastArgs).toEqual(["ollama", "", "http://ollama.lan:11434"]);
+ expect((getProvider("lm").constructor as any).lastArgs).toEqual(["lmstudio", "", "http://box:1234/v1"]);
+ expect((getProvider("oc").constructor as any).lastArgs).toEqual(["openai-compatible", "k", "http://box:8080/v1"]);
});
it("throws when no providers are configured (null and empty array)", () => {
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index dc9c7f426e..af2e95e4f6 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -3,7 +3,7 @@ import { getLog, options as optionService } from "@triliumnext/core";
import { AnthropicProvider } from "./providers/anthropic.js";
import { ClaudeAgentProvider } from "./providers/claude_agent.js";
import { GoogleProvider } from "./providers/google.js";
-import { OllamaProvider } from "./providers/ollama.js";
+import { LocalProvider } from "./providers/local.js";
import { OpenAiProvider } from "./providers/openai.js";
import type { LlmProvider, ModelInfo } from "./types.js";
@@ -27,7 +27,7 @@ export interface LlmProviderSetup {
}
/** Provider type identifiers that can be instantiated, for error messages. */
-const PROVIDER_TYPES = ["anthropic", "openai", "google", "claude-agent", "ollama"];
+const PROVIDER_TYPES = ["anthropic", "openai", "google", "claude-agent", "ollama", "lmstudio", "openai-compatible"];
/**
* Instantiate a provider from its type identifier.
@@ -51,9 +51,13 @@ function createProviderInstance(provider: string, apiKey: string, baseURL?: stri
// authentication is handled by Claude Code itself (`claude /login`).
case "claude-agent":
return new ClaudeAgentProvider();
- // Local models via Ollama's own API — no API key, only the instance URL.
+ // Self-hosted endpoints. The three cards differ only in the URL and setup
+ // hint the UI prefills; they all speak the OpenAI-compatible API, with
+ // Ollama and LM Studio additionally offering a richer native listing.
case "ollama":
- return new OllamaProvider(apiKey, baseURL);
+ case "lmstudio":
+ case "openai-compatible":
+ return new LocalProvider(provider, apiKey, baseURL);
default:
throw new Error(`Unknown LLM provider type: ${provider}. Available: ${PROVIDER_TYPES.join(", ")}`);
}
diff --git a/apps/server/src/services/llm/providers/local.spec.ts b/apps/server/src/services/llm/providers/local.spec.ts
new file mode 100644
index 0000000000..54ec2c201d
--- /dev/null
+++ b/apps/server/src/services/llm/providers/local.spec.ts
@@ -0,0 +1,298 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() })
+ };
+});
+
+const createOpenAiMock = vi.fn();
+
+vi.mock("@ai-sdk/openai", () => ({
+ createOpenAI: (opts: unknown) => {
+ createOpenAiMock(opts);
+ const fn: any = () => ({});
+ fn.chat = vi.fn((modelId: string) => ({ modelId }));
+ return fn;
+ }
+}));
+
+import { LocalProvider } from "./local.js";
+
+/** Minimal /api/tags payload with the fields the provider reads. */
+function ollamaTags(models: Array<{ name: string; parameter_size?: string; quantization_level?: string }>) {
+ return json({
+ models: models.map(m => ({
+ name: m.name,
+ model: m.name,
+ details: { parameter_size: m.parameter_size, quantization_level: m.quantization_level }
+ }))
+ });
+}
+
+/** Minimal /api/v0/models payload (LM Studio's own REST API). */
+function lmStudioModels(models: Array<{ id: string; quantization?: string; max_context_length?: number }>) {
+ return json({ data: models });
+}
+
+/** Minimal OpenAI-compatible /v1/models payload. */
+function openAiModels(ids: string[]) {
+ return json({ data: ids.map(id => ({ id, object: "model" })) });
+}
+
+function json(payload: unknown) {
+ return { ok: true, status: 200, json: async () => payload } as Response;
+}
+
+function status(code: number) {
+ return { ok: false, status: code } as Response;
+}
+
+/** Route each probe URL to a response, so the fallback chain can be driven precisely. */
+function routes(map: Record<string, Response>) {
+ return (url: string) => {
+ const response = Object.entries(map).find(([suffix]) => url.endsWith(suffix))?.[1];
+ return Promise.resolve(response ?? status(404));
+ };
+}
+
+describe("LocalProvider", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ createOpenAiMock.mockClear();
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ describe("endpoint resolution", () => {
+ it("prefills each card's default endpoint", () => {
+ new LocalProvider("ollama");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1" });
+
+ new LocalProvider("lmstudio");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:1234/v1" });
+ });
+
+ it("accepts a URL written with or without the /v1 suffix", () => {
+ new LocalProvider("openai-compatible", "", "http://box:8080");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://box:8080/v1" });
+
+ new LocalProvider("openai-compatible", "", "http://box:8080/v1");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://box:8080/v1" });
+ });
+
+ it("keeps a path prefix intact (proxied endpoints)", () => {
+ new LocalProvider("openai-compatible", "", "https://proxy.example.com/llm/v1");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "https://proxy.example.com/llm/v1" });
+ });
+
+ it("forwards a supplied API key to the SDK", () => {
+ new LocalProvider("openai-compatible", "sk-proxy", "http://box:8080/v1");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-proxy", baseURL: "http://box:8080/v1" });
+ });
+
+ it("falls back to the card's default for an invalid URL, but rejects one it cannot replace", () => {
+ new LocalProvider("ollama", "", "not a url");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1" });
+
+ new LocalProvider("ollama", "", "ftp://example.com");
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1" });
+
+ // The generic card has no default to fall back to.
+ expect(() => new LocalProvider("openai-compatible", "", "not a url")).toThrow(/Invalid base URL/);
+ expect(() => new LocalProvider("openai-compatible")).toThrow(/base URL is required/i);
+ });
+
+ it("chats through the Chat Completions API, which every runtime supports", () => {
+ const provider = new LocalProvider("ollama") as any;
+ expect(provider.createModel("llama3.2")).toEqual({ modelId: "llama3.2" });
+ });
+ });
+
+ describe("model listing", () => {
+ it("uses Ollama's /api/tags, with size and quantization in the name", async () => {
+ fetchMock.mockImplementation(routes({
+ "/api/tags": ollamaTags([
+ { name: "llama3.2:latest", parameter_size: "3.2B", quantization_level: "Q4_K_M" },
+ { name: "plain-model" }
+ ])
+ }));
+
+ const models = await new LocalProvider("ollama").listModels();
+
+ expect(models.map(m => m.name)).toEqual(["llama3.2:latest (3.2B, Q4_K_M)", "plain-model"]);
+ expect(models[0].isDefault).toBe(true);
+ expect(models.every(m => m.pricing?.input === 0 && m.pricing.output === 0)).toBe(true);
+ });
+
+ it("uses LM Studio's /api/v0/models, with quantization and context length", async () => {
+ fetchMock.mockImplementation(routes({
+ "/api/v0/models": lmStudioModels([{ id: "qwen3-8b", quantization: "Q4_K_M", max_context_length: 32768 }])
+ }));
+
+ const models = await new LocalProvider("lmstudio").listModels();
+
+ expect(models).toEqual([expect.objectContaining({
+ id: "qwen3-8b",
+ name: "qwen3-8b (Q4_K_M)",
+ contextWindow: 32768,
+ pricing: { input: 0, output: 0 }
+ })]);
+ // The Ollama-only endpoint is never probed for the LM Studio card.
+ expect(fetchMock.mock.calls.every(([url]) => !String(url).includes("/api/tags"))).toBe(true);
+ });
+
+ it("falls back to /v1/models when no native listing is served", async () => {
+ fetchMock.mockImplementation(routes({ "/v1/models": openAiModels(["mistral-7b", "qwen3-8b"]) }));
+
+ const models = await new LocalProvider("openai-compatible", "", "http://box:8080/v1").listModels();
+
+ expect(models.map(m => m.id)).toEqual(["mistral-7b", "qwen3-8b"]);
+ // Both native endpoints are tried first for the generic card.
+ const probed = fetchMock.mock.calls.map(([url]) => String(url));
+ expect(probed).toEqual([
+ "http://box:8080/api/tags",
+ "http://box:8080/api/v0/models",
+ "http://box:8080/v1/models"
+ ]);
+ });
+
+ it("leaves an unidentified endpoint unpriced, since it may be a metered proxy", async () => {
+ fetchMock.mockImplementation(routes({ "/v1/models": openAiModels(["gpt-4.1"]) }));
+ const provider = new LocalProvider("openai-compatible", "", "https://proxy.example.com/v1");
+
+ const models = await provider.listModels();
+
+ expect(models[0].pricing).toBeUndefined();
+ expect(provider.getModelPricing("gpt-4.1")).toBeUndefined();
+ });
+
+ it("prices an endpoint identified as a local runtime as free", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": ollamaTags([{ name: "m1" }]) }));
+ const provider = new LocalProvider("openai-compatible", "", "http://box:11434");
+
+ const models = await provider.listModels();
+
+ expect(models[0].pricing).toEqual({ input: 0, output: 0 });
+ expect(provider.getModelPricing("m1")).toEqual({ input: 0, output: 0 });
+ });
+
+ it("caches within the TTL and refetches after it expires", async () => {
+ vi.useFakeTimers();
+ fetchMock.mockImplementation(routes({ "/api/tags": ollamaTags([{ name: "m1" }]) }));
+
+ const provider = new LocalProvider("ollama");
+ await provider.listModels();
+ await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(61 * 60 * 1000);
+ await provider.listModels();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not cache an empty list, so a first-use setup can recover", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": ollamaTags([]) }));
+ const provider = new LocalProvider("ollama");
+ await expect(provider.listModels()).resolves.toEqual([]);
+
+ fetchMock.mockImplementation(routes({ "/api/tags": ollamaTags([{ name: "fresh" }]) }));
+ expect((await provider.listModels()).map(m => m.id)).toEqual(["fresh"]);
+ });
+ });
+
+ describe("listing failures", () => {
+ it("reports an unreachable endpoint instead of probing on", async () => {
+ fetchMock.mockRejectedValue(new Error("ECONNREFUSED"));
+
+ await expect(new LocalProvider("ollama").listModels()).rejects.toThrow(/ECONNREFUSED/);
+ // A dead host must not be reported as "no listing endpoint found".
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a rejected credential instead of probing on", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": status(401) }));
+ await expect(new LocalProvider("ollama").listModels()).rejects.toThrow(/Authentication failed \(HTTP 401\)/);
+ });
+
+ it("reports a server error instead of probing on", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": status(500) }));
+ await expect(new LocalProvider("ollama").listModels()).rejects.toThrow(/HTTP 500/);
+ });
+
+ it("reports an endpoint that serves no listing at all", async () => {
+ fetchMock.mockImplementation(routes({}));
+ await expect(new LocalProvider("openai-compatible", "", "http://box:9999").listModels())
+ .rejects.toThrow(/No model listing endpoint found/);
+ });
+
+ it("reports a foreign payload from the endpoint the card names", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": json({ error: "boom" }) }));
+ await expect(new LocalProvider("ollama").listModels()).rejects.toThrow(/Unexpected \/api\/tags response shape/);
+ });
+
+ it("treats a foreign native payload as 'not that runtime' for the generic card", async () => {
+ // Something answers /api/tags with unrelated JSON; the generic card
+ // keeps probing rather than failing on a guess it made itself.
+ fetchMock.mockImplementation(routes({
+ "/api/tags": json({ error: "boom" }),
+ "/v1/models": openAiModels(["m1"])
+ }));
+ const models = await new LocalProvider("openai-compatible", "", "http://box:8080").listModels();
+ expect(models.map(m => m.id)).toEqual(["m1"]);
+ });
+ });
+
+ describe("model defaults", () => {
+ it("chats with the first model and writes titles with a small one", async () => {
+ fetchMock.mockImplementation(routes({
+ "/api/tags": ollamaTags([
+ { name: "big-model", parameter_size: "70B" },
+ { name: "small-model", parameter_size: "3B" }
+ ])
+ }));
+
+ const provider = new LocalProvider("ollama");
+ await provider.listModels();
+
+ // Both are protected — observable only through the models the base
+ // class picks, so assert through the internal fields.
+ const internals = provider as unknown as { defaultModel: string; titleModel: string };
+ expect(internals.defaultModel).toBe("big-model");
+ expect(internals.titleModel).toBe("small-model");
+ });
+
+ it("falls back to a name-shaped small model, then to the default model", async () => {
+ fetchMock.mockImplementation(routes({ "/v1/models": openAiModels(["big-model", "phi-4"]) }));
+ const byName = new LocalProvider("openai-compatible", "", "http://box:8080");
+ await byName.listModels();
+ expect((byName as unknown as { titleModel: string }).titleModel).toBe("phi-4");
+
+ fetchMock.mockImplementation(routes({ "/v1/models": openAiModels(["only-big"]) }));
+ const onlyBig = new LocalProvider("openai-compatible", "", "http://box:8080");
+ await onlyBig.listModels();
+ expect((onlyBig as unknown as { titleModel: string }).titleModel).toBe("only-big");
+ });
+
+ it("resolves the title model before generating a title", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": ollamaTags([{ name: "tiny", parameter_size: "1B" }]) }));
+ const provider = new LocalProvider("ollama");
+ const generateTitle = vi.spyOn(
+ Object.getPrototypeOf(Object.getPrototypeOf(provider)) as { generateTitle: () => Promise<string> },
+ "generateTitle"
+ ).mockResolvedValue("A title");
+
+ await expect(provider.generateTitle("Hello")).resolves.toBe("A title");
+ expect((provider as unknown as { titleModel: string }).titleModel).toBe("tiny");
+ generateTitle.mockRestore();
+ });
+ });
+});
diff --git a/apps/server/src/services/llm/providers/local.ts b/apps/server/src/services/llm/providers/local.ts
new file mode 100644
index 0000000000..9344d0214f
--- /dev/null
+++ b/apps/server/src/services/llm/providers/local.ts
@@ -0,0 +1,347 @@
+/**
+ * Self-hosted LLM provider — the single implementation behind the Ollama, LM
+ * Studio and generic "OpenAI-compatible" provider cards.
+ *
+ * Every local runtime worth supporting (llama.cpp, vLLM, SGLang, LocalAI, Jan,
+ * KoboldCpp, llamafile, LiteLLM, …) exposes the OpenAI-compatible `/v1`
+ * surface, so that is the chat path in all cases. Two of them additionally
+ * serve a *native* model listing carrying metadata `/v1/models` omits — Ollama's
+ * `/api/tags` (parameter size, quantization) and LM Studio's `/api/v0/models`
+ * (quantization, context length) — so listing probes those first and falls back
+ * to `/v1/models` for everything else.
+ *
+ * The named cards exist only to prefill a URL and a setup hint in the UI; all
+ * three dispatch here, and the card id arrives as {@link LocalProviderKind}.
+ */
+
+import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";
+import { getLog } from "@triliumnext/core";
+
+import type { ModelInfo, ModelPricing } from "../types.js";
+import { BaseProvider, type RemoteModel } from "./base_provider.js";
+
+/** Provider card ids that map to this implementation. */
+export type LocalProviderKind = "ollama" | "lmstudio" | "openai-compatible";
+
+/**
+ * First-run URL per card. The generic card has none — an arbitrary
+ * OpenAI-compatible endpoint cannot be guessed, so its URL is required.
+ */
+const DEFAULT_BASE_URLS: Record<LocalProviderKind, string | undefined> = {
+ ollama: "http://localhost:11434",
+ lmstudio: "http://localhost:1234/v1",
+ "openai-compatible": undefined
+};
+
+/** Models served by a local runtime cost nothing to run. */
+const FREE_PRICING: ModelPricing = { input: 0, output: 0 };
+
+/** Sent when the endpoint needs no credential; local runtimes ignore it, the SDK requires it. */
+const PLACEHOLDER_API_KEY = "local";
+
+/** Timeout for a single model-listing request. */
+const MODEL_LIST_TIMEOUT_MS = 10_000;
+
+/** Below this parameter count (in billions) a model is cheap enough for titles. */
+const TITLE_MODEL_MAX_PARAMS_B = 4;
+
+/** Id shapes that suggest a small model, used when no parameter count is reported. */
+const SMALL_MODEL_NAME = /small|mini|tiny|phi|gemma.*2b/i;
+
+/** A listed model, plus the parameter count when the endpoint reports one. */
+interface LocalModel extends RemoteModel {
+ /** Parameter count in billions. */
+ paramsB?: number;
+}
+
+export class LocalProvider extends BaseProvider {
+ name: string;
+ // Both are resolved from the live model list — a self-hosted endpoint serves
+ // whatever the user installed, so there is nothing sensible to hardcode.
+ protected defaultModel = "";
+ protected titleModel = "";
+
+ private readonly kind: LocalProviderKind;
+ private openai: OpenAISDKProvider;
+ /** Canonical endpoint root, without a trailing `/v1`. */
+ private root: string;
+ /**
+ * Whether the models are known to come from a local runtime, and are
+ * therefore free to run. The named cards are local by definition; the
+ * generic card only counts once a native probe has identified the runtime,
+ * since it may equally point at a proxy in front of a metered API.
+ */
+ private isLocalRuntime: boolean;
+
+ constructor(kind: LocalProviderKind, apiKey = "", baseURL?: string) {
+ super(apiKey, baseURL);
+ this.kind = kind;
+ this.name = kind;
+ this.isLocalRuntime = kind !== "openai-compatible";
+ this.root = resolveRoot(kind, this.baseURL);
+
+ this.openai = createOpenAI({
+ apiKey: apiKey || PLACEHOLDER_API_KEY,
+ baseURL: `${this.root}/v1`
+ });
+ }
+
+ protected createModel(modelId: string) {
+ // Use the Chat Completions API explicitly — calling `this.openai(modelId)`
+ // defaults to the OpenAI Responses API, which most self-hosted runtimes
+ // don't implement (Ollama only since 0.13.3).
+ return this.openai.chat(modelId);
+ }
+
+ /**
+ * List the models the endpoint serves, preferring a native listing for its
+ * richer metadata and falling back to the OpenAI-compatible one.
+ */
+ protected override async fetchRemoteModels(): Promise<RemoteModel[] | null> {
+ const models = await this.listNativeModels() ?? await this.listOpenAiCompatibleModels();
+ this.pickModelDefaults(models);
+ return models;
+ }
+
+ /**
+ * Models are free when they run locally. The base class would otherwise
+ * look the id up in the committed price table, which covers only the
+ * metered vendor APIs and never a self-hosted build.
+ */
+ override async listModels(): Promise<ModelInfo[]> {
+ const models = await super.listModels();
+ return this.isLocalRuntime
+ ? models.map(model => ({ ...model, pricing: FREE_PRICING }))
+ : models;
+ }
+
+ override getModelPricing(model: string): ModelPricing | undefined {
+ return this.isLocalRuntime ? FREE_PRICING : super.getModelPricing(model);
+ }
+
+ /**
+ * The title model is only known once the endpoint has been listed, so make
+ * sure that happened before falling through to the base implementation
+ * (which chats with {@link titleModel}). The list is cached by the base
+ * class, so this is a no-op after the first call.
+ */
+ override async generateTitle(firstMessage: string): Promise<string> {
+ if (!this.titleModel) {
+ await this.listModels();
+ }
+ return super.generateTitle(firstMessage);
+ }
+
+ /**
+ * Try the native listing endpoints, skipping the one the selected card
+ * rules out. Returns null when neither is served here, so the caller falls
+ * back to `/v1/models`.
+ */
+ private async listNativeModels(): Promise<LocalModel[] | null> {
+ if (this.kind !== "lmstudio") {
+ const payload = await this.probeJson(`${this.root}/api/tags`);
+ const models = payload !== undefined ? parseOllamaTags(payload) : null;
+ if (models) {
+ this.isLocalRuntime = true;
+ return models;
+ }
+ // The Ollama card pointed at something that answers /api/tags with
+ // a foreign payload is a misconfiguration worth reporting, not a
+ // reason to silently try the next endpoint.
+ if (payload !== undefined && this.kind === "ollama") {
+ throw new Error("Unexpected /api/tags response shape");
+ }
+ }
+ if (this.kind !== "ollama") {
+ const payload = await this.probeJson(`${this.root}/api/v0/models`);
+ const models = payload !== undefined ? parseLmStudioModels(payload) : null;
+ if (models) {
+ this.isLocalRuntime = true;
+ return models;
+ }
+ if (payload !== undefined && this.kind === "lmstudio") {
+ throw new Error("Unexpected /api/v0/models response shape");
+ }
+ }
+ return null;
+ }
+
+ /** The universal fallback: the OpenAI-compatible `/v1/models` listing. */
+ private async listOpenAiCompatibleModels(): Promise<LocalModel[]> {
+ const url = `${this.root}/v1/models`;
+ const payload = await this.probeJson(url);
+ if (payload === undefined) {
+ throw new Error(`No model listing endpoint found at ${this.root} — is this an OpenAI-compatible server?`);
+ }
+ const data = (payload as { data?: unknown }).data;
+ if (!Array.isArray(data)) {
+ throw new Error(`Unexpected response shape from ${url}`);
+ }
+ return data
+ .filter((m): m is { id: string } => typeof (m as { id?: unknown }).id === "string")
+ .map(m => ({ id: m.id }));
+ }
+
+ /**
+ * GET a JSON document from a listing endpoint.
+ *
+ * Returns undefined when the endpoint isn't served here (404/405), which is
+ * how the probe chain advances. Everything else throws: an unreachable host
+ * or a rejected credential is a real problem the add/edit-provider screen
+ * must report, not a reason to keep trying other URLs.
+ */
+ private async probeJson(url: string): Promise<unknown | undefined> {
+ let response: Response;
+ try {
+ response = await fetch(url, {
+ headers: this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
+ signal: AbortSignal.timeout(MODEL_LIST_TIMEOUT_MS)
+ });
+ } catch (e) {
+ throw new Error(`Could not reach ${url}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ if (response.status === 404 || response.status === 405) {
+ return undefined;
+ }
+ if (!response.ok) {
+ if (response.status === 401 || response.status === 403) {
+ throw new Error(`Authentication failed (HTTP ${response.status}) — check the API key and base URL.`);
+ }
+ throw new Error(`HTTP ${response.status} from ${url}`);
+ }
+ return await response.json();
+ }
+
+ /**
+ * Remember which model to chat with by default and which to write chat
+ * titles with. A self-hosted endpoint has no notion of a default, so the
+ * first listed model wins; titles prefer the smallest model available,
+ * since they are a throwaway one-liner and a 70B model would make opening a
+ * chat sluggish.
+ */
+ private pickModelDefaults(models: LocalModel[]): void {
+ if (models.length === 0) {
+ return;
+ }
+ this.defaultModel = models[0].id;
+ const small = models.find(m => m.paramsB !== undefined && m.paramsB < TITLE_MODEL_MAX_PARAMS_B)
+ ?? models.find(m => SMALL_MODEL_NAME.test(m.id));
+ this.titleModel = small?.id ?? this.defaultModel;
+ }
+}
+
+/**
+ * Canonical endpoint root for a card: the configured URL (validated), or the
+ * card's own default, with any trailing `/v1` removed so both spellings a user
+ * might enter — `http://localhost:1234` and `http://localhost:1234/v1` — resolve
+ * to the same instance. The `/v1` is re-appended for the SDK and the
+ * OpenAI-compatible listing; the native listings hang off the root.
+ */
+function resolveRoot(kind: LocalProviderKind, baseURL: string | undefined): string {
+ const fallback = DEFAULT_BASE_URLS[kind];
+ if (!baseURL) {
+ if (!fallback) {
+ throw new Error("A base URL is required for an OpenAI-compatible provider.");
+ }
+ return stripApiVersion(fallback);
+ }
+ try {
+ const parsed = new URL(baseURL);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ throw new Error(`unsupported protocol ${parsed.protocol}`);
+ }
+ return stripApiVersion(baseURL);
+ } catch (e) {
+ if (!fallback) {
+ throw new Error(`Invalid base URL "${baseURL}": ${e instanceof Error ? e.message : String(e)}`);
+ }
+ getLog().error(`${kind}: invalid base URL "${baseURL}" (${e}), falling back to ${fallback}`);
+ return stripApiVersion(fallback);
+ }
+}
+
+/** Trailing slashes are already gone (the base class normalizes them). */
+function stripApiVersion(url: string): string {
+ return url.endsWith("/v1") ? url.slice(0, -"/v1".length) : url;
+}
+
+/**
+ * Shape of the Ollama `/api/tags` response.
+ * See https://github.com/ollama/ollama/blob/main/docs/api.md#list-local-models
+ */
+interface OllamaTag {
+ name: string;
+ details?: {
+ parameter_size?: string;
+ quantization_level?: string;
+ };
+}
+
+/** Parse an `/api/tags` payload, or null when it isn't one. */
+function parseOllamaTags(payload: unknown): LocalModel[] | null {
+ const models = (payload as { models?: unknown }).models;
+ if (!Array.isArray(models)) {
+ return null;
+ }
+ const tags = models.filter((m): m is OllamaTag => typeof (m as { name?: unknown }).name === "string");
+ if (tags.length !== models.length) {
+ return null;
+ }
+ return tags.map(m => ({
+ id: m.name,
+ name: describeModel(m.name, [m.details?.parameter_size, m.details?.quantization_level]),
+ paramsB: parseParamSize(m.details?.parameter_size)
+ }));
+}
+
+/**
+ * Shape of the LM Studio `/api/v0/models` response — its own richer REST API,
+ * alongside the OpenAI-compatible one.
+ */
+interface LmStudioModel {
+ id: string;
+ quantization?: string;
+ max_context_length?: number;
+}
+
+/** Parse an `/api/v0/models` payload, or null when it isn't one. */
+function parseLmStudioModels(payload: unknown): LocalModel[] | null {
+ const data = (payload as { data?: unknown }).data;
+ if (!Array.isArray(data)) {
+ return null;
+ }
+ const models = data.filter((m): m is LmStudioModel => typeof (m as { id?: unknown }).id === "string");
+ if (models.length !== data.length) {
+ return null;
+ }
+ return models.map(m => ({
+ id: m.id,
+ name: describeModel(m.id, [m.quantization]),
+ contextWindow: m.max_context_length
+ }));
+}
+
+/**
+ * Build a display name from whatever metadata the endpoint reported.
+ * Example: "llama3.2:latest" + ["3.2B", "Q4_K_M"] → "llama3.2:latest (3.2B, Q4_K_M)"
+ */
+function describeModel(id: string, details: Array<string | undefined>): string {
+ const parts = details.filter((part): part is string => !!part);
+ return parts.length > 0 ? `${id} (${parts.join(", ")})` : id;
+}
+
+/**
+ * Parse a parameter_size string like "7.6B" or "3.2B" into a number of billions.
+ * Returns undefined if the string cannot be parsed.
+ */
+function parseParamSize(paramSize?: string): number | undefined {
+ if (!paramSize) return undefined;
+ const match = paramSize.match(/^([\d.]+)\s*([BMK])/i);
+ if (!match) return undefined;
+ const value = parseFloat(match[1]);
+ const unit = match[2].toUpperCase();
+ if (unit === "B") return value;
+ if (unit === "M") return value / 1000;
+ if (unit === "K") return value / 1_000_000;
+ return undefined;
+}
diff --git a/apps/server/src/services/llm/providers/ollama.spec.ts b/apps/server/src/services/llm/providers/ollama.spec.ts
deleted file mode 100644
index 0acea6023e..0000000000
--- a/apps/server/src/services/llm/providers/ollama.spec.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() })
- };
-});
-
-const createOpenAiMock = vi.fn();
-
-vi.mock("@ai-sdk/openai", () => ({
- createOpenAI: (opts: unknown) => {
- createOpenAiMock(opts);
- const fn: any = () => ({});
- fn.chat = vi.fn((modelId: string) => ({ modelId }));
- return fn;
- }
-}));
-
-import { OllamaProvider } from "./ollama.js";
-
-/** Minimal /api/tags payload with the fields the provider reads. */
-function tagsResponse(models: Array<{ name: string; parameter_size?: string; quantization_level?: string }>) {
- return {
- ok: true,
- json: async () => ({
- models: models.map(m => ({
- name: m.name,
- model: m.name,
- details: {
- parameter_size: m.parameter_size,
- quantization_level: m.quantization_level
- }
- }))
- })
- } as Response;
-}
-
-describe("OllamaProvider", () => {
- const fetchMock = vi.fn();
-
- beforeEach(() => {
- fetchMock.mockReset();
- createOpenAiMock.mockClear();
- vi.stubGlobal("fetch", fetchMock);
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- vi.useRealTimers();
- });
-
- describe("construction", () => {
- it("points the OpenAI-compatible client at the instance's /v1 endpoint", () => {
- new OllamaProvider("", "http://ollama.lan:11434");
- expect(createOpenAiMock).toHaveBeenCalledWith({ apiKey: "ollama", baseURL: "http://ollama.lan:11434/v1" });
- });
-
- it("defaults to the local instance and strips trailing slashes", () => {
- new OllamaProvider();
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://localhost:11434/v1" });
-
- new OllamaProvider("", "http://ollama.lan:11434///");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://ollama.lan:11434/v1" });
- });
-
- it("falls back to the default base URL for invalid or non-http URLs", () => {
- new OllamaProvider("", "ftp://example.com");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://localhost:11434/v1" });
-
- new OllamaProvider("", "not a url");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://localhost:11434/v1" });
- });
-
- it("chats through the Chat Completions API, which every Ollama version supports", () => {
- const provider = new OllamaProvider() as any;
- expect(provider.createModel("llama3.2")).toEqual({ modelId: "llama3.2" });
- });
- });
-
- describe("listModels", () => {
- it("lists the installed models with names built from size and quantization", async () => {
- fetchMock.mockResolvedValue(tagsResponse([
- { name: "llama3.2:latest", parameter_size: "3.2B", quantization_level: "Q4_K_M" },
- { name: "plain-model" }
- ]));
-
- const models = await new OllamaProvider().listModels();
-
- expect(fetchMock).toHaveBeenCalledWith("http://localhost:11434/api/tags", expect.anything());
- expect(models.map(m => m.name)).toEqual([
- "llama3.2:latest (3.2B, Q4_K_M)",
- "plain-model"
- ]);
- // Models run on the user's own hardware, so they are free; the first
- // one stands in as the default since Ollama has no notion of one.
- expect(models[0].isDefault).toBe(true);
- expect(models.map(m => m.pricing)).toEqual([{ input: 0, output: 0 }, { input: 0, output: 0 }]);
- });
-
- it("caches the model list within the TTL and refetches after it expires", async () => {
- vi.useFakeTimers();
- fetchMock.mockResolvedValue(tagsResponse([{ name: "m1" }]));
-
- const provider = new OllamaProvider();
- await provider.listModels();
- await provider.listModels();
- expect(fetchMock).toHaveBeenCalledTimes(1);
-
- vi.advanceTimersByTime(61 * 60 * 1000);
- await provider.listModels();
- expect(fetchMock).toHaveBeenCalledTimes(2);
- });
-
- it("does not cache an empty model list, so a first-use setup can recover", async () => {
- fetchMock.mockResolvedValue(tagsResponse([]));
- const provider = new OllamaProvider();
- await expect(provider.listModels()).resolves.toEqual([]);
-
- // Models get pulled in Ollama, the next call must refetch.
- fetchMock.mockResolvedValue(tagsResponse([{ name: "fresh" }]));
- const models = await provider.listModels();
- expect(models.map(m => m.id)).toEqual(["fresh"]);
- expect(fetchMock).toHaveBeenCalledTimes(2);
- });
-
- it("surfaces an unreachable instance instead of masking it as an empty list", async () => {
- fetchMock.mockRejectedValue(new Error("ECONNREFUSED"));
- await expect(new OllamaProvider().listModels()).rejects.toThrow(/ECONNREFUSED/);
- });
-
- it("rejects a malformed /api/tags response", async () => {
- fetchMock.mockResolvedValue({ ok: true, json: async () => ({ error: "boom" }) } as Response);
- await expect(new OllamaProvider().listModels()).rejects.toThrow(/Unexpected \/api\/tags response shape/);
- });
-
- it("rejects when the instance responds with an error status", async () => {
- fetchMock.mockResolvedValue({ ok: false, status: 500 } as Response);
- await expect(new OllamaProvider().listModels()).rejects.toThrow(/HTTP 500/);
- });
- });
-
- describe("model defaults", () => {
- it("chats with the first model and writes titles with a small one", async () => {
- fetchMock.mockResolvedValue(tagsResponse([
- { name: "big-model", parameter_size: "70B" },
- { name: "small-model", parameter_size: "3B" }
- ]));
-
- const provider = new OllamaProvider();
- await provider.listModels();
- // Both are protected — observable only through the models the base
- // class picks, so assert through the internal fields.
- const internals = provider as unknown as { defaultModel: string; titleModel: string };
- expect(internals.defaultModel).toBe("big-model");
- expect(internals.titleModel).toBe("small-model");
- });
-
- it("falls back to a name-shaped small model, then to the default model", async () => {
- fetchMock.mockResolvedValue(tagsResponse([
- { name: "big-model", parameter_size: "70B" },
- { name: "phi-something" }
- ]));
- const byName = new OllamaProvider();
- await byName.listModels();
- expect((byName as unknown as { titleModel: string }).titleModel).toBe("phi-something");
-
- fetchMock.mockResolvedValue(tagsResponse([{ name: "only-big", parameter_size: "70B" }]));
- const onlyBig = new OllamaProvider();
- await onlyBig.listModels();
- expect((onlyBig as unknown as { titleModel: string }).titleModel).toBe("only-big");
- });
-
- it("resolves the title model before generating a title", async () => {
- fetchMock.mockResolvedValue(tagsResponse([{ name: "tiny", parameter_size: "1B" }]));
- const provider = new OllamaProvider();
- const generateTitle = vi.spyOn(
- Object.getPrototypeOf(Object.getPrototypeOf(provider)) as { generateTitle: () => Promise<string> },
- "generateTitle"
- ).mockResolvedValue("A title");
-
- await expect(provider.generateTitle("Hello")).resolves.toBe("A title");
- expect(fetchMock).toHaveBeenCalledWith("http://localhost:11434/api/tags", expect.anything());
- expect((provider as unknown as { titleModel: string }).titleModel).toBe("tiny");
- generateTitle.mockRestore();
- });
- });
-
- it("reports every model as free, whatever the price table knows", () => {
- expect(new OllamaProvider().getModelPricing()).toEqual({ input: 0, output: 0 });
- });
-});
diff --git a/apps/server/src/services/llm/providers/ollama.ts b/apps/server/src/services/llm/providers/ollama.ts
deleted file mode 100644
index 1222fc538a..0000000000
--- a/apps/server/src/services/llm/providers/ollama.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-/**
- * Ollama provider — chats through the OpenAI-compatible API that Ollama exposes
- * at `/v1`, but lists models through Ollama's own `/api/tags`, which reports the
- * parameter size and quantization level the OpenAI-compatible `/models`
- * endpoint omits.
- *
- * Everything about an Ollama instance is dynamic: the models are whatever the
- * user has pulled locally, and none of them appear in the committed price table
- * — they run on the user's own hardware, so they are free.
- */
-
-import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";
-import { getLog } from "@triliumnext/core";
-
-import type { ModelInfo, ModelPricing } from "../types.js";
-import { BaseProvider, type RemoteModel } from "./base_provider.js";
-
-const DEFAULT_BASE_URL = "http://localhost:11434";
-
-/** Ollama models run locally, so they cost nothing to use. */
-const FREE_PRICING: ModelPricing = { input: 0, output: 0 };
-
-/** Below this parameter count (in billions) a model is cheap enough for titles. */
-const TITLE_MODEL_MAX_PARAMS_B = 4;
-
-/**
- * Shape of the Ollama `/api/tags` response.
- * See https://github.com/ollama/ollama/blob/main/docs/api.md#list-local-models
- */
-interface OllamaTagsResponse {
- models: Array<{
- name: string;
- model: string;
- modified_at?: string;
- size?: number;
- digest?: string;
- details?: {
- parent_model?: string;
- format?: string;
- family?: string;
- families?: string[];
- parameter_size?: string;
- quantization_level?: string;
- };
- }>;
-}
-
-type OllamaTag = OllamaTagsResponse["models"][number];
-
-export class OllamaProvider extends BaseProvider {
- name = "ollama";
- // Both are resolved from the live model list — an Ollama instance serves
- // whatever the user pulled, so there is nothing sensible to hardcode.
- protected defaultModel = "";
- protected titleModel = "";
-
- private openai: OpenAISDKProvider;
- /** Validated instance URL, without a trailing slash. */
- private endpoint: string;
-
- constructor(apiKey = "", baseURL?: string) {
- super(apiKey, baseURL);
- this.endpoint = sanitizeBaseUrl(this.baseURL);
-
- // Ollama exposes an OpenAI-compatible endpoint at /v1
- this.openai = createOpenAI({
- apiKey: apiKey || "ollama", // Ollama ignores this but the SDK requires it
- baseURL: `${this.endpoint}/v1`
- });
- }
-
- protected createModel(modelId: string) {
- // Use the Chat Completions API explicitly — calling `this.openai(modelId)`
- // defaults to the OpenAI Responses API, which Ollama only supports
- // since 0.13.3. Chat Completions works on all Ollama versions.
- return this.openai.chat(modelId);
- }
-
- /**
- * List the models installed on the instance. Uses Ollama's native
- * `/api/tags` rather than the OpenAI-compatible `/models`: only the former
- * carries the parameter size and quantization level shown in the picker and
- * used to pick a cheap title model.
- */
- protected override async fetchRemoteModels(): Promise<RemoteModel[] | null> {
- const payload = await this.fetchJson(`${this.endpoint}/api/tags`, {});
- const models = (payload as OllamaTagsResponse).models;
- if (!Array.isArray(models)) {
- throw new Error("Unexpected /api/tags response shape");
- }
- this.pickModelDefaults(models);
- return models.map(m => ({ id: m.name, name: formatModelName(m) }));
- }
-
- /**
- * Ollama models never appear in the committed price table (they are local
- * builds, not a vendor catalog), so tag the merged list as free rather than
- * leaving the cost unknown in the picker.
- */
- override async listModels(): Promise<ModelInfo[]> {
- const models = await super.listModels();
- return models.map(model => ({ ...model, pricing: FREE_PRICING }));
- }
-
- /** Running a model locally is free, whatever the price table knows. */
- override getModelPricing(): ModelPricing {
- return FREE_PRICING;
- }
-
- /**
- * The title model is only known once the instance has been listed, so make
- * sure that happened before falling through to the base implementation
- * (which chats with {@link titleModel}). The list is cached by the base
- * class, so this is a no-op after the first call.
- */
- override async generateTitle(firstMessage: string): Promise<string> {
- if (!this.titleModel) {
- await this.listModels();
- }
- return super.generateTitle(firstMessage);
- }
-
- /**
- * Remember which model to chat with by default and which to write chat
- * titles with. Ollama has no notion of a default, so the first installed
- * model wins; titles prefer the smallest model available, since they are a
- * throwaway one-liner and a 70B model would make opening a chat sluggish.
- */
- private pickModelDefaults(models: OllamaTag[]): void {
- if (models.length === 0) {
- return;
- }
- this.defaultModel = models[0].name;
- const smallModel = models.find(m => {
- const size = parseParamSize(m.details?.parameter_size);
- return size !== undefined && size < TITLE_MODEL_MAX_PARAMS_B;
- }) ?? models.find(m => /small|mini|tiny|phi|gemma.*2b/i.test(m.name));
- this.titleModel = smallModel?.name ?? this.defaultModel;
- }
-}
-
-/**
- * Validate a user-supplied base URL: must parse as an http(s) URL.
- * Falls back to the default local instance URL otherwise.
- */
-function sanitizeBaseUrl(baseUrl: string | undefined): string {
- if (!baseUrl) {
- return DEFAULT_BASE_URL;
- }
- try {
- const parsed = new URL(baseUrl);
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
- throw new Error(`unsupported protocol ${parsed.protocol}`);
- }
- return baseUrl;
- } catch (e) {
- getLog().error(`Ollama: invalid base URL "${baseUrl}" (${e}), falling back to ${DEFAULT_BASE_URL}`);
- return DEFAULT_BASE_URL;
- }
-}
-
-/**
- * Parse a parameter_size string like "7.6B" or "3.2B" into a number of billions.
- * Returns undefined if the string cannot be parsed.
- */
-function parseParamSize(paramSize?: string): number | undefined {
- if (!paramSize) return undefined;
- const match = paramSize.match(/^([\d.]+)\s*([BMK])/i);
- if (!match) return undefined;
- const value = parseFloat(match[1]);
- const unit = match[2].toUpperCase();
- if (unit === "B") return value;
- if (unit === "M") return value / 1000;
- if (unit === "K") return value / 1_000_000;
- return undefined;
-}
-
-/**
- * Build a human-readable display name from Ollama model metadata.
- * Example: "llama3.2:latest" → "llama3.2:latest (3.2B, Q4_K_M)"
- */
-function formatModelName(m: OllamaTag): string {
- const parts: string[] = [];
- if (m.details?.parameter_size) {
- parts.push(m.details.parameter_size);
- }
- if (m.details?.quantization_level) {
- parts.push(m.details.quantization_level);
- }
- if (parts.length > 0) {
- return `${m.name} (${parts.join(", ")})`;
- }
- return m.name;
-}