Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): stream chat completions on standalone over the message channel

Elian Doran1e677910f238
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.ts
index fad8d4bd61..abc5c0d813 100644
--- a/apps/client/src/services/llm_chat.ts
+++ b/apps/client/src/services/llm_chat.ts
@@ -1,6 +1,8 @@
-import type { LlmChatConfig, LlmCitation, LlmErrorDetails, LlmMessage, LlmModelInfo,LlmUsage } from "@triliumnext/commons";
+import type { LlmChatConfig, LlmCitation, LlmErrorDetails, LlmMessage, LlmModelInfo, LlmStreamChunk, LlmUsage, WebSocketMessage } from "@triliumnext/commons";
import server from "./server.js";
+import { isStandalone, randomString } from "./utils.js";
+import { subscribeToMessages, unsubscribeToMessage } from "./ws.js";
/** Credentials describing a provider whose live model list should be fetched. */
export interface ProviderModelsQuery {
@@ -62,9 +64,29 @@ export interface StreamCallbacks {
}
/**
- * Stream a chat completion from the LLM API using Server-Sent Events.
+ * Stream a chat completion from the LLM API.
+ *
+ * Two transports, one contract: the completion is delivered chunk by chunk to
+ * {@link StreamCallbacks} and the promise settles when it is over, rejecting with
+ * an `AbortError` if `abortSignal` fired. Which transport is used depends on what
+ * the backend can be reached over — see {@link streamChatOverMessages}.
*/
-export async function streamChatCompletion(
+export function streamChatCompletion(
+ messages: LlmMessage[],
+ config: LlmChatConfig,
+ callbacks: StreamCallbacks,
+ abortSignal?: AbortSignal
+): Promise<void> {
+ return isStandalone
+ ? streamChatOverMessages(messages, config, callbacks, abortSignal)
+ : streamChatOverSse(messages, config, callbacks, abortSignal);
+}
+
+/**
+ * Stream a chat completion over Server-Sent Events, the response of a request
+ * that stays open for the whole completion.
+ */
+async function streamChatOverSse(
messages: LlmMessage[],
config: LlmChatConfig,
callbacks: StreamCallbacks,
@@ -120,51 +142,7 @@ export async function streamChatCompletion(
for (const line of lines) {
if (line.startsWith("data: ")) {
try {
- const data = JSON.parse(line.slice(6));
-
- switch (data.type) {
- case "text":
- callbacks.onChunk(data.content);
- break;
- case "thinking":
- callbacks.onThinking?.(data.content);
- break;
- case "tool_input_start":
- callbacks.onToolInputStart?.(data.toolCallId, data.toolName);
- // Yield to force Preact to commit the pending tool call
- // state before any deltas arrive.
- await new Promise((r) => setTimeout(r, 1));
- break;
- case "tool_input_delta":
- callbacks.onToolInputDelta?.(data.toolCallId, data.delta);
- break;
- case "tool_use":
- callbacks.onToolUse?.(data.toolCallId, data.toolName, data.toolInput);
- // Yield to force Preact to commit the pending tool call
- // state before we process the result.
- await new Promise((r) => setTimeout(r, 1));
- break;
- case "tool_result":
- callbacks.onToolResult?.(data.toolCallId, data.toolName, data.result, data.isError);
- await new Promise((r) => setTimeout(r, 1));
- break;
- case "citation":
- if (data.citation) {
- callbacks.onCitation?.(data.citation);
- }
- break;
- case "usage":
- if (data.usage) {
- callbacks.onUsage?.(data.usage);
- }
- break;
- case "error":
- callbacks.onError(data.error, data.errorDetails);
- break;
- case "done":
- callbacks.onDone();
- break;
- }
+ await handleChunk(JSON.parse(line.slice(6)), callbacks);
} catch (e) {
console.error("Failed to parse SSE data line:", line, e);
}
@@ -181,3 +159,128 @@ export async function streamChatCompletion(
reader.releaseLock();
}
}
+
+/**
+ * Stream a chat completion over the WebSocket-style message channel, for the
+ * standalone build: its backend runs in a worker reached through a request bridge
+ * that answers with one buffered body, so a response cannot stay open. The
+ * request here only starts the completion; the chunks arrive as `llm-stream`
+ * messages and an `llm-stream-end` says when there are no more.
+ *
+ * The stream id is minted here, before the completion is asked for, so the
+ * subscription is already in place when the first chunk lands. Every tab receives
+ * the messages — only the leader holds the worker, and the rest hear it through a
+ * relay — so the id is also what makes a tab keep just its own.
+ */
+async function streamChatOverMessages(
+ messages: LlmMessage[],
+ config: LlmChatConfig,
+ callbacks: StreamCallbacks,
+ abortSignal?: AbortSignal
+): Promise<void> {
+ const streamId = randomString(12);
+ let resolveEnd: () => void = () => undefined;
+ const ended = new Promise<void>((resolve) => { resolveEnd = resolve; });
+ // Handlers are dispatched without being awaited, so nothing else keeps the
+ // chunks in order: each is chained onto the one before it.
+ let handled: Promise<void> = Promise.resolve();
+
+ const onMessage = (message: WebSocketMessage) => {
+ if (message.type === "llm-stream" && message.streamId === streamId) {
+ handled = handled.then(() => handleChunk(message.chunk, callbacks));
+ } else if (message.type === "llm-stream-end" && message.streamId === streamId) {
+ resolveEnd();
+ }
+ };
+ subscribeToMessages(onMessage);
+
+ try {
+ try {
+ await server.post("llm-chat/stream-start", { streamId, messages, config });
+ } catch (e) {
+ callbacks.onError(`Failed to start the LLM stream: ${serverErrorMessage(e)}`);
+ return;
+ }
+
+ try {
+ await Promise.race([ended, rejectWhenAborted(abortSignal)]);
+ } catch (e) {
+ // Tell the backend to stop the completion; it has no disconnect to notice.
+ void server.post("llm-chat/stream-abort", { streamId }).catch(() => undefined);
+ throw e;
+ }
+
+ // Chunks delivered right before the end marker may still be in the chain.
+ await handled;
+ } finally {
+ unsubscribeToMessage(onMessage);
+ }
+}
+
+/**
+ * A promise that rejects the way an aborted `fetch` does, so both transports fail
+ * a stopped generation identically. Never settles when there is no signal.
+ */
+function rejectWhenAborted(signal?: AbortSignal): Promise<never> {
+ return new Promise((_resolve, reject) => {
+ if (!signal) {
+ return;
+ }
+ const fail = () => reject(new DOMException("The LLM stream was aborted.", "AbortError"));
+ if (signal.aborted) {
+ fail();
+ } else {
+ signal.addEventListener("abort", fail, { once: true });
+ }
+ });
+}
+
+/**
+ * Dispatch one chunk to the callbacks. Shared by both transports, so a chunk means
+ * the same thing however it arrived.
+ */
+async function handleChunk(chunk: LlmStreamChunk, callbacks: StreamCallbacks): Promise<void> {
+ switch (chunk.type) {
+ case "text":
+ callbacks.onChunk(chunk.content);
+ break;
+ case "thinking":
+ callbacks.onThinking?.(chunk.content);
+ break;
+ case "tool_input_start":
+ callbacks.onToolInputStart?.(chunk.toolCallId, chunk.toolName);
+ // Yield to force Preact to commit the pending tool call
+ // state before any deltas arrive.
+ await new Promise((r) => setTimeout(r, 1));
+ break;
+ case "tool_input_delta":
+ callbacks.onToolInputDelta?.(chunk.toolCallId, chunk.delta);
+ break;
+ case "tool_use":
+ callbacks.onToolUse?.(chunk.toolCallId, chunk.toolName, chunk.toolInput);
+ // Yield to force Preact to commit the pending tool call
+ // state before we process the result.
+ await new Promise((r) => setTimeout(r, 1));
+ break;
+ case "tool_result":
+ callbacks.onToolResult?.(chunk.toolCallId, chunk.toolName, chunk.result, chunk.isError);
+ await new Promise((r) => setTimeout(r, 1));
+ break;
+ case "citation":
+ if (chunk.citation) {
+ callbacks.onCitation?.(chunk.citation);
+ }
+ break;
+ case "usage":
+ if (chunk.usage) {
+ callbacks.onUsage?.(chunk.usage);
+ }
+ break;
+ case "error":
+ callbacks.onError(chunk.error, chunk.errorDetails);
+ break;
+ case "done":
+ callbacks.onDone();
+ break;
+ }
+}
diff --git a/apps/client/src/services/llm_chat_standalone.spec.ts b/apps/client/src/services/llm_chat_standalone.spec.ts
new file mode 100644
index 0000000000..0023f0e1f7
--- /dev/null
+++ b/apps/client/src/services/llm_chat_standalone.spec.ts
@@ -0,0 +1,157 @@
+/**
+ * The standalone build's chat transport, which delivers a completion over the
+ * WebSocket-style message channel instead of Server-Sent Events.
+ *
+ * A file of its own because the choice between the two is made from
+ * `isStandalone`, a module-level constant read off `window.glob` at import time:
+ * the SSE tests in `llm_chat.spec.ts` need it false, and these need it true.
+ */
+
+import type { LlmChatConfig, LlmMessage, LlmStreamChunk, WebSocketMessage } from "@triliumnext/commons";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("./utils.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./utils.js")>(),
+ isStandalone: true,
+ randomString: () => "stream1"
+}));
+
+const handlers: ((message: WebSocketMessage) => void)[] = vi.hoisted(() => []);
+vi.mock("./ws.js", () => ({
+ subscribeToMessages: (handler: (message: WebSocketMessage) => void) => { handlers.push(handler); },
+ unsubscribeToMessage: (handler: (message: WebSocketMessage) => void) => {
+ handlers.splice(handlers.indexOf(handler), 1);
+ }
+}));
+
+import { streamChatCompletion, type StreamCallbacks } from "./llm_chat.js";
+import server from "./server.js";
+
+function makeCallbacks(): Record<keyof StreamCallbacks, ReturnType<typeof vi.fn>> & StreamCallbacks {
+ return {
+ onChunk: vi.fn(),
+ onThinking: vi.fn(),
+ onToolInputStart: vi.fn(),
+ onToolInputDelta: vi.fn(),
+ onToolUse: vi.fn(),
+ onToolResult: vi.fn(),
+ onCitation: vi.fn(),
+ onUsage: vi.fn(),
+ onError: vi.fn(),
+ onDone: vi.fn()
+ } as Record<keyof StreamCallbacks, ReturnType<typeof vi.fn>> & StreamCallbacks;
+}
+
+/** Deliver a message to whoever is listening, as the worker's relay would. */
+function broadcast(message: WebSocketMessage) {
+ for (const handler of [...handlers]) {
+ handler(message);
+ }
+}
+
+const chunk = (c: LlmStreamChunk): WebSocketMessage => ({ type: "llm-stream", streamId: "stream1", chunk: c });
+const end: WebSocketMessage = { type: "llm-stream-end", streamId: "stream1" };
+
+const messages: LlmMessage[] = [{ role: "user", content: "hi" }];
+const config = {} as LlmChatConfig;
+
+describe("streamChatCompletion in standalone", () => {
+ let posts: [string, unknown][];
+
+ beforeEach(() => {
+ posts = [];
+ server.post = vi.fn(async (url: string, body?: unknown) => { posts.push([url, body]); }) as typeof server.post;
+ });
+
+ afterEach(() => {
+ handlers.length = 0;
+ vi.restoreAllMocks();
+ });
+
+ it("starts the completion under the id it minted, then delivers only that stream's chunks", async () => {
+ const cb = makeCallbacks();
+ const streaming = streamChatCompletion(messages, config, cb);
+
+ // The subscription is in place before the request goes out, so an
+ // opening chunk cannot outrun it.
+ expect(handlers).toHaveLength(1);
+ await Promise.resolve();
+ expect(posts).toEqual([["llm-chat/stream-start", { streamId: "stream1", messages, config }]]);
+
+ broadcast(chunk({ type: "text", content: "hel" }));
+ broadcast({ type: "llm-stream", streamId: "someone-else", chunk: { type: "text", content: "not mine" } });
+ broadcast({ type: "llm-stream-end", streamId: "someone-else" });
+ broadcast(chunk({ type: "text", content: "lo" }));
+ broadcast(chunk({ type: "done" }));
+ broadcast(end);
+
+ await streaming;
+ expect(cb.onChunk.mock.calls).toEqual([["hel"], ["lo"]]);
+ expect(cb.onDone).toHaveBeenCalledTimes(1);
+ // The subscription is dropped once the stream is over.
+ expect(handlers).toHaveLength(0);
+ });
+
+ it("delivers chunks in order even when they arrive faster than they are handled", async () => {
+ const cb = makeCallbacks();
+ const streaming = streamChatCompletion(messages, config, cb);
+ await Promise.resolve();
+
+ // A tool_use chunk yields to the renderer before the next is handled, so
+ // without the chain the text that follows it would be applied first.
+ broadcast(chunk({ type: "tool_use", toolCallId: "t1", toolName: "search", toolInput: {} }));
+ broadcast(chunk({ type: "text", content: "after" }));
+ broadcast(end);
+
+ await streaming;
+ expect(cb.onToolUse).toHaveBeenCalledWith("t1", "search", {});
+ expect(cb.onChunk).toHaveBeenCalledWith("after");
+ expect(cb.onToolUse.mock.invocationCallOrder[0]).toBeLessThan(cb.onChunk.mock.invocationCallOrder[0]);
+ });
+
+ it("reports a failure to start the completion, and does not wait for a stream that never began", async () => {
+ server.post = vi.fn(async () => { throw JSON.stringify({ message: "No LLM providers configured." }); }) as typeof server.post;
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+
+ expect(cb.onError).toHaveBeenCalledWith("Failed to start the LLM stream: No LLM providers configured.");
+ expect(handlers).toHaveLength(0);
+ });
+
+ it("fails an aborted generation the way a cancelled fetch does, and tells the backend to stop", async () => {
+ const controller = new AbortController();
+ const cb = makeCallbacks();
+ const streaming = streamChatCompletion(messages, config, cb, controller.signal);
+ await Promise.resolve();
+
+ broadcast(chunk({ type: "text", content: "partial" }));
+ controller.abort();
+
+ await expect(streaming).rejects.toThrow(expect.objectContaining({ name: "AbortError" }));
+ expect(posts.map(([url]) => url)).toContain("llm-chat/stream-abort");
+ expect(posts.at(-1)?.[1]).toEqual({ streamId: "stream1" });
+ expect(handlers).toHaveLength(0);
+ });
+
+ it("fails immediately when handed a signal that has already been aborted", async () => {
+ const cb = makeCallbacks();
+ await expect(streamChatCompletion(messages, config, cb, AbortSignal.abort()))
+ .rejects.toThrow(expect.objectContaining({ name: "AbortError" }));
+ expect(handlers).toHaveLength(0);
+ });
+
+ it("survives a backend that cannot be told to stop", async () => {
+ const controller = new AbortController();
+ server.post = vi.fn(async (url: string) => {
+ if (url.endsWith("stream-abort")) throw new Error("worker gone");
+ }) as typeof server.post;
+
+ const cb = makeCallbacks();
+ const streaming = streamChatCompletion(messages, config, cb, controller.signal);
+ await Promise.resolve();
+ controller.abort();
+
+ await expect(streaming).rejects.toThrow(expect.objectContaining({ name: "AbortError" }));
+ });
+});
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
index 816b6d7911..04414c9d2f 100644
--- a/apps/server/src/routes/api/llm_chat.spec.ts
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -2,49 +2,20 @@ import type { Request, Response } from "express";
import { afterEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
- configured: true,
chunks: [] as unknown[],
- availableModels: [{ id: "m1", name: "Model One", isDefault: true }] as { id: string; name: string; isDefault?: boolean }[],
- chatThrows: undefined as unknown,
- // When true, the fake provider is chunk-native (implements chatChunks) and
- // records the abort signal the route wires to the response lifecycle.
- chunkNative: false,
- chunkSignal: undefined as AbortSignal | undefined,
- // Records how streamChat resolved the provider.
- providerIdRequested: undefined as string | undefined,
- providerTypeRequested: undefined as string | undefined
+ /** The signal runChat was handed, so the disconnect wiring can be asserted. */
+ signal: undefined as AbortSignal | undefined
}));
-vi.mock("../../services/llm/index.js", () => {
- const makeProvider = () => ({
- chat: () => { if (state.chatThrows !== undefined) throw state.chatThrows; return {}; },
- chatChunks: state.chunkNative
- ? async function* (_messages: unknown, _config: unknown, signal?: AbortSignal) {
- state.chunkSignal = signal;
- for (const c of state.chunks) yield c;
- }
- : undefined,
- getAvailableModels: () => state.availableModels,
- getModelPricing: () => ({ input: 0, output: 0 })
- });
- return {
- hasConfiguredProviders: () => state.configured,
- getSelectedModel: () => undefined,
- getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
- getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
- };
-});
-
-// Only the stream itself is faked; `formatStreamError` (used for the log line) is a pure
-// function and stays real, so the logged text is asserted against the production format.
-vi.mock("@triliumnext/core/src/services/llm/stream.js", async (importOriginal) => ({
- ...await importOriginal<typeof import("@triliumnext/core/src/services/llm/stream.js")>(),
- async *streamToChunks () { for (const c of state.chunks) yield c; }
+// The completion itself is core's and tested there; what this route adds is the
+// SSE framing around it, so only the chunk source is faked.
+vi.mock("../../services/llm/index.js", () => ({
+ async *runChat(_messages: unknown, _config: unknown, signal?: AbortSignal) {
+ state.signal = signal;
+ for (const c of state.chunks) yield c;
+ }
}));
-const generateChatTitle = vi.fn(async (..._args: unknown[]) => {});
-vi.mock("@triliumnext/core/src/services/llm/chat_title.js", () => ({ generateChatTitle: (...args: unknown[]) => generateChatTitle(...args) }));
-
import llmChatRoute from "./llm_chat.js";
function fakeRes({ withFlush = false } = {}) {
@@ -74,161 +45,54 @@ function fakeRes({ withFlush = false } = {}) {
};
}
-describe("LLM chat API", () => {
+function req(body: unknown) { return { body } as unknown as Request; }
+
+describe("streamChat", () => {
afterEach(() => {
- Object.assign(state, {
- configured: true,
- chunks: [],
- availableModels: [{ id: "m1", name: "Model One", isDefault: true }],
- chatThrows: undefined,
- chunkNative: false,
- chunkSignal: undefined,
- providerIdRequested: undefined,
- providerTypeRequested: undefined
- });
- generateChatTitle.mockClear();
+ state.chunks = [];
+ state.signal = undefined;
});
- describe("streamChat", () => {
- function req(body: unknown) { return { body } as unknown as Request; }
-
- it("returns 400 for an empty messages array", async () => {
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [] }), r.res);
- expect(r.statusCode).toBe(400);
- expect(r.jsonBody).toEqual({ error: "messages array is required" });
- });
-
- it("emits an SSE error when no providers are configured", async () => {
- state.configured = false;
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }] }), r.res);
- expect(r.writes.join("")).toContain("No LLM providers configured");
- expect(r.ended).toBe(true);
- });
-
- it("routes by providerId when present, falling back to provider type", async () => {
- state.chunks = [{ type: "done" }];
- const r1 = fakeRes();
- await llmChatRoute.streamChat(req({
- messages: [{ role: "user", content: "hi" }],
- config: { provider: "openai", providerId: "openai_123" }
- }), r1.res);
- expect(state.providerIdRequested).toBe("openai_123");
- expect(state.providerTypeRequested).toBeUndefined();
-
- // No providerId (chat saved before it existed) → type-based resolution.
- state.providerIdRequested = undefined;
- const r2 = fakeRes();
- await llmChatRoute.streamChat(req({
- messages: [{ role: "user", content: "hi" }],
- config: { provider: "openai" }
- }), r2.res);
- expect(state.providerIdRequested).toBeUndefined();
- expect(state.providerTypeRequested).toBe("openai");
- });
-
- it("emits an SSE error when no model can be resolved", async () => {
- state.availableModels = [];
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);
- expect(r.writes.join("")).toContain("No model specified");
- });
-
- it("streams chunks, logs errors, ends the response and generates a title", async () => {
- state.chunks = [{ type: "text", content: "Hi" }, { type: "error", error: "boom" }, { type: "done" }];
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hello" }], config: { chatNoteId: "abc" } }), r.res);
- const body = r.writes.join("");
- expect(body).toContain('"type":"text"');
- expect(body).toContain('"type":"done"');
- expect(r.ended).toBe(true);
- expect(generateChatTitle).toHaveBeenCalledWith("abc", "hello");
- expect(r.headers["Content-Type"]).toBe("text/event-stream");
- });
-
- it("writes an SSE error when the provider throws", async () => {
- state.chatThrows = new Error("provider exploded");
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);
- expect(r.writes.join("")).toContain("provider exploded");
- expect(r.ended).toBe(true);
- });
-
- it("writes a generic SSE error when the provider throws a non-Error", async () => {
- state.chatThrows = "weird failure";
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);
- expect(r.writes.join("")).toContain("Unknown error");
- });
-
- it("prefers a chunk-native provider, wires the disconnect abort, and flushes each chunk", async () => {
- state.chunkNative = true;
- state.chunks = [{ type: "text", content: "native" }, { type: "done" }];
- const r = fakeRes({ withFlush: true });
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: { provider: "claude-agent" } }), r.res);
-
- const body = r.writes.join("");
- expect(body).toContain('"content":"native"');
- expect(r.flushes).toBeGreaterThanOrEqual(2);
-
- // The provider received the signal tied to the response lifecycle:
- // a client disconnect (res close) aborts the in-flight agent turn.
- const signal = state.chunkSignal;
- expect(signal).toBeInstanceOf(AbortSignal);
- expect(signal?.aborted).toBe(false);
- r.listeners.close();
- expect(signal?.aborted).toBe(true);
- });
-
- it("falls back to the raw model id as display name for an unlisted model", async () => {
- state.chunks = [{ type: "error", error: "boom" }];
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: { model: "custom-model" } }), r.res);
- expect(r.writes.join("")).toContain("boom");
- expect(r.ended).toBe(true);
- });
+ it("returns 400 for an empty messages array, without opening a stream", async () => {
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [] }), r.res);
+ expect(r.statusCode).toBe(400);
+ expect(r.jsonBody).toEqual({ error: "messages array is required" });
+ expect(r.writes).toEqual([]);
+ });
- it("titles from the text parts of a multimodal first message, and skips image-only ones", async () => {
- const r1 = fakeRes();
- await llmChatRoute.streamChat(req({
- messages: [{ role: "user", content: [
- { type: "image", attachmentId: "a1", mime: "image/png" },
- { type: "text", text: "describe this" }
- ] }],
- config: { chatNoteId: "abc" }
- }), r1.res);
- expect(generateChatTitle).toHaveBeenCalledWith("abc", "describe this");
+ it("writes each chunk as an SSE event, flushes it, and ends the response", async () => {
+ state.chunks = [{ type: "text", content: "Hi" }, { type: "done" }];
+ const r = fakeRes({ withFlush: true });
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hello" }] }), r.res);
+
+ expect(r.headers["Content-Type"]).toBe("text/event-stream");
+ expect(r.headers["X-Accel-Buffering"]).toBe("no");
+ expect(r.writes).toEqual([
+ 'data: {"type":"text","content":"Hi"}\n\n',
+ 'data: {"type":"done"}\n\n'
+ ]);
+ expect(r.flushes).toBe(2);
+ expect(r.ended).toBe(true);
+ });
- generateChatTitle.mockClear();
- const r2 = fakeRes();
- await llmChatRoute.streamChat(req({
- messages: [{ role: "user", content: [{ type: "image", attachmentId: "a1", mime: "image/png" }] }],
- config: { chatNoteId: "abc" }
- }), r2.res);
- expect(generateChatTitle).not.toHaveBeenCalled();
- });
+ it("ends the response and streams without a flush method available", async () => {
+ state.chunks = [{ type: "done" }];
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }] }), r.res);
+ expect(r.writes.join("")).toContain('"type":"done"');
+ expect(r.ended).toBe(true);
+ });
- it("does not title follow-up turns", async () => {
- const r = fakeRes();
- await llmChatRoute.streamChat(req({
- messages: [
- { role: "user", content: "first" },
- { role: "assistant", content: "reply" },
- { role: "user", content: "second" }
- ],
- config: { chatNoteId: "abc" }
- }), r.res);
- expect(generateChatTitle).not.toHaveBeenCalled();
- });
+ it("aborts the completion when the client disconnects", async () => {
+ state.chunks = [{ type: "done" }];
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }] }), r.res);
- it("keeps the chat alive when title generation fails", async () => {
- generateChatTitle.mockRejectedValueOnce(new Error("title model down"));
- state.chunks = [{ type: "done" }];
- const r = fakeRes();
- await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hello" }], config: { chatNoteId: "abc" } }), r.res);
- expect(r.writes.join("")).toContain('"type":"done"');
- expect(r.ended).toBe(true);
- });
+ const signal = state.signal;
+ expect(signal).toBeInstanceOf(AbortSignal);
+ expect(signal?.aborted).toBe(false);
+ r.listeners.close();
+ expect(signal?.aborted).toBe(true);
});
});
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index ed43c52ee4..577179bac4 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -1,11 +1,7 @@
-import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
-import { getLog } from "@triliumnext/core";
-import { generateChatTitle } from "@triliumnext/core/src/services/llm/chat_title.js";
-import { formatStreamError, streamToChunks } from "@triliumnext/core/src/services/llm/stream.js";
+import type { LlmMessage } from "@triliumnext/commons";
import type { Request, Response } from "express";
-import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, type LlmProviderConfig } from "../../services/llm/index.js";
-import { safeExtractMessageAndStackFromError } from "../../services/utils.js";
+import { type LlmProviderConfig, runChat } from "../../services/llm/index.js";
interface ChatRequest {
messages: LlmMessage[];
@@ -44,82 +40,19 @@ async function streamChat(req: Request, res: Response) {
// Type assertion for flush method (available when compression is used)
const flushableRes = res as Response & { flush?: () => void };
- try {
- if (!hasConfiguredProviders()) {
- res.write(`data: ${JSON.stringify({ type: "error", error: "No LLM providers configured. Please add a provider in Options → AI / LLM." })}\n\n`);
- return;
- }
-
- // Prefer routing by the provider config id — it disambiguates multiple
- // configs of the same type (e.g. OpenAI + a self-hosted Ollama). Chats
- // saved before providerId existed fall back to type-based resolution.
- const provider = config.providerId
- ? getProvider(config.providerId)
- : getProviderByType(config.provider || "anthropic");
-
- // Get pricing and display name for the model
- const modelId = config.model || provider.getAvailableModels().find(m => m.isDefault)?.id;
- if (!modelId) {
- res.write(`data: ${JSON.stringify({ type: "error", error: "No model specified and no default model available for the provider." })}\n\n`);
- return;
- }
-
- // Prefer the config's stored selection for name/pricing — it carries the
- // 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);
- const pricing = selectedModel?.pricing ?? provider.getModelPricing(modelId);
- const modelDisplayName = selectedModel?.name
- ?? provider.getAvailableModels().find(m => m.id === modelId)?.name
- ?? modelId;
+ // Stop the turn when the client disconnects mid-stream, so a closed tab
+ // doesn't leave an agent loop running against the provider.
+ const abortController = new AbortController();
+ res.on("close", () => abortController.abort());
- let chunks: AsyncIterable<LlmStreamChunk>;
- if (provider.chatChunks) {
- // Chunk-native provider (e.g. Claude Agent): it owns its own agentic
- // loop and produces LlmStreamChunks directly. Abort the underlying
- // agent turn when the client disconnects mid-stream.
- const abortController = new AbortController();
- res.on("close", () => abortController.abort());
- chunks = provider.chatChunks(messages, config, abortController.signal);
- } else {
- chunks = streamToChunks(provider.chat(messages, config), { model: modelDisplayName, provider: provider.name, pricing });
- }
-
- for await (const chunk of chunks) {
- if (chunk.type === "error") {
- // The status/URL/response body travel beside the message for the UI's
- // benefit; the log gets them rejoined onto the one line it can show.
- const described = formatStreamError({ message: chunk.error, details: chunk.errorDetails });
- getLog().error(`LLM chat stream error (model ${modelDisplayName}): ${described}`);
- }
+ try {
+ for await (const chunk of runChat(messages, config, abortController.signal)) {
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
// Flush immediately to ensure real-time streaming
if (typeof flushableRes.flush === "function") {
flushableRes.flush();
}
}
- // Auto-generate a title for the chat note on the first user message
- const userMessages = messages.filter(m => m.role === "user");
- if (userMessages.length === 1 && config.chatNoteId) {
- try {
- const firstContent = userMessages[0].content;
- // Multimodal content: title from the text parts only — image
- // bytes are useless to the title model.
- const firstText = typeof firstContent === "string"
- ? firstContent
- : firstContent.filter(p => p.type === "text").map(p => p.text).join("\n").trim();
- if (firstText) {
- await generateChatTitle(config.chatNoteId, firstText);
- }
- } catch (err) {
- // Title generation is best-effort; don't fail the chat
- getLog().error(`Failed to generate chat title: ${safeExtractMessageAndStackFromError(err)}`);
- }
- }
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
- getLog().error(`LLM chat stream failed: ${safeExtractMessageAndStackFromError(error)}`);
- res.write(`data: ${JSON.stringify({ type: "error", error: errorMessage })}\n\n`);
} finally {
res.end();
}
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index 64279b3b61..e108b26a9b 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -18,6 +18,7 @@ import { skillTools } from "./skills/index.js";
import { getDocNoteHtml } from "./tools/doc_notes.js";
import { helpTools } from "./tools/help_tools.js";
+export { runChat } from "@triliumnext/core/src/services/llm/chat.js";
export {
clearProviderCache,
getProvider,
diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.ts
index f21bac77a4..1251436833 100644
--- a/packages/commons/src/lib/ws_api.ts
+++ b/packages/commons/src/lib/ws_api.ts
@@ -1,3 +1,5 @@
+import type { LlmStreamChunk } from "./llm_api.js";
+
export interface EntityChange {
id?: number | null;
noteId?: string;
@@ -181,4 +183,23 @@ export type WebSocketMessage = AllTaskDefinitions | {
* value carried no stack.
*/
stack?: string;
+} | {
+ /**
+ * One chunk of an LLM chat completion, for runtimes that cannot carry the Server-Sent Events the
+ * `llm-chat/stream` route replies with — the standalone build answers a request with a single
+ * buffered body, so its chunks ride this channel instead. `streamId` is minted by the client
+ * before it asks for the completion, and is what lets the tab that asked pick its own chunks out
+ * of a channel every tab receives.
+ */
+ type: "llm-stream";
+ streamId: string;
+ chunk: LlmStreamChunk;
+} | {
+ /**
+ * Marks the end of an {@link WebSocketMessage} `llm-stream` sequence, whether it ended in a `done`
+ * chunk, an error or an abort. It is deliberately not a `done` chunk: an errored stream must not
+ * finalize the assistant message, and the last chunk alone cannot say which case it was.
+ */
+ type: "llm-stream-end";
+ streamId: string;
}
diff --git a/packages/trilium-core/src/routes/api/llm.spec.ts b/packages/trilium-core/src/routes/api/llm.spec.ts
index 4e700cb69a..2b362f7efb 100644
--- a/packages/trilium-core/src/routes/api/llm.spec.ts
+++ b/packages/trilium-core/src/routes/api/llm.spec.ts
@@ -1,11 +1,22 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, 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
+ throws: undefined as unknown,
+ /** Chunks the faked completion yields, one per `await` tick. */
+ chunks: [] as unknown[],
+ /** When set, runChat throws this instead of yielding. */
+ chatThrows: undefined as unknown,
+ /** The signal the completion was handed, so the abort route can be asserted. */
+ signal: undefined as AbortSignal | undefined,
+ /** Keeps the faked completion running until it is aborted, as a real one would. */
+ holdUntilAborted: false,
+ /** Every message broadcast while a stream ran. */
+ sent: [] as WebSocketMessage[]
}));
// The route reaches the provider registry through a dynamic import, so that the
@@ -18,14 +29,74 @@ vi.mock("../../services/llm/index.js", () => ({
}
}));
-import { getProviderModels } from "./llm.js";
+vi.mock("../../services/llm/chat.js", () => ({
+ async *runChat(_messages: unknown, _config: unknown, signal?: AbortSignal) {
+ state.signal = signal;
+ if (state.chatThrows !== undefined) throw state.chatThrows;
+ for (const c of state.chunks) yield c;
+ if (state.holdUntilAborted) {
+ await new Promise<void>(resolve => signal?.addEventListener("abort", () => resolve(), { once: true }));
+ }
+ }
+}));
-describe("getProviderModels", () => {
- afterEach(() => {
- state.models = [];
- state.args = undefined;
- state.throws = undefined;
+import { getLog } from "../../services/log.js";
+import ws from "../../services/ws.js";
+
+import { abortChatStream, getProviderModels, startChatStream } from "./llm.js";
+
+/**
+ * Poll until the completion — which runs detached from the request that started
+ * it — reaches the state a test is waiting for. Wall-clock rather than a fixed
+ * number of ticks: the completion's first step is a dynamic import, which the
+ * test runner can take arbitrarily long to resolve the first time.
+ */
+function until(condition: () => boolean, what: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const deadline = Date.now() + 2000;
+ const check = () => {
+ if (condition()) {
+ resolve();
+ } else if (Date.now() > deadline) {
+ reject(new Error(`Timed out waiting for ${what}`));
+ } else {
+ setTimeout(check, 1);
+ }
+ };
+ check();
+ });
+}
+
+const untilStreamEnds = () => until(() => state.sent.some(m => m.type === "llm-stream-end"), "the stream to end");
+
+const HELLO = [{ role: "user" as const, content: "hi" }];
+
+/**
+ * Spied rather than mocked: core loads both modules while it initialises, before
+ * a per-file `vi.mock` could take their place, so the route would go on using the
+ * real ones.
+ */
+let errorLog: MockInstance<(...args: unknown[]) => void>;
+beforeEach(() => {
+ vi.spyOn(ws, "sendMessageToAllClients").mockImplementation((message) => { state.sent.push(message); });
+ errorLog = vi.spyOn(getLog(), "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ Object.assign(state, {
+ models: [],
+ args: undefined,
+ throws: undefined,
+ chunks: [],
+ chatThrows: undefined,
+ signal: undefined,
+ holdUntilAborted: false,
+ sent: []
});
+});
+
+describe("getProviderModels", () => {
it("lists models for the credentials in the request body, defaulting a missing key to an empty string", async () => {
state.models = [{ id: "m1" }];
@@ -52,3 +123,79 @@ describe("getProviderModels", () => {
.rejects.toThrow("socket hang up");
});
});
+
+describe("startChatStream", () => {
+ it("answers immediately, then broadcasts the chunks under the client's id and an end marker", async () => {
+ state.chunks = [{ type: "text", content: "Hi" }, { type: "done" }];
+
+ expect(startChatStream({ body: { streamId: "s1", messages: HELLO } })).toEqual({});
+ // Nothing has been broadcast yet: the completion outlives the request.
+ expect(state.sent).toEqual([]);
+
+ await untilStreamEnds();
+ expect(state.sent).toEqual([
+ { type: "llm-stream", streamId: "s1", chunk: { type: "text", content: "Hi" } },
+ { type: "llm-stream", streamId: "s1", chunk: { type: "done" } },
+ { type: "llm-stream-end", streamId: "s1" }
+ ]);
+ });
+
+ it("rejects a request that could not be matched back to a stream", () => {
+ expect(() => startChatStream({ body: { streamId: "", messages: HELLO } })).toThrow(/streamId is required/);
+ expect(() => startChatStream({ body: { streamId: "s1", messages: [] } })).toThrow(/messages array is required/);
+ expect(() => startChatStream({ body: {} as never })).toThrow(/streamId is required/);
+ });
+
+ it("refuses to reuse the id of a stream still running, and frees it once it ends", async () => {
+ state.chunks = [{ type: "done" }];
+ startChatStream({ body: { streamId: "s1", messages: HELLO } });
+ expect(() => startChatStream({ body: { streamId: "s1", messages: HELLO } }))
+ .toThrow(/'s1' is already running/);
+
+ await untilStreamEnds();
+ expect(() => startChatStream({ body: { streamId: "s1", messages: HELLO } })).not.toThrow();
+ });
+
+ it("still ends the stream when the completion throws, reporting it as a chunk", async () => {
+ state.chatThrows = new Error("worker died");
+ startChatStream({ body: { streamId: "s1", messages: HELLO } });
+ await untilStreamEnds();
+
+ expect(state.sent).toEqual([
+ { type: "llm-stream", streamId: "s1", chunk: { type: "error", error: "worker died" } },
+ { type: "llm-stream-end", streamId: "s1" }
+ ]);
+ expect(errorLog).toHaveBeenCalledWith(expect.stringContaining("LLM chat stream s1 failed"));
+ });
+
+ it("reports a non-Error failure by its string form", async () => {
+ state.chatThrows = "socket hang up";
+ startChatStream({ body: { streamId: "s1", messages: HELLO } });
+ await untilStreamEnds();
+ expect(state.sent[0]).toEqual({
+ type: "llm-stream", streamId: "s1", chunk: { type: "error", error: "socket hang up" }
+ });
+ });
+});
+
+describe("abortChatStream", () => {
+ it("aborts the signal the running completion was given, which ends the stream", async () => {
+ state.holdUntilAborted = true;
+ startChatStream({ body: { streamId: "s1", messages: HELLO } });
+ // Let the completion start, so it has been handed its signal.
+ await until(() => state.signal !== undefined, "the completion to start");
+ expect(state.signal?.aborted).toBe(false);
+ expect(state.sent).toEqual([]);
+
+ expect(abortChatStream({ body: { streamId: "s1" } })).toEqual({});
+ expect(state.signal?.aborted).toBe(true);
+
+ await untilStreamEnds();
+ expect(state.sent).toEqual([{ type: "llm-stream-end", streamId: "s1" }]);
+ });
+
+ it("ignores an id that is not running, and a request with no id at all", () => {
+ expect(() => abortChatStream({ body: { streamId: "nope" } })).not.toThrow();
+ expect(() => abortChatStream({ body: {} })).not.toThrow();
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/llm.ts b/packages/trilium-core/src/routes/api/llm.ts
index 7c41348802..0c102afbb9 100644
--- a/packages/trilium-core/src/routes/api/llm.ts
+++ b/packages/trilium-core/src/routes/api/llm.ts
@@ -1,13 +1,21 @@
/**
* 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.
+ * Streaming over Server-Sent Events is not among them — the browser build's
+ * request bridge answers a request with one buffered body and cannot carry a
+ * response that stays open. That route stays in `apps/server`; the equivalent
+ * here starts a completion that reports itself over the WebSocket-style channel,
+ * which every runtime already has.
*/
+import type { LlmMessage } from "@triliumnext/commons";
+
import { ValidationError } from "../../errors.js";
+import * as cls from "../../services/context.js";
+import type { LlmProviderConfig } from "../../services/llm/types.js";
+import { getLog } from "../../services/log.js";
+import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";
+import ws from "../../services/ws.js";
interface ProviderModelsRequest {
provider: string;
@@ -15,6 +23,12 @@ interface ProviderModelsRequest {
baseURL?: string;
}
+interface ChatStreamRequest {
+ streamId: string;
+ messages: LlmMessage[];
+ config?: LlmProviderConfig;
+}
+
/**
* 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
@@ -43,6 +57,92 @@ export async function getProviderModels(req: { body: ProviderModelsRequest }) {
}
}
+/**
+ * Start a chat completion whose chunks arrive as `llm-stream` messages rather
+ * than in this response, which returns as soon as the completion is under way.
+ *
+ * The id is minted by the client rather than returned from here so it can start
+ * listening before it asks — otherwise the opening chunks could arrive while the
+ * request that announces the stream is still in flight.
+ */
+export function startChatStream(req: { body: ChatStreamRequest }) {
+ const { streamId, messages, config } = req.body ?? {};
+ if (!streamId) {
+ throw new ValidationError("streamId is required");
+ }
+ if (!Array.isArray(messages) || messages.length === 0) {
+ throw new ValidationError("messages array is required");
+ }
+ if (activeStreams.has(streamId)) {
+ throw new ValidationError(`Stream '${streamId}' is already running`);
+ }
+
+ const abortController = new AbortController();
+ activeStreams.set(streamId, abortController);
+ // Deliberately not awaited: the completion outlives this request, and holding
+ // it open would put a minutes-long provider call behind whatever timeout the
+ // caller's transport imposes.
+ void streamToClients(streamId, messages, config ?? {}, abortController.signal);
+
+ return {};
+}
+
+/** Stop a completion started by {@link startChatStream}; unknown ids are a no-op. */
+export function abortChatStream(req: { body: { streamId?: string } }) {
+ activeStreams.get(req.body?.streamId ?? "")?.abort();
+ return {};
+}
+
+/**
+ * Streams in flight, by the id the client minted for each. An entry exists for
+ * exactly as long as its completion is running, so it doubles as the abort
+ * route's lookup and as the guard against reusing a live id.
+ */
+const activeStreams = new Map<string, AbortController>();
+
+/**
+ * Run the completion and broadcast its chunks, ending — whatever happens — with
+ * the `llm-stream-end` that releases the client's wait.
+ *
+ * The chunks go to every connected client because the standalone build has no
+ * way to address one: only the tab holding the database has a worker, and the
+ * others hear it through a relay. The tab that asked recognises its own by id
+ * and the rest ignore them.
+ */
+async function streamToClients(
+ streamId: string,
+ messages: LlmMessage[],
+ config: LlmProviderConfig,
+ signal: AbortSignal
+): Promise<void> {
+ try {
+ // Imported here for the same reason as in getProviderModels: this module is
+ // reachable from the shared route table that the standalone worker builds
+ // during startup, and the AI SDK must stay out of that path.
+ const { runChat } = await import("../../services/llm/chat.js");
+
+ // The tools a completion may call write notes, which needs a context of
+ // its own: the request that started this one has long since answered.
+ await cls.init(async () => {
+ for await (const chunk of runChat(messages, config, signal)) {
+ ws.sendMessageToAllClients({ type: "llm-stream", streamId, chunk });
+ }
+ });
+ } catch (error) {
+ getLog().error(`LLM chat stream ${streamId} failed: ${safeExtractMessageAndStackFromError(error)}`);
+ ws.sendMessageToAllClients({
+ type: "llm-stream",
+ streamId,
+ chunk: { type: "error", error: error instanceof Error ? error.message : String(error) }
+ });
+ } finally {
+ activeStreams.delete(streamId);
+ ws.sendMessageToAllClients({ type: "llm-stream-end", streamId });
+ }
+}
+
export default {
- getProviderModels
+ getProviderModels,
+ startChatStream,
+ abortChatStream
};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 1e6841b372..781c2c7249 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -208,6 +208,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
apiRoute(GET, "/api/search-templates", searchRoute.searchTemplates);
asyncApiRoute(PST, "/api/llm-chat/provider-models", llmRoute.getProviderModels);
+ apiRoute(PST, "/api/llm-chat/stream-start", llmRoute.startChatStream);
+ apiRoute(PST, "/api/llm-chat/stream-abort", llmRoute.abortChatStream);
apiRoute(GET, "/api/autocomplete", autocompleteApiRoute.getAutocomplete);
apiRoute(GET, "/api/autocomplete/notesCount", autocompleteApiRoute.getNotesCount);
diff --git a/packages/trilium-core/src/services/llm/chat.spec.ts b/packages/trilium-core/src/services/llm/chat.spec.ts
new file mode 100644
index 0000000000..5c9cf77dfd
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/chat.spec.ts
@@ -0,0 +1,188 @@
+import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ configured: true,
+ chunks: [] as unknown[],
+ availableModels: [{ id: "m1", name: "Model One", isDefault: true }] as { id: string; name: string; isDefault?: boolean }[],
+ chatThrows: undefined as unknown,
+ /** When true the fake provider is chunk-native, and records the signal it was handed. */
+ chunkNative: false,
+ chunkSignal: undefined as AbortSignal | undefined,
+ /** Records how runChat resolved the provider. */
+ providerIdRequested: undefined as string | undefined,
+ providerTypeRequested: undefined as string | undefined
+}));
+
+vi.mock("./index.js", () => {
+ const makeProvider = () => ({
+ name: "fake",
+ chat: () => { if (state.chatThrows !== undefined) throw state.chatThrows; return {}; },
+ chatChunks: state.chunkNative
+ ? async function* (_messages: unknown, _config: unknown, signal?: AbortSignal) {
+ state.chunkSignal = signal;
+ for (const c of state.chunks) yield c;
+ }
+ : undefined,
+ getAvailableModels: () => state.availableModels,
+ getModelPricing: () => ({ input: 0, output: 0 })
+ });
+ return {
+ hasConfiguredProviders: () => state.configured,
+ getSelectedModel: () => undefined,
+ getProvider: (id: string) => { state.providerIdRequested = id; return makeProvider(); },
+ getProviderByType: (type: string) => { state.providerTypeRequested = type; return makeProvider(); }
+ };
+});
+
+// Only the stream itself is faked; `formatStreamError` (used for the log line) is a pure
+// function and stays real, so the logged text is asserted against the production format.
+vi.mock("./stream.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./stream.js")>(),
+ async *streamToChunks() { for (const c of state.chunks) yield c; }
+}));
+
+const generateChatTitle = vi.fn(async (..._args: unknown[]) => {});
+vi.mock("./chat_title.js", () => ({ generateChatTitle: (...args: unknown[]) => generateChatTitle(...args) }));
+
+const errorMock = vi.fn();
+vi.mock("../log.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../log.js")>(),
+ getLog: () => ({ error: errorMock, info: vi.fn(), warn: vi.fn() })
+}));
+
+import { runChat } from "./chat.js";
+
+/** Drain a completion into an array, which is how every assertion here reads it. */
+async function collect(messages: LlmMessage[], config: object = {}, signal?: AbortSignal): Promise<LlmStreamChunk[]> {
+ const collected: LlmStreamChunk[] = [];
+ for await (const chunk of runChat(messages, config, signal)) {
+ collected.push(chunk);
+ }
+ return collected;
+}
+
+const HELLO: LlmMessage[] = [{ role: "user", content: "hi" }];
+
+describe("runChat", () => {
+ afterEach(() => {
+ Object.assign(state, {
+ configured: true,
+ chunks: [],
+ availableModels: [{ id: "m1", name: "Model One", isDefault: true }],
+ chatThrows: undefined,
+ chunkNative: false,
+ chunkSignal: undefined,
+ providerIdRequested: undefined,
+ providerTypeRequested: undefined
+ });
+ generateChatTitle.mockClear();
+ errorMock.mockClear();
+ });
+
+ it("yields an error chunk and stops when nothing can serve the completion", async () => {
+ state.configured = false;
+ expect(await collect(HELLO)).toEqual([
+ { type: "error", error: expect.stringContaining("No LLM providers configured") }
+ ]);
+
+ state.configured = true;
+ state.availableModels = [];
+ expect(await collect(HELLO)).toEqual([
+ { type: "error", error: expect.stringContaining("No model specified") }
+ ]);
+ });
+
+ it("routes by providerId when present, falling back to provider type", async () => {
+ state.chunks = [{ type: "done" }];
+ await collect(HELLO, { provider: "openai", providerId: "openai_123" });
+ expect(state.providerIdRequested).toBe("openai_123");
+ expect(state.providerTypeRequested).toBeUndefined();
+
+ // No providerId (chat saved before it existed) → type-based resolution.
+ state.providerIdRequested = undefined;
+ await collect(HELLO, { provider: "openai" });
+ expect(state.providerIdRequested).toBeUndefined();
+ expect(state.providerTypeRequested).toBe("openai");
+ });
+
+ it("passes chunks through, logging the errors among them with their provider context", async () => {
+ state.chunks = [
+ { type: "text", content: "Hi" },
+ { type: "error", error: "boom", errorDetails: { statusCode: 429 } },
+ { type: "done" }
+ ];
+ expect(await collect(HELLO, { model: "m1" })).toEqual(state.chunks);
+ expect(errorMock).toHaveBeenCalledWith(expect.stringContaining("boom (HTTP 429)"));
+ });
+
+ it("names an unlisted model by its raw id in the log line", async () => {
+ state.chunks = [{ type: "error", error: "boom" }];
+ await collect(HELLO, { model: "custom-model" });
+ expect(errorMock).toHaveBeenCalledWith(expect.stringContaining("model custom-model"));
+ });
+
+ it("reports a throwing provider as an error chunk, whether or not it threw an Error", async () => {
+ state.chatThrows = new Error("provider exploded");
+ expect(await collect(HELLO)).toEqual([{ type: "error", error: "provider exploded" }]);
+
+ state.chatThrows = "weird failure";
+ expect(await collect(HELLO)).toEqual([{ type: "error", error: "Unknown error" }]);
+ });
+
+ it("prefers a chunk-native provider and hands it the abort signal", async () => {
+ state.chunkNative = true;
+ state.chunks = [{ type: "text", content: "native" }, { type: "done" }];
+ const controller = new AbortController();
+ expect(await collect(HELLO, { provider: "claude-agent" }, controller.signal)).toEqual(state.chunks);
+ expect(state.chunkSignal).toBe(controller.signal);
+ });
+
+ it("stops at the next chunk once aborted", async () => {
+ state.chunks = [{ type: "text", content: "a" }, { type: "text", content: "b" }];
+ const controller = new AbortController();
+ const collected: LlmStreamChunk[] = [];
+ for await (const chunk of runChat(HELLO, {}, controller.signal)) {
+ collected.push(chunk);
+ controller.abort();
+ }
+ expect(collected).toEqual([{ type: "text", content: "a" }]);
+ });
+
+ describe("title generation", () => {
+ it("titles the note from the opening message, including the text parts of a multimodal one", async () => {
+ await collect([{ role: "user", content: "hello" }], { chatNoteId: "abc" });
+ expect(generateChatTitle).toHaveBeenCalledWith("abc", "hello");
+
+ generateChatTitle.mockClear();
+ await collect([{ role: "user", content: [
+ { type: "image", attachmentId: "a1", mime: "image/png" },
+ { type: "text", text: "describe this" }
+ ] }], { chatNoteId: "abc" });
+ expect(generateChatTitle).toHaveBeenCalledWith("abc", "describe this");
+ });
+
+ it("skips an image-only opening message, a follow-up turn, and a chat with no note", async () => {
+ await collect([{ role: "user", content: [{ type: "image", attachmentId: "a1", mime: "image/png" }] }], { chatNoteId: "abc" });
+ expect(generateChatTitle).not.toHaveBeenCalled();
+
+ await collect([
+ { role: "user", content: "first" },
+ { role: "assistant", content: "reply" },
+ { role: "user", content: "second" }
+ ], { chatNoteId: "abc" });
+ expect(generateChatTitle).not.toHaveBeenCalled();
+
+ await collect([{ role: "user", content: "hello" }], {});
+ expect(generateChatTitle).not.toHaveBeenCalled();
+ });
+
+ it("keeps a completed chat intact when titling fails", async () => {
+ generateChatTitle.mockRejectedValueOnce(new Error("title model down"));
+ state.chunks = [{ type: "done" }];
+ expect(await collect([{ role: "user", content: "hello" }], { chatNoteId: "abc" }))
+ .toEqual([{ type: "done" }]);
+ expect(errorMock).toHaveBeenCalledWith(expect.stringContaining("Failed to generate chat title"));
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/llm/chat.ts b/packages/trilium-core/src/services/llm/chat.ts
new file mode 100644
index 0000000000..19657bea93
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/chat.ts
@@ -0,0 +1,112 @@
+/**
+ * Running one chat completion, independent of how its chunks reach the client.
+ *
+ * The server writes them to a Server-Sent Events response; the standalone build
+ * cannot (its request bridge answers with one buffered body) and posts them over
+ * the WebSocket-style channel instead. Both drive this generator, so provider
+ * resolution, pricing lookup, error logging and title generation happen once.
+ */
+
+import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
+
+import { getLog } from "../log.js";
+import { safeExtractMessageAndStackFromError } from "../utils/index.js";
+import { generateChatTitle } from "./chat_title.js";
+import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, type LlmProviderConfig } from "./index.js";
+import { formatStreamError, streamToChunks } from "./stream.js";
+
+/**
+ * Stream one assistant turn, yielding the chunks as the provider produces them.
+ *
+ * Never throws: a failure is yielded as an `error` chunk, because the caller has
+ * usually already committed to a response by the time one happens. The sequence
+ * ends with a `done` chunk only when the turn completed — an errored one stops
+ * after its `error` chunk, so a caller that needs a terminator must add its own.
+ *
+ * @param abortSignal stops the turn early; for a chunk-native provider it aborts
+ * the agent loop itself, otherwise the stream is simply left at the next chunk.
+ */
+export async function* runChat(
+ messages: LlmMessage[],
+ config: LlmProviderConfig = {},
+ abortSignal?: AbortSignal
+): AsyncGenerator<LlmStreamChunk> {
+ try {
+ if (!hasConfiguredProviders()) {
+ yield { type: "error", error: "No LLM providers configured. Please add a provider in Options → AI / LLM." };
+ return;
+ }
+
+ // Prefer routing by the provider config id — it disambiguates multiple
+ // configs of the same type (e.g. OpenAI + a self-hosted Ollama). Chats
+ // saved before providerId existed fall back to type-based resolution.
+ const provider = config.providerId
+ ? getProvider(config.providerId)
+ : getProviderByType(config.provider || "anthropic");
+
+ const modelId = config.model || provider.getAvailableModels().find(m => m.isDefault)?.id;
+ if (!modelId) {
+ yield { type: "error", error: "No model specified and no default model available for the provider." };
+ return;
+ }
+
+ // Prefer the config's stored selection for name/pricing — it carries the
+ // 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);
+ const pricing = selectedModel?.pricing ?? provider.getModelPricing(modelId);
+ const modelDisplayName = selectedModel?.name
+ ?? provider.getAvailableModels().find(m => m.id === modelId)?.name
+ ?? modelId;
+
+ // Chunk-native provider (e.g. Claude Agent): it owns its own agentic loop
+ // and produces LlmStreamChunks directly, including honouring the abort.
+ const chunks = provider.chatChunks
+ ? provider.chatChunks(messages, config, abortSignal)
+ : streamToChunks(provider.chat(messages, config), { model: modelDisplayName, provider: provider.name, pricing });
+
+ for await (const chunk of chunks) {
+ if (abortSignal?.aborted) {
+ return;
+ }
+ if (chunk.type === "error") {
+ // The status/URL/response body travel beside the message for the UI's
+ // benefit; the log gets them rejoined onto the one line it can show.
+ const described = formatStreamError({ message: chunk.error, details: chunk.errorDetails });
+ getLog().error(`LLM chat stream error (model ${modelDisplayName}): ${described}`);
+ }
+ yield chunk;
+ }
+
+ await generateTitleForFirstTurn(messages, config);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ getLog().error(`LLM chat stream failed: ${safeExtractMessageAndStackFromError(error)}`);
+ yield { type: "error", error: errorMessage };
+ }
+}
+
+/**
+ * Name the chat note after the user's opening message, once the first turn is
+ * answered. Best-effort: a failure here must not fail a completed chat.
+ */
+async function generateTitleForFirstTurn(messages: LlmMessage[], config: LlmProviderConfig): Promise<void> {
+ const userMessages = messages.filter(m => m.role === "user");
+ if (userMessages.length !== 1 || !config.chatNoteId) {
+ return;
+ }
+
+ try {
+ const firstContent = userMessages[0].content;
+ // Multimodal content: title from the text parts only — image bytes are
+ // useless to the title model.
+ const firstText = typeof firstContent === "string"
+ ? firstContent
+ : firstContent.filter(p => p.type === "text").map(p => p.text).join("\n").trim();
+ if (firstText) {
+ await generateChatTitle(config.chatNoteId, firstText);
+ }
+ } catch (err) {
+ getLog().error(`Failed to generate chat title: ${safeExtractMessageAndStackFromError(err)}`);
+ }
+}