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
import { dayjs, type NoteMimeCount, type SearchResultDetailsResponse, type SearchWithTokensResponse, type TemplatesResponse } from "@triliumnext/commons";
import { beforeAll, describe, expect, it } from "vitest";
import becca from "../../becca/becca.js";
import { createTextNote } from "../../test/api_fixtures";
import { CoreApiTester } from "../../test/api_tester";
import { isNewTemplate } from "./search";
let api: CoreApiTester;
const UNIQUE_TOKEN = "ZzUniqueSearchTokenQwerty";
const SLASH_TOKEN = "ZzUniqueSearch/TokenQwerty";
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;
}
/** Runs a quick search as a client hoisted into `hoistedNoteId`, or unhoisted when it is omitted. */
function quickSearch(searchString: string, hoistedNoteId?: string) {
return api.get<{ searchResultNoteIds: string[] }>("/api/quick-search", {
query: { searchString },
headers: hoistedNoteId ? { "trilium-hoisted-note-id": hoistedNoteId } : undefined
});
}
describe("Search API (core)", () => {
let createdNoteId: string;
let slashNoteId: string;
beforeAll(async () => {
api = CoreApiTester.build();
({ noteId: createdNoteId } = await createTextNote(api, { title: UNIQUE_TOKEN }));
({ noteId: slashNoteId } = await createTextNote(api, { title: SLASH_TOKEN }));
});
it("returns matching note ids for a full search", async () => {
const res = await api.get<string[]>("/api/search", {
query: { searchString: UNIQUE_TOKEN }
});
expect(res.status).toBe(200);
expect(Array.isArray(res.body)).toBe(true);
expect(res.body).toContain(createdNoteId);
});
it("describes a full search on one line for the request log", async () => {
const token = "ZzLoggedSearchQwerty";
await createTextNote(api, { title: `${token} one` });
await createTextNote(api, { title: `${token} two` });
const res = await api.get("/api/search", {
query: { searchString: ` note.title *=*\n ${token} ` }
});
expect(res.locals?.logSummary).toBe(`Search: note.title *=* ${token} (returned 2 items)`);
});
it("restricts a full search to the given ancestor's subtree", async () => {
const token = "ZzScopedSearchQwerty";
const board = await createTextNote(api, { title: "Board" });
const inside = await createTextNote(api, { parentNoteId: board.noteId, title: `${token} inside` });
const outside = await createTextNote(api, { title: `${token} outside` });
const scoped = await api.get<string[]>("/api/search", {
query: { searchString: token, ancestorNoteId: board.noteId }
});
expect(scoped.status).toBe(200);
expect(scoped.body).toContain(inside.noteId);
expect(scoped.body).not.toContain(outside.noteId);
const unscoped = await api.get<string[]>("/api/search", { query: { searchString: token } });
expect(unscoped.body).toContain(inside.noteId);
expect(unscoped.body).toContain(outside.noteId);
});
it("leaves archived notes out of a full search only when asked to", async () => {
const token = "ZzArchivedSearchQwerty";
const board = await createTextNote(api, { title: "Board" });
const live = await createTextNote(api, { parentNoteId: board.noteId, title: `${token} live` });
const archived = await createTextNote(api, { parentNoteId: board.noteId, title: `${token} archived` });
await api.post(`/api/notes/${archived.noteId}/attributes`, {
body: { type: "label", name: "archived", value: "" }
});
const search = (includeArchivedNotes?: string) => api.get<string[]>("/api/search", {
query: { searchString: token, ancestorNoteId: board.noteId, includeArchivedNotes }
});
expect((await search()).body).toEqual(expect.arrayContaining([ live.noteId, archived.noteId ]));
expect((await search("true")).body).toEqual(expect.arrayContaining([ live.noteId, archived.noteId ]));
const withoutArchived = await search("false");
expect(withoutArchived.body).toContain(live.noteId);
expect(withoutArchived.body).not.toContain(archived.noteId);
});
it("returns note ids with token infos and the error when includeTokens is set", async () => {
const withTokens = await api.get<SearchWithTokensResponse>("/api/search", {
query: { searchString: UNIQUE_TOKEN, includeTokens: "true" }
});
expect(withTokens.status).toBe(200);
expect(withTokens.body.searchResultNoteIds).toContain(createdNoteId);
expect(withTokens.body.highlightedTokens).toContainEqual({
token: UNIQUE_TOKEN.toLowerCase(),
type: "plain"
});
expect(withTokens.body.error).toBeNull();
// A query the parser rejects still answers 200, with the parse error in the body for the
// client to show inline.
const broken = await api.get<SearchWithTokensResponse>(
"/api/search",
{ query: { searchString: "#label = ", includeTokens: "true" } }
);
expect(broken.status).toBe(200);
expect(broken.body.error).toBeTruthy();
});
it("accepts slash-bearing full-search queries", async () => {
const res = await api.get<string[]>("/api/search", {
query: { searchString: SLASH_TOKEN }
});
expect(res.status).toBe(200);
expect(res.body).toContain(slashNoteId);
});
it("returns structured quick-search results with snippets", async () => {
const res = await api.get<{ searchResultNoteIds: string[]; searchResults: unknown[]; highlightedTokens: string[] }>(
"/api/quick-search",
{ query: { searchString: UNIQUE_TOKEN } }
);
expect(res.status).toBe(200);
expect(res.body.searchResultNoteIds).toContain(createdNoteId);
expect(Array.isArray(res.body.searchResults)).toBe(true);
// highlightedTokens lets clients (quick-search dropdown, jump-to-match) know which
// tokens the server highlighted, without re-deriving them from the raw query string.
expect(res.body.highlightedTokens).toContain(UNIQUE_TOKEN.toLowerCase());
});
it("excludes regex (`%=`) tokens from quick-search highlightedTokens", async () => {
// The client seeds these into the find bar as literal jump-to-match terms; a raw regex
// pattern would match nothing there (silent no-op), so the server must drop regex tokens.
const pattern = "ZzRegexQwerty";
const res = await api.get<{ highlightedTokens: string[]; error: string | null }>(
"/api/quick-search",
{ query: { searchString: `note.content %= '${pattern}'` } }
);
expect(res.status).toBe(200);
expect(res.body.error).toBeFalsy();
expect(res.body.highlightedTokens).not.toContain(pattern);
});
it("confines a quick search to the hoisted subtree, hidden subtree included", async () => {
const token = "ZzHoistedQuickSearchQwerty";
const workspace = await createTextNote(api, { title: "Workspace" });
const inside = await createTextNote(api, { parentNoteId: workspace.noteId, title: `${token} inside` });
const outside = await createTextNote(api, { title: `${token} outside` });
const hidden = await createTextNote(api, { parentNoteId: "_lbBookmarks", title: `${token} hidden` });
const inWorkspace = await quickSearch(token, workspace.noteId);
expect(inWorkspace.status).toBe(200);
expect(inWorkspace.body.searchResultNoteIds).toContain(inside.noteId);
expect(inWorkspace.body.searchResultNoteIds).not.toContain(outside.noteId);
// A hoist into the hidden subtree scopes the search to that subtree like any other hoist,
// so browsing the in-app help does not surface the user's own notes.
const inHidden = await quickSearch(token, "_lbBookmarks");
expect(inHidden.status).toBe(200);
expect(inHidden.body.searchResultNoteIds).toContain(hidden.noteId);
expect(inHidden.body.searchResultNoteIds).not.toContain(outside.noteId);
});
it("omits hidden notes from an unhoisted quick search", async () => {
const token = "ZzUnhoistedQuickSearchQwerty";
const visible = await createTextNote(api, { title: `${token} visible` });
const hidden = await createTextNote(api, { parentNoteId: "_lbBookmarks", title: `${token} hidden` });
const res = await quickSearch(token);
expect(res.status).toBe(200);
expect(res.body.searchResultNoteIds).toContain(visible.noteId);
expect(res.body.searchResultNoteIds).not.toContain(hidden.noteId);
});
it("accepts slash-bearing quick-search queries", async () => {
const res = await api.get<{ searchResultNoteIds: string[] }>("/api/quick-search", {
query: { searchString: SLASH_TOKEN }
});
expect(res.status).toBe(200);
expect(res.body.searchResultNoteIds).toContain(slashNoteId);
});
it("rejects missing and empty search query parameters", async () => {
for (const path of [ "/api/search", "/api/quick-search" ]) {
expect((await api.get(path)).status).toBe(400);
expect((await api.get(path, { query: { searchString: "" } })).status).toBe(400);
}
});
it("takes the search string only from the query", async () => {
expect((await api.get(`/api/search/${UNIQUE_TOKEN}`)).status).toBe(404);
expect((await api.get(`/api/quick-search/${UNIQUE_TOKEN}`)).status).toBe(404);
});
it("lists template note ids including a freshly-labelled template", async () => {
const { noteId } = await createTextNote(api, { title: "A template note" });
await api.post(`/api/notes/${noteId}/attributes`, {
body: { type: "label", name: "template", value: "" }
});
const res = await api.get<TemplatesResponse>("/api/search-templates");
expect(res.status).toBe(200);
expect(res.body.templateNoteIds).toContain(noteId);
expect(Array.isArray(res.body.newTemplateNoteIds)).toBe(true);
});
it("400s when searching from a note that is not a search note", async () => {
const res = await api.get("/api/search-note/root");
expect(res.status).toBe(400);
});
it("returns related notes for an attribute query", async () => {
const res = await api.post<{ count: number; results: unknown[] }>("/api/search-related", {
body: { type: "label", name: "docName", value: "hidden" }
});
expect(res.status).toBe(200);
expect(typeof res.body.count).toBe("number");
expect(Array.isArray(res.body.results)).toBe(true);
});
it("caps related-note results at 20 even with many matches", async () => {
// Create more than 20 notes carrying the same label so the result loop
// hits its >= 20 break.
for (let i = 0; i < 22; i++) {
const { noteId } = await createTextNote(api, { title: `Related ${i}` });
await api.post(`/api/notes/${noteId}/attributes`, {
body: { type: "label", name: "relTestLabel", value: "relTestValue" }
});
}
const res = await api.post<{ count: number; results: unknown[] }>("/api/search-related", {
body: { type: "label", name: "relTestLabel", value: "relTestValue" }
});
expect(res.status).toBe(200);
expect(res.body.count).toBeGreaterThanOrEqual(22);
expect(res.body.results).toHaveLength(20);
});
it("runs a saved search note and executes bulk actions over it", async () => {
const created = await api.post<{ noteId: string; type: string }>(
"/api/special-notes/search-note",
{ body: { searchString: UNIQUE_TOKEN } }
);
expect(created.body.type).toBe("search");
const searchNoteId = created.body.noteId;
const fromNote = await api.get<{ searchResultNoteIds: string[] }>(
`/api/search-note/${searchNoteId}`
);
expect(fromNote.status).toBe(200);
expect(fromNote.body.searchResultNoteIds).toContain(createdNoteId);
// searchAndExecute returns no body (204) — the note has no action labels,
// so executing over the results is a safe no-op.
const exec = await api.post(`/api/search-and-execute-note/${searchNoteId}`);
expect(exec.status).toBe(204);
});
it("400s when executing a note that is not a search note", async () => {
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);
});
});
it("counts the MIME types of the user's notes, the most used first", async () => {
const createCodeNote = (parentNoteId: string, mime: string) =>
api.post(`/api/notes/${parentNoteId}/children?target=into`, {
body: { title: "MIME", type: "code", mime, content: "" }
});
await createCodeNote("root", "text/x-zz-once");
await createCodeNote("root", "text/x-zz-twice");
await createCodeNote("root", "text/x-zz-twice");
// `_share` lies in the hidden subtree, but what the user puts there is still theirs.
expect((await createCodeNote("_share", "text/x-zz-shared")).status).toBe(200);
const res = await api.get<NoteMimeCount[]>("/api/search/note-mimes");
expect(res.status).toBe(200);
const mimes = res.body.map(({ mime }) => mime);
expect(res.body.find(({ mime }) => mime === "text/x-zz-twice")?.count).toBe(2);
expect(res.body.find(({ mime }) => mime === "text/x-zz-once")?.count).toBe(1);
expect(mimes.indexOf("text/x-zz-twice")).toBeLessThan(mimes.indexOf("text/x-zz-once"));
expect(mimes).toContain("text/x-zz-shared");
expect(mimes).not.toContain("");
// System notes carry MIME types too, but only the user's notes are counted.
const notes = Object.values(becca.notes);
expect(notes.some(({ noteId, mime }) => noteId.startsWith("_") && mime)).toBe(true);
for (const { mime, count } of res.body) {
expect(count).toBe(notes.filter((note) => !note.noteId.startsWith("_") && note.mime === mime).length);
}
});
});
describe("isNewTemplate", () => {
const ROOT_CREATED = "2026-01-01 00:00:00.000Z";
const utc = (date: dayjs.Dayjs) => date.format("YYYY-MM-DD HH:mm:ss.SSS[Z]");
it("marks recent templates as new and leaves older ones alone", () => {
expect(isNewTemplate(utc(dayjs.utc().subtract(1, "day")), ROOT_CREATED)).toBe(true);
expect(isNewTemplate(utc(dayjs.utc().subtract(4, "day")), ROOT_CREATED)).toBe(false);
expect(isNewTemplate(null, ROOT_CREATED)).toBe(false);
});
it("never marks the predefined templates set up alongside the root note", () => {
const root = dayjs.utc().subtract(1, "hour");
// Created together with the database: within the grace period, so not new
// despite being only an hour old.
expect(isNewTemplate(utc(root.add(10, "second")), utc(root))).toBe(false);
// Added later on, e.g. by an upgrade.
expect(isNewTemplate(utc(root.add(1, "minute")), utc(root))).toBe(true);
});
it("falls back to the age check when the root creation date is unknown", () => {
expect(isNewTemplate(utc(dayjs.utc()), null)).toBe(true);
expect(isNewTemplate(utc(dayjs.utc().subtract(4, "day")), undefined)).toBe(false);
});
});