Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): add an opt-in profiler for tracking down UI stalls

Elian Doran11f17c4c5429
diff --git a/apps/client/src/entities/fattribute.ts b/apps/client/src/entities/fattribute.ts
index df5dd9a52c..c4bc977c66 100644
--- a/apps/client/src/entities/fattribute.ts
+++ b/apps/client/src/entities/fattribute.ts
@@ -1,5 +1,6 @@
import { promotedAttributeDefinitionParser } from "@triliumnext/commons";
+import { perfSpan } from "../services/debug_perf.js";
import type { Froca } from "../services/froca-interface.js";
/**
@@ -87,7 +88,14 @@ class FAttribute {
}
getDefinition() {
- return promotedAttributeDefinitionParser.parse(this.value);
+ // Re-parses the definition string on every call, so a caller in a render path pays for it
+ // once per attribute per render; the span is what makes that visible.
+ const endSpan = perfSpan("FAttribute.getDefinition");
+ try {
+ return promotedAttributeDefinitionParser.parse(this.value);
+ } finally {
+ endSpan();
+ }
}
isDefinitionFor(attr: FAttribute) {
diff --git a/apps/client/src/services/debug_perf.ts b/apps/client/src/services/debug_perf.ts
new file mode 100644
index 0000000000..1d0164554f
--- /dev/null
+++ b/apps/client/src/services/debug_perf.ts
@@ -0,0 +1,226 @@
+/**
+ * Opt-in main-thread instrumentation for tracking down UI stalls.
+ *
+ * Recording is off by default and every entry point costs one boolean check when off, so call
+ * sites can sit in hot paths (per-card renders, per-cell formatting) without being paid for in
+ * normal use. Drive it from the devtools console:
+ *
+ * ```js
+ * triliumPerf.enable(); // start recording; also logs every long task as it happens
+ * triliumPerf.report(); // print what has been gathered so far
+ * triliumPerf.reset(); // clear the counters, keep recording
+ * triliumPerf.disable();
+ * ```
+ *
+ * Spans additionally land on the User Timing track via `performance.measure()`, so a DevTools
+ * performance capture shows them lined up against the long tasks they explain.
+ */
+
+interface Counter {
+ calls: number;
+ totalMs: number;
+ maxMs: number;
+}
+
+const NOOP = () => {
+ /* recording is off */
+};
+
+/**
+ * A main-thread block this long counts as a stall. Matches the Long Tasks API's own threshold, so
+ * the two detectors below report comparable numbers.
+ */
+const STALL_THRESHOLD_MS = 50;
+
+let enabled = false;
+let recordingStartedAt = 0;
+let longTaskObserver: PerformanceObserver | undefined;
+let stallFrameHandle: number | undefined;
+const counters = new Map<string, Counter>();
+
+export function isPerfRecording() {
+ return enabled;
+}
+
+/**
+ * Opens a span. Call the returned function to close it, which records the elapsed time under
+ * `label` and emits a matching `performance.measure()` entry.
+ *
+ * Returns a no-op when recording is off, so the caller does not need to branch.
+ */
+export function perfSpan(label: string): () => void {
+ if (!enabled) {
+ return NOOP;
+ }
+
+ const start = performance.now();
+ return () => {
+ const end = performance.now();
+ record(label, end - start);
+
+ try {
+ // Same clock as performance.now(), so the span lands where it actually happened.
+ performance.measure(label, { start, end });
+ } catch (e) {
+ // A measure() that the browser rejects must not take the instrumented code down.
+ }
+ };
+}
+
+/** Records `count` occurrences of `label` without timing them. */
+export function perfCount(label: string, count = 1) {
+ if (!enabled) {
+ return;
+ }
+
+ record(label, 0, count);
+}
+
+/** Times a synchronous call and returns its result untouched. */
+export function perfTime<T>(label: string, fn: () => T): T {
+ if (!enabled) {
+ return fn();
+ }
+
+ const start = performance.now();
+ try {
+ return fn();
+ } finally {
+ record(label, performance.now() - start);
+ }
+}
+
+/** Logs a one-off event, stamped with how far into the recording it happened. */
+export function perfLog(label: string, detail?: Record<string, unknown>) {
+ if (!enabled) {
+ return;
+ }
+
+ const at = (performance.now() - recordingStartedAt).toFixed(0);
+ console.log(`[perf +${at}ms] ${label}`, detail ?? "");
+}
+
+function record(label: string, durationMs: number, count = 1) {
+ let counter = counters.get(label);
+ if (!counter) {
+ counter = { calls: 0, totalMs: 0, maxMs: 0 };
+ counters.set(label, counter);
+ }
+
+ counter.calls += count;
+ counter.totalMs += durationMs;
+ counter.maxMs = Math.max(counter.maxMs, durationMs);
+}
+
+function enable() {
+ if (enabled) {
+ return;
+ }
+
+ enabled = true;
+ recordingStartedAt = performance.now();
+ counters.clear();
+
+ startStallDetection();
+
+ console.log("[perf] recording. triliumPerf.report() to print, triliumPerf.disable() to stop.");
+}
+
+function disable() {
+ enabled = false;
+ longTaskObserver?.disconnect();
+ longTaskObserver = undefined;
+
+ if (stallFrameHandle !== undefined) {
+ cancelAnimationFrame(stallFrameHandle);
+ stallFrameHandle = undefined;
+ }
+
+ console.log("[perf] stopped.");
+}
+
+/**
+ * Starts reporting main-thread stalls, preferring the Long Tasks API and falling back to watching
+ * for late animation frames where it is missing.
+ *
+ * The fallback exists because only Chromium implements the `longtask` entry type, and
+ * `observe({ entryTypes })` drops an unrecognized type with nothing but a console warning rather
+ * than throwing — so on Firefox the observer silently reports nothing at all, which reads as "no
+ * stalls happened" instead of "this browser cannot see them".
+ */
+function startStallDetection() {
+ if (PerformanceObserver.supportedEntryTypes?.includes("longtask")) {
+ longTaskObserver = new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ reportStall(entry.startTime, entry.duration);
+ }
+ });
+ longTaskObserver.observe({ entryTypes: [ "longtask" ] });
+ console.log("[perf] stalls: Long Tasks API.");
+ return;
+ }
+
+ console.log("[perf] stalls: animation-frame watchdog (this browser has no Long Tasks API).");
+ watchForLateFrames();
+}
+
+/**
+ * Approximates long tasks by measuring the gap between animation frames: work that blocks the main
+ * thread pushes the next frame out by roughly its own duration.
+ *
+ * Less precise than the Long Tasks API -- it cannot see a block that lands while the page is not
+ * painting, and it charges the gap to the frame boundary rather than to the task -- but it is
+ * enough to time a stall and line it up against the spans around it.
+ */
+function watchForLateFrames() {
+ let previousFrameAt = performance.now();
+
+ const onFrame = () => {
+ if (!enabled) {
+ return;
+ }
+
+ const now = performance.now();
+ const gap = now - previousFrameAt;
+ if (gap >= STALL_THRESHOLD_MS) {
+ reportStall(previousFrameAt, gap);
+ }
+
+ previousFrameAt = now;
+ stallFrameHandle = requestAnimationFrame(onFrame);
+ };
+
+ stallFrameHandle = requestAnimationFrame(onFrame);
+}
+
+function reportStall(startTime: number, durationMs: number) {
+ record("stall", durationMs);
+ const at = (startTime - recordingStartedAt).toFixed(0);
+ console.log(`[perf +${at}ms] STALL ${durationMs.toFixed(0)}ms`);
+}
+
+function reset() {
+ counters.clear();
+ recordingStartedAt = performance.now();
+}
+
+function report() {
+ const elapsed = performance.now() - recordingStartedAt;
+ const rows = [ ...counters.entries() ]
+ .sort((a, b) => b[1].totalMs - a[1].totalMs || b[1].calls - a[1].calls)
+ .map(([ label, { calls, totalMs, maxMs } ]) => ({
+ label,
+ calls,
+ "total (ms)": +totalMs.toFixed(1),
+ "avg (ms)": +(totalMs / calls).toFixed(3),
+ "max (ms)": +maxMs.toFixed(1)
+ }));
+
+ console.log(`[perf] ${(elapsed / 1000).toFixed(1)}s recorded`);
+ console.table(rows);
+}
+
+const triliumPerf = { enable, disable, reset, report };
+export default triliumPerf;
+
+window.triliumPerf = triliumPerf;
diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.ts
index f2145f60cc..133f3009cc 100644
--- a/apps/client/src/types.d.ts
+++ b/apps/client/src/types.d.ts
@@ -1,6 +1,7 @@
import { BootstrapDefinition, ElectronApi, ElectronContextMenuParams, StandaloneApi } from "@triliumnext/commons";
import appContext, { AppContext } from "./components/app_context";
+import type triliumPerf from "./services/debug_perf";
import type FNote from "./entities/fnote";
import type { PrintReport } from "./print";
import type { lint } from "./services/eslint";
@@ -44,6 +45,9 @@ declare global {
logError(message: string);
logInfo(message: string);
+ /** Opt-in main-thread profiler, driven from the devtools console. See `services/debug_perf`. */
+ triliumPerf: typeof triliumPerf;
+
process?: ElectronProcess;
glob?: CustomGlobals;
diff --git a/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx b/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx
index d3e2ddcbce..f7d9ddea35 100644
--- a/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx
+++ b/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx
@@ -7,6 +7,7 @@ import { useState } from "preact/hooks";
import FNote from "../../entities/fnote";
import attributes from "../../services/attributes";
import { getReadableTextColor } from "../../services/css_class_manager";
+import { perfSpan } from "../../services/debug_perf";
import { formatDateTime } from "../../utils/formatters";
import { useTriliumEvent } from "../react/hooks";
import Icon from "../react/Icon";
@@ -116,6 +117,15 @@ function buildUserAttribute(attr: AttributeWithDefinitions): ComponentChildren {
}
function getAttributesWithDefinitions(note: FNote, attributesToIgnore: string[] = []): AttributeWithDefinitions[] {
+ const endSpan = perfSpan("UserAttributesList.getAttributesWithDefinitions");
+ try {
+ return gatherAttributesWithDefinitions(note, attributesToIgnore);
+ } finally {
+ endSpan();
+ }
+}
+
+function gatherAttributesWithDefinitions(note: FNote, attributesToIgnore: string[]): AttributeWithDefinitions[] {
const attributeDefintions = note.getAttributeDefinitions();
const result: AttributeWithDefinitions[] = [];
for (const attr of attributeDefintions) {
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index b67a004087..0b35aa92f8 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -5,6 +5,7 @@ import BoardApi from "./api";
import { BoardViewContext, TitleEditor } from ".";
import { ContextMenuEvent } from "../../../menus/context_menu";
import { openNoteContextMenu } from "./context_menu";
+import { perfCount } from "../../../services/debug_perf";
import { t } from "../../../services/i18n";
import UserAttributesDisplay from "../../attribute_widgets/UserAttributesList";
import { useTriliumEvent } from "../../react/hooks";
@@ -33,6 +34,8 @@ export default function Card({
index: number,
isDragging: boolean
}) {
+ perfCount("board.card.render");
+
const { branchIdToEdit, setBranchIdToEdit, setDraggedCard } = useContext(BoardViewContext)!;
const isEditing = branch.branchId === branchIdToEdit;
const colorClass = note.getColorClass() || '';
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 9a823a5eb9..186bb534d1 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -1,10 +1,12 @@
import "./index.css";
import { createContext, TargetedKeyboardEvent } from "preact";
-import { Dispatch, StateUpdater, useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import { Dispatch, StateUpdater, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import FNote from "../../../entities/fnote";
+import { perfLog, perfSpan } from "../../../services/debug_perf";
import { t } from "../../../services/i18n";
+import type LoadResults from "../../../services/load_results";
import { isIMEComposing } from "../../../services/shortcuts";
import toast from "../../../services/toast";
import CollectionProperties from "../../note_bars/CollectionProperties";
@@ -90,9 +92,22 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
dropTarget, setDropTarget
]);
+ /**
+ * Closed by the layout effect below rather than at the end of `refresh()`, so the span covers
+ * the commit the refresh causes and not just the state write, which Preact defers.
+ */
+ const renderSpanRef = useRef<(() => void) | null>(null);
+
+ useLayoutEffect(() => {
+ renderSpanRef.current?.();
+ renderSpanRef.current = null;
+ });
+
function refresh() {
+ const endData = perfSpan("board.getBoardData");
getBoardData(parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived, statusDefinition?.options ?? [])
.then(({ byColumn, columns, newPersistedData, isInRelationMode }) => {
+ endData();
setByColumn(byColumn);
setIsRelationMode(isInRelationMode);
setColumns(columns);
@@ -132,22 +147,13 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
setDefinitionRevision(revision => revision + 1);
}
- // Check if any changes affect our board
- const hasRelevantChanges =
- // React to changes in status attribute for notes in this board
- loadResults.getAttributeRows().some(attr => attr.name === api.statusAttribute && noteIds.includes(attr.noteId!)) ||
- // React to changes in note title
- loadResults.getNoteIds().some(noteId => noteIds.includes(noteId)) ||
- // React to changes in branches for subchildren (e.g., moved, added, or removed notes)
- loadResults.getBranchRows().some(branch => noteIds.includes(branch.noteId!)) ||
- // React to changes in note icon or color.
- loadResults.getAttributeRows().some(attr => [ "iconClass", "color" ].includes(attr.name ?? "") && noteIds.includes(attr.noteId ?? "")) ||
- // External changes to the board.json attachment arrive via the viewConfig prop
- // (see useViewModeConfig), which re-triggers the refresh effect.
- // React to changes in "groupBy"
- loadResults.getAttributeRows().some(attr => attr.name === "board:groupBy" && attr.noteId === parentNote.noteId);
-
- if (hasRelevantChanges) {
+ const endMatch = perfSpan("board.matchRefreshReason");
+ const reason = findRefreshReason(loadResults, api.statusAttribute, noteIds, parentNote.noteId);
+ endMatch();
+
+ if (reason) {
+ perfLog("board.refresh", { reason, changedNotes: loadResults.getNoteIds().length, cards: noteIds.length });
+ renderSpanRef.current = perfSpan(`board.refreshToPaint[${reason}]`);
refresh();
}
});
@@ -217,6 +223,43 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
);
}
+/**
+ * Names the first change in `loadResults` that the board has to redraw for, or null if none does.
+ *
+ * The checks are the same ones, in the same short-circuit order, that used to be `||`-chained
+ * inline; naming the winner is what lets the profiler attribute a redraw to a cause instead of
+ * reporting only that one happened.
+ */
+function findRefreshReason(loadResults: LoadResults, statusAttribute: string, noteIds: string[], parentNoteId: string): string | null {
+ // A card moved between columns.
+ if (loadResults.getAttributeRows().some(attr => attr.name === statusAttribute && noteIds.includes(attr.noteId ?? ""))) {
+ return "status-attribute";
+ }
+
+ // Intended as "a card's title changed", but getNoteIds() reports every note in the change set,
+ // so a plain content save of a card lands here too.
+ if (loadResults.getNoteIds().some(noteId => noteIds.includes(noteId))) {
+ return "note-row";
+ }
+
+ // Subchildren moved, added or removed.
+ if (loadResults.getBranchRows().some(branch => noteIds.includes(branch.noteId ?? ""))) {
+ return "branch";
+ }
+
+ if (loadResults.getAttributeRows().some(attr => [ "iconClass", "color" ].includes(attr.name ?? "") && noteIds.includes(attr.noteId ?? ""))) {
+ return "icon-or-color";
+ }
+
+ // External changes to the board.json attachment arrive via the viewConfig prop
+ // (see useViewModeConfig), which re-triggers the refresh effect.
+ if (loadResults.getAttributeRows().some(attr => attr.name === "board:groupBy" && attr.noteId === parentNoteId)) {
+ return "group-by";
+ }
+
+ return null;
+}
+
function AddNewColumn({ api, isInRelationMode }: { api: BoardApi, isInRelationMode: boolean }) {
const [ isCreatingNewColumn, setIsCreatingNewColumn ] = useState(false);