Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): guard deferred seeded find and paginated note loads against navigation races

perfectra1n8d6168b1ef61
diff --git a/apps/client/src/services/search_jump.spec.ts b/apps/client/src/services/search_jump.spec.ts
index a64ceb5c02..c3c8cc2c79 100644
--- a/apps/client/src/services/search_jump.spec.ts
+++ b/apps/client/src/services/search_jump.spec.ts
@@ -71,6 +71,19 @@ describe("consumeSearchTerms", () => {
expect(triggerCommand).not.toHaveBeenCalled();
});
+ it("aborts the deferred trigger when the context navigates before the frame fires", () => {
+ const ctx = makeContext([ "foo" ]);
+
+ consumeSearchTerms(ctx, "ntx1");
+ // Navigation replaces the context's viewScope object (note_context.setNote /
+ // resetViewScope) before the animation frame fires; the stale seeded find must not
+ // open the find bar on whatever note the tab shows now.
+ ctx.viewScope = {};
+ flushRaf();
+
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
it("is idempotent: a second call after consumption does nothing", () => {
const ctx = makeContext([ "foo" ]);
diff --git a/apps/client/src/services/search_jump.ts b/apps/client/src/services/search_jump.ts
index c1446c028b..f44f7eb72b 100644
--- a/apps/client/src/services/search_jump.ts
+++ b/apps/client/src/services/search_jump.ts
@@ -24,5 +24,14 @@ export function consumeSearchTerms(noteContext: NoteContext | undefined | null,
}
viewScope.searchTerms = undefined;
- requestAnimationFrame(() => appContext.triggerCommand("findInText", { ntxId, searchTerms }));
+ requestAnimationFrame(() => {
+ // Navigation replaces the context's viewScope object (note_context.setNote /
+ // resetViewScope), so an identity change here means the tab moved on before the frame
+ // fired — the seeded find would target the wrong note. A fresh navigation from search
+ // results carries its own searchTerms and runs its own consumption, so aborting is safe.
+ if (noteContext.viewScope !== viewScope) {
+ return;
+ }
+ appContext.triggerCommand("findInText", { ntxId, searchTerms });
+ });
}
diff --git a/apps/client/src/widgets/collections/Pagination.spec.tsx b/apps/client/src/widgets/collections/Pagination.spec.tsx
index 5260fddbcf..8b0b9efdf2 100644
--- a/apps/client/src/widgets/collections/Pagination.spec.tsx
+++ b/apps/client/src/widgets/collections/Pagination.spec.tsx
@@ -5,22 +5,23 @@
*/
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import Component from "../../components/component";
import type FNote from "../../entities/fnote";
+import froca from "../../services/froca";
import { buildNote, buildNotes } from "../../test/easy-froca";
import { ParentComponent } from "../react/react_utils";
import { usePagination } from "./Pagination";
-let observed: { pageSize: number; pageCount: number; page: number } | undefined;
+let observed: { pageSize: number; pageCount: number; page: number; pageNotes?: FNote[]; setPage?: (page: number) => void } | undefined;
// 25 real froca notes so usePagination's froca.getNotes() slice never round-trips to the server.
const NOTE_IDS = buildNotes(Array.from({ length: 25 }, (_, i) => ({ id: `pag-${i}`, title: `N${i}` })));
-function Harness({ note, defaultPageSize }: { note: FNote; defaultPageSize?: number }) {
- const { page, pageSize, pageCount } = usePagination(note, NOTE_IDS, defaultPageSize);
- observed = { pageSize, pageCount, page };
+function Harness({ note, noteIds = NOTE_IDS, defaultPageSize }: { note: FNote; noteIds?: string[]; defaultPageSize?: number }) {
+ const { page, setPage, pageNotes, pageSize, pageCount } = usePagination(note, noteIds, defaultPageSize);
+ observed = { pageSize, pageCount, page, pageNotes, setPage };
return null;
}
@@ -74,4 +75,35 @@ describe("usePagination default page size", () => {
await mount(note, Number.NaN);
expect(observed?.pageSize).toBe(20);
});
+
+ it("discards a stale note load that resolves after a newer page's load", async () => {
+ // Take over froca.getNotes with manually-resolved deferreds so resolution order can be
+ // inverted: rapid page flips issue overlapping loads, and the older one must not win.
+ const pending: Array<{ ids: string[]; resolve: (notes: FNote[]) => void }> = [];
+ const getNotesSpy = vi.spyOn(froca, "getNotes").mockImplementation((ids) =>
+ new Promise((resolve) => pending.push({ ids: ids as string[], resolve }))
+ );
+ try {
+ const note = buildNote({ title: "Search", type: "search" });
+ await mount(note, 10);
+
+ // Initial load for page 1, then flip to page 2 and quickly on to page 3.
+ expect(pending.length).toBe(1);
+ await act(async () => observed?.setPage?.(2));
+ await act(async () => observed?.setPage?.(3));
+ expect(pending.length).toBe(3);
+
+ const [ , page2Load, page3Load ] = pending;
+ const toNotes = (ids: string[]) => ids.map((id) => froca.notes[id]).filter((n): n is FNote => Boolean(n));
+
+ // Newest (page 3) resolves first, then the stale page-2 load arrives late.
+ await act(async () => page3Load.resolve(toNotes(page3Load.ids)));
+ await act(async () => page2Load.resolve(toNotes(page2Load.ids)));
+
+ expect(observed?.page).toBe(3);
+ expect(observed?.pageNotes?.map((n) => n.noteId)).toEqual(page3Load.ids);
+ } finally {
+ getNotesSpy.mockRestore();
+ }
+ });
});
diff --git a/apps/client/src/widgets/collections/Pagination.tsx b/apps/client/src/widgets/collections/Pagination.tsx
index 76075668e6..72079111ff 100644
--- a/apps/client/src/widgets/collections/Pagination.tsx
+++ b/apps/client/src/widgets/collections/Pagination.tsx
@@ -152,7 +152,23 @@ export function usePagination(note: FNote, noteIds: string[], defaultPageSize =
const pageNoteIds = noteIds.slice(startIdx, Math.min(endIdx, noteIds.length));
useEffect(() => {
- froca.getNotes(pageNoteIds).then(setPageNotes);
+ // While the clamp effect above is stepping an out-of-range page back onto the last valid
+ // one, the slice is empty; loading it would only flash the list blank for a frame.
+ if (pageCount > 0 && page > pageCount) {
+ return;
+ }
+
+ // Overlapping loads (rapid page flips, a shrinking result set) can resolve out of order;
+ // the cleanup flag makes sure a superseded load can no longer overwrite the current page.
+ let cancelled = false;
+ froca.getNotes(pageNoteIds).then((notes) => {
+ if (!cancelled) {
+ setPageNotes(notes);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
}, [ note, noteIds, page, normalizedPageSize ]);
return {