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
feat(search): lazy result-details endpoint for search notes
perfectra1n9d74c41fecdb
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 8b4c15b022..56cc35ac52 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -242,6 +242,11 @@ export interface HighlightedTokenInfo {type: "plain" | "regex";}+/** Request body for `POST /api/search-note/:noteId/result-details` (max 100 noteIds). */+export interface SearchResultDetailsRequest {+ noteIds: string[];+}+/*** Per-note snippet + highlight details for one search result, built lazily for a* page of results. Snippet fields are absent when there is nothing to show (e.g.@@ -260,6 +265,14 @@ export interface SearchResultDetails {icon: string;}+/** Response for `POST /api/search-note/:noteId/result-details`. */+export interface SearchResultDetailsResponse {+ /** Requested-order details; requested ids not in the result set are omitted. */+ results: SearchResultDetails[];+ highlightedTokenInfos: HighlightedTokenInfo[];+ error: string | null;+}+export interface SimilarNote {score: number;notePath: string[];diff --git a/packages/trilium-core/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.tsindex 7711a53aab..072e46ba00 100644--- a/packages/trilium-core/src/routes/api/search.spec.ts+++ b/packages/trilium-core/src/routes/api/search.spec.ts@@ -1,3 +1,4 @@+import type { SearchResultDetailsResponse } from "@triliumnext/commons";import { beforeAll, describe, expect, it } from "vitest";import { createTextNote } from "../../test/api_fixtures";@@ -6,6 +7,13 @@ import { CoreApiTester } from "../../test/api_tester";let api: CoreApiTester;const UNIQUE_TOKEN = "ZzUniqueSearchTokenQwerty";+async function createSearchNote(searchString: string): Promise<string> {+ const created = await api.post<{ noteId: string }>("/api/special-notes/search-note", {+ body: { searchString }+ });+ return created.body.noteId;+}+describe("Search API (core)", () => {let createdNoteId: string;@@ -98,4 +106,111 @@ describe("Search API (core)", () => {const res = await api.post("/api/search-and-execute-note/root");expect(res.status).toBe(400);});++ describe("result-details endpoint", () => {+ it("returns snippet details in requested order with highlightedTokenInfos", async () => {+ const token = "ZzDetailsUniqueQwerty";+ const alpha = await createTextNote(api, {+ title: `${token} Alpha`,+ content: `<p>${token} shows up in the alpha body text</p>`+ });+ const beta = await createTextNote(api, {+ title: `${token} Beta`,+ content: `<p>${token} shows up in the beta body text</p>`+ });+ await api.post(`/api/notes/${alpha.noteId}/attributes`, {+ body: { type: "label", name: token, value: "" }+ });++ const searchNoteId = await createSearchNote(token);++ // Request in the reverse of natural order to prove requested-order preservation.+ const res = await api.post<SearchResultDetailsResponse>(+ `/api/search-note/${searchNoteId}/result-details`,+ { body: { noteIds: [beta.noteId, alpha.noteId] } }+ );++ expect(res.status).toBe(200);+ expect(res.body.results.map((r) => r.noteId)).toEqual([beta.noteId, alpha.noteId]);+ expect(res.body.error).toBeNull();++ const alphaDetail = res.body.results.find((r) => r.noteId === alpha.noteId);+ expect(alphaDetail?.noteTitle).toContain(token);+ expect(alphaDetail?.notePath).toContain(alpha.noteId);+ expect(alphaDetail?.icon).toBeTruthy();+ expect(alphaDetail?.contentSnippet).toContain(token);+ expect(alphaDetail?.highlightedContentSnippet).toContain(`<b>${token}</b>`);+ expect(alphaDetail?.attributeSnippet).toContain(token);++ expect(+ res.body.highlightedTokenInfos.some(+ (t) => t.token.toLowerCase() === token.toLowerCase() && t.type === "plain"+ )+ ).toBe(true);+ });++ it("omits requested ids that are not in the result set", async () => {+ const token = "ZzOmitUniqueQwerty";+ const inScope = await createTextNote(api, { title: `${token} note`, content: `<p>${token}</p>` });+ const outOfScope = await createTextNote(api, { title: "Unrelated note", content: "<p>nothing here</p>" });++ const searchNoteId = await createSearchNote(token);++ const res = await api.post<SearchResultDetailsResponse>(+ `/api/search-note/${searchNoteId}/result-details`,+ { body: { noteIds: [inScope.noteId, outOfScope.noteId, "nonexistentNoteId"] } }+ );++ expect(res.status).toBe(200);+ expect(res.body.results.map((r) => r.noteId)).toEqual([inScope.noteId]);+ });++ it("400s on a note that is not a search note", async () => {+ const res = await api.post("/api/search-note/root/result-details", { body: { noteIds: [] } });+ expect(res.status).toBe(400);+ });++ it("400s when more than 100 noteIds are requested", async () => {+ const searchNoteId = await createSearchNote("anything");+ const noteIds = Array.from({ length: 101 }, (_, i) => `note${i}`);++ const res = await api.post(`/api/search-note/${searchNoteId}/result-details`, {+ body: { noteIds }+ });+ expect(res.status).toBe(400);+ });++ it("400s when noteIds is not a string array", async () => {+ const searchNoteId = await createSearchNote("anything");++ const res = await api.post(`/api/search-note/${searchNoteId}/result-details`, {+ body: { noteIds: "not-an-array" }+ });+ expect(res.status).toBe(400);+ });++ it("produces a regex token info and a match-centered snippet for a %= query", async () => {+ const marker = "ZzRegexHaystackQwerty";+ const target = await createTextNote(api, {+ title: "Regex target",+ content: `<p>${"padding words ".repeat(30)}${marker}${" trailing words".repeat(30)}</p>`+ });++ const searchNoteId = await createSearchNote(`note.content %= '${marker}'`);++ const res = await api.post<SearchResultDetailsResponse>(+ `/api/search-note/${searchNoteId}/result-details`,+ { body: { noteIds: [target.noteId] } }+ );++ expect(res.status).toBe(200);+ expect(res.body.highlightedTokenInfos.some((t) => t.type === "regex")).toBe(true);++ const detail = res.body.results.find((r) => r.noteId === target.noteId);+ expect(detail?.contentSnippet).toContain(marker);+ expect(detail?.highlightedContentSnippet).toContain(`<b>${marker}</b>`);+ // Match-centered: the padding-heavy head is trimmed to an ellipsis, not shown from index 0.+ expect(detail?.contentSnippet?.startsWith("padding words padding")).toBe(false);+ });+ });});diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.tsindex fbe6ad491f..302203a8cb 100644--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@ -1,6 +1,8 @@+import type { SearchResultDetails, SearchResultDetailsRequest, SearchResultDetailsResponse } from "@triliumnext/commons";import type { Request } from "express";import becca from "../../becca/becca.js";+import becca_service from "../../becca/becca_service.js";import attributeFormatter from "../../services/attribute_formatter.js";import bulkActionService from "../../services/bulk_actions.js";import hoistedNoteService from "../../services/hoisted_note.js";@@ -44,6 +46,61 @@ function searchAndExecute(req: Request<{ noteId: string }>) {bulkActionService.executeActionsFromNote(note, searchResultNoteIds);}+/**+ * Lazily builds snippet + highlight details for a page of a saved search's results.+ * The client fetches these per visible page rather than for the whole result set.+ *+ * Stateless by design: the search is re-run per request. A future optimization+ * could cache the result set in an LRU keyed by (search noteId + searchString),+ * but that is intentionally not built here.+ */+function getSearchResultDetails(req: Request<{ noteId: string }>): SearchResultDetailsResponse {+ const note = becca.getNoteOrThrow(req.params.noteId);++ if (note.type !== "search") {+ throw new ValidationError(`Note '${req.params.noteId}' is not a search note.`);+ }++ const { noteIds } = (req.body ?? {}) as Partial<SearchResultDetailsRequest>;+ if (!Array.isArray(noteIds) || noteIds.some((noteId) => typeof noteId !== "string")) {+ throw new ValidationError("Request body must contain a 'noteIds' string array.");+ }+ if (noteIds.length > 100) {+ throw new ValidationError("A maximum of 100 noteIds can be requested at once.");+ }++ const { searchResults, searchContext } = searchService.searchFromNoteWithContext(note);++ // Restrict to actual result notes so the endpoint can't be used as a snippet+ // oracle for arbitrary notes; preserve the caller's requested order.+ const resultByNoteId = new Map(searchResults.map((sr) => [sr.noteId, sr]));+ const requestedResults = noteIds+ .map((noteId) => resultByNoteId.get(noteId))+ .filter((sr): sr is SearchResult => sr !== undefined);++ // Script-based searches have no lexed query: return titles/icons, no snippets/tokens.+ if (!searchContext) {+ const results: SearchResultDetails[] = requestedResults.map((sr) => {+ const { title, icon } = becca_service.getNoteTitleAndIcon(sr.noteId);+ return {+ noteId: sr.noteId,+ notePath: sr.notePath,+ noteTitle: title,+ notePathTitle: sr.notePathTitle,+ icon: icon ?? "bx bx-note"+ };+ });++ return { results, highlightedTokenInfos: [], error: null };+ }++ return {+ results: searchService.buildSearchResultDetails(requestedResults, searchContext),+ highlightedTokenInfos: searchContext.getHighlightedTokenInfos(),+ error: searchContext.getError()+ };+}+function quickSearch(req: Request<{ searchString: string }>) {const { searchString } = req.params;@@ -132,6 +189,7 @@ function searchTemplates() {export default {searchFromNote,+ getSearchResultDetails,searchAndExecute,getRelatedNotes,quickSearch,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 9edf775393..1a700964dd 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -159,6 +159,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutapiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);apiRoute(GET, "/api/search-note/:noteId", searchRoute.searchFromNote);+ apiRoute(PST, "/api/search-note/:noteId/result-details", searchRoute.getSearchResultDetails);apiRoute(PST, "/api/search-and-execute-note/:noteId", searchRoute.searchAndExecute);apiRoute(PST, "/api/search-related", searchRoute.getRelatedNotes);apiRoute(GET, "/api/search/:searchString", searchRoute.search);