Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doran8c01a762b6c5
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 a59dad7e2f..1001d6801d 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.css
@@ -18,6 +18,13 @@
overflow-y: auto;
}
+/* Content-end sentinel watched by the jump-to-latest IntersectionObserver. A 1px
+ height keeps it reliably observable across browsers (zero-area targets are flaky). */
+.chat-messages-end {
+ min-height: 1px;
+ flex-shrink: 0;
+}
+
/* Reserved room below the last message so a new reply can be parked near the top and
type out in place. Height is set imperatively by useLlmChat (sized to what the turn
actually needs), so long replies leave little trailing blank. */
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 923fc2e5c7..58e33a3504 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessageList.tsx
@@ -62,7 +62,7 @@ export default function ChatMessageList({ chat, emptyStateText, className }: Cha
isStreaming
/>
)}
- <div ref={chat.messagesEndRef} />
+ <div ref={chat.messagesEndRef} className="chat-messages-end" aria-hidden="true" />
<div ref={chat.bottomSpacerRef} className="chat-bottom-spacer" aria-hidden="true" />
</div>
{chat.showScrollToBottom && (
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 dfe1cc3568..63f730e18f 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -251,21 +251,6 @@ export function useLlmChat(
}
}, [refreshModels]));
- // The timeline does not follow the stream — the model can outpace the reader, and
- // moving text is hard to read. A jump-to-latest button appears whenever there is
- // content below the fold; its visibility is measured against the real content end
- // (the messagesEnd anchor).
- const updateScrollButton = useCallback(() => {
- const container = scrollContainerRef.current;
- const endEl = messagesEndRef.current;
- if (!container || !endEl) {
- setShowScrollToBottom(false);
- return;
- }
- const distance = endEl.getBoundingClientRect().top - container.getBoundingClientRect().bottom;
- setShowScrollToBottom(distance > SCROLL_BOTTOM_THRESHOLD);
- }, []);
-
/** Jump to the latest content (ignores the trailing spacer). */
const scrollToBottom = useCallback(() => {
messagesEndRef.current?.scrollIntoView({ block: "end", behavior: "instant" });
@@ -361,12 +346,27 @@ export function useLlmChat(
smoothScrollTo(container.scrollTop + boundaryWithinView - offsetAboveBoundary);
}, [scrollToBottom, smoothScrollTo]);
+ // The timeline does not follow the stream — the model can outpace the reader, and
+ // moving text is hard to read. A jump-to-latest button appears whenever the content
+ // end sits below the fold. An IntersectionObserver on the messagesEnd anchor drives
+ // it: it fires only when the anchor crosses the viewport edge — no per-scroll layout
+ // reads — and covers scrolling, resize, streaming growth, and message changes alike.
useEffect(() => {
const container = scrollContainerRef.current;
- if (!container) return;
- container.addEventListener("scroll", updateScrollButton, { passive: true });
- return () => container.removeEventListener("scroll", updateScrollButton);
- }, [updateScrollButton]);
+ const endEl = messagesEndRef.current;
+ if (!container || !endEl || typeof IntersectionObserver === "undefined") return;
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ const rootBounds = entry.rootBounds;
+ // Show only when the content end is genuinely below the fold — not when it
+ // has been scrolled above (matches the previous distance-based check).
+ setShowScrollToBottom(rootBounds ? entry.boundingClientRect.top > rootBounds.bottom : false);
+ },
+ { root: container, rootMargin: `0px 0px ${SCROLL_BOTTOM_THRESHOLD}px 0px`, threshold: 0 }
+ );
+ observer.observe(endEl);
+ return () => observer.disconnect();
+ }, []);
// Re-fit the spacer and run any pending one-shot scroll as the message list changes.
// A layout effect lets the spacer settle synchronously so the anchor scroll already
@@ -383,30 +383,23 @@ export function useLlmChat(
scrollToBottom();
}
}
- updateScrollButton();
- }, [messages, recomputeBottomSpacer, anchorReplyToTop, scrollToBottom, updateScrollButton]);
-
- // While streaming, the reply grows without changing `messages` — refresh only the
- // button (the spacer intentionally stays at its turn-start size; nothing scrolls).
- useEffect(() => {
- updateScrollButton();
- }, [smoothedTailText, streamingThinking, updateScrollButton]);
+ }, [messages, recomputeBottomSpacer, anchorReplyToTop, scrollToBottom]);
// Re-fit the spacer when the container is resized (pane split, window resize, etc.).
+ // The button is handled by the IntersectionObserver, which reacts to resize itself.
useEffect(() => {
const container = scrollContainerRef.current;
if (!container || typeof ResizeObserver === "undefined") return;
- const observer = new ResizeObserver(() => {
- recomputeBottomSpacer();
- updateScrollButton();
- });
+ const observer = new ResizeObserver(() => recomputeBottomSpacer());
observer.observe(container);
return () => observer.disconnect();
- }, [recomputeBottomSpacer, updateScrollButton]);
+ }, [recomputeBottomSpacer]);
- // Stop any in-flight anchor animation when the widget unmounts.
+ // On unmount, stop the anchor animation and abort any active stream so it stops
+ // consuming API tokens and can't push chunks into an unmounted component.
useEffect(() => () => {
if (anchorRafRef.current != null) cancelAnimationFrame(anchorRafRef.current);
+ abortControllerRef.current?.abort();
}, []);
// Load state from content object
diff --git a/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts b/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
index b7b428f775..4b4652f102 100644
--- a/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
@@ -2,7 +2,7 @@ import { Compartment, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { describe, expect, it } from "vitest";
-import { triliumLogHighlighter } from "./trilium_log_highlighter.js";
+import { MAX_HIGHLIGHTED_LINES, triliumLogHighlighter } from "./trilium_log_highlighter.js";
interface DecorationSpan {
from: number;
@@ -111,6 +111,25 @@ describe("triliumLogHighlighter", () => {
expect(decorationsOf(state("just some text\nanother line"))).toHaveLength(0);
expect(decorationsOf(state(""))).toHaveLength(0);
});
+
+ it("only highlights the last MAX_HIGHLIGHTED_LINES lines of a large log", () => {
+ // First line (beyond the cap) is an error header; if the whole doc were scanned it would be
+ // coloured. The tail stays highlighted.
+ const lines = [ "17:00:00.000 JS Error: old boom" ];
+ for (let i = 0; i < MAX_HIGHLIGHTED_LINES + 50; i++) {
+ lines.push(`18:00:00.${String(i % 1000).padStart(3, "0")} Slow query ${i}`);
+ }
+ const s = state(lines.join("\n"));
+
+ // The first line's error header is beyond the cap, so it is never coloured.
+ expect(lineClassesAt(s, 1)).toHaveLength(0);
+ expect(classesOfState(s)).not.toContain("cm-log-error");
+
+ // The tail is highlighted, and the number of scanned lines is bounded by the cap.
+ const timestamps = classesOfState(s).filter((c) => c === "cm-log-timestamp");
+ expect(timestamps.length).toBeGreaterThan(0);
+ expect(timestamps.length).toBeLessThanOrEqual(MAX_HIGHLIGHTED_LINES);
+ });
});
function state(doc: string): EditorState {
diff --git a/packages/codemirror/src/extensions/trilium_log_highlighter.ts b/packages/codemirror/src/extensions/trilium_log_highlighter.ts
index 3be1c604b3..c79f9413ff 100644
--- a/packages/codemirror/src/extensions/trilium_log_highlighter.ts
+++ b/packages/codemirror/src/extensions/trilium_log_highlighter.ts
@@ -7,8 +7,11 @@ import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";
* than a view plugin) so they are applied deterministically the instant the extension enters the
* configuration — e.g. when a code note is switched to the `text/x-trilium-log` MIME type — instead
* of only after the next edit or scroll (a dynamically added view plugin doesn't paint until the
- * following update). The whole document is scanned top-to-bottom, which also lets the error/info
- * block state carry across continuation lines without a separate backwards scan.
+ * following update). Only the last {@link MAX_HIGHLIGHTED_LINES} lines are scanned (top-to-bottom
+ * within that window) so a large backend log — potentially a whole day of per-request lines — can't
+ * block the main thread; logs append newest-last and the view scrolls to the end, so the tail is
+ * the relevant part. That single pass also lets the error/info block state carry across continuation
+ * lines without a separate backwards scan.
*
* Recognised entries:
* - the leading timestamp (muted, on every entry)
@@ -28,6 +31,9 @@ const HTTP_REQUEST = /^\d{2}:\d{2}:\d{2}\.\d{3} (\d{3}) (GET|POST|PUT|PATCH|DELE
const ERROR_LINE = /^\d{2}:\d{2}:\d{2}\.\d{3} (?:JS Error|ERROR):/;
const INFO_LINE = /^\d{2}:\d{2}:\d{2}\.\d{3} JS Info:/;
+/** Upper bound on how many (trailing) lines are highlighted, to cap the per-rebuild work. */
+export const MAX_HIGHLIGHTED_LINES = 10_000;
+
const timestampMark = Decoration.mark({ class: "cm-log-timestamp" });
const verbMark = Decoration.mark({ class: "cm-log-verb" });
const urlMark = Decoration.mark({ class: "cm-log-url" });
@@ -73,10 +79,13 @@ function buildLogDecorations(state: EditorState): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
const doc = state.doc;
- // A single top-to-bottom pass keeps the error/info block state (used to colour continuation
- // lines) flowing naturally across lines.
+ // Scan at most the last MAX_HIGHLIGHTED_LINES lines. A single top-to-bottom pass over that window
+ // keeps the error/info block state (used to colour continuation lines) flowing across lines; a
+ // stack trace straddling the window's top edge may miss its colour, which is acceptable for a log
+ // that large.
+ const firstLine = Math.max(1, doc.lines - MAX_HIGHLIGHTED_LINES + 1);
let blockLine: Decoration | null = null;
- for (let n = 1; n <= doc.lines; n++) {
+ for (let n = firstLine; n <= doc.lines; n++) {
blockLine = decorateLine(builder, doc.line(n), blockLine);
}