Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
Merge remote-tracking branch 'origin/main' into feat/llm-ollama-provider
Elian Dorane5f0ea230696
diff --cc apps/client/src/services/llm_model_cost.tsindex 0000000000,b1345e958e..06216d91b4mode 000000,100644..100644--- a/apps/client/src/services/llm_model_cost.ts+++ b/apps/client/src/services/llm_model_cost.ts@@@ -1,0 -1,20 +1,25 @@@+ import type { LlmModelInfo } from "@triliumnext/commons";++ import { t } from "./i18n.js";++ /**+ * Human-readable per-model cost hint for the model pickers: "Subscription" for+ * subscription-covered models, "$3 / $15 per Mtok" (input / output, USD per+ * million tokens) for metered ones, and undefined when pricing is unknown —+ * dynamically discovered models the price table doesn't cover. Replaces the old+ * relative "Nx" multiplier, which was only comparable within a single provider.+ */+ export function formatModelCost(model: Pick<LlmModelInfo, "isSubscription" | "pricing">): string | undefined {+ if (model.isSubscription) {+ return t("llm_chat.model_cost_included");+ }+ if (!model.pricing) {+ return undefined;+ }++ // Models that run on the user's own hardware (Ollama) are priced at zero —++ // "Free" reads better there than "$0 / $0 per Mtok".++ if (model.pricing.input === 0 && model.pricing.output === 0) {++ return t("llm_chat.free");++ }+ return t("llm.model_cost_per_mtok", { input: model.pricing.input, output: model.pricing.output });+ }diff --cc apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsxindex 839b623b2e,4a96db9dfd..2c4c483dec--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx@@@ -27,10 -32,18 +32,21 @@@ import { useLlmChat } from "./useLlmChatype LlmChatApi = ReturnType<typeof useLlmChat>;type LlmChatOptions = Parameters<typeof useLlmChat>[1];- const MODELS = [- { id: "sonnet", name: "Sonnet", provider: "claude-agent", isDefault: true, isSubscription: true },- { id: "opus", name: "Opus", provider: "anthropic", costMultiplier: 5 },- { id: "mini", name: "Mini", provider: "openai" }+ // 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", pricing: { input: 3, output: 15 } }+ ] },+ { id: "o_1", name: "OpenAI", provider: "openai", selectedModels: [+ { id: "mini", name: "Mini" }++ ] },++ { id: "ol_1", name: "My Ollama", provider: "ollama", selectedModels: [++ { id: "llama3.2", name: "llama3.2 (3.2B)", pricing: { input: 0, output: 0 } }+ ] }];describe("useLlmChat", () => {@@@ -91,8 -105,26 +108,27 @@@const costById = new Map(api().availableModels.map((m) => [m.id, m.costDescription]));expect(costById.get("sonnet")).toBe("llm_chat.model_cost_included"); // subscription → "included" label- expect(costById.get("opus")).toBe("5x"); // metered multiplier- expect(costById.get("mini")).toBeUndefined(); // baseline cost — no annotation+ expect(costById.get("opus")).toBe("llm.model_cost_per_mtok"); // metered → per-Mtok price label (key echoed by the i18n mock)+ expect(costById.get("mini")).toBeUndefined(); // unknown pricing — no annotation++ expect(costById.get("llama3.2")).toBe("llm_chat.free"); // locally run (zero-priced) → "free" label+ });++ it("groups models per provider, keeping a provider with no selected models as an empty group", async () => {+ // A config migrated from before selection existed: no selectedModels.+ optionsGetJsonMock.mockReturnValue([+ { id: "a_1", name: "Anthropic", provider: "anthropic", selectedModels: [{ id: "opus", name: "Opus" }] },+ { id: "legacy_1", name: "My OpenAI", provider: "openai" }+ ]);+ await mountChat();++ expect(api().modelGroups.map(g => [g.id, g.models.length])).toEqual([+ ["a_1", 1],+ ["legacy_1", 0] // still present so the dropdown can prompt the user to configure it+ ]);+ // A configured-but-empty provider still counts as "has provider".+ expect(api().hasProvider).toBe(true);+ // The empty group contributes no selectable models.+ expect(api().availableModels.map(m => m.id)).toEqual(["opus"]);});it("sends with the provider recorded at model selection", async () => {diff --cc apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsxindex dfff9eb783,b861a70748..9f5b242cf5--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx@@@ -13,8 -14,8 +14,9 @@@ import SelectableCard, { SelectableCardimport anthropicIcon from "./icons/anthropic.svg?url";import claudeAgentIcon from "./icons/claude-ai.svg?url";import geminiIcon from "./icons/gemini.svg?url";+import ollamaIcon from "./icons/ollama.svg?url";import openaiIcon from "./icons/openai.svg?url";+ import ModelSelection from "./ModelSelection";export interface LlmProviderConfig {id: string;@@@ -81,28 -88,56 +93,59 @@@ export default function AddProviderModa[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 trimmedApiKey = apiKey.trim();const trimmedBaseUrl = baseUrl.trim();const baseUrlIsValid = isValidBaseUrl(trimmedBaseUrl);- const canSubmit = (usesApiKey ? !!apiKey.trim() : true) && (usesBaseUrl ? baseUrlIsValid : true);- const connectionValid = usesApiKey ? !!trimmedApiKey && baseUrlIsValid : true;++ const connectionValid = (usesApiKey ? !!trimmedApiKey : true) && (usesBaseUrl ? baseUrlIsValid : true);++ const modelQuery = useMemo(+ () => ({ provider: selectedProvider, apiKey: trimmedApiKey, baseURL: trimmedBaseUrl || undefined }),+ [selectedProvider, trimmedApiKey, trimmedBaseUrl]+ );++ // Seed the recommended models only when the provider has no stored selection+ // yet: a brand-new provider, or a pre-selection config being migrated (where+ // seeding is the whole point of the "configure models" prompt). An existing+ // but explicitly emptied selection (`[]`, truthy) is a deliberate "hide all"+ // and must not be silently re-populated when the editor is reopened — hence+ // the check against `undefined` rather than edit mode or `length === 0`.+ const seedDefaultModels = !existingProvider?.selectedModels;++ function reset() {+ setStep(initialStep);+ 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() : "",- ...(usesBaseUrl && trimmedBaseUrl && { baseURL: trimmedBaseUrl })+ apiKey: usesApiKey ? trimmedApiKey : "",- ...(usesApiKey && trimmedBaseUrl && { baseURL: trimmedBaseUrl }),++ ...(usesBaseUrl && trimmedBaseUrl && { baseURL: trimmedBaseUrl }),+ selectedModels};- onSave(newProvider);- resetForm();+ onSave(saved);+ reset();onHidden();}@@@ -139,82 -174,79 +182,100 @@@</>}>- <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>- ) : usesBaseUrl ? (- // Key-less self-hosted provider (Ollama): the base URL is- // the primary connection detail.- <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}- 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>++ ) : 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.++ <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}++ 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={seedDefaultModels}+ /></CardSection></Card>)}diff --cc apps/server/src/services/llm/index.spec.tsindex f2c4d89ea8,15379c17b8..645a78ba30--- a/apps/server/src/services/llm/index.spec.ts+++ b/apps/server/src/services/llm/index.spec.ts@@@ -31,6 -41,6 +41,7 @@@ vi.mock("./providers/anthropic.js", ()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") }));import {clearProviderCache,@@@ -78,13 -92,13 +93,16 @@@ describe("llm/index provider registry"{ id: "a", name: "A", provider: "anthropic", apiKey: "ka" },{ 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: "c", name: "C", provider: "claude-agent", apiKey: "" },++ { id: "l", name: "L", provider: "ollama", apiKey: "", baseURL: "http://ollama.lan:11434" }]);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"]);});it("throws when no providers are configured (null and empty array)", () => {diff --cc apps/server/src/services/llm/index.tsindex 16f42873cc,d80c6dbed5..dc9c7f426e--- a/apps/server/src/services/llm/index.ts+++ b/apps/server/src/services/llm/index.ts@@@ -18,19 -17,43 +18,46 @@@ export interface LlmProviderSetupapiKey: 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 */- const providerFactories: Record<string, (apiKey: string, baseURL?: string) => LlmProvider> = {- anthropic: (apiKey, baseURL) => new AnthropicProvider(apiKey, baseURL),- openai: (apiKey, baseURL) => new OpenAiProvider(apiKey, baseURL),- google: (apiKey, baseURL) => new GoogleProvider(apiKey, baseURL),- // Claude Pro/Max subscription via the Claude Agent SDK — no API key;- // authentication is handled by Claude Code itself (`claude /login`).- "claude-agent": () => new ClaudeAgentProvider(),- // Local models via Ollama's OpenAI-compatible API — no API key needed.- ollama: (_apiKey, baseURL) => new OllamaProvider(baseURL)- };+ /** Provider type identifiers that can be instantiated, for error messages. */-const PROVIDER_TYPES = ["anthropic", "openai", "google", "claude-agent"];++const PROVIDER_TYPES = ["anthropic", "openai", "google", "claude-agent", "ollama"];++ /**+ * Instantiate a provider from its type identifier.+ *+ * Deliberately a switch over literal cases rather than a lookup table: the+ * provider type is user-controlled, and looking a factory up by it — with a+ * plain object *or* a Map — makes the invoked function a value derived from+ * untrusted input, which is exactly what CodeQL's+ * `js/unvalidated-dynamic-method-call` flags. Here every branch calls a+ * statically known constructor, so no dynamic dispatch is possible at all.+ */+ function createProviderInstance(provider: string, apiKey: string, baseURL?: string): LlmProvider {+ switch (provider) {+ case "anthropic":+ return new AnthropicProvider(apiKey, baseURL);+ case "openai":+ return new OpenAiProvider(apiKey, baseURL);+ case "google":+ return new GoogleProvider(apiKey, baseURL);+ // Claude Pro/Max subscription via the Claude Agent SDK — no API key;+ // 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.++ case "ollama":++ return new OllamaProvider(apiKey, baseURL);+ default:+ throw new Error(`Unknown LLM provider type: ${provider}. Available: ${PROVIDER_TYPES.join(", ")}`);+ }+ }/** Cache of instantiated providers by their config ID */let cachedProviders: Record<string, LlmProvider> = {};diff --cc apps/server/src/services/llm/providers/ollama.spec.tsindex de91e35020,0000000000..0acea6023emode 100644,000000..100644--- a/apps/server/src/services/llm/providers/ollama.spec.ts+++ b/apps/server/src/services/llm/providers/ollama.spec.ts@@@ -1,140 -1,0 +1,194 @@@+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();+ });+- it("loads models with display 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 provider = new OllamaProvider();- const models = await provider.loadModels();-- 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"- ]);- // Local models are free and the first one is the default.- expect(models[0].isDefault).toBe(true);- expect(models[0].pricing).toEqual({ input: 0, output: 0 });- });++ 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("caches the model list within the TTL and refetches after it expires", async () => {- vi.useFakeTimers();- fetchMock.mockResolvedValue(tagsResponse([{ name: "m1" }]));++ it("defaults to the local instance and strips trailing slashes", () => {++ new OllamaProvider();++ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://localhost:11434/v1" });+- const provider = new OllamaProvider();- await provider.loadModels();- await provider.loadModels();- expect(fetchMock).toHaveBeenCalledTimes(1);++ new OllamaProvider("", "http://ollama.lan:11434///");++ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://ollama.lan:11434/v1" });++ });+- vi.advanceTimersByTime(61_000);- await provider.loadModels();- 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.loadModels()).resolves.toEqual([]);-- // Models get pulled in Ollama, the next call must refetch.- fetchMock.mockResolvedValue(tagsResponse([{ name: "fresh" }]));- const models = await provider.loadModels();- expect(models).toHaveLength(1);- expect(fetchMock).toHaveBeenCalledTimes(2);- });++ 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" });+- it("keeps the previous model list when the instance is unreachable", async () => {- vi.useFakeTimers();- fetchMock.mockResolvedValue(tagsResponse([{ name: "m1" }]));- const provider = new OllamaProvider();- await provider.loadModels();++ new OllamaProvider("", "not a url");++ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "ollama", baseURL: "http://localhost:11434/v1" });++ });+- vi.advanceTimersByTime(61_000);- fetchMock.mockRejectedValue(new Error("ECONNREFUSED"));- const models = await provider.loadModels();- expect(models.map(m => m.id)).toEqual(["m1"]);++ 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" });++ });+ });+- it("returns the current list on a malformed /api/tags response", async () => {- fetchMock.mockResolvedValue({ ok: true, json: async () => ({ error: "boom" }) } as Response);- const provider = new OllamaProvider();- await expect(provider.loadModels()).resolves.toEqual([]);- });-- it("returns the current list when the instance responds with an error status", async () => {- fetchMock.mockResolvedValue({ ok: false, status: 500 } as Response);- const provider = new OllamaProvider();- await expect(provider.loadModels()).resolves.toEqual([]);- });-- it("falls back to the default base URL for invalid or non-http URLs", async () => {- fetchMock.mockResolvedValue(tagsResponse([]));-- await new OllamaProvider("ftp://example.com").loadModels();- expect(fetchMock).toHaveBeenLastCalledWith("http://localhost:11434/api/tags", expect.anything());-- await new OllamaProvider("not a url").loadModels();- expect(fetchMock).toHaveBeenLastCalledWith("http://localhost:11434/api/tags", expect.anything());++ 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/);++ });+ });+- it("strips trailing slashes from a valid base URL", async () => {- fetchMock.mockResolvedValue(tagsResponse([]));- await new OllamaProvider("http://ollama.lan:11434///").loadModels();- expect(fetchMock).toHaveBeenLastCalledWith("http://ollama.lan:11434/api/tags", expect.anything());++ 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("prefers a small model for title generation", async () => {- fetchMock.mockResolvedValue(tagsResponse([- { name: "big-model", parameter_size: "70B" },- { name: "small-model", parameter_size: "3B" }- ]));-- const provider = new OllamaProvider();- await provider.loadModels();- // titleModel is protected — observable via generateTitle's model choice,- // so assert through the internal field cast instead.- expect((provider as unknown as { titleModel: string }).titleModel).toBe("small-model");++ it("reports every model as free, whatever the price table knows", () => {++ expect(new OllamaProvider().getModelPricing()).toEqual({ input: 0, output: 0 });+ });+});diff --cc apps/server/src/services/llm/providers/ollama.tsindex fa76659f91,0000000000..1222fc538amode 100644,000000..100644--- a/apps/server/src/services/llm/providers/ollama.ts+++ b/apps/server/src/services/llm/providers/ollama.ts@@@ -1,184 -1,0 +1,194 @@@+/**- * Ollama provider — uses the OpenAI-compatible API that Ollama exposes.++ * 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.+ *- * Because Ollama runs locally with a dynamic model list, this provider- * fetches available models from the Ollama instance at runtime instead- * of using a hardcoded list.++ * 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 { BaseProvider } from "./base_provider.js";+import type { ModelInfo, ModelPricing } from "../types.js";++import { BaseProvider, type RemoteModel } from "./base_provider.js";++const DEFAULT_BASE_URL = "http://localhost:11434";+- /** How long a fetched model list stays fresh before it is re-fetched. */- const MODEL_LIST_TTL_MS = 60_000;-- /** Ollama models are local and free. */++/** 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.replace(/\/+$/, "");++ 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: OllamaTagsResponse["models"][number]): string {++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;+}-- export class OllamaProvider extends BaseProvider {- name = "ollama";- protected defaultModel = "";- protected titleModel = "";- protected availableModels: ModelInfo[] = [];- protected modelPricing: Record<string, ModelPricing> = {};-- private openai: OpenAISDKProvider;- private baseUrl: string;- /** Timestamp of the last successful non-empty model fetch (0 = never). */- private modelsLoadedAt = 0;-- constructor(baseUrl?: string) {- super();- this.baseUrl = sanitizeBaseUrl(baseUrl);-- // Ollama exposes an OpenAI-compatible endpoint at /v1- this.openai = createOpenAI({- apiKey: "ollama", // Ollama ignores this but the SDK requires it- baseURL: `${this.baseUrl}/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);- }-- /**- * Fetch available models from the Ollama instance. The list is cached for- * a short TTL so pulling a new model in Ollama shows up without a server- * restart; an empty list is never cached so first-use setups can recover.- */- async loadModels(): Promise<ModelInfo[]> {- if (this.availableModels.length > 0 && Date.now() - this.modelsLoadedAt < MODEL_LIST_TTL_MS) {- return this.availableModels;- }-- try {- const res = await fetch(`${this.baseUrl}/api/tags`, {- signal: AbortSignal.timeout(5000)- });- if (!res.ok) {- getLog().error(`Ollama: failed to fetch models (${res.status})`);- return this.availableModels;- }-- const data = (await res.json()) as OllamaTagsResponse;- if (!Array.isArray(data.models)) {- getLog().error("Ollama: unexpected /api/tags response shape");- return this.availableModels;- }- this.availableModels = data.models.map((m, i) => ({- id: m.name,- name: formatModelName(m),- pricing: FREE_PRICING,- costMultiplier: 0,- isDefault: i === 0- }));-- this.modelPricing = Object.fromEntries(- this.availableModels.map((m) => [m.id, FREE_PRICING])- );-- if (this.availableModels.length > 0) {- this.defaultModel = this.availableModels[0].id;- // Prefer smaller model for titles if available (under 4B params)- const smallModel = data.models.find((m) => {- const size = parseParamSize(m.details?.parameter_size);- return size !== undefined && size < 4;- }) ?? data.models.find((m) =>- /small|mini|tiny|phi|gemma.*2b/i.test(m.name)- );- this.titleModel = smallModel?.name || this.defaultModel;- this.modelsLoadedAt = Date.now();- }-- return this.availableModels;- } catch (e) {- getLog().error(`Ollama: failed to connect to ${this.baseUrl}: ${e}`);- return this.availableModels;- }- }- }