Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): serve model enumeration from the shared route table

Elian Doranf540d568f03a
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
index c90f23a44d..816b6d7911 100644
--- a/apps/server/src/routes/api/llm_chat.spec.ts
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -3,7 +3,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
configured: true,
- models: [] as unknown[],
chunks: [] as unknown[],
availableModels: [{ id: "m1", name: "Model One", isDefault: true }] as { id: string; name: string; isDefault?: boolean }[],
chatThrows: undefined as unknown,
@@ -13,11 +12,7 @@ const state = vi.hoisted(() => ({
chunkSignal: undefined as AbortSignal | undefined,
// Records how streamChat resolved the provider.
providerIdRequested: undefined as string | undefined,
- providerTypeRequested: undefined as string | undefined,
- // Records the credentials passed to listProviderModels by the provider-models route.
- providerModelsArgs: undefined as unknown[] | undefined,
- // When set, listProviderModels rejects with this (simulates a bad key).
- providerModelsThrows: undefined as unknown
+ providerTypeRequested: undefined as string | undefined
}));
vi.mock("../../services/llm/index.js", () => {
@@ -34,11 +29,6 @@ vi.mock("../../services/llm/index.js", () => {
});
return {
hasConfiguredProviders: () => state.configured,
- listProviderModels: async (...args: unknown[]) => {
- state.providerModelsArgs = args;
- if (state.providerModelsThrows !== undefined) throw state.providerModelsThrows;
- return state.models;
- },
getSelectedModel: () => undefined,
getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
@@ -88,52 +78,17 @@ describe("LLM chat API", () => {
afterEach(() => {
Object.assign(state, {
configured: true,
- models: [],
chunks: [],
availableModels: [{ id: "m1", name: "Model One", isDefault: true }],
chatThrows: undefined,
chunkNative: false,
chunkSignal: undefined,
providerIdRequested: undefined,
- providerTypeRequested: undefined,
- providerModelsArgs: undefined,
- providerModelsThrows: undefined
+ providerTypeRequested: undefined
});
generateChatTitle.mockClear();
});
- describe("getProviderModels", () => {
- it("lists models for the credentials in the request body", async () => {
- state.models = [{ id: "m1" }];
- const req = { body: { provider: "openai", apiKey: "sk-test", baseURL: "http://localhost:11434/v1" } } as unknown as Request;
- await expect(llmChatRoute.getProviderModels(req, {} as Response)).resolves.toEqual({ models: [{ id: "m1" }] });
- expect(state.providerModelsArgs).toEqual(["openai", "sk-test", "http://localhost:11434/v1"]);
- });
-
- it("throws when no provider is given", async () => {
- const req = { body: {} } as unknown as Request;
- await expect(llmChatRoute.getProviderModels(req, {} as Response)).rejects.toThrow(/provider is required/);
- });
-
- it("surfaces a listing failure (e.g. a bad API key) instead of masking it", async () => {
- state.providerModelsThrows = new Error("Authentication failed (HTTP 401) — check the API key.");
- const req = { body: { provider: "openai", apiKey: "bad-key" } } as unknown as Request;
- await expect(llmChatRoute.getProviderModels(req, {} as Response)).rejects.toThrow(/Authentication failed \(HTTP 401\)/);
- });
-
- it("defaults a missing apiKey to an empty string", async () => {
- const req = { body: { provider: "claude-agent" } } as unknown as Request;
- await llmChatRoute.getProviderModels(req, {} as Response);
- expect(state.providerModelsArgs).toEqual(["claude-agent", "", undefined]);
- });
-
- it("stringifies a non-Error listing failure into the validation error", async () => {
- state.providerModelsThrows = "socket hang up";
- const req = { body: { provider: "openai", apiKey: "k" } } as unknown as Request;
- await expect(llmChatRoute.getProviderModels(req, {} as Response)).rejects.toThrow("socket hang up");
- });
- });
-
describe("streamChat", () => {
function req(body: unknown) { return { body } as unknown as Request; }
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index ad0c9e172d..ed43c52ee4 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -1,10 +1,10 @@
import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
-import { getLog, ValidationError } from "@triliumnext/core";
-import type { Request, Response } from "express";
-
+import { getLog } from "@triliumnext/core";
import { generateChatTitle } from "@triliumnext/core/src/services/llm/chat_title.js";
-import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, listProviderModels, type LlmProviderConfig } from "../../services/llm/index.js";
import { formatStreamError, streamToChunks } from "@triliumnext/core/src/services/llm/stream.js";
+import type { Request, Response } from "express";
+
+import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, type LlmProviderConfig } from "../../services/llm/index.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";
interface ChatRequest {
@@ -125,33 +125,6 @@ async function streamChat(req: Request, res: Response) {
}
}
-interface ProviderModelsRequest {
- provider: string;
- apiKey?: string;
- baseURL?: string;
-}
-
-/**
- * List the live models for a provider described by raw credentials. Used by the
- * model-selection screen while adding or editing a provider — the config need
- * not be saved yet, so credentials come in the request body rather than by id.
- */
-async function getProviderModels(req: Request, _res: Response) {
- const { provider, apiKey, baseURL } = req.body as ProviderModelsRequest;
- if (!provider) {
- throw new ValidationError("provider is required");
- }
- try {
- return { models: await listProviderModels(provider, apiKey ?? "", baseURL) };
- } catch (error) {
- // A live-listing failure is almost always a bad credential or an
- // unreachable endpoint the user just entered — surface it as a 400 so
- // the model-selection screen shows the reason instead of a generic 500.
- throw new ValidationError(error instanceof Error ? error.message : String(error));
- }
-}
-
export default {
- streamChat,
- getProviderModels
+ streamChat
};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index f0df90f9c8..c5ed6df467 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -165,7 +165,6 @@ function register(app: express.Application) {
// LLM chat endpoints
asyncRoute(PST, "/api/llm-chat/stream", [auth.checkApiAuthOrElectron, csrfMiddleware], llmChatRoute.streamChat, null);
- asyncApiRoute(PST, "/api/llm-chat/provider-models", llmChatRoute.getProviderModels);
// no CSRF since this is called from android app
asyncRoute(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
index 113b598aad..9896c4a76c 100644
--- a/apps/standalone/src/lightweight/browser_routes.spec.ts
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -28,6 +28,16 @@ describe("registerRoutes (real wiring)", () => {
expect(parseJson(res.body)).toEqual({ isCpuArchMismatch: false });
});
+ // The model-selection screen calls this while adding a provider. It is an async
+ // handler in the shared table, so reaching its validation error here proves the
+ // browser router registers and awaits it — a provider name is rejected before the
+ // route reaches for the AI SDK, so no provider is contacted.
+ it("serves the LLM provider-models route", async () => {
+ const res = await router.dispatch("POST", "http://localhost/api/llm-chat/provider-models", {});
+ expect(res.status).toBe(400);
+ expect(text(res.body)).toContain("provider is required");
+ });
+
it("serves the compatibility dummy routes", async () => {
expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/widgets")).body)).toEqual([]);
expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/startup")).body)).toEqual([]);
diff --git a/packages/trilium-core/src/routes/api/llm.spec.ts b/packages/trilium-core/src/routes/api/llm.spec.ts
new file mode 100644
index 0000000000..4e700cb69a
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/llm.spec.ts
@@ -0,0 +1,54 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ models: [] as unknown[],
+ /** Records the credentials the route passed to listProviderModels. */
+ args: undefined as unknown[] | undefined,
+ /** When set, listProviderModels rejects with this (simulates a bad key). */
+ throws: undefined as unknown
+}));
+
+// The route reaches the provider registry through a dynamic import, so that the
+// AI SDK stays out of the startup chunk; mocking the module id covers it either way.
+vi.mock("../../services/llm/index.js", () => ({
+ listProviderModels: async (...args: unknown[]) => {
+ state.args = args;
+ if (state.throws !== undefined) throw state.throws;
+ return state.models;
+ }
+}));
+
+import { getProviderModels } from "./llm.js";
+
+describe("getProviderModels", () => {
+ afterEach(() => {
+ state.models = [];
+ state.args = undefined;
+ state.throws = undefined;
+ });
+
+ it("lists models for the credentials in the request body, defaulting a missing key to an empty string", async () => {
+ state.models = [{ id: "m1" }];
+ await expect(getProviderModels({ body: { provider: "openai", apiKey: "sk-test", baseURL: "http://localhost:11434/v1" } }))
+ .resolves.toEqual({ models: [{ id: "m1" }] });
+ expect(state.args).toEqual(["openai", "sk-test", "http://localhost:11434/v1"]);
+
+ // The subscription provider carries no key of its own — auth is Claude Code's.
+ await getProviderModels({ body: { provider: "claude-agent" } });
+ expect(state.args).toEqual(["claude-agent", "", undefined]);
+ });
+
+ it("throws when no provider is given", async () => {
+ await expect(getProviderModels({ body: {} as never })).rejects.toThrow(/provider is required/);
+ });
+
+ it("surfaces a listing failure instead of masking it, whether or not it is an Error", async () => {
+ state.throws = new Error("Authentication failed (HTTP 401) — check the API key.");
+ await expect(getProviderModels({ body: { provider: "openai", apiKey: "bad-key" } }))
+ .rejects.toThrow(/Authentication failed \(HTTP 401\)/);
+
+ state.throws = "socket hang up";
+ await expect(getProviderModels({ body: { provider: "openai", apiKey: "k" } }))
+ .rejects.toThrow("socket hang up");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/llm.ts b/packages/trilium-core/src/routes/api/llm.ts
new file mode 100644
index 0000000000..7c41348802
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/llm.ts
@@ -0,0 +1,48 @@
+/**
+ * LLM endpoints that every runtime can serve.
+ *
+ * Streaming a chat is not here: it is Server-Sent Events, which the browser
+ * build's request bridge cannot carry (it answers a request with one buffered
+ * body). That route stays in `apps/server` until the worker grows a chunk
+ * channel of its own.
+ */
+
+import { ValidationError } from "../../errors.js";
+
+interface ProviderModelsRequest {
+ provider: string;
+ apiKey?: string;
+ baseURL?: string;
+}
+
+/**
+ * List the live models for a provider described by raw credentials. Used by the
+ * model-selection screen while adding or editing a provider — the config need
+ * not be saved yet, so credentials come in the request body rather than by id.
+ */
+export async function getProviderModels(req: { body: ProviderModelsRequest }) {
+ const { provider, apiKey, baseURL } = req.body;
+ if (!provider) {
+ throw new ValidationError("provider is required");
+ }
+
+ // Imported here rather than at module scope so the AI SDK lands in a lazy
+ // chunk. This module is reachable from the shared route table, which the
+ // standalone worker builds during startup — a static import would put
+ // ~200 KB of provider SDK in that startup path for every user, whether or
+ // not they have ever enabled the feature.
+ const { listProviderModels } = await import("../../services/llm/index.js");
+
+ try {
+ return { models: await listProviderModels(provider, apiKey ?? "", baseURL) };
+ } catch (error) {
+ // A live-listing failure is almost always a bad credential or an
+ // unreachable endpoint the user just entered — surface it as a 400 so
+ // the model-selection screen shows the reason instead of a generic 500.
+ throw new ValidationError(error instanceof Error ? error.message : String(error));
+ }
+}
+
+export default {
+ getProviderModels
+};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 069d45535f..ac2f0be744 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -37,6 +37,7 @@ import loginApiRoute from "./api/login";
import fontsRoute from "./api/fonts";
import ocrRoute from "./api/ocr";
import linkEmbedRoute from "./api/link_embed";
+import llmRoute from "./api/llm";
// TODO: Deduplicate with routes.ts
const GET = "get",
@@ -206,6 +207,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
apiRoute(GET, "/api/search/:searchString", searchRoute.search);
apiRoute(GET, "/api/search-templates", searchRoute.searchTemplates);
+ asyncApiRoute(PST, "/api/llm-chat/provider-models", llmRoute.getProviderModels);
+
apiRoute(GET, "/api/autocomplete", autocompleteApiRoute.getAutocomplete);
apiRoute(GET, "/api/autocomplete/notesCount", autocompleteApiRoute.getNotesCount);