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 branch 'main' into feat/llm-ollama-provider
Tomáš Adámek1ba45f080b81
diff --cc apps/client/src/translations/en/translation.jsonindex 55f475ddd0,6597c9477c..f4735831f2--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@@ -1661,7 -2174,31 +2174,32 @@@"note_context_disabled": "Click to include current note in context","no_provider_message": "No AI provider configured. Add one to start chatting.","add_provider": "Add AI Provider",- "free": "Free"++ "free": "Free",+ "stop": "Stop",+ "retry": "Retry",+ "scroll_to_bottom": "Scroll to latest",+ "read_only_notice": "Replying is not available because this AI chat is read-only.",+ "toc_file": "File: {{name}}",+ "highlights_title": "Highlights ({{count}})",+ "highlights_empty": "No highlights yet. Select text in a message and choose \"Highlight\".",+ "copy": "Copy",+ "highlight_add": "Highlight",+ "highlight_remove": "Remove highlight",+ "highlight_remove_confirm": "Remove this highlight?",+ "quote_selection": "Quote selection",+ "quoted_from": "Quoted from",+ "show_quote_source": "Show quote source",+ "copy_message": "Copy message",+ "save_to_subnote": "Save to sub-note",+ "save_as_note": "Save as note",+ "save_note_failed": "Failed to create a note from the message.",+ "regenerate": "Regenerate",+ "delete_message": "Delete message",+ "delete_message_confirm": "Delete this message? This operation cannot be undone.",+ "attach_file": "Attach image, PDF, or text file",+ "remove_attachment": "Remove attachment",+ "attachment_upload_failed": "Failed to upload \"{{name}}\".",+ "attachment_unsupported_type": "\"{{name}}\" isn't a supported attachment type. Use an image (PNG, JPEG, GIF, WebP), a PDF, or a text/source file."},"sidebar_chat": {"title": "AI Chat",@@@ -2342,6 -3143,9 +3144,10 @@@"api_key": "API Key","api_key_placeholder": "Enter your API key","base_url": "Base URL",+ "base_url_description": "Optional. Override the default API endpoint — useful for self-hosted models (Ollama, LM Studio, vLLM) or proxies.",+ "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.","cancel": "Cancel","mcp_title": "MCP (Model Context Protocol)","mcp_enabled": "MCP server",diff --cc apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex 0303f90851,5f8247a76d..bf12bef5a3--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@@ -11,16 -77,6 +77,19 @@@ export interface ModelOption extends LlcostDescription?: string;}+function getCostDescription(model: LlmModelInfo): string | undefined {++ if (model.isSubscription) {++ return t("llm_chat.model_cost_included");++ }+ if (model.costMultiplier) {+ return `${model.costMultiplier}x`;+ }+ if (model.pricing.input === 0 && model.pricing.output === 0) {+ return t("llm_chat.free");+ }+ return undefined;+}+export interface LlmChatOptions {/** Default value for enableNoteTools */defaultEnableNoteTools?: boolean;diff --cc apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsxindex 755bcd8d64,b9191b301f..dfff9eb783--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx@@@ -1,10 -1,19 +1,20 @@@+ import "./AddProviderModal.css";+import { createPortal } from "preact/compat";- import { useState, useRef } from "preact/hooks";- import Modal from "../../../react/Modal";+ import { useMemo, useRef, useState } from "preact/hooks";++ import { t } from "../../../../services/i18n";+ import { Badge } from "../../../react/Badge";+ import { Card, CardSection } from "../../../react/Card";import FormGroup from "../../../react/FormGroup";- import FormSelect from "../../../react/FormSelect";import FormTextBox from "../../../react/FormTextBox";- import { t } from "../../../../services/i18n";+ import Modal from "../../../react/Modal";+ import SelectableCard, { SelectableCardGrid } from "../../../react/SelectableCard";+ import 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";export interface LlmProviderConfig {id: string;@@@ -18,21 -26,39 +27,43 @@@export interface ProviderType {id: string;name: string;- /** Whether this provider needs an API key (defaults to true). */- needsApiKey?: boolean;- /** Whether this provider needs a base URL. */- needsBaseUrl?: boolean;- /** Default base URL for the provider. */- defaultBaseUrl?: string;+ defaultBaseUrl: string;+ /** URL of the provider's logo (an imported `*.svg?url`), rendered monochrome via a CSS mask. */+ iconUrl: string;+ /** Short blurb shown under the provider name on its selectable card. */+ description: 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;}+ // 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.export const PROVIDER_TYPES: ProviderType[] = [- { id: "anthropic", name: "Anthropic" },- { id: "openai", name: "OpenAI" },- { id: "google", name: "Google Gemini" },- { id: "ollama", name: "Ollama", needsApiKey: false, needsBaseUrl: true, defaultBaseUrl: "http://localhost:11434" }+ { 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: "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") }++ { 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 }];+ function isValidBaseUrl(value: string): boolean {+ if (!value) {+ return true;+ }+ try {+ const parsed = new URL(value);+ return parsed.protocol === "http:" || parsed.protocol === "https:";+ } catch {+ return false;+ }+ }+interface AddProviderModalProps {show: boolean;onHidden: () => void;@@@ -45,22 -71,17 +76,20 @@@ export default function AddProviderModaconst [baseUrl, setBaseUrl] = useState("");const formRef = useRef<HTMLFormElement>(null);- const providerType = PROVIDER_TYPES.find(p => p.id === selectedProvider);- const needsApiKey = providerType?.needsApiKey !== false;- const needsBaseUrl = providerType?.needsBaseUrl === true;-- function handleProviderChange(value: string) {- setSelectedProvider(value);- const pt = PROVIDER_TYPES.find(p => p.id === value);- if (pt?.defaultBaseUrl) {- setBaseUrl(pt.defaultBaseUrl);- } else {- setBaseUrl("");- }- }+ const providerType = useMemo(+ () => 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 trimmedBaseUrl = baseUrl.trim();+ const baseUrlIsValid = isValidBaseUrl(trimmedBaseUrl);- const canSubmit = usesApiKey ? !!apiKey.trim() && baseUrlIsValid : true;++ const canSubmit = (usesApiKey ? !!apiKey.trim() : true) && (usesBaseUrl ? baseUrlIsValid : true);function handleSubmit() {- if (needsApiKey && !apiKey.trim()) {+ if (!canSubmit) {return;}@@@ -68,8 -89,8 +97,8 @@@id: `${selectedProvider}_${Date.now()}`,name: providerType?.name || selectedProvider,provider: selectedProvider,- apiKey: apiKey.trim(),- ...(needsBaseUrl && baseUrl.trim() ? { baseUrl: baseUrl.trim() } : {})+ apiKey: usesApiKey ? apiKey.trim() : "",- ...(usesApiKey && trimmedBaseUrl && { baseURL: trimmedBaseUrl })++ ...(usesBaseUrl && trimmedBaseUrl && { baseURL: trimmedBaseUrl })};onSave(newProvider);@@@ -110,36 -131,64 +139,84 @@@</>}>- <FormGroup name="provider-type" label={t("llm.provider_type")}>- <FormSelect- values={PROVIDER_TYPES}- keyProperty="id"- titleProperty="name"- currentValue={selectedProvider}- onChange={handleProviderChange}- />- </FormGroup>-- {needsApiKey && (- <FormGroup name="api-key" label={t("llm.api_key")}>- <FormTextBox- type="password"- currentValue={apiKey}- onChange={setApiKey}- placeholder={t("llm.api_key_placeholder")}- autoFocus- />- </FormGroup>- )}-- {needsBaseUrl && (- <FormGroup name="base-url" label={t("llm.base_url")}>- <FormTextBox- currentValue={baseUrl}- onChange={setBaseUrl}- placeholder={providerType?.defaultBaseUrl || "http://localhost:11434"}- />- </FormGroup>+ <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>+ )}+ </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>)}</Modal>,document.bodydiff --cc apps/client/src/widgets/type_widgets/options/llm/icons/ollama.svgindex 0000000000,0000000000..432f73e738new file mode 100644--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/llm/icons/ollama.svg@@@ -1,0 -1,0 +1,1 @@@++<svg fill="#000000" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Ollama</title><path d="M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z"/></svg>diff --cc apps/server/src/routes/api/llm_chat.tsindex 6ea84b6c45,66ef7f524f..4a8120c22c--- a/apps/server/src/routes/api/llm_chat.ts+++ b/apps/server/src/routes/api/llm_chat.ts@@@ -53,13 -52,6 +52,10 @@@ async function streamChat(req: Requestconst provider = getProviderByType(config.provider || "anthropic");- // Ensure Ollama models are loaded so defaultModel/titleModel are set- if (provider instanceof OllamaProvider) {- await provider.loadModels();- }-- const result = provider.chat(messages, config);++ // Providers with a dynamic model list (Ollama) need it loaded so++ // defaultModel/titleModel are populated before chatting++ await provider.loadModels?.();+// Get pricing and display name for the modelconst modelId = config.model || provider.getAvailableModels().find(m => m.isDefault)?.id;if (!modelId) {diff --cc apps/server/src/routes/routes.tsindex fab968bf56,24e55816d2..6b11d40e26--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@@ -321,20 -171,12 +171,12 @@@ function register(app: express.ApplicatapiRoute(GET, "/api/database/check-integrity", databaseRoute.checkIntegrity);- asyncRoute(PST, "/api/script/exec", [auth.checkApiAuth, csrfMiddleware], scriptRoute.exec, apiResultHandler);-- apiRoute(PST, "/api/script/run/:noteId", scriptRoute.run);- apiRoute(GET, "/api/script/startup", scriptRoute.getStartupBundles);- apiRoute(GET, "/api/script/widgets", scriptRoute.getWidgetBundles);- apiRoute(PST, "/api/script/bundle/:noteId", scriptRoute.getBundle);- apiRoute(GET, "/api/script/relation/:noteId/:relationName", scriptRoute.getRelationBundles);-// LLM chat endpointsasyncRoute(PST, "/api/llm-chat/stream", [auth.checkApiAuthOrElectron, csrfMiddleware], llmChatRoute.streamChat, null);- apiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);+ asyncApiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);// no CSRF since this is called from android app- route(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);+ asyncRoute(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);asyncRoute(PST, "/api/sender/image", [auth.checkEtapiToken, uploadMiddlewareWithErrorHandling], senderRoute.uploadImage, apiResultHandler);asyncRoute(PST, "/api/sender/note", [auth.checkEtapiToken], senderRoute.saveNote, apiResultHandler);diff --cc apps/server/src/services/llm/chat_title.tsindex fffec5b2d6,2f45bd5385..84a4b7f83d--- a/apps/server/src/services/llm/chat_title.ts+++ b/apps/server/src/services/llm/chat_title.ts@@@ -29,12 -28,6 +28,8 @@@ export async function generateChatTitle}const provider = getProvider();-- // Ensure Ollama models are loaded so titleModel is set- if (provider instanceof OllamaProvider) {- await provider.loadModels();- }-++ // Providers with a dynamic model list (Ollama) need it loaded for the title model++ await provider.loadModels?.();const title = await provider.generateTitle(firstMessage);if (title) {note.title = title;diff --cc apps/server/src/services/llm/index.tsindex b64cdddf3d,5a0bf0d314..16f42873cc--- a/apps/server/src/services/llm/index.ts+++ b/apps/server/src/services/llm/index.ts@@@ -1,10 -1,10 +1,11 @@@- import type { LlmProvider, ModelInfo } from "./types.js";+ 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 { OpenAiProvider } from "./providers/openai.js";- import optionService from "../options.js";- import log from "../log.js";+ import type { LlmProvider, ModelInfo } from "./types.js";/*** Configuration for a single LLM provider instance.@@@ -20,11 -20,13 +21,15 @@@ export interface LlmProviderSetup}/** Factory functions for creating provider instances */- const providerFactories: Record<string, (apiKey: string, baseUrl?: string) => LlmProvider> = {- anthropic: (apiKey) => new AnthropicProvider(apiKey),- openai: (apiKey) => new OpenAiProvider(apiKey),- google: (apiKey) => new GoogleProvider(apiKey),- ollama: (_apiKey, baseUrl) => new OllamaProvider(baseUrl)+ 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()++ "claude-agent": () => new ClaudeAgentProvider(),++ // Local models via Ollama's OpenAI-compatible API — no API key needed.++ ollama: (_apiKey, baseURL) => new OllamaProvider(baseURL)};/** Cache of instantiated providers by their config ID */@@@ -120,12 -122,6 +125,8 @@@ export async function getAllModels(): Ptry {const provider = getProvider(config.id);-- // Ollama needs to fetch models from the running instance- if (provider instanceof OllamaProvider) {- await provider.loadModels();- }-++ // Providers with a dynamic model list (Ollama) fetch it at runtime++ await provider.loadModels?.();const models = provider.getAvailableModels();for (const model of models) {allModels.push({ ...model, provider: config.provider });diff --cc apps/server/src/services/llm/providers/ollama.tsindex c47caabd3c,0000000000..bc3ffa9d85mode 100644,000000..100644--- a/apps/server/src/services/llm/providers/ollama.ts+++ b/apps/server/src/services/llm/providers/ollama.ts@@@ -1,159 -1,0 +1,180 @@@+/**+ * Ollama provider — uses the OpenAI-compatible API that Ollama exposes.+ *+ * 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.+ */++import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";++import { getLog } from "@triliumnext/core";+- import log from "../../log.js";+import { BaseProvider } from "./base_provider.js";+import type { ModelInfo, ModelPricing } from "../types.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. */+const FREE_PRICING: ModelPricing = { input: 0, output: 0 };++/**+ * 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;+ };+ }>;+}+++/**++ * 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(/\/+$/, "");++ } 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 {+ 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;- private modelsLoaded = false;++ /** Timestamp of the last successful non-empty model fetch (0 = never). */++ private modelsLoadedAt = 0;++ constructor(baseUrl?: string) {+ super();- this.baseUrl = baseUrl || DEFAULT_BASE_URL;++ 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);+ }+- override getAvailableModels(): ModelInfo[] {- return this.availableModels;- }-+ /**- * Fetch available models from the Ollama instance.- * Called by the route handler before returning models to the client.++ * 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.modelsLoaded) {++ 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) {- log.error(`Ollama: failed to fetch models (${res.status})`);- return [];++ getLog().error(`Ollama: failed to fetch models (${res.status})`);++ return this.availableModels;+ }++ const data = (await res.json()) as OllamaTagsResponse;+ 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();+ }+- this.modelsLoaded = true;+ return this.availableModels;+ } catch (e) {- log.error(`Ollama: failed to connect to ${this.baseUrl}: ${e}`);- return [];++ getLog().error(`Ollama: failed to connect to ${this.baseUrl}: ${e}`);++ return this.availableModels;+ }+ }+}diff --cc apps/server/src/services/llm/types.tsindex 3924d8601c,451f80ca5b..2943cf9e38--- a/apps/server/src/services/llm/types.ts+++ b/apps/server/src/services/llm/types.ts@@@ -74,6 -90,6 +90,13 @@@ export interface LlmProvider*/getAvailableModels(): ModelInfo[];++ /**++ * For providers with a dynamic model list (e.g. Ollama), fetch the models++ * from the running instance. Call sites should `await provider.loadModels?.()`++ * before reading the model list. No-op for providers with static model lists.++ */++ loadModels?(): Promise<ModelInfo[]>;++/*** Generate a short title summarizing a message.* Used for auto-renaming chat notes. Should use a fast, cheap model.