Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: improve performance

Adorian Doran4551c2795bcb
diff --git a/apps/client/src/widgets/react/ActionButton.tsx b/apps/client/src/widgets/react/ActionButton.tsx
index 81228828d8..03c1735622 100644
--- a/apps/client/src/widgets/react/ActionButton.tsx
+++ b/apps/client/src/widgets/react/ActionButton.tsx
@@ -1,5 +1,6 @@
+import type { Tooltip } from "bootstrap";
import { HTMLAttributes } from "preact";
-import { useEffect, useRef, useState } from "preact/hooks";
+import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { CommandNames } from "../../components/app_context";
import keyboard_actions from "../../services/keyboard_actions";
@@ -26,14 +27,17 @@ export default function ActionButton({ text, icon, className, triggerCommand, ti
const buttonRef = useRef<HTMLButtonElement>(null);
const [ keyboardShortcut, setKeyboardShortcut ] = useState<string[]>();
- useStaticTooltip(buttonRef, {
+ // Memoized so useStaticTooltip's effect (keyed on config identity) doesn't dispose and
+ // recreate the Bootstrap tooltip on every re-render.
+ const tooltipConfig = useMemo<Partial<Tooltip.Options>>(() => ({
title: keyboardShortcut?.length ? `${text} (${keyboardShortcut?.join(",")})` : text,
placement: titlePosition ?? "bottom",
fallbackPlacements: [ titlePosition ?? "bottom" ],
customClass: tooltipClass ?? "",
trigger: cachedIsMobile ? "focus" : "hover focus",
animation: false
- });
+ }), [text, keyboardShortcut, titlePosition, tooltipClass]);
+ useStaticTooltip(buttonRef, tooltipConfig);
useEffect(() => {
if (triggerCommand) {
diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsx
index 94f87430cd..d2889d8c07 100644
--- a/apps/client/src/widgets/react/Dropdown.tsx
+++ b/apps/client/src/widgets/react/Dropdown.tsx
@@ -1,7 +1,7 @@
import { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";
import { ComponentChildren, HTMLAttributes } from "preact";
import { createPortal, CSSProperties, HTMLProps } from "preact/compat";
-import { MutableRef, useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { MutableRef, useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { isMobile } from "../../services/utils";
import { useTooltip, useUniqueName } from "./hooks";
@@ -50,17 +50,21 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
const triggerRef = useRef<HTMLButtonElement | null>(null);
const dropdownContainerRef = useRef<HTMLUListElement | null>(null);
- const { showTooltip, hideTooltip } = useTooltip(containerRef, {
+ // Memoized so useTooltip's effect (keyed on config identity) doesn't dispose and recreate the
+ // Bootstrap tooltip on every re-render — only when the title (or positioning) actually changes.
+ const tooltipConfig = useMemo<Partial<Tooltip.Options>>(() => ({
...titleOptions,
// Drive the tooltip from config, not just the `title` attribute: Bootstrap reads the attribute once
- // on init, so a dynamic title (e.g. the media play-mode button) would otherwise go stale (useTooltip
- // recreates the tooltip each render, keeping this in sync). Prefer the `title` prop, then a
- // `titleOptions.title` escape-hatch, then "" (Bootstrap rejects `undefined`; "" shows no tooltip).
+ // on init, so a dynamic title (e.g. the media play-mode button) would otherwise go stale (`title` is
+ // a dependency of this memo, so a change recreates the tooltip, keeping it in sync). Prefer the
+ // `title` prop, then a `titleOptions.title` escape-hatch, then "" (Bootstrap rejects `undefined`;
+ // "" shows no tooltip).
title: title ?? titleOptions?.title ?? "",
placement: titlePosition ?? "bottom",
fallbackPlacements: [ titlePosition ?? "bottom" ],
trigger: "manual"
- });
+ }), [title, titleOptions, titlePosition]);
+ const { showTooltip, hideTooltip } = useTooltip(containerRef, tooltipConfig);
const [ shown, setShown ] = useState(false);
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 5f44244e39..b9a6921382 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -1111,9 +1111,12 @@ export function useStaticTooltip(elRef: RefObject<Element>, config?: Partial<Too
tooltip.dispose();
}
- // Remove any lingering tooltip popup elements from the DOM.
+ // Remove any lingering tooltip popup elements from the DOM. This must stay
+ // unconditional: delegated (`selector:`) configs spawn per-target Tooltip
+ // instances whose popups the parent's dispose() does not remove, and cleanups
+ // run before DOM removal, so a disconnected-only sweep would not catch them.
document
- .querySelectorAll('.tooltip')
+ .querySelectorAll(".tooltip")
.forEach(t => t.remove());
};
}, [ elRef, config ]);
diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsx
index 444185d4bb..7cd3b8d679 100644
--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx
+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx
@@ -131,7 +131,12 @@ export default function SidebarChat() {
// Custom submit handler that ensures chat note exists first
const handleSubmit = useCallback(async (e: Event) => {
e.preventDefault();
- if (!chat.input.trim() || chat.isStreaming) return;
+ if (!chat.hasInputText || chat.isStreaming) return;
+
+ // Snapshot the draft before any await: as soon as this handler suspends, the input
+ // bar clears the editor, which zeroes the live draft ref the delegated
+ // chat.handleSubmit below reads.
+ const draft = chat.getInput();
// Ensure chat note exists before sending (lazy creation)
let noteId = chatNoteId;
@@ -157,7 +162,9 @@ export default function SidebarChat() {
// setChatNoteId above won't be visible until next render)
chat.setChatNoteId(noteId);
- // Delegate to shared handler
+ // Restore the draft (the editor clear wiped it during the awaits above), then
+ // delegate to the shared handler.
+ chat.setInput(draft);
await chat.handleSubmit(e);
}, [chatNoteId, chat]);
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index 01e8c6f1e8..05f6d4bd3c 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -131,16 +131,16 @@ export default function ChatInputBar({
// Clear the editor immediately when a submit fires with non-empty, non-streaming
// input — mirrors the rejection check inside chat.handleSubmit so we don't wipe
// text that won't actually be sent. Doing it here (instead of as a useEffect on
- // chat.input) avoids the React-render / CKEditor-change-event race that left the
- // editor visually populated after submit.
+ // the draft state) avoids the React-render / CKEditor-change-event race that left
+ // the editor visually populated after submit.
const handleSubmit = useCallback((e: Event) => {
- const willSubmit = (chat.input.trim() || chat.pendingAttachments.length > 0) && !chat.isStreaming;
+ const willSubmit = (chat.hasInputText || chat.pendingAttachments.length > 0) && !chat.isStreaming;
baseSubmit(e);
if (willSubmit) {
editorApiRef.current?.setText("");
editorApiRef.current?.focus();
}
- }, [baseSubmit, chat.input, chat.isStreaming, chat.pendingAttachments.length]);
+ }, [baseSubmit, chat.hasInputText, chat.isStreaming, chat.pendingAttachments.length]);
submitRef.current = handleSubmit;
// Expose the reply-input editor to the chat hook so timeline actions (e.g. quoting a selection)
@@ -422,7 +422,7 @@ export default function ChatInputBar({
icon={chat.isStreaming ? "bx bx-stop" : "bx bx-send"}
text={chat.isStreaming ? t("llm_chat.stop") : t("llm_chat.send")}
onClick={chat.isStreaming ? chat.stopStreaming : handleSubmit}
- disabled={!chat.isStreaming && !chat.input.trim() && chat.pendingAttachments.length === 0}
+ disabled={!chat.isStreaming && !chat.hasInputText && chat.pendingAttachments.length === 0}
className={`llm-chat-send-btn ${chat.isStreaming ? "llm-chat-stop-btn" : ""}`}
/>
</div>
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
index 9862b65ef2..e8cb94c962 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
@@ -4,6 +4,14 @@
margin-top: 1rem;
padding-bottom: 1.25rem;
max-width: 85%;
+ /* Isolate each message: layout, paint and style invalidations stop at the message
+ boundary instead of walking the whole timeline. Deliberately NOT content-visibility:
+ auto — skipped messages sit at placeholder sizes, which silently breaks everything
+ that measures the timeline (ToC scroll-spy offsets, the bottom-spacer/reply-park
+ math in useLlmChat, smooth scrollIntoView landings). Paint containment clips ink at
+ the wrapper edge, so overflowing effects must be inset (see the jump flash below)
+ and wide content needs its own scroll context (see the KaTeX rule). */
+ contain: content;
}
.llm-chat-message-wrapper:first-child {
@@ -243,6 +251,13 @@
font-size: 0.85em;
}
+/* KaTeX display math is white-space: nowrap; give it its own scroll context (like `pre`
+ above) so a wide equation stays reachable — the wrapper's paint containment would
+ otherwise clip its tail with no scrollbar. */
+.llm-chat-markdown .katex-display {
+ overflow-x: auto;
+}
+
.llm-chat-markdown blockquote {
margin: 0.75em 0;
padding: 0.5em 1em;
@@ -284,16 +299,17 @@
cursor: pointer;
}
-/* Flash the referenced bubble when jumped to. A box-shadow outline pulse (no layout shift)
- works on both the user bubble and the transparent assistant bubble. Duration mirrors
+/* Flash the referenced bubble when jumped to. An inset box-shadow pulse (no layout shift)
+ works on both the user bubble and the transparent assistant bubble — and, unlike an outer
+ shadow, isn't clipped by the message wrapper's paint containment. Duration mirrors
FLASH_DURATION_MS in chat_message_jump.ts. */
.llm-chat-message-wrapper.llm-chat-message-jump-target .llm-chat-message {
animation: llm-chat-jump-flash 1.2s ease-out;
}
@keyframes llm-chat-jump-flash {
- from { box-shadow: 0 0 0 2px var(--quick-search-result-highlight-color, #007bff); }
- to { box-shadow: 0 0 0 2px transparent; }
+ from { box-shadow: inset 0 0 0 2px var(--quick-search-result-highlight-color, #007bff); }
+ to { box-shadow: inset 0 0 0 2px transparent; }
}
/* Message footer (timestamp + token usage, sits below the bubble) */
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
index 7617b5484f..d1ae698389 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
@@ -32,6 +32,16 @@ function MarkdownContent({ html, isStreaming }: { html: string; isStreaming?: bo
);
}
+/**
+ * Markdown for one text block, memoized per content string: while a reply streams, each
+ * commit re-renders the whole streaming message, but only the smoothed tail block's content
+ * actually changes — earlier blocks skip both the re-render and the markdown re-parse.
+ */
+const TextBlockContent = memo(function TextBlockContent({ content, isStreaming }: { content: string; isStreaming?: boolean }) {
+ const html = useMemo(() => renderMarkdown(content), [content]);
+ return <MarkdownContent html={html} isStreaming={isStreaming} />;
+});
+
interface Props {
message: StoredMessage;
isStreaming?: boolean;
@@ -224,11 +234,11 @@ function ChatMessage({ message, isStreaming, onRetry }: Props) {
);
}
-// Memoized: the message list re-renders on every reply-input keystroke (input state lives in the
-// same hook), so without this every message reconciles per character — sluggish on long chats. Props
-// are stable across keystrokes (same `message` object, `isStreaming` false, stable `onRetry`), so
-// completed messages are skipped; the streaming placeholder uses a fresh object each render, so it
-// still updates.
+// Memoized: the message list re-renders on every chat state change (streaming updates arrive at
+// animation-frame rate), so without this every message reconciles per update — sluggish on long
+// chats. Props are stable across those renders (same `message` object, `isStreaming` false, stable
+// `onRetry`), so completed messages are skipped; the streaming placeholder uses a fresh object each
+// render, so it still updates.
export default memo(ChatMessage);
/** Group content blocks so that consecutive tool_calls are merged into one entry. */
@@ -261,11 +271,10 @@ function groupContentBlocks(blocks: ContentBlock[]): ContentGroup[] {
function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {
return groupContentBlocks(blocks).map((group) => {
if (group.type === "text") {
- const html = renderMarkdown(group.block.content);
const isLastBlock = group.index === blocks.length - 1;
return (
<div key={group.index}>
- <MarkdownContent html={html} isStreaming={isStreaming && isLastBlock} />
+ <TextBlockContent content={group.block.content} isStreaming={isStreaming && isLastBlock} />
</div>
);
}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css
index 1001d6801d..42d0c6b3b5 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css
@@ -16,6 +16,9 @@
flex: 1;
min-height: 0;
overflow-y: auto;
+ /* Layout/paint changes inside the timeline (e.g. streaming appends) stay inside it;
+ the element's own size comes from the flex container, so this is safe and free. */
+ contain: layout paint;
}
/* Content-end sentinel watched by the jump-to-latest IntersectionObserver. A 1px
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx
index 58e33a3504..640e6e7953 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx
@@ -1,9 +1,12 @@
import "./ChatMessageList.css";
+import { useMemo } from "preact/hooks";
+
import { t } from "../../../services/i18n.js";
import ActionButton from "../../react/ActionButton.js";
import NoItems from "../../react/NoItems.js";
import ChatMessage from "./ChatMessage.js";
+import type { StoredMessage } from "./llm_chat_types.js";
import type { UseLlmChatReturn } from "./useLlmChat.js";
interface ChatMessageListProps {
@@ -21,44 +24,57 @@ interface ChatMessageListProps {
* scroll anchor. Shared by the chat note type widget and the sidebar chat.
*/
export default function ChatMessageList({ chat, emptyStateText, className }: ChatMessageListProps) {
+ const { messages, isStreaming, retryLast } = chat;
+
+ // Rebuilt only when the timeline itself changes: renders caused by anything else
+ // (streaming commits, toggles) skip the O(messages) vnode allocation and the
+ // per-message memo compares entirely.
+ const storedMessages = useMemo(() => messages.map((msg, idx) => (
+ <ChatMessage
+ key={msg.id}
+ message={msg}
+ onRetry={
+ idx === messages.length - 1 && msg.type === "error" && !isStreaming
+ ? retryLast
+ : undefined
+ }
+ />
+ )), [messages, isStreaming, retryLast]);
+
+ // Stable placeholder objects: rebuilt only when their streamed content advances, so
+ // renders caused by anything else let memo(ChatMessage) skip the placeholders too.
+ const thinkingMessage = useMemo<StoredMessage | null>(() => chat.streamingThinking ? {
+ id: "streaming-thinking",
+ role: "assistant",
+ content: chat.streamingThinking,
+ createdAt: new Date().toISOString(),
+ type: "thinking"
+ } : null, [chat.streamingThinking]);
+
+ const streamingMessage = useMemo<StoredMessage | null>(() => chat.streamingBlocks.length > 0 ? {
+ id: "streaming",
+ role: "assistant",
+ content: chat.streamingBlocks,
+ createdAt: new Date().toISOString(),
+ citations: chat.pendingCitations.length > 0 ? chat.pendingCitations : undefined
+ } : null, [chat.streamingBlocks, chat.pendingCitations]);
+
return (
<div className="chat-message-list-wrapper">
<div className={`chat-message-list ${className ?? ""}`} ref={chat.scrollContainerRef}>
- {chat.messages.length === 0 && !chat.isStreaming && (
+ {messages.length === 0 && !isStreaming && (
<NoItems icon="bx bx-conversation" text={emptyStateText} />
)}
- {chat.messages.map((msg, idx) => (
- <ChatMessage
- key={msg.id}
- message={msg}
- onRetry={
- idx === chat.messages.length - 1 && msg.type === "error" && !chat.isStreaming
- ? chat.retryLast
- : undefined
- }
- />
- ))}
- {chat.isStreaming && chat.streamingThinking && (
+ {storedMessages}
+ {isStreaming && thinkingMessage && (
<ChatMessage
- message={{
- id: "streaming-thinking",
- role: "assistant",
- content: chat.streamingThinking,
- createdAt: new Date().toISOString(),
- type: "thinking"
- }}
+ message={thinkingMessage}
isStreaming
/>
)}
- {chat.isStreaming && chat.streamingBlocks.length > 0 && (
+ {isStreaming && streamingMessage && (
<ChatMessage
- message={{
- id: "streaming",
- role: "assistant",
- content: chat.streamingBlocks,
- createdAt: new Date().toISOString(),
- citations: chat.pendingCitations.length > 0 ? chat.pendingCitations : undefined
- }}
+ message={streamingMessage}
isStreaming
/>
)}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
index 09fefac915..ed0b08728d 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
@@ -44,32 +44,50 @@ export function useChatToc(chat: UseLlmChatReturn, noteContext: NoteContext | un
}
}, []);
- // Scroll-spy: recompute the active heading whenever the timeline scrolls or resizes.
- // Layout reads are batched into a single animation frame so a fast scroll can't queue
- // a backlog of reflows.
+ // Scroll-spy: pick the active heading whenever the timeline scrolls or resizes. Heading
+ // offsets are measured once per headings change or container resize — never per scroll
+ // frame, where per-heading geometry reads would force layout across the whole timeline.
+ // Scrolling only reads scrollTop. Offsets can drift when content resizes without
+ // resizing the container (e.g. an image loading mid-history); the drift only affects
+ // the highlight and heals on the next measure.
useEffect(() => {
const container = scrollContainerRef.current;
if (!container) return;
+ // Offsets relative to the scroll content, independent of the scroll position.
+ let offsets: HeadingOffset[] = [];
+ let activationLine = 0;
+ const measure = () => {
+ const contentTop = container.getBoundingClientRect().top - container.scrollTop;
+ offsets = [];
+ for (const heading of headings) {
+ if (!heading.element?.isConnected) continue;
+ offsets.push({ id: heading.id, top: heading.element.getBoundingClientRect().top - contentTop });
+ }
+ activationLine = container.clientHeight * ACTIVATION_LINE_FRACTION;
+ };
+
let rafId: number | null = null;
+ let measureNeeded = true;
const recompute = () => {
rafId = null;
- const containerTop = container.getBoundingClientRect().top;
- const entries: HeadingOffset[] = [];
- for (const heading of headings) {
- if (!heading.element?.isConnected) continue;
- entries.push({ id: heading.id, top: heading.element.getBoundingClientRect().top - containerTop });
+ if (measureNeeded) {
+ measureNeeded = false;
+ measure();
}
- const activationLine = container.clientHeight * ACTIVATION_LINE_FRACTION;
- setActiveHeadingId(pickActiveHeadingId(entries, activationLine));
+ setActiveHeadingId(pickActiveHeadingId(offsets, activationLine + container.scrollTop));
};
const schedule = () => {
if (rafId == null) rafId = requestAnimationFrame(recompute);
};
+ const scheduleMeasure = () => {
+ measureNeeded = true;
+ schedule();
+ };
recompute();
container.addEventListener("scroll", schedule, { passive: true });
- const resizeObserver = typeof ResizeObserver !== "undefined" ? new ResizeObserver(schedule) : null;
+ const resizeObserver = typeof ResizeObserver !== "undefined" ? new ResizeObserver(scheduleMeasure) : null;
resizeObserver?.observe(container);
return () => {
@@ -95,19 +113,27 @@ export function useChatToc(chat: UseLlmChatReturn, noteContext: NoteContext | un
interface HeadingOffset {
id: string;
- /** Distance (px) of the message's top edge below the scroll container's top edge. */
+ /** The heading's top edge position, in the same coordinate space as the activation line. */
top: number;
}
-function findMessageElement(container: HTMLElement | null, messageId: string): HTMLElement | null {
- if (!container) return null;
- // Compare the parsed dataset value rather than interpolating the id into a CSS selector:
- // persisted or imported chats may carry ids with characters (quotes, backslashes, newlines)
- // that would make an attribute selector invalid and throw.
+/**
+ * Map every rendered message element by its id in one pass, so heading extraction stays
+ * O(messages) instead of running a full-timeline query per message. The dataset value is
+ * compared as parsed rather than interpolated into a CSS selector: persisted or imported
+ * chats may carry ids with characters (quotes, backslashes, newlines) that would make an
+ * attribute selector invalid and throw.
+ */
+function buildMessageElementMap(container: HTMLElement | null): Map<string, HTMLElement> {
+ const elementById = new Map<string, HTMLElement>();
+ if (!container) return elementById;
for (const el of container.querySelectorAll<HTMLElement>("[data-message-id]")) {
- if (el.dataset.messageId === messageId) return el;
+ const id = el.dataset.messageId;
+ if (id !== undefined && !elementById.has(id)) {
+ elementById.set(id, el);
+ }
}
- return null;
+ return elementById;
}
/** Headings inside an assistant reply's rendered markdown (excludes tool cards, citations, etc.). */
@@ -121,6 +147,7 @@ const REPLY_HEADING_SELECTOR = [1, 2, 3, 4, 5, 6].map(n => `.llm-chat-markdown h
* them (e.g. an imported chat), they keep their own level so the hierarchy starts at 1.
*/
export function extractChatHeadings(messages: StoredMessage[], container: HTMLElement | null): ChatHeading[] {
+ const elementById = buildMessageElementMap(container);
const headings: ChatHeading[] = [];
let hasUserHeading = false;
for (const message of messages) {
@@ -134,11 +161,11 @@ export function extractChatHeadings(messages: StoredMessage[], container: HTMLEl
id: message.id,
level: 1,
text: escapeHtml(preview),
- element: findMessageElement(container, message.id)
+ element: elementById.get(message.id) ?? null
});
hasUserHeading = true;
} else if (message.role === "assistant") {
- const messageEl = findMessageElement(container, message.id);
+ const messageEl = elementById.get(message.id);
if (!messageEl) continue;
const levelOffset = hasUserHeading ? 1 : 0;
let index = 0;
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 6512ef68c4..a1fa4c456d 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -90,9 +90,11 @@ export interface LlmChatOptions {
export interface UseLlmChatReturn {
// State
messages: StoredMessage[];
- input: string;
+ /** Whether the reply-input draft has non-whitespace text. The draft itself is kept out of
+ * state (typing must not re-render the chat tree); read it at submit time via
+ * {@link getInput}. */
+ hasInputText: boolean;
isStreaming: boolean;
- streamingContent: string;
streamingBlocks: ContentBlock[];
streamingThinking: string;
pendingCitations: LlmCitation[];
@@ -125,6 +127,9 @@ export interface UseLlmChatReturn {
/** Append a preformatted block (e.g. a Markdown quote) to the reply input and focus it. */
appendToInput: (text: string) => void;
+ /** Read the current reply-input draft text (kept in a ref, not state — see {@link hasInputText}). */
+ getInput: () => string;
+
// Setters
setInput: (value: string) => void;
setMessages: (messages: StoredMessage[]) => void;
@@ -162,7 +167,16 @@ export function useLlmChat(
const { defaultEnableNoteTools = false, supportsExtendedThinking = false, contextNoteId: initialContextNoteId, chatNoteId: initialChatNoteId } = options;
const [messages, setMessagesInternal] = useState<StoredMessage[]>([]);
- const [input, setInput] = useState("");
+ // The reply-input draft lives in a ref so typing never re-renders the chat tree; only the
+ // empty <-> non-empty transition is stateful (it drives the send button), and same-value
+ // setState calls bail out of re-rendering.
+ const inputRef = useRef("");
+ const [hasInputText, setHasInputText] = useState(false);
+ const setInput = useCallback((value: string) => {
+ inputRef.current = value;
+ setHasInputText(value.trim().length > 0);
+ }, []);
+ const getInput = useCallback(() => inputRef.current, []);
const [isStreaming, setIsStreaming] = useState(false);
// The canonical "target" content received from the stream so far. The
// displayed `streamingBlocks` is derived from this with the trailing text
@@ -237,11 +251,16 @@ export function useLlmChat(
setPendingAttachments(prev => prev.filter(a => a.attachmentId !== attachmentId));
}, []);
- // Wrapper to call onMessagesChange when messages update
+ // Wrapper to call onMessagesChange when messages update. The callback goes through a ref:
+ // both hosts pass inline arrows, and keeping them out of the deps keeps setMessages — and the
+ // whole action-callback chain built on it (runStream, handleSubmit, retryLast, ...) — stable
+ // across renders.
+ const onMessagesChangeRef = useRef(onMessagesChange);
+ onMessagesChangeRef.current = onMessagesChange;
const setMessages = useCallback((newMessages: StoredMessage[]) => {
setMessagesInternal(newMessages);
- onMessagesChange?.(newMessages);
- }, [onMessagesChange]);
+ onMessagesChangeRef.current?.(newMessages);
+ }, []);
// Fetch available models on mount
const refreshModels = useCallback(() => {
@@ -743,7 +762,7 @@ export function useLlmChat(
const handleSubmit = useCallback(async (e: Event) => {
e.preventDefault();
if (isStreaming) return;
- const trimmedInput = input.trim();
+ const trimmedInput = inputRef.current.trim();
const attachments = pendingAttachmentsRef.current;
if (!trimmedInput && attachments.length === 0) return;
@@ -774,7 +793,7 @@ export function useLlmChat(
setPendingAttachments([]);
pendingScrollRef.current = "anchor";
await runStream([...messages, userMessage]);
- }, [input, isStreaming, messages, runStream]);
+ }, [isStreaming, messages, runStream, setInput]);
/** Re-run the last turn after a failed response, dropping the trailing error message. */
const retryLast = useCallback(async () => {
@@ -825,17 +844,11 @@ export function useLlmChat(
];
}, [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,
- input,
+ hasInputText,
isStreaming,
- streamingContent,
streamingBlocks,
streamingThinking,
pendingCitations,
@@ -858,6 +871,7 @@ export function useLlmChat(
registerInputEditor,
appendToInput,
+ getInput,
// Setters
setInput,
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts b/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts
index 6f87715bfe..396950b25e 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useSmoothStreaming.ts
@@ -11,6 +11,9 @@ interface SmoothStreamingOptions {
maxBacklogSeconds?: number;
}
+/** Minimum time between displayed-text state commits (see the cadence cap in `tick`). */
+const MIN_COMMIT_INTERVAL_MS = 40;
+
export interface SmoothStreamingHandle {
/** The smoothed prefix of the appended target text — render this. */
displayedText: string;
@@ -42,6 +45,15 @@ export function useSmoothStreaming(options: SmoothStreamingOptions = {}): Smooth
const tick = useCallback(() => {
const now = performance.now();
+
+ // Cap the commit cadence: every setDisplayedText re-renders the whole chat tree, and
+ // rAF fires at display refresh rate (up to 144 Hz). ~25 commits/s still reads as a
+ // smooth typewriter (the reveal rate is time-based, so throughput is unaffected).
+ if (now - lastTickRef.current < MIN_COMMIT_INTERVAL_MS) {
+ rafRef.current = requestAnimationFrame(tick);
+ return;
+ }
+
const dt = (now - lastTickRef.current) / 1000;
lastTickRef.current = now;