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
fix(llm): disable AI SDK telemetry so a failed stream cannot leak a rejection
Elian Doranacec38b36125
diff --git a/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts b/packages/trilium-core/src/services/llm/providers/anthropic.spec.tsindex f51b7bf721..51bddb3821 100644--- a/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts+++ b/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts@@ -144,6 +144,9 @@ describe("AnthropicProvider message building", () => {expect(opts.messages.every((m: any) => m.role !== "system")).toBe(true);expect(opts.system.role).toBe("system");expect(opts.system.content).toContain("BASE PROMPT");+ // This override builds its own options, so it has to carry the base's+ // telemetry opt-out with them — see TELEMETRY_OFF in base_provider.ts.+ expect(opts.telemetry).toEqual({ isEnabled: false });});});diff --git a/packages/trilium-core/src/services/llm/providers/anthropic.ts b/packages/trilium-core/src/services/llm/providers/anthropic.tsindex 7e29c452b8..0c9df8bbcf 100644--- a/packages/trilium-core/src/services/llm/providers/anthropic.ts+++ b/packages/trilium-core/src/services/llm/providers/anthropic.ts@@ -3,7 +3,7 @@ import type { LlmMessage } from "@triliumnext/commons";import { type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";import type { LlmProviderConfig, ModelInfo, StreamResult } from "../types.js";-import { BaseProvider, buildModelMessage, type RemoteModel } from "./base_provider.js";+import { BaseProvider, buildModelMessage, type RemoteModel, TELEMETRY_OFF } from "./base_provider.js";const OFFICIAL_BASE_URL = "https://api.anthropic.com/v1";@@ -150,6 +150,7 @@ export class AnthropicProvider extends BaseProvider {maxOutputTokens: maxTokens,// Reject any system message smuggled into `messages` (prompt injection guard).allowSystemInMessages: false,+ telemetry: TELEMETRY_OFF,providerOptions: {anthropic: { thinking }}diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts b/packages/trilium-core/src/services/llm/providers/base_provider.spec.tsindex c1c94c9950..0bff68a2da 100644--- a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts+++ b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts@@ -547,6 +547,14 @@ describe("BaseProvider chat / pricing / models / title", () => {// onError is silenced (no-op) rather than left to the SDK's stdout dump.expect(typeof opts.onError).toBe("function");expect(opts.onError(new Error("x"))).toBeUndefined();+ // Telemetry off — see TELEMETRY_OFF, and browser_runtime.spec.ts for what+ // leaving it on costs the browser build.+ expect(opts.telemetry).toEqual({ isEnabled: false });+ });++ it("disables telemetry on the title call too", async () => {+ await new TestProvider().generateTitle("some first message");+ expect((generateTextMock.mock.calls[0][0] as any).telemetry).toEqual({ isEnabled: false });});it("invokes the no-op base addWebSearchTool when web search is enabled (adds nothing)", () => {diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.tsindex 2ef45edeb4..cf0dfa86cc 100644--- a/packages/trilium-core/src/services/llm/providers/base_provider.ts+++ b/packages/trilium-core/src/services/llm/providers/base_provider.ts@@ -16,6 +16,20 @@ import MODEL_PRICES_JSON from "./model_prices.json" with { type: "json" };const DEFAULT_MAX_TOKENS = 8096;const TITLE_MAX_TOKENS = 30;+/**+ * Turns the AI SDK's telemetry off, on every call into it.+ *+ * Nothing here registers a telemetry integration and the SDK's tracing channel is+ * Node-only (`node:diagnostics_channel`), so this gives up nothing at all. What it+ * avoids is a leak in the browser build: left enabled, `streamText` eagerly builds+ * `totalUsage.promise.then(…)` to hand the tracer a completion signal, and outside+ * Node the tracer returns without ever taking it. The moment the stream fails — a+ * 400 from the provider is enough — that derived promise rejects with nothing+ * listening, and standalone reports the stray rejection to the user. Disabling+ * telemetry leaves the dispatcher empty, so the promise is never built.+ */+export const TELEMETRY_OFF = { isEnabled: false } as const;+/*** A model as reported by a provider's models endpoint. Only what the listing* APIs actually return — pricing is never part of it.@@ -383,7 +397,8 @@ export abstract class BaseProvider implements LlmProvider {// to stdout, bypassing Trilium's logger. The error is still delivered through// `fullStream`, where `streamToChunks` turns it into a detailed message that// the chat route logs — so suppress the unstructured stdout dump here.- onError: () => {}+ onError: () => {},+ telemetry: TELEMETRY_OFF};const tools = this.buildTools(config);@@ -449,6 +464,7 @@ export abstract class BaseProvider implements LlmProvider {const { text } = await generateText({model: this.createModel(this.titleModel),maxOutputTokens: TITLE_MAX_TOKENS,+ telemetry: TELEMETRY_OFF,messages: [{role: "user",diff --git a/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.ts b/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.tsnew file mode 100644index 0000000000..a26cc2ced7--- /dev/null+++ b/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.ts@@ -0,0 +1,56 @@+/**+ * What the AI SDK does when it is *not* running under Node — the standalone+ * build, whose backend lives in a browser worker.+ *+ * The tests here deliberately use the real SDK rather than the `ai` mock the+ * other provider specs install: the behaviour under test is the SDK's own, and a+ * stub would assert nothing about it.+ */++import type { LlmStreamChunk } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { streamToChunks } from "../stream.js";+import { AnthropicProvider } from "./anthropic.js";++/** Collected while a case runs; asserted empty at the end of each. */+const leaked: unknown[] = [];+const collectLeak = (reason: unknown) => { leaked.push(reason); };++const realRelease = process.release;++describe("a failing completion outside Node", () => {+ beforeEach(() => {+ leaked.length = 0;+ process.on("unhandledRejection", collectLeak);+ // The SDK decides whether it can trace by looking here, and everything it+ // does differently in a browser follows from the answer being "no".+ Object.defineProperty(process, "release", { value: { name: "browser" }, configurable: true });+ });++ afterEach(() => {+ process.off("unhandledRejection", collectLeak);+ Object.defineProperty(process, "release", { value: realRelease, configurable: true });+ vi.unstubAllGlobals();+ });++ it("leaves no rejection unhandled when the provider rejects the request", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(+ JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "Your credit balance is too low" } }),+ { status: 400, headers: { "content-type": "application/json" } }+ )));++ const provider = new AnthropicProvider("sk-fake", "https://example.invalid/v1");+ const chunks: LlmStreamChunk[] = [];+ for await (const chunk of streamToChunks(provider.chat([{ role: "user", content: "hi" }], {}))) {+ chunks.push(chunk);+ }++ expect(chunks).toEqual([expect.objectContaining({ type: "error", error: expect.stringContaining("credit balance") })]);++ // A rejection escaping here is not cosmetic: standalone reports every one+ // of them to the user, so a routine API error would look like a crash.+ await new Promise(resolve => setTimeout(resolve, 300));+ expect(leaked.map(l => (l as Error)?.name)).toEqual([]);+ });+});diff --git a/packages/trilium-core/src/services/llm/providers/google.spec.ts b/packages/trilium-core/src/services/llm/providers/google.spec.tsindex 2958d5c61c..6e4041633c 100644--- a/packages/trilium-core/src/services/llm/providers/google.spec.ts+++ b/packages/trilium-core/src/services/llm/providers/google.spec.ts@@ -97,6 +97,9 @@ describe("GoogleProvider message building", () => {expect(opts.messages.every((m: any) => m.role !== "system")).toBe(true);expect(typeof opts.system).toBe("string");expect(opts.system).toContain("BASE PROMPT");+ // This override builds its own options, so it has to carry the base's+ // telemetry opt-out with them — see TELEMETRY_OFF in base_provider.ts.+ expect(opts.telemetry).toEqual({ isEnabled: false });});it("chat() with extended thinking also guards against system messages in `messages`", () => {diff --git a/packages/trilium-core/src/services/llm/providers/google.ts b/packages/trilium-core/src/services/llm/providers/google.tsindex 6201738a50..b8ec6c4d20 100644--- a/packages/trilium-core/src/services/llm/providers/google.ts+++ b/packages/trilium-core/src/services/llm/providers/google.ts@@ -4,7 +4,7 @@ import { getLog } from "../../../services/log.js";import { stepCountIs, streamText, type ToolSet } from "ai";import type { LlmProviderConfig, StreamResult } from "../types.js";-import { BaseProvider, type RemoteModel } from "./base_provider.js";+import { BaseProvider, type RemoteModel, TELEMETRY_OFF } from "./base_provider.js";const OFFICIAL_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";@@ -104,6 +104,7 @@ export class GoogleProvider extends BaseProvider {maxOutputTokens: config.maxTokens || 8096,// Reject any system message smuggled into `messages` (prompt injection guard).allowSystemInMessages: false,+ telemetry: TELEMETRY_OFF,providerOptions: {google: {thinkingConfig: {