Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): smooth streaming

Elian Doran6d6cf15edab7
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index 5804ac30b7..9cc118c58a 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -1,10 +1,11 @@
import type { LlmCitation, LlmMessage, LlmMessagePart, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
import { RefObject } from "preact";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { getAvailableModels, streamChatCompletion } from "../../../services/llm_chat.js";
import { randomString } from "../../../services/utils.js";
import type { ContentBlock, FileBlock, ImageBlock, LlmChatContent, StoredMessage, TextFileBlock } from "./llm_chat_types.js";
+import { useSmoothStreaming } from "./useSmoothStreaming.js";
/** A user-supplied attachment waiting to be sent with the next message. */
export type AttachmentBlock = ImageBlock | FileBlock | TextFileBlock;
@@ -119,9 +120,12 @@ export function useLlmChat(
const [messages, setMessagesInternal] = useState<StoredMessage[]>([]);
const [input, setInput] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
- const [streamingContent, setStreamingContent] = useState("");
- const [streamingBlocks, setStreamingBlocks] = useState<ContentBlock[]>([]);
+ // The canonical "target" content received from the stream so far. The
+ // displayed `streamingBlocks` is derived from this with the trailing text
+ // block smoothed via useSmoothStreaming for a steady reveal cadence.
+ const [targetBlocks, setTargetBlocks] = useState<ContentBlock[]>([]);
const [streamingThinking, setStreamingThinking] = useState("");
+ const { displayedText: smoothedTailText, append: smoothAppend, drain: smoothDrain, reset: smoothReset } = useSmoothStreaming();
const [pendingCitations, setPendingCitations] = useState<LlmCitation[]>([]);
const [pendingAttachments, setPendingAttachments] = useState<AttachmentBlock[]>([]);
const [availableModels, setAvailableModels] = useState<ModelOption[]>([]);
@@ -228,7 +232,7 @@ export function useLlmChat(
useEffect(() => {
scrollToBottom();
- }, [messages, streamingContent, streamingThinking, scrollToBottom]);
+ }, [messages, smoothedTailText, streamingThinking, scrollToBottom]);
// Load state from content object
const loadFromContent = useCallback((content: LlmChatContent) => {
@@ -278,9 +282,9 @@ export function useLlmChat(
setPendingCitations([]);
setMessagesInternal(conversation);
setIsStreaming(true);
- setStreamingContent("");
- setStreamingBlocks([]);
+ setTargetBlocks([]);
setStreamingThinking("");
+ smoothReset();
let thinkingContent = "";
const contentBlocks: ContentBlock[] = [];
@@ -321,6 +325,11 @@ export function useLlmChat(
/** Shared cleanup: finalize collected content and reset streaming state. */
function finalizeStream() {
+ // Reveal any remaining smoothed text instantly so the trailing chars
+ // don't get clipped when the streaming placeholder is swapped for
+ // the finalized message.
+ smoothDrain();
+
// Mark any in-progress tool calls as stopped so they don't show infinite spinners.
// Also clear `inputStreaming` so a half-streamed JSON arg list doesn't render.
for (const [i, block] of contentBlocks.entries()) {
@@ -364,8 +373,7 @@ export function useLlmChat(
setMessages([...conversation, ...finalNewMessages]);
}
- setStreamingContent("");
- setStreamingBlocks([]);
+ setTargetBlocks([]);
setStreamingThinking("");
setPendingCitations([]);
setIsStreaming(false);
@@ -377,18 +385,28 @@ export function useLlmChat(
streamOptions,
{
onChunk: (text) => {
+ // A new text block begins whenever the previous tail is
+ // anything other than text (or there's nothing yet). In
+ // that case the smoother needs to start fresh so it doesn't
+ // pin the displayed length from the previous block.
+ const prev = contentBlocks[contentBlocks.length - 1];
+ const isNewTextBlock = prev?.type !== "text";
lastTextBlock().content += text;
- setStreamingContent(contentBlocks
- .filter((b): b is ContentBlock & { type: "text" } => b.type === "text")
- .map(b => b.content)
- .join(""));
- setStreamingBlocks([...contentBlocks]);
+ if (isNewTextBlock) {
+ smoothReset();
+ }
+ smoothAppend(text);
+ setTargetBlocks([...contentBlocks]);
},
onThinking: (text) => {
thinkingContent += text;
setStreamingThinking(thinkingContent);
},
onToolInputStart: (toolCallId, toolName) => {
+ // Snap any pending smoothed text to its full value before
+ // the tool_call block appears — otherwise the trailing
+ // chars of the previous text block would be left hanging.
+ smoothDrain();
contentBlocks.push({
type: "tool_call",
toolCall: {
@@ -398,7 +416,7 @@ export function useLlmChat(
inputStreaming: ""
}
});
- setStreamingBlocks([...contentBlocks]);
+ setTargetBlocks([...contentBlocks]);
},
onToolInputDelta: (toolCallId, delta) => {
for (let i = contentBlocks.length - 1; i >= 0; i--) {
@@ -414,7 +432,7 @@ export function useLlmChat(
break;
}
}
- setStreamingBlocks([...contentBlocks]);
+ setTargetBlocks([...contentBlocks]);
},
onToolUse: (toolCallId, toolName, toolInput) => {
// Some providers skip tool-input-start/delta entirely and only emit
@@ -431,15 +449,19 @@ export function useLlmChat(
inputStreaming: undefined
}
};
- setStreamingBlocks([...contentBlocks]);
+ setTargetBlocks([...contentBlocks]);
return;
}
}
+ // Provider went straight to a full tool_call with no
+ // start/delta events — drain so any preceding text is
+ // shown in full before the tool_call card replaces it.
+ smoothDrain();
contentBlocks.push({
type: "tool_call",
toolCall: { id: toolCallId, toolName, input: toolInput }
});
- setStreamingBlocks([...contentBlocks]);
+ setTargetBlocks([...contentBlocks]);
},
onToolResult: (toolCallId, _toolName, result, isError) => {
// Replace the matching block with a new object so Preact sees the change.
@@ -453,7 +475,7 @@ export function useLlmChat(
break;
}
}
- setStreamingBlocks([...contentBlocks]);
+ setTargetBlocks([...contentBlocks]);
},
onCitation: (citation) => {
// Deduplicate by URL
@@ -477,8 +499,8 @@ export function useLlmChat(
};
const finalMessages = [...conversation, errorMessage];
setMessages(finalMessages);
- setStreamingContent("");
- setStreamingBlocks([]);
+ smoothReset();
+ setTargetBlocks([]);
setStreamingThinking("");
setIsStreaming(false);
},
@@ -505,13 +527,13 @@ export function useLlmChat(
createdAt: new Date().toISOString(),
type: "error"
}]);
- setStreamingContent("");
- setStreamingBlocks([]);
+ smoothReset();
+ setTargetBlocks([]);
setStreamingThinking("");
setIsStreaming(false);
abortControllerRef.current = null;
});
- }, [selectedModel, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages]);
+ }, [selectedModel, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);
const handleSubmit = useCallback(async (e: Event) => {
e.preventDefault();
@@ -569,6 +591,27 @@ export function useLlmChat(
}
}, []);
+ // Build the rendered view by swapping the trailing text block's content for
+ // the smoother's progressively-revealed prefix. Earlier text blocks are
+ // already drained to their full content (drain() runs whenever a tool_call
+ // pushes onto the stack), so only the tail needs substitution.
+ const streamingBlocks = useMemo<ContentBlock[]>(() => {
+ if (targetBlocks.length === 0) return targetBlocks;
+ const lastIdx = targetBlocks.length - 1;
+ const last = targetBlocks[lastIdx];
+ if (last.type !== "text") return targetBlocks;
+ if (last.content === smoothedTailText) return targetBlocks;
+ return [
+ ...targetBlocks.slice(0, lastIdx),
+ { ...last, content: smoothedTailText }
+ ];
+ }, [targetBlocks, smoothedTailText]);
+
+ const streamingContent = useMemo(() => streamingBlocks
+ .filter((b): b is ContentBlock & { type: "text" } => b.type === "text")
+ .map(b => b.content)
+ .join(""), [streamingBlocks]);
+
return {
// State
messages,
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts b/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts
new file mode 100644
index 0000000000..6f87715bfe
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts
@@ -0,0 +1,104 @@
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+interface SmoothStreamingOptions {
+ /** Baseline reveal rate in characters per second when the buffer is small. */
+ baseCharsPerSecond?: number;
+ /**
+ * Maximum time (seconds) we let the displayed text lag behind the target.
+ * When the backlog implies a higher rate than the baseline to stay within
+ * this window, the reveal speeds up.
+ */
+ maxBacklogSeconds?: number;
+}
+
+export interface SmoothStreamingHandle {
+ /** The smoothed prefix of the appended target text — render this. */
+ displayedText: string;
+ /** Add a chunk to the target buffer; it will be revealed gradually. */
+ append: (delta: string) => void;
+ /** Reveal everything still buffered immediately and stop animating. */
+ drain: () => void;
+ /** Wipe target and displayed text (start of a new streaming session). */
+ reset: () => void;
+}
+
+/**
+ * Smooths bursty token-streamed text into a steady character-by-character
+ * reveal driven by `requestAnimationFrame`. Providers tend to push SSE chunks
+ * in irregular bursts (a few tokens at a time, then a pause); applying this
+ * hook to the visible text turns that jitter into a consistent typewriter
+ * cadence without sacrificing throughput — if the source races ahead, the
+ * reveal rate adapts upward to drain the backlog within `maxBacklogSeconds`.
+ */
+export function useSmoothStreaming(options: SmoothStreamingOptions = {}): SmoothStreamingHandle {
+ const { baseCharsPerSecond = 80, maxBacklogSeconds = 0.5 } = options;
+
+ const [displayedText, setDisplayedText] = useState("");
+
+ const targetRef = useRef("");
+ const displayedLenRef = useRef(0);
+ const rafRef = useRef<number | null>(null);
+ const lastTickRef = useRef(0);
+
+ const tick = useCallback(() => {
+ const now = performance.now();
+ const dt = (now - lastTickRef.current) / 1000;
+ lastTickRef.current = now;
+
+ const backlog = targetRef.current.length - displayedLenRef.current;
+ if (backlog <= 0) {
+ rafRef.current = null;
+ return;
+ }
+
+ // With a small backlog the baseline cadence dominates (calm, readable);
+ // with a large backlog we accelerate so the lag stays bounded.
+ const rate = Math.max(baseCharsPerSecond, backlog / maxBacklogSeconds);
+ const charsToAdd = Math.max(1, Math.floor(rate * dt));
+ const newLen = Math.min(targetRef.current.length, displayedLenRef.current + charsToAdd);
+
+ displayedLenRef.current = newLen;
+ setDisplayedText(targetRef.current.slice(0, newLen));
+
+ rafRef.current = requestAnimationFrame(tick);
+ }, [baseCharsPerSecond, maxBacklogSeconds]);
+
+ const ensureRunning = useCallback(() => {
+ if (rafRef.current != null) return;
+ lastTickRef.current = performance.now();
+ rafRef.current = requestAnimationFrame(tick);
+ }, [tick]);
+
+ const append = useCallback((delta: string) => {
+ if (!delta) return;
+ targetRef.current += delta;
+ ensureRunning();
+ }, [ensureRunning]);
+
+ const drain = useCallback(() => {
+ if (rafRef.current != null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ if (displayedLenRef.current !== targetRef.current.length) {
+ displayedLenRef.current = targetRef.current.length;
+ setDisplayedText(targetRef.current);
+ }
+ }, []);
+
+ const reset = useCallback(() => {
+ if (rafRef.current != null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ targetRef.current = "";
+ displayedLenRef.current = 0;
+ setDisplayedText("");
+ }, []);
+
+ useEffect(() => () => {
+ if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
+ }, []);
+
+ return { displayedText, append, drain, reset };
+}