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(core): virtual note providers; make in-app help a virtual subtree
Claude5a993fe85d72
diff --git a/apps/server/src/services/hidden_subtree.spec.ts b/apps/server/src/services/hidden_subtree.spec.tsindex 736a60dd06..aef73ec7cd 100644--- a/apps/server/src/services/hidden_subtree.spec.ts+++ b/apps/server/src/services/hidden_subtree.spec.ts@@ -1,5 +1,5 @@import { deferred, LOCALES } from "@triliumnext/commons";-import { becca, becca_loader, binary_utils, cls, hidden_subtree as hiddenSubtreeService, i18n, note_service as notes, TaskContext } from "@triliumnext/core";+import { becca, becca_loader, binary_utils, cls, getSql, hidden_subtree as hiddenSubtreeService, i18n, note_service as notes, TaskContext } from "@triliumnext/core";import protectedSessionService from "@triliumnext/core/src/services/protected_session.js";import { beforeAll, describe, expect, it } from "vitest";@@ -32,38 +32,36 @@ describe("Hidden Subtree", () => {expect(childBranches![0].parentNoteId).toStrictEqual("_lbVisibleLaunchers");});- it("should enforce the correct placement of help", () => {- // First, verify the help note exists in its original correct location- const originalBranch = becca.getBranchFromChildAndParent("_help_Vc8PjrjAGuOp", "_help_gh7bpGYxajRS");- expect(originalBranch).toBeDefined();- expect(originalBranch?.parentNoteId).toBe("_help_gh7bpGYxajRS");-- // Move the help note to an incorrect location (_help root instead of its proper parent)- cls.init(() => {- branches.moveBranchToNote(originalBranch!, "_help");- });-- // Verify the note was moved to the wrong location- const movedBranches = becca.notes["_help_Vc8PjrjAGuOp"]?.getParentBranches()- .filter((b) => !b.isDeleted);- expect(movedBranches).toBeDefined();- expect(movedBranches![0].parentNoteId).toBe("_help");+ it("provides the help subtree as virtual notes, with no persisted rows left behind", () => {+ // The help subtree is injected into becca from the bundled meta as virtual notes;+ // the fixture DB carried persisted _help rows (dbVersion 239) which migration 240+ // must have removed, entity_changes included.+ const helpRoot = becca.getNoteOrThrow("_help");+ expect(helpRoot.isVirtual).toBe(true);+ expect(helpRoot.getParentNotes().map((n) => n.noteId)).toEqual(["_hidden"]);+ expect(helpRoot.getChildNotes().length).toBeGreaterThan(0);++ const page = becca.getNoteOrThrow("_help_Vc8PjrjAGuOp");+ expect(page.isVirtual).toBe(true);++ const sql = getSql();+ expect(sql.getValue(/*sql*/`SELECT COUNT(*) FROM notes WHERE noteId LIKE '\\_help%' ESCAPE '\\'`)).toBe(0);+ expect(sql.getValue(/*sql*/`SELECT COUNT(*) FROM branches WHERE noteId LIKE '\\_help%' ESCAPE '\\' OR parentNoteId LIKE '\\_help%' ESCAPE '\\'`)).toBe(0);+ expect(sql.getValue(/*sql*/`SELECT COUNT(*) FROM attributes WHERE noteId LIKE '\\_help%' ESCAPE '\\'`)).toBe(0);+ expect(sql.getValue(/*sql*/`SELECT COUNT(*) FROM entity_changes WHERE entityId LIKE '\\_help%' ESCAPE '\\'`)).toBe(0);+ });- // Run the hidden subtree integrity check- cls.init(() => {- hiddenSubtreeService.checkHiddenSubtree(true);- });+ it("rejects moving a help note", () => {+ const originalBranch = becca.getBranchFromChildAndParent("_help_Vc8PjrjAGuOp", "_help_gh7bpGYxajRS");+ expect(originalBranch?.isVirtual).toBe(true);- // Verify that the integrity check moved the help note back to its correct location- const correctedBranches = becca.notes["_help_Vc8PjrjAGuOp"]?.getParentBranches()- .filter((b) => !b.isDeleted);- expect(correctedBranches).toBeDefined();- expect(correctedBranches![0].parentNoteId).toBe("_help_gh7bpGYxajRS");+ // validateParentChild rejects the move before anything is touched+ const result = originalBranch && cls.init(() => branches.moveBranchToNote(originalBranch, "_help"));+ expect(Array.isArray(result) ? result[1] : result).toMatchObject({ success: false });- // Ensure the note is no longer under the incorrect parent- const helpRootChildren = becca.notes["_help"]?.getChildNotes();- const incorrectChild = helpRootChildren?.find(note => note.noteId === "_help_Vc8PjrjAGuOp");- expect(incorrectChild).toBeUndefined();+ // structure is unchanged+ const parents = becca.getNoteOrThrow("_help_Vc8PjrjAGuOp").getParentNotes().map((n) => n.noteId);+ expect(parents).toEqual(["_help_gh7bpGYxajRS"]);});it("enforces renames of launcher notes", () => {@@ -96,19 +94,15 @@ describe("Hidden Subtree", () => {expect(updatedBoardTemplate?.title).not.toBe("My renamed board");});- it("enforces webviewSrc of templates", () => {- const apiRefNote = becca.getNote("_help_9qPsTWBorUhQ");- expect(apiRefNote).toBeDefined();+ it("rejects attribute changes on virtual help notes", () => {+ const apiRefNote = becca.getNoteOrThrow("_help_9qPsTWBorUhQ");+ expect(apiRefNote.isVirtual).toBe(true);- cls.init(() => {- apiRefNote!.setAttribute("label", "webViewSrc", "foo");- apiRefNote!.save();- hiddenSubtreeService.checkHiddenSubtree(true);- });+ expect(() => cls.init(() => apiRefNote.setAttribute("label", "webViewSrc", "foo"))).toThrow(/virtual/);- const updatedApiRefNote = becca.getNote("_help_9qPsTWBorUhQ");- expect(updatedApiRefNote).toBeDefined();- expect(updatedApiRefNote?.getLabelValue("webViewSrc")).not.toBe("foo");+ // nothing was persisted; reload to shed the in-memory leftover of the failed save+ cls.init(() => becca_loader.reload("test"));+ expect(becca.getNoteOrThrow("_help_9qPsTWBorUhQ").getLabelValue("webViewSrc")).not.toBe("foo");});it("maintains launchers hidden, if they were shown by default but moved by the user", () => {diff --git a/packages/trilium-core/src/becca/becca_loader.ts b/packages/trilium-core/src/becca/becca_loader.tsindex 1c9d113dbb..374c34f922 100644--- a/packages/trilium-core/src/becca/becca_loader.ts+++ b/packages/trilium-core/src/becca/becca_loader.ts@@ -14,6 +14,7 @@ import BNote from "./entities/bnote.js";import BOption from "./entities/boption.js";import { getSql } from "../services/sql";import { getContext } from "../services/context.js";+import { getVirtualNoteProviders, type VirtualNoteProvider, type VirtualSubtreeItem } from "../services/virtual_notes.js";export const beccaLoaded = new Promise<void>(async (res, rej) => {// We have to import async since options init requires keyboard actions which require translations.@@ -64,6 +65,8 @@ function load() {});+ injectVirtualSubtrees();+for (const noteId in becca.notes) {becca.notes[noteId].sortParents();}@@ -73,6 +76,156 @@ function load() {getLog().info(`Becca (note cache) load took ${Date.now() - start}ms`);}+/**+ * Builds the becca entities of every registered virtual note provider (see+ * `services/virtual_notes.ts`). Runs on every load, after the persisted entities: virtual+ * entities live only in becca, so a full reload (e.g. `becca_loader.reload()`) both refreshes+ * them and is the way to pick up provider-side changes.+ */+function injectVirtualSubtrees() {+ const log = getLog();+ let injectedAny = false;++ for (const provider of getVirtualNoteProviders()) {+ if (!(provider.parentNoteId in becca.notes)) {+ // E.g. the first load during initial database creation, which happens before the+ // hidden subtree exists; the post-dbReady load will inject.+ log.info(`Virtual note provider '${provider.namespace}': anchor note '${provider.parentNoteId}' not present, skipping injection.`);+ continue;+ }++ try {+ const subtree = provider.getSubtree();+ validateVirtualSubtree(provider, subtree);++ // Sort the injected roots after the anchor's persisted children so their+ // notePositions don't collide.+ const basePosition = becca.notes[provider.parentNoteId]+ .getChildBranches()+ .reduce((max, childBranch) => Math.max(max, childBranch?.notePosition ?? 0), 0);++ subtree.forEach((item, index) => injectVirtualItem(provider, provider.parentNoteId, item, basePosition + (index + 1) * 10));+ injectedAny = true;+ } catch (e) {+ // A broken provider must never take down the becca load.+ log.error(`Virtual note provider '${provider.namespace}' failed, skipping: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`);+ }+ }++ if (injectedAny) {+ backfillVirtualTargetRelations();+ }+}++function validateVirtualSubtree(provider: VirtualNoteProvider, items: VirtualSubtreeItem[], seenIds = new Set<string>()) {+ for (const item of items) {+ if (!item.id.startsWith(provider.namespace)) {+ throw new Error(`Item '${item.id}' is outside the provider's namespace '${provider.namespace}'.`);+ }++ if (seenIds.has(item.id)) {+ throw new Error(`Duplicate item ID '${item.id}'.`);+ }++ seenIds.add(item.id);+ validateVirtualSubtree(provider, item.children ?? [], seenIds);+ }+}++function injectVirtualItem(provider: VirtualNoteProvider, parentNoteId: string, item: VirtualSubtreeItem, defaultPosition: number) {+ let note = becca.notes[item.id];++ if (note && !note.isVirtual && note.type !== undefined) {+ // A persisted note still occupies this ID (e.g. rows predating the migration that+ // removed the persisted variant of this subtree). Persisted data wins to avoid+ // corrupting it; the conflict is surfaced instead of silently overridden.+ getLog().error(`Virtual note provider '${provider.namespace}': a persisted note '${item.id}' already exists, skipping injection of this item and its children.`);+ return;+ }++ const noteRow: Partial<NoteRow> = {+ noteId: item.id,+ title: item.title,+ type: item.type,+ mime: item.mime ?? "",+ isProtected: false+ };++ if (note) {+ // Skeleton created by a forward reference (e.g. a persisted branch or relation loaded+ // before this virtual note existed) — fill it in place so those links survive.+ note.updateFromRow(noteRow);+ } else {+ note = new BNote(noteRow);+ }++ note.isVirtual = true;++ const branchId = `${parentNoteId}_${item.id}`;++ if (!becca.branches[branchId]) {+ const branch = new BBranch({+ branchId,+ noteId: item.id,+ parentNoteId,+ prefix: null,+ notePosition: item.notePosition ?? defaultPosition,+ isExpanded: !!item.isExpanded+ });+ branch.isVirtual = true;+ }++ const attributeDefs = [...(item.attributes ?? [])];++ if (item.icon) {+ attributeDefs.push({ type: "label", name: "iconClass", value: `bx ${item.icon}` });+ }++ attributeDefs.forEach((def, index) => {+ // Deterministic ID, unique thanks to the note-ID prefix; the index suffix disambiguates+ // multiple same-named attributes on one note.+ let attributeId = `v_${item.id}_${def.type.charAt(0)}${def.name}`;+ if (becca.attributes[attributeId]) {+ attributeId = `${attributeId}_${index}`;+ }++ const attribute = new BAttribute({+ attributeId,+ noteId: item.id,+ type: def.type,+ name: def.name,+ value: def.value ?? "",+ isInheritable: !!def.isInheritable,+ position: (index + 1) * 10+ });+ attribute.isVirtual = true;+ });++ (item.children ?? []).forEach((child, index) => injectVirtualItem(provider, item.id, child, (index + 1) * 10));+}++/**+ * Relations pointing into a virtual namespace load before the virtual notes exist, so their+ * target-relation backlinks could not be established in `BAttribute.init()` — including+ * relations between virtual notes when the target comes later in the subtree. One pass after+ * injection fixes both.+ */+function backfillVirtualTargetRelations() {+ for (const attributeId in becca.attributes) {+ const attribute = becca.attributes[attributeId];++ if (attribute.type !== "relation" || !attribute.value) {+ continue;+ }++ const targetNote = becca.notes[attribute.value];++ if (targetNote?.isVirtual && !targetNote.targetRelations.includes(attribute)) {+ targetNote.targetRelations.push(attribute);+ }+ }+}+function reload(reason: string) {load();diff --git a/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts b/packages/trilium-core/src/becca/entities/abstract_becca_entity.tsindex da336a81dd..5852f3fa07 100644--- a/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts+++ b/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts@@ -33,6 +33,23 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {isSynced?: boolean;blobId?: string;+ /**+ * Virtual entities exist only in becca — they are injected by a virtual note provider+ * (see `services/virtual_notes.ts`), never persisted to the database and never synced.+ * They are read-only: {@link save}, {@link markAsDeleted} and content updates throw.+ */+ isVirtual?: boolean;++ /** @throws Error when this entity is virtual — virtual entities must never touch the database. */+ protected ensureNotVirtual(action: string) {+ if (!this.isVirtual) {+ return;+ }++ const constructorData = this.constructor as unknown as ConstructorData<T>;+ throw new Error(`Cannot ${action} ${constructorData.entityName} '${(this as any)[constructorData.primaryKeyName]}': it is a virtual entity (provided by a virtual note provider) and is read-only.`);+ }+protected beforeSaving(opts?: {}) {const constructorData = this.constructor as unknown as ConstructorData<T>;if (!(this as any)[constructorData.primaryKeyName]) {@@ -103,6 +120,8 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {* Saves entity - executes SQL, but doesn't commit the transaction on its own*/save(opts?: {}): this {+ this.ensureNotVirtual("save");+const constructorData = this.constructor as unknown as ConstructorData<T>;const entityName = constructorData.entityName;const primaryKeyName = constructorData.primaryKeyName;@@ -141,6 +160,8 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}protected _setContent(content: string | Uint8Array, opts: ContentOpts = {}) {+ this.ensureNotVirtual("set content of");+// client code asks to save entity even if blobId didn't change (something else was changed)opts.forceSave = !!opts.forceSave;opts.forceFrontendReload = !!opts.forceFrontendReload;@@ -293,6 +314,8 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {* This is a low-level method, for notes and branches use `note.deleteNote()` and 'branch.deleteBranch()` instead.*/markAsDeleted(deleteId: string | null = null) {+ this.ensureNotVirtual("delete");+const constructorData = this.constructor as unknown as ConstructorData<T>;const entityId = (this as any)[constructorData.primaryKeyName];const entityName = constructorData.entityName;@@ -320,6 +343,8 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}markAsDeletedSimple() {+ this.ensureNotVirtual("delete");+const constructorData = this.constructor as unknown as ConstructorData<T>;const entityId = (this as any)[constructorData.primaryKeyName];const entityName = constructorData.entityName;diff --git a/packages/trilium-core/src/becca/entities/battribute.ts b/packages/trilium-core/src/becca/entities/battribute.tsindex ee90b0e48a..161e54c4a8 100644--- a/packages/trilium-core/src/becca/entities/battribute.ts+++ b/packages/trilium-core/src/becca/entities/battribute.ts@@ -184,6 +184,13 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}override beforeSaving(opts: SavingOpts = {}) {+ // Virtual notes (e.g. the in-app help) are not user-customizable, so no persisted+ // attribute may be attached to them. (Relations *pointing to* virtual notes from+ // regular notes are fine — this guards the owning note only.)+ if (this.becca.notes[this.noteId]?.isVirtual) {+ throw new Error(`Cannot save attribute '${this.name}' for note '${this.noteId}': attributes of virtual notes cannot be modified.`);+ }+if (!opts.skipValidation) {this.validate();}diff --git a/packages/trilium-core/src/becca/entities/bbranch.ts b/packages/trilium-core/src/becca/entities/bbranch.tsindex 1468e04599..16a1c19e74 100644--- a/packages/trilium-core/src/becca/entities/bbranch.ts+++ b/packages/trilium-core/src/becca/entities/bbranch.ts@@ -210,6 +210,16 @@ class BBranch extends AbstractBeccaEntity<BBranch> {throw new Error(`noteId and parentNoteId are mandatory properties for Branch`);}+ // Virtual notes (e.g. the in-app help) cannot be cloned or moved: a persisted branch+ // referencing a virtual note would dangle on other sync instances and after upgrades.+ if (this.becca.notes[this.noteId]?.isVirtual) {+ throw new Error(`Cannot save branch for note '${this.noteId}': virtual notes cannot be cloned or moved.`);+ }++ if (this.becca.notes[this.parentNoteId]?.isVirtual) {+ throw new Error(`Cannot place note '${this.noteId}' under '${this.parentNoteId}': virtual notes cannot receive children.`);+ }+this.branchId = `${this.parentNoteId}_${this.noteId}`;if (this.notePosition === undefined || this.notePosition === null) {diff --git a/packages/trilium-core/src/becca/entities/bnote.ts b/packages/trilium-core/src/becca/entities/bnote.tsindex d0c1b77065..2b05c64a95 100644--- a/packages/trilium-core/src/becca/entities/bnote.ts+++ b/packages/trilium-core/src/becca/entities/bnote.ts@@ -20,6 +20,7 @@ import BRevision from "./brevision.js";import { getLog } from "../../services/log.js";import { getSql } from "../../services/sql/index.js";import { formatDownloadTitle, isStringNote, normalize, randomString, replaceAll } from "../../services/utils/index.js";+import { getVirtualNoteContent } from "../../services/virtual_notes.js";const LABEL = "label";const RELATION = "relation";@@ -206,6 +207,11 @@ class BNote extends AbstractBeccaEntity<BNote> {* - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)*/getContent() {+ if (this.isVirtual) {+ // Virtual notes have no blob row; content (if any) comes from their provider.+ return getVirtualNoteContent(this.noteId);+ }+return this._getContent();}diff --git a/packages/trilium-core/src/becca/virtual_notes_injection.spec.ts b/packages/trilium-core/src/becca/virtual_notes_injection.spec.tsnew file mode 100644index 0000000000..20d75b599d--- /dev/null+++ b/packages/trilium-core/src/becca/virtual_notes_injection.spec.ts@@ -0,0 +1,208 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { getContext } from "../services/context.js";+import noteService from "../services/notes.js";+import { getSql } from "../services/sql/index.js";+import { registerVirtualNoteProvider, unregisterVirtualNoteProvider, type VirtualSubtreeItem } from "../services/virtual_notes.js";+import becca from "./becca.js";+import { load } from "./becca_loader.js";+import BAttribute from "./entities/battribute.js";+import BBranch from "./entities/bbranch.js";++const SUBTREE: VirtualSubtreeItem[] = [+ {+ id: "_vtest",+ title: "Virtual root",+ type: "book",+ icon: "bx-cube",+ isExpanded: true,+ children: [+ {+ id: "_vtestPage",+ title: "Virtual page",+ type: "text",+ attributes: [{ type: "label", name: "docName", value: "vtest_page" }]+ },+ {+ id: "_vtestLinked",+ title: "Linked page",+ type: "text",+ // relation to a sibling that is injected *after* this note — exercises the+ // backfill of forward references within a virtual subtree+ attributes: [{ type: "relation", name: "seeAlso", value: "_vtestLast" }]+ },+ { id: "_vtestLast", title: "Last page", type: "text" }+ ]+ }+];++function reloadBecca() {+ getContext().init(() => load());+}++function countRows(table: string, column: string): number {+ return getSql().getValue<number>(`SELECT COUNT(*) FROM ${table} WHERE ${column} LIKE '\\_vtest%' ESCAPE '\\'`);+}++describe("virtual note injection", () => {+ beforeAll(() => {+ registerVirtualNoteProvider({+ namespace: "_vtest",+ parentNoteId: "_hidden",+ getSubtree: () => SUBTREE,+ getContent: (noteId) => (noteId === "_vtestPage" ? "<p>virtual content</p>" : null)+ });+ reloadBecca();+ });++ afterAll(() => {+ unregisterVirtualNoteProvider("_vtest");+ reloadBecca();+ });++ it("builds the subtree in becca with virtual notes, branches and attributes", () => {+ const root = becca.getNoteOrThrow("_vtest");+ expect(root.isVirtual).toBe(true);+ expect(root.title).toBe("Virtual root");+ expect(root.type).toBe("book");+ expect(root.getParentNotes().map((note) => note.noteId)).toEqual(["_hidden"]);+ expect(root.getChildNotes().map((note) => note.noteId)).toEqual(["_vtestPage", "_vtestLinked", "_vtestLast"]);++ // deterministic branch IDs, registered in all becca maps+ const rootBranch = becca.getBranch("_hidden__vtest");+ expect(rootBranch?.isVirtual).toBe(true);+ expect(rootBranch?.isExpanded).toBe(true);+ expect(becca.getBranchFromChildAndParent("_vtestPage", "_vtest")?.isVirtual).toBe(true);++ // the root sorts after the anchor's persisted children+ const siblingPositions = becca.getNoteOrThrow("_hidden")+ .getChildBranches()+ .filter((branch) => branch && branch.noteId !== "_vtest")+ .map((branch) => branch?.notePosition ?? 0);+ expect(rootBranch?.notePosition).toBeGreaterThan(Math.max(...siblingPositions));++ // attributes: explicit ones and the icon-derived label+ const page = becca.getNoteOrThrow("_vtestPage");+ expect(page.getLabelValue("docName")).toBe("vtest_page");+ expect(becca.getNoteOrThrow("_vtest").getLabelValue("iconClass")).toBe("bx bx-cube");+ expect(page.getOwnedAttributes().every((attribute) => attribute.isVirtual)).toBe(true);+ });++ it("persists nothing to the database", () => {+ expect(countRows("notes", "noteId")).toBe(0);+ expect(countRows("branches", "noteId")).toBe(0);+ expect(countRows("attributes", "noteId")).toBe(0);+ expect(getSql().getValue<number>(`SELECT COUNT(*) FROM entity_changes WHERE entityId LIKE '\\_vtest%' ESCAPE '\\'`)).toBe(0);+ });++ it("virtual entities are read-only", () => {+ const note = becca.getNoteOrThrow("_vtestPage");+ expect(() => getContext().init(() => note.save())).toThrow(/read-only/);+ expect(() => getContext().init(() => note.setContent("<p>nope</p>"))).toThrow(/read-only/);+ expect(() => getContext().init(() => note.markAsDeleted())).toThrow(/read-only/);++ const branch = becca.getBranch("_hidden__vtest");+ expect(branch).toBeTruthy();+ expect(() => getContext().init(() => branch?.markAsDeleted())).toThrow(/read-only/);++ const attribute = note.getOwnedAttributes()[0];+ expect(() => getContext().init(() => attribute.save())).toThrow(/read-only/);+ });++ it("rejects persisting branches or attributes that reference virtual notes", () => {+ const realNote = getContext().init(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: "real note for virtual tests",+ content: "",+ type: "text"+ }).note+ );++ // cloning a virtual note out into the persisted tree+ expect(() => getContext().init(() =>+ new BBranch({ noteId: "_vtestPage", parentNoteId: realNote.noteId, isExpanded: false }).save()+ )).toThrow(/cloned or moved/);++ // placing a persisted note under a virtual parent+ expect(() => getContext().init(() =>+ new BBranch({ noteId: realNote.noteId, parentNoteId: "_vtest", isExpanded: false }).save()+ )).toThrow(/receive children/);++ // annotating a virtual note+ expect(() => getContext().init(() =>+ new BAttribute({ noteId: "_vtest", type: "label", name: "myLabel", value: "x" }).save()+ )).toThrow(/virtual/);+ });++ it("serves content from the provider, defaulting to empty", () => {+ expect(becca.getNoteOrThrow("_vtestPage").getContent()).toBe("<p>virtual content</p>");+ expect(becca.getNoteOrThrow("_vtest").getContent()).toBe("");+ });++ it("resolves relations targeting virtual notes across reloads (backfill)", () => {+ const realNote = getContext().init(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: "note linking into virtual subtree",+ content: "",+ type: "text"+ }).note+ );+ getContext().init(() =>+ new BAttribute({ noteId: realNote.noteId, type: "relation", name: "linksTo", value: "_vtestLinked" }).save()+ );++ // On reload the persisted relation loads before the virtual notes exist; the+ // injection backfill must re-establish the target-relation backlink.+ reloadBecca();++ const target = becca.getNoteOrThrow("_vtestLinked");+ expect(target.isVirtual).toBe(true);+ expect(target.targetRelations.some((rel) => rel.name === "linksTo" && rel.noteId === realNote.noteId)).toBe(true);++ // ...including forward references between virtual notes themselves+ const last = becca.getNoteOrThrow("_vtestLast");+ expect(last.targetRelations.some((rel) => rel.name === "seeAlso" && rel.noteId === "_vtestLinked")).toBe(true);+ });++ it("skips providers whose anchor note does not exist, without creating skeletons", () => {+ registerVirtualNoteProvider({+ namespace: "_vghost",+ parentNoteId: "_doesNotExist",+ getSubtree: () => [{ id: "_vghost", title: "Ghost", type: "text" }]+ });++ try {+ reloadBecca();+ expect(becca.getNote("_vghost")).toBeNull();+ expect(becca.getNote("_doesNotExist")).toBeNull();+ } finally {+ unregisterVirtualNoteProvider("_vghost");+ }+ });++ it("skips a provider whose subtree strays outside its namespace, leaving others intact", () => {+ registerVirtualNoteProvider({+ namespace: "_vbad",+ parentNoteId: "_hidden",+ getSubtree: () => [{+ id: "_vbad",+ title: "Bad",+ type: "text",+ children: [{ id: "_outsider", title: "Outside the namespace", type: "text" }]+ }]+ });++ try {+ reloadBecca();+ // validation runs before injection, so nothing of the bad provider materializes+ expect(becca.getNote("_vbad")).toBeNull();+ expect(becca.getNote("_outsider")).toBeNull();+ // and the healthy provider is unaffected+ expect(becca.getNote("_vtest")?.isVirtual).toBe(true);+ } finally {+ unregisterVirtualNoteProvider("_vbad");+ }+ });+});diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 91459f4938..cd2eeaac1e 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -107,6 +107,16 @@ export { default as sync_mutex } from "./services/sync_mutex";export { default as setup } from "./services/setup";export { getPlatform, type PlatformProvider } from "./services/platform";export { InAppHelpProvider } from "./services/in_app_help";+export {+ getVirtualNoteContent,+ getVirtualNoteProvider,+ getVirtualNoteProviders,+ registerVirtualNoteProvider,+ unregisterVirtualNoteProvider,+ type VirtualNoteProvider,+ type VirtualSubtreeAttribute,+ type VirtualSubtreeItem+} from "./services/virtual_notes";export { type ImageProvider, type ImageFormat, type ProcessedImage, getImageProvider } from "./services/image_provider";export { type CoreConfig, initConfig, getConfig } from "./services/config";export { default as imageService } from "./services/image";@@ -168,6 +178,11 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,initZipProvider(zip);initZipExportProviderFactory(zipExportProviderFactory);initContext(executionContext);+ if (inAppHelp) {+ // Must precede initSql: it registers the _help virtual note provider, and initSql can+ // resolve dbReady, which triggers the becca load that injects virtual subtrees.+ initInAppHelp(inAppHelp);+ }await initSql(new SqlService(dbConfig, getLog()));initSchema(schema);initImageProvider(image);@@ -181,7 +196,4 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,if (request) {initRequest(request);}- if (inAppHelp) {- initInAppHelp(inAppHelp);- }};diff --git a/packages/trilium-core/src/migrations/migrations.ts b/packages/trilium-core/src/migrations/migrations.tsindex 7faf7a9a41..811aa4e196 100644--- a/packages/trilium-core/src/migrations/migrations.ts+++ b/packages/trilium-core/src/migrations/migrations.ts@@ -9,6 +9,35 @@ export function getMaxMigrationVersion() {// Migrations should be kept in descending order, so the latest migration is first.export const MIGRATIONS: (SqlMigration | JsMigration)[] = [+ // The in-app help (`_help` subtree) became virtual — injected into becca from the bundled+ // help meta on every load, never persisted or synced (see services/virtual_notes.ts).+ // Remove the previously persisted rows, including their entity_changes so the deletions+ // don't churn through sync: every instance in a cluster runs this same migration (the+ // accompanying sync-version bump guarantees no un-migrated peers), so all copies converge.+ // User clones of help notes and user attributes on them are dropped by design — the help+ // structure is application-owned. Orphaned blobs are vacuumed by the regular erase job.+ // The rows for indirectly-keyed entities must be removed from entity_changes before their+ // base rows disappear from under the subselects.+ {+ version: 240,+ sql: /*sql*/`+ DELETE FROM entity_changes WHERE entityName = 'branches' AND entityId IN+ (SELECT branchId FROM branches WHERE noteId LIKE '\\_help%' ESCAPE '\\' OR parentNoteId LIKE '\\_help%' ESCAPE '\\');+ DELETE FROM entity_changes WHERE entityName = 'attributes' AND entityId IN+ (SELECT attributeId FROM attributes WHERE noteId LIKE '\\_help%' ESCAPE '\\');+ DELETE FROM entity_changes WHERE entityName = 'revisions' AND entityId IN+ (SELECT revisionId FROM revisions WHERE noteId LIKE '\\_help%' ESCAPE '\\');+ DELETE FROM entity_changes WHERE entityName = 'attachments' AND entityId IN+ (SELECT attachmentId FROM attachments WHERE ownerId LIKE '\\_help%' ESCAPE '\\');+ DELETE FROM entity_changes WHERE entityName = 'notes' AND entityId LIKE '\\_help%' ESCAPE '\\';+ DELETE FROM entity_changes WHERE entityName = 'note_reordering' AND entityId LIKE '\\_help%' ESCAPE '\\';+ DELETE FROM branches WHERE noteId LIKE '\\_help%' ESCAPE '\\' OR parentNoteId LIKE '\\_help%' ESCAPE '\\';+ DELETE FROM attributes WHERE noteId LIKE '\\_help%' ESCAPE '\\';+ DELETE FROM revisions WHERE noteId LIKE '\\_help%' ESCAPE '\\';+ DELETE FROM attachments WHERE ownerId LIKE '\\_help%' ESCAPE '\\';+ DELETE FROM notes WHERE noteId LIKE '\\_help%' ESCAPE '\\';+ `+ },// Turn TOTP back off for installs that had disabled MFA before the enable flag was removed{version: 239,diff --git a/packages/trilium-core/src/services/app_info.ts b/packages/trilium-core/src/services/app_info.tsindex 70d5251f19..86cfb4ae10 100644--- a/packages/trilium-core/src/services/app_info.ts+++ b/packages/trilium-core/src/services/app_info.ts@@ -3,7 +3,9 @@ import packageJson from "../../package.json" with { type: "json" };import { AppInfo } from "@triliumnext/commons";import { getMaxMigrationVersion } from "../migrations/migrations.js";-const SYNC_VERSION = 39;+// 40: in-app help notes became virtual (never persisted/synced); un-migrated peers would+// still push _help entity changes, so they must upgrade before syncing.+const SYNC_VERSION = 40;const CLIPPER_PROTOCOL_VERSION = "1.0";const appInfo: AppInfo = {diff --git a/packages/trilium-core/src/services/hidden_subtree.ts b/packages/trilium-core/src/services/hidden_subtree.tsindex de67b7886e..c964780bb9 100644--- a/packages/trilium-core/src/services/hidden_subtree.ts+++ b/packages/trilium-core/src/services/hidden_subtree.ts@@ -7,7 +7,6 @@ import BBranch from "../becca/entities/bbranch.js";import BNote from "../becca/entities/bnote.js";import buildLaunchBarConfig from "./hidden_subtree_launcherbar.js";import buildHiddenSubtreeTemplates from "./hidden_subtree_templates.js";-import { cleanUpHelp, getHelpHiddenSubtreeData } from "./in_app_help.js";import migrationService from "./migration.js";import noteService from "./notes.js";import { getLog } from "./log.js";@@ -32,7 +31,7 @@ export const LBTPL_CUSTOM_WIDGET = "_lbTplCustomWidget";let hiddenSubtreeDefinition: HiddenSubtreeItem;-function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenSubtreeItem {+function buildHiddenSubtreeDefinition(): HiddenSubtreeItem {const launchbarConfig = buildLaunchBarConfig();return {@@ -316,14 +315,9 @@ function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenS{ id: "_optionsAdvanced", title: t("hidden-subtree.advanced-title"), type: "contentWidget" }]},- {- id: "_help",- title: t("hidden-subtree.user-guide"),- type: "book",- icon: "bx-help-circle",- children: helpSubtree,- isExpanded: true- },+ // The in-app help (`_help`) is deliberately absent here: it is a virtual subtree+ // injected into becca by the provider registered in `services/in_app_help.ts`,+ // never persisted or synced.buildHiddenSubtreeTemplates()]};@@ -340,9 +334,8 @@ function checkHiddenSubtree(force = false, extraOpts: CheckHiddenExtraOpts = {})return;}- const helpSubtree = getHelpHiddenSubtreeData();if (!hiddenSubtreeDefinition || force) {- hiddenSubtreeDefinition = buildHiddenSubtreeDefinition(helpSubtree);+ hiddenSubtreeDefinition = buildHiddenSubtreeDefinition();}getSql().transactional(() => {@@ -355,13 +348,6 @@ function checkHiddenSubtree(force = false, extraOpts: CheckHiddenExtraOpts = {})if (!taskStatesExisted) {seedDefaultTaskStates();}-- try {- cleanUpHelp(helpSubtree);- } catch (e) {- // Non-critical operation should something go wrong.- console.error(e);- }});}@@ -457,7 +443,7 @@ function checkHiddenSubtreeRecursively(parentNoteId: string, item: HiddenSubtree}}- if (item.enforceBranches || item.id.startsWith("_help")) {+ if (item.enforceBranches) {// Clean up any branches that shouldn't exist according to the meta definition// For hidden subtree notes, we want to ensure they only exist in their designated locations@@ -517,7 +503,7 @@ function checkHiddenSubtreeRecursively(parentNoteId: string, item: HiddenSubtree}}- const shouldRestoreNames = extraOpts.restoreNames || note.noteId.startsWith("_help") || item.id.startsWith("_lb") || item.id.startsWith("_template");+ const shouldRestoreNames = extraOpts.restoreNames || item.id.startsWith("_lb") || item.id.startsWith("_template");if (shouldRestoreNames && note.title !== item.title) {note.title = item.title;note.save();@@ -587,7 +573,7 @@ function checkHiddenSubtreeRecursively(parentNoteId: string, item: HiddenSubtreevalue: attr.value,isInheritable: attr.isInheritable}).save();- } else if (attr.name === "docName" || (existingAttribute.noteId.startsWith("_help") && attr.name === "iconClass")) {+ } else if (attr.name === "docName") {if (existingAttribute.value !== attr.value) {log.info(`Updating attribute ${attrId} from "${existingAttribute.value}" to "${attr.value}"`);existingAttribute.value = attr.value ?? "";diff --git a/packages/trilium-core/src/services/i18n.ts b/packages/trilium-core/src/services/i18n.tsindex 2673728ea5..735b2c4e4e 100644--- a/packages/trilium-core/src/services/i18n.ts+++ b/packages/trilium-core/src/services/i18n.ts@@ -35,6 +35,11 @@ function getCurrentLanguage(): LOCALE_IDS {export async function changeLanguage(locale: string) {await i18next.changeLanguage(locale);hidden_subtree.checkHiddenSubtree(true, { restoreNames: true });++ // Virtual subtrees (e.g. the in-app help) build their titles with t() at injection time,+ // so a becca reload is needed to re-render them in the new language.+ const { reload } = await import("../becca/becca_loader.js");+ reload("locale changed");}/**diff --git a/packages/trilium-core/src/services/in_app_help.spec.ts b/packages/trilium-core/src/services/in_app_help.spec.tsindex 0cc6f51f92..d6430dc9ec 100644--- a/packages/trilium-core/src/services/in_app_help.spec.ts+++ b/packages/trilium-core/src/services/in_app_help.spec.ts@@ -1,117 +1,67 @@-import { beforeAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { HiddenSubtreeItem } from "@triliumnext/commons";import becca from "../becca/becca.js";+import { load } from "../becca/becca_loader.js";import { getContext } from "./context.js";-import {- cleanUpHelp,- getHelpHiddenSubtreeData,- InAppHelpProvider,- initInAppHelp-} from "./in_app_help.js";+import { getHelpHiddenSubtreeData, InAppHelpProvider, initInAppHelp } from "./in_app_help.js";+import { getVirtualNoteProvider } from "./virtual_notes.js";-/** Minimal concrete provider so the abstract `cleanUpHelp` logic can be exercised. */+/** Minimal concrete provider standing in for the platform-specific implementations. */class TestHelpProvider extends InAppHelpProvider {-constructor(private data: HiddenSubtreeItem[]) {super();}+getHelpHiddenSubtreeData(): HiddenSubtreeItem[] {return this.data;}-}-const noteService = (await import("./notes.js")).default;--/** Creates a note with a forced id under the given parent within the help subtree. */-function createHelpNote(noteId: string, parentNoteId: string) {- return getContext().init(- () =>- noteService.createNewNote({- noteId,- parentNoteId,- title: noteId,- content: "help content",- type: "text",- // The help subtree (`_help*`) is a forbidden parent by default.- ignoreForbiddenParents: true- }).note- );+function reloadBecca() {+ getContext().init(() => load());}-describe("in_app_help - module accessors", () => {+describe("in_app_help", () => {it("delegates getHelpHiddenSubtreeData to the registered provider", () => {// The server suite registers a real provider during initializeCore;// override it with a deterministic stub for this isolated fork.- const data: HiddenSubtreeItem[] = [- { id: "_helpFoo", title: "Foo", type: "text" }- ];+ const data: HiddenSubtreeItem[] = [{ id: "_helpFoo", title: "Foo", type: "text" }];initInAppHelp(new TestHelpProvider(data));expect(getHelpHiddenSubtreeData()).toBe(data);});-});--describe("in_app_help - cleanUpHelp", () => {- beforeAll(() => {- // `_help` already exists in the fixture (empty). Build a subtree under it:- // _help- // ├── _helpKeep- // │ └── _helpKeepChild- // └── _helpStale- createHelpNote("_helpKeep", "_help");- createHelpNote("_helpKeepChild", "_helpKeep");- createHelpNote("_helpStale", "_help");- });- it("deletes notes absent from the definition and preserves the rest", () => {- // Definition keeps _helpKeep (and its child) but omits _helpStale.- const definition: HiddenSubtreeItem[] = [+ it("injects the help subtree as virtual notes under _hidden", () => {+ const data: HiddenSubtreeItem[] = [{- id: "_help",- title: "Help",- type: "text",- children: [- {- id: "_helpKeep",- title: "Keep",- type: "text",- children: [- {- id: "_helpKeepChild",- title: "Keep child",- type: "text"- }- ]- }- ]+ id: "_helpStub",+ title: "Stub page",+ type: "doc",+ icon: "bx-file",+ attributes: [{ type: "label", name: "docName", value: "stub" }]}];+ initInAppHelp(new TestHelpProvider(data));+ reloadBecca();- getContext().init(() => cleanUpHelp(definition));+ const helpRoot = becca.getNoteOrThrow("_help");+ expect(helpRoot.isVirtual).toBe(true);+ expect(helpRoot.type).toBe("book");+ expect(helpRoot.getParentNotes().map((note) => note.noteId)).toEqual(["_hidden"]);- // The stale note is gone; the kept notes (incl. nested child and root) survive.- expect(becca.getNote("_helpStale")?.isDeleted ?? true).toBe(true);- expect(becca.getNote("_helpKeep")?.isDeleted).toBe(false);- expect(becca.getNote("_helpKeepChild")?.isDeleted).toBe(false);- expect(becca.getNote("_help")?.isDeleted).toBe(false);+ const stub = becca.getNoteOrThrow("_helpStub");+ expect(stub.isVirtual).toBe(true);+ expect(stub.getParentNotes().map((note) => note.noteId)).toEqual(["_help"]);+ expect(stub.getLabelValue("docName")).toBe("stub");+ expect(stub.getLabelValue("iconClass")).toBe("bx bx-file");});- it("is a no-op when the _help subtree does not exist", () => {- // Remove the whole _help subtree, so becca.getNote("_help") is null and- // the recursive flattener hits its empty-note short-circuit.- getContext().init(() => becca.getNote("_help")?.deleteNote());- expect(becca.getNote("_help")).toBeNull();-- expect(() => getContext().init(() => cleanUpHelp([]))).not.toThrow();- });-});--describe("in_app_help - no provider registered", () => {- // Runs last: it clears the provider for the rest of this isolated fork.- it("falls back to defaults when no provider is registered", () => {+ it("unregisters the help provider when none is supplied", () => {initInAppHelp(undefined as unknown as InAppHelpProvider);expect(getHelpHiddenSubtreeData()).toEqual([]);- expect(() => cleanUpHelp([])).not.toThrow();+ expect(getVirtualNoteProvider("_help")).toBeNull();++ reloadBecca();+ expect(becca.getNote("_help")).toBeNull();});});diff --git a/packages/trilium-core/src/services/in_app_help.ts b/packages/trilium-core/src/services/in_app_help.tsindex 76201f02dd..0f66ec0f3f 100644--- a/packages/trilium-core/src/services/in_app_help.ts+++ b/packages/trilium-core/src/services/in_app_help.ts@@ -1,73 +1,55 @@import type { HiddenSubtreeItem } from "@triliumnext/commons";--import becca from "../becca/becca.js";-import type BNote from "../becca/entities/bnote.js";-+import { t } from "i18next";++import { registerVirtualNoteProvider, unregisterVirtualNoteProvider, type VirtualSubtreeItem } from "./virtual_notes.js";++/**+ * Platform-specific source of the in-app help (User Guide) tree definition — the server reads+ * it from `RESOURCE_DIR/doc_notes`, the standalone build from a bundled JSON asset.+ *+ * The help notes themselves are **virtual notes**: they exist only in becca, injected under+ * `_hidden` by the `_help` virtual note provider registered in {@link initInAppHelp}. They are+ * never persisted or synced — their structure is owned by the application, not the user — and+ * their HTML content is fetched by the client directly from the bundled assets (see the+ * client's `doc_renderer`), so the provider supplies no content.+ */export abstract class InAppHelpProvider {abstract getHelpHiddenSubtreeData(): HiddenSubtreeItem[];-- /**- * Iterates recursively through the help subtree that the user has and compares it against the definition- * to remove any notes that are no longer present in the latest version of the help.- */- cleanUpHelp(helpDefinition: HiddenSubtreeItem[]): void {- function getFlatIds(items: HiddenSubtreeItem | HiddenSubtreeItem[]) {- const ids: (string | string[])[] = [];- if (Array.isArray(items)) {- for (const item of items) {- ids.push(getFlatIds(item));- }- } else {- if (items.children) {- for (const child of items.children) {- ids.push(getFlatIds(child));- }- }- ids.push(items.id);- }- return ids.flat();- }-- function getFlatIdsFromNote(note: BNote | null) {- if (!note) {- return [];- }-- const ids: (string | string[])[] = [];-- for (const subnote of note.getChildNotes()) {- ids.push(getFlatIdsFromNote(subnote));- }-- ids.push(note.noteId);- return ids.flat();- }-- const definitionHelpIds = new Set(getFlatIds(helpDefinition));- const realHelpIds = getFlatIdsFromNote(becca.getNote("_help"));-- for (const realHelpId of realHelpIds) {- if (realHelpId === "_help") {- continue;- }-- if (!definitionHelpIds.has(realHelpId)) {- becca.getNote(realHelpId)?.deleteNote();- }- }- }}let provider: InAppHelpProvider | null = null;+export const HELP_SUBTREE_NAMESPACE = "_help";+export function initInAppHelp(p: InAppHelpProvider) {provider = p;++ if (!p) {+ // defensive: callers passing nothing get no help subtree rather than an empty one+ unregisterVirtualNoteProvider(HELP_SUBTREE_NAMESPACE);+ return;+ }++ registerVirtualNoteProvider({+ namespace: HELP_SUBTREE_NAMESPACE,+ parentNoteId: "_hidden",+ getSubtree(): VirtualSubtreeItem[] {+ return [+ {+ id: HELP_SUBTREE_NAMESPACE,+ title: t("hidden-subtree.user-guide"),+ type: "book",+ icon: "bx-help-circle",+ isExpanded: true,+ // HiddenSubtreeItem is structurally a VirtualSubtreeItem (its enforce*+ // fields are simply ignored here).+ children: getHelpHiddenSubtreeData()+ }+ ];+ }+ });}export function getHelpHiddenSubtreeData(): HiddenSubtreeItem[] {return provider?.getHelpHiddenSubtreeData() ?? [];}--export function cleanUpHelp(items: HiddenSubtreeItem[]): void {- provider?.cleanUpHelp(items);-}diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.tsindex 50e52cd212..9e6ea48717 100644--- a/packages/trilium-core/src/services/tree.ts+++ b/packages/trilium-core/src/services/tree.ts@@ -23,6 +23,16 @@ function validateParentChild(parentNoteId: string, childNoteId: string, branchIdreturn { branch: null, success: false, message: `Cannot move anything into 'none' parent.` };}+ // Virtual notes (e.g. the in-app help) exist only in becca — a persisted branch+ // referencing them would dangle after upgrades and on other sync instances.+ if (becca.getNote(childNoteId)?.isVirtual) {+ return { branch: null, success: false, message: `Note '${childNoteId}' is a virtual note and cannot be cloned or moved.` };+ }++ if (becca.getNote(parentNoteId)?.isVirtual) {+ return { branch: null, success: false, message: `Note '${parentNoteId}' is a virtual note and cannot receive children.` };+ }+const existingBranch = becca.getBranchFromChildAndParent(childNoteId, parentNoteId);if (existingBranch && existingBranch.branchId !== branchId) {diff --git a/packages/trilium-core/src/services/virtual_notes.spec.ts b/packages/trilium-core/src/services/virtual_notes.spec.tsnew file mode 100644index 0000000000..28b70c8c61--- /dev/null+++ b/packages/trilium-core/src/services/virtual_notes.spec.ts@@ -0,0 +1,78 @@+import { afterEach, describe, expect, it } from "vitest";++import {+ getVirtualNoteContent,+ getVirtualNoteProvider,+ getVirtualNoteProviders,+ registerVirtualNoteProvider,+ unregisterVirtualNoteProvider,+ type VirtualNoteProvider+} from "./virtual_notes.js";++function makeProvider(namespace: string, overrides: Partial<VirtualNoteProvider> = {}): VirtualNoteProvider {+ return {+ namespace,+ parentNoteId: "_hidden",+ getSubtree: () => [],+ ...overrides+ };+}++const TEST_NAMESPACES = ["_vnreg", "_vnother"];++describe("virtual_notes registry", () => {+ afterEach(() => {+ for (const namespace of TEST_NAMESPACES) {+ unregisterVirtualNoteProvider(namespace);+ }+ });++ it("registers, looks up by note-ID prefix, and unregisters providers", () => {+ const provider = makeProvider("_vnreg");+ registerVirtualNoteProvider(provider);++ expect(getVirtualNoteProviders()).toContain(provider);+ expect(getVirtualNoteProvider("_vnregSomeNote")).toBe(provider);+ expect(getVirtualNoteProvider("_unrelated")).toBeNull();++ unregisterVirtualNoteProvider("_vnreg");+ expect(getVirtualNoteProvider("_vnregSomeNote")).toBeNull();+ });++ it("rejects namespaces not starting with an underscore", () => {+ expect(() => registerVirtualNoteProvider(makeProvider("vnreg"))).toThrow(/must start with '_'/);+ });++ it("rejects overlapping namespaces but allows re-registering the same one", () => {+ registerVirtualNoteProvider(makeProvider("_vnreg"));++ // one namespace being a prefix of another would make provider lookup ambiguous+ expect(() => registerVirtualNoteProvider(makeProvider("_vnregSub"))).toThrow(/overlaps/);+ expect(() => registerVirtualNoteProvider(makeProvider("_vn"))).toThrow(/overlaps/);++ // disjoint namespace is fine+ expect(() => registerVirtualNoteProvider(makeProvider("_vnother"))).not.toThrow();++ // same namespace replaces the previous registration (idempotent re-initialization)+ const replacement = makeProvider("_vnreg");+ registerVirtualNoteProvider(replacement);+ expect(getVirtualNoteProvider("_vnreg")).toBe(replacement);+ expect(getVirtualNoteProviders().filter((p) => p.namespace === "_vnreg")).toHaveLength(1);+ });++ it("delegates content to the provider and falls back to an empty string", () => {+ registerVirtualNoteProvider(makeProvider("_vnreg", {+ getContent: (noteId) => (noteId === "_vnregPage" ? "<p>hello</p>" : null)+ }));++ expect(getVirtualNoteContent("_vnregPage")).toBe("<p>hello</p>");+ // provider returns null → empty content+ expect(getVirtualNoteContent("_vnregOther")).toBe("");+ // no provider at all → empty content+ expect(getVirtualNoteContent("_nowhere")).toBe("");++ // provider without getContent → empty content+ registerVirtualNoteProvider(makeProvider("_vnother"));+ expect(getVirtualNoteContent("_vnotherPage")).toBe("");+ });+});diff --git a/packages/trilium-core/src/services/virtual_notes.ts b/packages/trilium-core/src/services/virtual_notes.tsnew file mode 100644index 0000000000..97bb445ce7--- /dev/null+++ b/packages/trilium-core/src/services/virtual_notes.ts@@ -0,0 +1,126 @@+import type { NoteType } from "@triliumnext/commons";++/**+ * Virtual notes are notes that exist only in becca (and, through it, in the client's froca) —+ * they are never persisted to the database and never produce entity changes, so they are+ * invisible to sync, backups and consistency checks. They are meant for content whose structure+ * is owned by the application (or an external source) rather than by the user: the in-app help,+ * and in the future e.g. computed hierarchies or read-only mounts of external data.+ *+ * A {@link VirtualNoteProvider} declares a subtree of {@link VirtualSubtreeItem}s under an+ * existing anchor note. The subtree is (re)built by `becca_loader` on every becca load, so a+ * provider can be refreshed by triggering `becca_loader.reload()`.+ *+ * Ground rules enforced by this module and the becca entities:+ *+ * - Virtual entities carry `isVirtual = true` and refuse `save()`, `setContent()` and+ * `markAsDeleted()` — they are read-only and their lifecycle is owned by the provider.+ * - Persisted (non-virtual) branches and attributes may not be attached to virtual notes, so+ * virtual notes cannot be cloned into the user's tree, moved, or annotated. Relations+ * *pointing to* virtual notes from regular notes are allowed — the target resolves in becca.+ * - Provider namespaces must start with `_` (the hidden-subtree convention), keeping virtual+ * notes out of user-facing note operations that already special-case `_`-prefixed IDs.+ */+export interface VirtualNoteProvider {+ /**+ * Unique note-ID prefix owned by this provider (e.g. `_help`). Must start with `_`.+ * Every item ID in the provided subtree must start with this namespace, which guarantees+ * providers cannot collide with each other or with user note IDs.+ */+ namespace: string;++ /**+ * ID of the (persisted) note the virtual subtree is attached under, e.g. `_hidden`.+ * If the anchor is not present in becca at load time (e.g. during initial database+ * creation, before the hidden subtree exists), injection is skipped for that load and+ * happens on the next one.+ */+ parentNoteId: string;++ /**+ * Returns the root item(s) of the virtual subtree. Called on every becca (re)load, so the+ * result may change between calls (e.g. after an application upgrade ships new help pages).+ */+ getSubtree(): VirtualSubtreeItem[];++ /**+ * Optional note content lookup, for providers whose notes carry content (e.g. file-system+ * mounts). When absent — or when it returns `null`/`undefined` — the content is `""`.+ * The in-app help does not use this: help pages are `doc` notes whose HTML the client+ * fetches directly from bundled assets.+ */+ getContent?(noteId: string): string | Uint8Array | null | undefined;+}++export interface VirtualSubtreeItem {+ /** Must start with the owning provider's namespace. */+ id: string;+ title: string;+ type: NoteType;+ /** MIME type; defaults to "". */+ mime?: string;+ /** Icon in `bx-icon-name` format (without the leading `bx `), exposed as an `iconClass` label. */+ icon?: string;+ attributes?: VirtualSubtreeAttribute[];+ children?: VirtualSubtreeItem[];+ isExpanded?: boolean;+ /** Position among siblings; defaults to definition order. */+ notePosition?: number;+}++export interface VirtualSubtreeAttribute {+ type: "label" | "relation";+ name: string;+ value?: string;+ isInheritable?: boolean;+}++const providers = new Map<string, VirtualNoteProvider>();++/**+ * Registers a provider. Re-registering the same namespace replaces the previous provider+ * (making repeated initialization idempotent). Takes effect on the next becca load, so+ * providers should be registered during application initialization, before the database+ * is ready.+ */+export function registerVirtualNoteProvider(provider: VirtualNoteProvider) {+ if (!provider.namespace.startsWith("_")) {+ throw new Error(`Virtual note provider namespace must start with '_', got '${provider.namespace}'.`);+ }++ for (const existing of providers.keys()) {+ if (existing === provider.namespace) {+ continue; // same namespace replaces the previous registration+ }++ if (existing.startsWith(provider.namespace) || provider.namespace.startsWith(existing)) {+ throw new Error(`Virtual note provider namespace '${provider.namespace}' overlaps with already registered namespace '${existing}'.`);+ }+ }++ providers.set(provider.namespace, provider);+}++export function unregisterVirtualNoteProvider(namespace: string) {+ providers.delete(namespace);+}++export function getVirtualNoteProviders(): VirtualNoteProvider[] {+ return [...providers.values()];+}++/** Returns the provider owning the given note ID, based on its namespace prefix. */+export function getVirtualNoteProvider(noteId: string): VirtualNoteProvider | null {+ for (const provider of providers.values()) {+ if (noteId.startsWith(provider.namespace)) {+ return provider;+ }+ }++ return null;+}++/** Content of a virtual note, delegated to its provider; `""` when the provider has none. */+export function getVirtualNoteContent(noteId: string): string | Uint8Array {+ return getVirtualNoteProvider(noteId)?.getContent?.(noteId) ?? "";+}