Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/AI chat: remove the auto-scroll, add a scroll to bottom button
Adorian Doran781a2e84662e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 07fc5fa352..d625fd3640 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2068,6 +2068,7 @@"add_provider": "Add AI Provider","stop": "Stop","retry": "Retry",+ "scroll_to_bottom": "Scroll to latest","attach_file": "Attach image, PDF, or text file","remove_attachment": "Remove attachment","attachment_upload_failed": "Failed to upload \"{{name}}\".",diff --git a/apps/client/src/widgets/sidebar/SidebarChat.css b/apps/client/src/widgets/sidebar/SidebarChat.cssindex d13aa3450c..a5428ec7f4 100644--- a/apps/client/src/widgets/sidebar/SidebarChat.css+++ b/apps/client/src/widgets/sidebar/SidebarChat.css@@ -17,7 +17,9 @@/* Scroll-container essentials (flex/min-height/overflow) come from .chat-message-list. */.sidebar-chat-messages {- padding: 0.5rem;+ /* Extra bottom padding mirrors the main chat widget: room for the first lines of+ an incoming reply to appear without auto-following the stream. */+ padding: 0.5rem 0.5rem 4em;display: flex;flex-direction: column;gap: 0.5rem;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.cssindex a3cb1e9288..c5439fd622 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css@@ -1,3 +1,14 @@+/* Positioned host so the jump-to-bottom button can float over the scroll area+ without scrolling along with the content. Fills the space the scroll container+ used to occupy directly. */+.chat-message-list-wrapper {+ position: relative;+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+}+/* Shared scroll container for the chat message list (used by both the chat notetype widget and the sidebar chat). Widget-specific padding/layout lives in therespective widget CSS, keyed off the extra class passed via `className`. */@@ -6,3 +17,30 @@min-height: 0;overflow-y: auto;}++/* Floating jump-to-bottom button, centered along the bottom edge of the timeline. */+.chat-message-list-wrapper .chat-scroll-to-bottom.icon-action {+ position: absolute;+ bottom: 0.75em;+ left: 50%;+ transform: translateX(-50%);+ z-index: 10;+ width: 2.2rem;+ height: 2.2rem;+ font-size: 1.3rem;+ line-height: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 50%;+ background-color: var(--main-background-color);+ border: 1px solid var(--main-border-color);+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);+ color: var(--main-text-color);+ opacity: 0.95;+}++.chat-message-list-wrapper .chat-scroll-to-bottom.icon-action:hover {+ opacity: 1;+ background-color: var(--hover-item-background-color);+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsxindex f3d0307053..380f46e241 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx@@ -1,5 +1,7 @@import "./ChatMessageList.css";+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 { UseLlmChatReturn } from "./useLlmChat.js";@@ -20,46 +22,57 @@ interface ChatMessageListProps {*/export default function ChatMessageList({ chat, emptyStateText, className }: ChatMessageListProps) {return (- <div className={`chat-message-list ${className ?? ""}`} ref={chat.scrollContainerRef}>- {chat.messages.length === 0 && !chat.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 && (- <ChatMessage- message={{- id: "streaming-thinking",- role: "assistant",- content: chat.streamingThinking,- createdAt: new Date().toISOString(),- type: "thinking"- }}- isStreaming- />- )}- {chat.isStreaming && chat.streamingBlocks.length > 0 && (- <ChatMessage- message={{- id: "streaming",- role: "assistant",- content: chat.streamingBlocks,- createdAt: new Date().toISOString(),- citations: chat.pendingCitations.length > 0 ? chat.pendingCitations : undefined- }}- isStreaming+ <div className="chat-message-list-wrapper">+ <div className={`chat-message-list ${className ?? ""}`} ref={chat.scrollContainerRef}>+ {chat.messages.length === 0 && !chat.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 && (+ <ChatMessage+ message={{+ id: "streaming-thinking",+ role: "assistant",+ content: chat.streamingThinking,+ createdAt: new Date().toISOString(),+ type: "thinking"+ }}+ isStreaming+ />+ )}+ {chat.isStreaming && chat.streamingBlocks.length > 0 && (+ <ChatMessage+ message={{+ id: "streaming",+ role: "assistant",+ content: chat.streamingBlocks,+ createdAt: new Date().toISOString(),+ citations: chat.pendingCitations.length > 0 ? chat.pendingCitations : undefined+ }}+ isStreaming+ />+ )}+ <div ref={chat.messagesEndRef} />+ </div>+ {chat.showScrollToBottom && (+ <ActionButton+ className="chat-scroll-to-bottom"+ icon="bx bx-chevron-down"+ text={t("llm_chat.scroll_to_bottom")}+ titlePosition="top"+ onClick={chat.scrollToBottom}/>)}- <div ref={chat.messagesEndRef} /></div>);}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.css b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.cssindex b429ada78d..e9e6a64375 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.css@@ -5,7 +5,10 @@box-sizing: border-box;.llm-chat-messages {- padding: 1em;+ /* Extra bottom padding leaves breathing room below the last message, so the+ first few lines of an incoming reply stream into view rather than below+ the fold (the timeline no longer auto-follows the stream). */+ padding: 1em 1em 6em;}.llm-chat-input-form {diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex 89f1055f03..fc540fc59a 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -11,6 +11,9 @@ import { useSmoothStreaming } from "./useSmoothStreaming.js";/** A user-supplied attachment waiting to be sent with the next message. */export type AttachmentBlock = ImageBlock | FileBlock | TextFileBlock;+/** Distance (px) from the bottom within which the timeline counts as "at bottom". */+const SCROLL_BOTTOM_THRESHOLD = 50;+/*** Flatten a stored message's content into the wire format the server expects.* Plain string content stays as-is; block-shaped content (with images) becomes@@ -79,6 +82,10 @@ export interface UseLlmChatReturn {lastPromptTokens: number;messagesEndRef: RefObject<HTMLDivElement>;scrollContainerRef: RefObject<HTMLDivElement>;+ /** Whether the timeline is scrolled away from the bottom (drives the jump-to-bottom button). */+ showScrollToBottom: boolean;+ /** Jump the timeline to the latest content. */+ scrollToBottom: () => void;/** Whether a provider is configured and available */hasProvider: boolean;/** Whether we're still checking for providers */@@ -139,10 +146,13 @@ export function useLlmChat(const [lastPromptTokens, setLastPromptTokens] = useState<number>(0);const [hasProvider, setHasProvider] = useState<boolean>(true); // Assume true initiallyconst [isCheckingProvider, setIsCheckingProvider] = useState<boolean>(true);+ const [showScrollToBottom, setShowScrollToBottom] = useState(false);const messagesEndRef = useRef<HTMLDivElement>(null);const scrollContainerRef = useRef<HTMLDivElement>(null);const abortControllerRef = useRef<AbortController | null>(null);- const isNearBottomRef = useRef(true);+ // Set when the user sends a message, so the next render scrolls their message+ // into view exactly once — distinct from the (now removed) follow-while-streaming.+ const scrollOnNextMessagesRef = useRef(false);// Refs to get fresh values in getContent (avoids stale closures)const messagesRef = useRef(messages);@@ -217,36 +227,49 @@ export function useLlmChat(}}, [refreshModels]));- // Track whether the user is near the bottom of the scroll container- useEffect(() => {+ // The timeline never follows the stream automatically — the model can outpace+ // the reader. Instead we surface a jump-to-bottom button whenever there is+ // content below the fold, and the user decides when to catch up.+ const updateScrollButton = useCallback(() => {const container = scrollContainerRef.current;- if (!container) return;-- const THRESHOLD = 50; // px from bottom- const handleScroll = () => {- isNearBottomRef.current =- container.scrollHeight - container.scrollTop - container.clientHeight <= THRESHOLD;- };-- container.addEventListener("scroll", handleScroll, { passive: true });- return () => container.removeEventListener("scroll", handleScroll);+ if (!container) {+ setShowScrollToBottom(false);+ return;+ }+ const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;+ setShowScrollToBottom(distanceFromBottom > SCROLL_BOTTOM_THRESHOLD);}, []);- // Scroll to bottom when content changes, but only if user hasn't scrolled away.- // Always use instant scroll — smooth animations race with the scroll listener- // during streaming, causing the auto-scroll to "unstick" mid-animation.+ /** Jump the timeline to the latest content (used by the jump-to-bottom button). */const scrollToBottom = useCallback(() => {- if (isNearBottomRef.current) {- messagesEndRef.current?.scrollIntoView({ behavior: "instant" });- }+ messagesEndRef.current?.scrollIntoView({ behavior: "instant" });}, []);useEffect(() => {- scrollToBottom();- }, [messages, smoothedTailText, streamingThinking, scrollToBottom]);+ const container = scrollContainerRef.current;+ if (!container) return;+ container.addEventListener("scroll", updateScrollButton, { passive: true });+ return () => container.removeEventListener("scroll", updateScrollButton);+ }, [updateScrollButton]);++ // Recompute button visibility as content changes. When the user has just sent a+ // message, scroll once so their message (and the first lines of the reply that+ // streams into the bottom spacing) stay in view — but never follow after that.+ useEffect(() => {+ if (scrollOnNextMessagesRef.current) {+ scrollOnNextMessagesRef.current = false;+ scrollToBottom();+ }+ updateScrollButton();+ }, [messages, smoothedTailText, streamingThinking, scrollToBottom, updateScrollButton]);// Load state from content objectconst loadFromContent = useCallback((content: LlmChatContent) => {+ // Opening an existing chat should land on the most recent message, so scroll+ // once after the loaded messages render (same one-shot path as sending).+ if ((content.messages?.length ?? 0) > 0) {+ scrollOnNextMessagesRef.current = true;+ }setMessagesInternal(content.messages || []);if (content.selectedModel) {setSelectedModel(content.selectedModel);@@ -578,6 +601,7 @@ export function useLlmChat(};setInput("");setPendingAttachments([]);+ scrollOnNextMessagesRef.current = true;await runStream([...messages, userMessage]);}, [input, isStreaming, messages, runStream]);@@ -585,6 +609,7 @@ export function useLlmChat(const retryLast = useCallback(async () => {if (isStreaming) return;if (messages[messages.length - 1]?.type !== "error") return;+ scrollOnNextMessagesRef.current = true;await runStream(messages.slice(0, -1));}, [isStreaming, messages, runStream]);@@ -643,6 +668,8 @@ export function useLlmChat(lastPromptTokens,messagesEndRef,scrollContainerRef,+ showScrollToBottom,+ scrollToBottom,hasProvider,isCheckingProvider,