Skip to content

Build your personal knowledge base with Trilium Notes

fix(llm): filter earlier attachments by the stored model

Elian Doran9375088b6653
diff --git a/packages/trilium-core/src/services/llm/chat.spec.ts b/packages/trilium-core/src/services/llm/chat.spec.ts
index 97b2ed7adb..1830569957 100644
--- a/packages/trilium-core/src/services/llm/chat.spec.ts
+++ b/packages/trilium-core/src/services/llm/chat.spec.ts
@@ -5,6 +5,8 @@ const state = vi.hoisted(() => ({
configured: true,
chunks: [] as unknown[],
availableModels: [{ id: "m1", name: "Model One", isDefault: true }] as { id: string; name: string; isDefault?: boolean }[],
+ /** What `getSelectedModel()` finds in the stored provider configuration. */
+ selectedModel: undefined as { id: string; name: string; attachmentKinds?: string[] } | undefined,
chatThrows: undefined as unknown,
/** When true the fake provider is chunk-native, and records the signal it was handed. */
chunkNative: false,
@@ -47,7 +49,7 @@ vi.mock("./index.js", () => {
});
return {
hasConfiguredProviders: () => state.configured,
- getSelectedModel: () => undefined,
+ getSelectedModel: () => state.selectedModel,
getSearchProviderSetup: (id: string | undefined) => (id === "s1" ? { id: "s1", provider: "tavily", apiKey: "tk" } : undefined),
getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(`id:${id}`); },
getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(`type:${type}`); }
@@ -101,6 +103,7 @@ describe("runChat", () => {
configured: true,
chunks: [],
availableModels: [{ id: "m1", name: "Model One", isDefault: true }],
+ selectedModel: undefined,
chatThrows: undefined,
chunkNative: false,
chunkSignal: undefined,
@@ -113,6 +116,17 @@ describe("runChat", () => {
errorMock.mockClear();
});
+ it("hands the provider the attachment kinds of the stored model, never the request's", async () => {
+ state.selectedModel = { id: "m1", name: "Model One", attachmentKinds: [] };
+ await collect(HELLO, { model: "m1", attachmentKinds: [ "image", "file" ] });
+ expect((state.chatConfig as LlmProviderConfig).attachmentKinds).toEqual([]);
+
+ // A stored model without the field reads everything, so the provider decides.
+ state.selectedModel = { id: "m1", name: "Model One" };
+ await collect(HELLO, { model: "m1", attachmentKinds: [ "image" ] });
+ expect((state.chatConfig as LlmProviderConfig).attachmentKinds).toBeUndefined();
+ });
+
it("yields an error chunk and stops when nothing can serve the completion", async () => {
state.configured = false;
expect(await collect(HELLO)).toEqual([
diff --git a/packages/trilium-core/src/services/llm/chat.ts b/packages/trilium-core/src/services/llm/chat.ts
index 77df2c079a..7e62048259 100644
--- a/packages/trilium-core/src/services/llm/chat.ts
+++ b/packages/trilium-core/src/services/llm/chat.ts
@@ -53,11 +53,12 @@ export async function* runChat(
return;
}
- // `webSearch` and `toolApprovals` come from here only, never from the request.
+ // `webSearch`, `toolApprovals` and `attachmentKinds` come from here only, never from the request.
const config: LlmProviderConfig = {
...requestConfig,
webSearch: getSearchProviderSetup(requestConfig.webSearchProviderId),
- toolApprovals
+ toolApprovals,
+ attachmentKinds: undefined
};
try {
if (!hasConfiguredProviders()) {
@@ -86,6 +87,7 @@ export async function* runChat(
// denormalized metadata even for dynamically discovered models the curated
// list doesn't know. Fall back to the provider's curated list, then the id.
const selectedModel = getSelectedModel(config.providerId, modelId);
+ config.attachmentKinds = selectedModel?.attachmentKinds;
const pricing = selectedModel?.pricing ?? provider.getModelPricing(modelId);
const modelDisplayName = selectedModel?.name
?? provider.getAvailableModels().find(m => m.id === modelId)?.name
diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.ts
index 6dbe896ab6..f7495eb22e 100644
--- a/packages/trilium-core/src/services/llm/providers/base_provider.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.ts
@@ -314,8 +314,11 @@ export abstract class BaseProvider implements LlmProvider {
* separately via the `system` option of `streamText` (see `buildSystemMessage`),
* which is resilient against prompt injection.
*/
- protected buildMessages(chatMessages: LlmMessage[], modelId: string): ModelMessage[] {
- return chatMessages.map(m => buildModelMessage(m, kind => this.acceptsAttachment(kind, modelId)));
+ protected buildMessages(chatMessages: LlmMessage[], modelId: string, attachmentKinds?: LlmAttachmentKind[]): ModelMessage[] {
+ const accepts: AttachmentFilter = attachmentKinds
+ ? kind => attachmentKinds.includes(kind)
+ : kind => this.acceptsAttachment(kind, modelId);
+ return chatMessages.map(m => buildModelMessage(m, accepts));
}
/**
@@ -409,7 +412,7 @@ export abstract class BaseProvider implements LlmProvider {
const systemPrompt = this.buildSystemPrompt(messages, config);
const chatMessages = this.applyNoteHint(messages.filter(m => m.role !== "system"), config);
const modelId = config.model || this.defaultModel;
- const coreMessages = this.buildMessages(chatMessages, modelId);
+ const coreMessages = this.buildMessages(chatMessages, modelId, config.attachmentKinds);
const streamOptions: Parameters<typeof streamText>[0] = {
model: this.createModel(modelId),
diff --git a/packages/trilium-core/src/services/llm/providers/google.ts b/packages/trilium-core/src/services/llm/providers/google.ts
index e4d57f963d..ab777c3f50 100644
--- a/packages/trilium-core/src/services/llm/providers/google.ts
+++ b/packages/trilium-core/src/services/llm/providers/google.ts
@@ -97,7 +97,7 @@ export class GoogleProvider extends BaseProvider {
const systemPrompt = this.buildSystemPrompt(messages, config);
const chatMessages = this.applyNoteHint(messages.filter(m => m.role !== "system"), config);
const modelId = config.model || this.defaultModel;
- const coreMessages = this.buildMessages(chatMessages, modelId);
+ const coreMessages = this.buildMessages(chatMessages, modelId, config.attachmentKinds);
const streamOptions: Parameters<typeof streamText>[0] = {
model: this.createModel(modelId),
diff --git a/packages/trilium-core/src/services/llm/providers/openrouter.spec.ts b/packages/trilium-core/src/services/llm/providers/openrouter.spec.ts
index de53df9c77..cc90fd6499 100644
--- a/packages/trilium-core/src/services/llm/providers/openrouter.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/openrouter.spec.ts
@@ -17,7 +17,18 @@ vi.mock("@openrouter/ai-sdk-provider", async (importOriginal) => {
};
});
-import type { LlmStreamChunk } from "@triliumnext/commons";
+// Attachments resolve by kind rather than from Becca: an image part to PNG bytes.
+vi.mock("../attachment_content.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../attachment_content.js")>();
+ return {
+ ...actual,
+ resolveAttachmentPart: (part: { type: string; text?: string }) => (part.type === "text"
+ ? { kind: "text", text: part.text }
+ : { kind: "image", bytes: new Uint8Array([ 137, 80, 78, 71 ]), mime: "image/png" })
+ };
+});
+
+import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
import { streamToChunks } from "../stream.js";
@@ -224,6 +235,22 @@ describe("OpenRouterProvider chat", () => {
expect((await requestBody({ model: "anthropic/claude-haiku-5.5", reasoningEffort: "max" })).body).not.toHaveProperty("reasoning");
});
+ it("sends a placeholder for an earlier attachment the stored model can't read", async () => {
+ // The chat's provider instance never lists models, so the kinds come from the stored selection.
+ const messages: LlmMessage[] = [
+ { role: "user", content: [ { type: "text", text: "What is this?" }, { type: "image", attachmentId: "img1", mime: "image/png" } ] },
+ { role: "assistant", content: "A cat." },
+ { role: "user", content: "And now?" }
+ ];
+ fetchMock.mockClear();
+ const config: LlmProviderConfig = { model: "deepseek/deepseek-v4-pro", attachmentKinds: [] };
+ for await (const _ of streamToChunks(new OpenRouterProvider("sk-or").chat(messages, config))) { /* drain */ }
+ const body = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));
+ const first = body.messages.find((m: { role: string }) => m.role === "user").content;
+ expect(JSON.stringify(first)).toContain("[attached image]");
+ expect(JSON.stringify(first)).not.toContain("image_url");
+ });
+
it("names Trilium on each request", async () => {
const { headers } = await requestBody({ model: "openrouter/auto" });
expect(headers.get("Authorization")).toBe("Bearer sk-or");
diff --git a/packages/trilium-core/src/services/llm/providers/openrouter.ts b/packages/trilium-core/src/services/llm/providers/openrouter.ts
index 96b504cc8f..f1e707cc38 100644
--- a/packages/trilium-core/src/services/llm/providers/openrouter.ts
+++ b/packages/trilium-core/src/services/llm/providers/openrouter.ts
@@ -139,7 +139,10 @@ export class OpenRouterProvider extends BaseProvider {
return effort ? { openrouter: { reasoning: { effort } } } : undefined;
}
- /** Reads the model's input modalities; a model not listed yet is sent everything. */
+ /**
+ * Reads the model's input modalities, which become the stored model's `attachmentKinds` that a
+ * chat turn filters by instead. A model not listed yet is sent everything.
+ */
protected override acceptsAttachment(kind: LlmAttachmentKind, modelId: string): boolean {
const modalities = this.catalog.get(modelId)?.architecture?.input_modalities;
return !modalities || modalities.includes(kind);
diff --git a/packages/trilium-core/src/services/llm/types.ts b/packages/trilium-core/src/services/llm/types.ts
index ffdfad3761..61a7e8e1a1 100644
--- a/packages/trilium-core/src/services/llm/types.ts
+++ b/packages/trilium-core/src/services/llm/types.ts
@@ -26,6 +26,11 @@ export interface LlmProviderConfig extends LlmChatConfig {
* tools run unasked.
*/
toolApprovals?: ToolApprovals;
+ /**
+ * The attachment kinds the turn's model reads natively, from its stored selection, set by
+ * `runChat()`. Absent, the provider's own `acceptsAttachment()` decides.
+ */
+ attachmentKinds?: LlmAttachmentKind[];
}
/**