Skip to content

Build your personal knowledge base with Trilium Notes

test(llm): cover the provider paths the patch left untested

Elian Doran8231c66a9fd4
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.ts
index 3dfd3aaa96..1ae37f2a39 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@ -40,6 +40,7 @@ function makeProviderMock(tag: string) {
vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock("anthropic") }));
vi.mock("./providers/openai.js", () => ({ OpenAiProvider: makeProviderMock("openai") }));
vi.mock("./providers/google.js", () => ({ GoogleProvider: makeProviderMock("google") }));
+vi.mock("./providers/deepseek.js", () => ({ DeepSeekProvider: makeProviderMock("deepseek") }));
vi.mock("./providers/claude_agent.js", () => ({ ClaudeAgentProvider: makeProviderMock("claude-agent") }));
vi.mock("./providers/local.js", () => ({ LocalProvider: makeProviderMock("local") }));
@@ -93,6 +94,7 @@ 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: "d", name: "D", provider: "deepseek", apiKey: "kd" },
{ id: "c", name: "C", provider: "claude-agent", apiKey: "" },
{ id: "l", name: "L", provider: "ollama", apiKey: "", baseURL: "http://ollama.lan:11434" },
{ id: "lm", name: "LM", provider: "lmstudio", apiKey: "", baseURL: "http://box:1234/v1" },
@@ -101,6 +103,9 @@ describe("llm/index provider registry", () => {
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]);
+ // Its own class rather than the shared self-hosted one, despite speaking
+ // the same protocol — that is what gives its models a price.
+ expect((getProvider("d").constructor as any).lastArgs).toEqual(["kd", undefined]);
// The subscription provider takes no constructor args — auth is Claude Code's.
expect((getProvider("c").constructor as any).lastArgs).toEqual([]);
// The three self-hosted cards share one class, which receives the card
diff --git a/apps/server/src/services/llm/providers/deepseek.spec.ts b/apps/server/src/services/llm/providers/deepseek.spec.ts
index 39e34e012c..d477112415 100644
--- a/apps/server/src/services/llm/providers/deepseek.spec.ts
+++ b/apps/server/src/services/llm/providers/deepseek.spec.ts
@@ -12,6 +12,15 @@ vi.mock("@ai-sdk/openai", () => ({
}
}));
+const { generateTextMock } = vi.hoisted(() => ({
+ generateTextMock: vi.fn(async () => ({ text: " A generated title " }) as any)
+}));
+
+vi.mock("ai", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("ai")>();
+ return { ...actual, generateText: generateTextMock };
+});
+
import { DeepSeekProvider, deepSeekModelName } from "./deepseek.js";
describe("DeepSeekProvider construction", () => {
@@ -82,6 +91,13 @@ describe("DeepSeekProvider model listing", () => {
expect(provider.titleModel).toBe("deepseek-v4-flash");
expect(provider.defaultModel).toBe("deepseek-v4-pro");
expect(models.find((m: any) => m.isDefault)?.id).toBe("deepseek-v4-pro");
+
+ // Same verdict whichever order the endpoint happens to list them in.
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "deepseek-v4-flash" }, { id: "deepseek-v4-pro" }] }));
+ const reversed = new DeepSeekProvider("sk-deep") as any;
+ await reversed.listModels();
+ expect(reversed.titleModel).toBe("deepseek-v4-flash");
+ expect(reversed.defaultModel).toBe("deepseek-v4-pro");
});
it("keeps the alias when a listing never happens, and never titles with an unpriced id", async () => {
@@ -100,6 +116,26 @@ describe("DeepSeekProvider model listing", () => {
expect(proxied.titleModel).toBe("deepseek-v4-flash");
});
+ it("leaves the fallbacks alone when the endpoint lists nothing", async () => {
+ // An empty catalogue gives nothing to point the defaults at, so the aliases
+ // stand and the base class falls back to the price table's own list.
+ fetchMock.mockResolvedValue(okJson({ data: [] }));
+ const provider = new DeepSeekProvider("sk-deep") as any;
+ await provider.listModels();
+ expect(provider.titleModel).toBe("deepseek-chat");
+ expect(provider.defaultModel).toBe("deepseek-chat");
+ });
+
+ it("falls back to listing order when the table prices none of the models", async () => {
+ // A gateway serving ids the table doesn't know: nothing can be ranked on
+ // cost, so both defaults settle on the first one listed.
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "house-model" }, { id: "other-model" }] }));
+ const provider = new DeepSeekProvider("sk-deep") as any;
+ await provider.listModels();
+ expect(provider.titleModel).toBe("house-model");
+ expect(provider.defaultModel).toBe("house-model");
+ });
+
it("honours a base URL override and surfaces listing failures", async () => {
fetchMock.mockResolvedValue(okJson({ data: [{ id: "deepseek-chat" }] }));
await new DeepSeekProvider("sk-deep", "https://gateway.example/v1").listModels();
@@ -113,6 +149,48 @@ describe("DeepSeekProvider model listing", () => {
});
});
+describe("DeepSeekProvider title generation", () => {
+ const fetchMock = vi.fn();
+ const okJson = (body: unknown) => ({ ok: true, json: async () => body });
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ chatMock.mockClear();
+ generateTextMock.mockClear();
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ it("lists the endpoint first, so the title goes to a model the account has", async () => {
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "deepseek-v4-pro" }, { id: "deepseek-v4-flash" }] }));
+
+ const title = await new DeepSeekProvider("sk-deep").generateTitle("Explain quantum tunnelling");
+ // Not the `deepseek-chat` alias baked into the class — a v4-era account
+ // doesn't list it, so titling with it would be a request that just fails.
+ expect(chatMock).toHaveBeenCalledWith("deepseek-v4-flash");
+ expect(title).toBe("A generated title");
+ });
+
+ it("doesn't list again once the defaults are resolved", async () => {
+ fetchMock.mockResolvedValue(okJson({ data: [{ id: "deepseek-v4-flash" }] }));
+ const provider = new DeepSeekProvider("sk-deep");
+ await provider.listModels();
+
+ const probes = fetchMock.mock.calls.length;
+ await provider.generateTitle("Explain quantum tunnelling");
+ expect(fetchMock.mock.calls.length).toBe(probes);
+ });
+
+ it("still titles when the endpoint can't be listed", async () => {
+ // Offline, or a listing that errors: the alias is the last resort, and the
+ // user loses nothing.
+ fetchMock.mockRejectedValue(new Error("offline"));
+
+ const title = await new DeepSeekProvider("sk-deep").generateTitle("Explain quantum tunnelling");
+ expect(chatMock).toHaveBeenCalledWith("deepseek-chat");
+ expect(title).toBe("A generated title");
+ });
+});
+
describe("DeepSeekProvider recommendations", () => {
it("pre-selects the current line but not the superseded coder models", () => {
const provider = new DeepSeekProvider("sk-deep");
diff --git a/apps/server/src/services/llm/providers/deepseek.ts b/apps/server/src/services/llm/providers/deepseek.ts
index ec42ff9928..3ff7d80b15 100644
--- a/apps/server/src/services/llm/providers/deepseek.ts
+++ b/apps/server/src/services/llm/providers/deepseek.ts
@@ -84,12 +84,21 @@ export class DeepSeekProvider extends BaseProvider {
const priced = ids.filter(id => prices[id]);
const ranked = priced.length > 0 ? priced : ids;
const cost = (id: string) => prices[id]?.output ?? 0;
- const costs = ranked.map(cost);
- const cheapest = Math.min(...costs);
- const dearest = Math.max(...costs);
- this.titleModel = ranked.find(id => cost(id) === cheapest) ?? ids[0];
- this.defaultModel = ranked.find(id => cost(id) === dearest) ?? ids[0];
+ // Strict comparisons, so a tie leaves the first-listed id in place.
+ let cheapest = ranked[0];
+ let dearest = ranked[0];
+ for (const id of ranked) {
+ if (cost(id) < cost(cheapest)) {
+ cheapest = id;
+ }
+ if (cost(id) > cost(dearest)) {
+ dearest = id;
+ }
+ }
+
+ this.titleModel = cheapest;
+ this.defaultModel = dearest;
this.defaultsFromListing = true;
}
diff --git a/apps/server/src/services/llm/providers/local.spec.ts b/apps/server/src/services/llm/providers/local.spec.ts
index 54ec2c201d..cf4f5a7af9 100644
--- a/apps/server/src/services/llm/providers/local.spec.ts
+++ b/apps/server/src/services/llm/providers/local.spec.ts
@@ -218,6 +218,15 @@ describe("LocalProvider", () => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});
+ it("sends the key on the probe when the endpoint is behind a gateway", async () => {
+ fetchMock.mockImplementation(routes({ "/v1/models": openAiModels(["m1"]) }));
+ await new LocalProvider("openai-compatible", "sk-gateway", "http://box:8080").listModels();
+ expect(fetchMock).toHaveBeenCalledWith(
+ "http://box:8080/v1/models",
+ expect.objectContaining({ headers: { Authorization: "Bearer sk-gateway" } })
+ );
+ });
+
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\)/);
@@ -239,6 +248,40 @@ describe("LocalProvider", () => {
await expect(new LocalProvider("ollama").listModels()).rejects.toThrow(/Unexpected \/api\/tags response shape/);
});
+ it("reports a foreign payload from LM Studio's own API", async () => {
+ // Mirror of the Ollama case: the named card trusts its own endpoint, so
+ // a reply that isn't a model list is a misconfiguration, not a miss.
+ fetchMock.mockImplementation(routes({ "/api/v0/models": json({ error: "boom" }) }));
+ await expect(new LocalProvider("lmstudio").listModels())
+ .rejects.toThrow(/Unexpected \/api\/v0\/models response shape/);
+
+ // Same verdict when the list is there but an entry has no id.
+ fetchMock.mockImplementation(routes({ "/api/v0/models": json({ data: [{ id: "ok" }, { quantization: "Q4" }] }) }));
+ await expect(new LocalProvider("lmstudio").listModels())
+ .rejects.toThrow(/Unexpected \/api\/v0\/models response shape/);
+ });
+
+ it("reports an Ollama tag list with an unnamed entry", async () => {
+ fetchMock.mockImplementation(routes({ "/api/tags": json({ models: [{ name: "ok" }, { size: 123 }] }) }));
+ await expect(new LocalProvider("ollama").listModels())
+ .rejects.toThrow(/Unexpected \/api\/tags response shape/);
+ });
+
+ it("reports an OpenAI-compatible listing whose data isn't a list", async () => {
+ fetchMock.mockImplementation(routes({ "/v1/models": json({ data: { object: "list" } }) }));
+ await expect(new LocalProvider("openai-compatible", "", "http://box:8080").listModels())
+ .rejects.toThrow(/Unexpected response shape from http:\/\/box:8080\/v1\/models/);
+ });
+
+ it("falls back to the OpenAI-compatible listing when Ollama's own is absent", async () => {
+ // The Ollama card pointed at a plain OpenAI-compatible server: /api/tags
+ // 404s, and the LM Studio probe is skipped entirely for this card.
+ fetchMock.mockImplementation(routes({ "/v1/models": openAiModels(["llama3"]) }));
+ const models = await new LocalProvider("ollama").listModels();
+ expect(models.map(m => m.id)).toEqual(["llama3"]);
+ expect(fetchMock.mock.calls.every(([url]) => !String(url).includes("/api/v0/models"))).toBe(true);
+ });
+
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.
@@ -282,6 +325,42 @@ describe("LocalProvider", () => {
expect((onlyBig as unknown as { titleModel: string }).titleModel).toBe("only-big");
});
+ it("reads parameter sizes below a billion, and ignores ones it can't parse", async () => {
+ // Ollama reports sub-billion models in M and K; both are well under the
+ // 4B ceiling, so either should win the title job over a 70B model.
+ fetchMock.mockImplementation(routes({
+ "/api/tags": ollamaTags([
+ { name: "big-model", parameter_size: "70B" },
+ { name: "milli-model", parameter_size: "500M" }
+ ])
+ }));
+ const milli = new LocalProvider("ollama");
+ await milli.listModels();
+ expect((milli as unknown as { titleModel: string }).titleModel).toBe("milli-model");
+
+ fetchMock.mockImplementation(routes({
+ "/api/tags": ollamaTags([
+ { name: "big-model", parameter_size: "70B" },
+ { name: "kilo-model", parameter_size: "800K" }
+ ])
+ }));
+ const kilo = new LocalProvider("ollama");
+ await kilo.listModels();
+ expect((kilo as unknown as { titleModel: string }).titleModel).toBe("kilo-model");
+
+ // An unparseable size disqualifies nothing but decides nothing either —
+ // with no name-shaped small model around, the default takes the job.
+ fetchMock.mockImplementation(routes({
+ "/api/tags": ollamaTags([
+ { name: "big-model", parameter_size: "70B" },
+ { name: "odd-model", parameter_size: "quite large" }
+ ])
+ }));
+ const odd = new LocalProvider("ollama");
+ await odd.listModels();
+ expect((odd as unknown as { titleModel: string }).titleModel).toBe("big-model");
+ });
+
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");
@@ -292,6 +371,11 @@ describe("LocalProvider", () => {
await expect(provider.generateTitle("Hello")).resolves.toBe("A title");
expect((provider as unknown as { titleModel: string }).titleModel).toBe("tiny");
+
+ // Already resolved: a second title costs no further listing.
+ const probes = fetchMock.mock.calls.length;
+ await provider.generateTitle("Hello again");
+ expect(fetchMock.mock.calls.length).toBe(probes);
generateTitle.mockRestore();
});
});
diff --git a/apps/server/src/services/llm/providers/local.ts b/apps/server/src/services/llm/providers/local.ts
index 9344d0214f..a23ad03593 100644
--- a/apps/server/src/services/llm/providers/local.ts
+++ b/apps/server/src/services/llm/providers/local.ts
@@ -339,9 +339,9 @@ function parseParamSize(paramSize?: string): number | undefined {
const match = paramSize.match(/^([\d.]+)\s*([BMK])/i);
if (!match) return undefined;
const value = parseFloat(match[1]);
+ // The pattern admits no other unit, so K needs no test of its own.
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;
+ return value / 1_000_000;
}