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(llm): move the LLM chat special notes into core
Elian Doran874db724b2b7
diff --git a/apps/server/src/routes/api/llm_special_notes.spec.ts b/apps/server/src/routes/api/llm_special_notes.spec.tsdeleted file mode 100644index 796f41a505..0000000000--- a/apps/server/src/routes/api/llm_special_notes.spec.ts+++ /dev/null@@ -1,41 +0,0 @@-import { cls } from "@triliumnext/core";-import type { Request } from "express";-import { describe, expect, it } from "vitest";--import llmSpecialNotesRoute from "./llm_special_notes.js";--describe("LLM special notes API", () => {- it("creates an LLM chat note", () => {- const chat = cls.init(() => llmSpecialNotesRoute.createLlmChat());- expect(chat.noteId).toBeTruthy();- });-- it("gets or creates, then returns it as the most recent chat", () => {- const created = cls.init(() => llmSpecialNotesRoute.getOrCreateLlmChat());- expect(created).toBeTruthy();-- const recent = cls.init(() => llmSpecialNotesRoute.getMostRecentLlmChat());- expect(recent).not.toBeNull();- });-- it("lists recent chats honouring the limit query param", () => {- const req = { query: { limit: "1" } } as unknown as Request;- const chats = cls.init(() => llmSpecialNotesRoute.getRecentLlmChats(req));- expect(Array.isArray(chats)).toBe(true);- expect(chats.length).toBeLessThanOrEqual(1);- });-- it("defaults the limit when not a number", () => {- const req = { query: {} } as unknown as Request;- const chats = cls.init(() => llmSpecialNotesRoute.getRecentLlmChats(req));- expect(Array.isArray(chats)).toBe(true);- });-- it("saves a chat by note id", () => {- const created = cls.init(() => llmSpecialNotesRoute.createLlmChat());- const noteId = created.noteId;- const req = { body: { llmChatNoteId: noteId } } as unknown as Request<{ llmChatNoteId: string }>;- const saved = cls.init(() => llmSpecialNotesRoute.saveLlmChat(req));- expect(saved).toBeTruthy();- });-});diff --git a/apps/server/src/routes/api/llm_special_notes.ts b/apps/server/src/routes/api/llm_special_notes.tsdeleted file mode 100644index 9f60871024..0000000000--- a/apps/server/src/routes/api/llm_special_notes.ts+++ /dev/null@@ -1,34 +0,0 @@-import { Request } from "express";--import specialNotesService from "../../services/special_notes";--function createLlmChat() {- return specialNotesService.createLlmChat();-}--function getMostRecentLlmChat() {- const chat = specialNotesService.getMostRecentLlmChat();- // Return null explicitly if no chat found (not undefined)- return chat || null;-}--function getOrCreateLlmChat() {- return specialNotesService.getOrCreateLlmChat();-}--function getRecentLlmChats(req: Request) {- const limit = parseInt(req.query.limit as string) || 10;- return specialNotesService.getRecentLlmChats(limit);-}--function saveLlmChat(req: Request<{ llmChatNoteId: string }>) {- return specialNotesService.saveLlmChat(req.body?.llmChatNoteId);-}--export default {- createLlmChat,- getMostRecentLlmChat,- getOrCreateLlmChat,- getRecentLlmChats,- saveLlmChat,-};diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex c5ed6df467..42b5c9198a 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -23,7 +23,6 @@ import etapiTokensApiRoutes from "./api/etapi_tokens.js";import filesRoute from "./api/files.js";// API routesimport llmChatRoute from "./api/llm_chat.js";-import llmSpecialNotesRoute from "./api/llm_special_notes.js";import loginApiRoute from "./api/login.js";import metricsRoute from "./api/metrics.js";import ocrRoute from "./api/ocr.js";@@ -141,11 +140,6 @@ function register(app: express.Application) {route(PST, "/api/clipper/open/:noteId", clipperMiddleware, clipperRoute.openNote, apiResultHandler);asyncRoute(GET, "/api/clipper/notes-by-url/:noteUrl", clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);- apiRoute(PST, "/api/special-notes/llm-chat", llmSpecialNotesRoute.createLlmChat);- apiRoute(GET, "/api/special-notes/most-recent-llm-chat", llmSpecialNotesRoute.getMostRecentLlmChat);- apiRoute(GET, "/api/special-notes/get-or-create-llm-chat", llmSpecialNotesRoute.getOrCreateLlmChat);- apiRoute(GET, "/api/special-notes/recent-llm-chats", llmSpecialNotesRoute.getRecentLlmChats);- apiRoute(PST, "/api/special-notes/save-llm-chat", llmSpecialNotesRoute.saveLlmChat);asyncRoute(PST, "/api/database/anonymize/:type", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler);apiRoute(GET, "/api/database/anonymized-databases", databaseRoute.getExistingAnonymizedDatabases);route(GET, "/api/database/anonymized/download", [auth.checkApiAuthOrElectron], databaseRoute.downloadAnonymizedDatabase);diff --git a/apps/server/src/services/special_notes.spec.ts b/apps/server/src/services/special_notes.spec.tsdeleted file mode 100644index d0429345b8..0000000000--- a/apps/server/src/services/special_notes.spec.ts+++ /dev/null@@ -1,232 +0,0 @@-import { becca, cls, hoisted_note as hoistedNoteService, note_service as noteService, search as searchService, SearchContext } from "@triliumnext/core";-import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";--import sql_init from "./sql_init.js";-import specialNotes from "./special_notes.js";--function countLlmChats() {- return searchService.searchNotes(- "note.type = llmChat",- new SearchContext({ ancestorNoteId: "_llmChat" })- ).length;-}--describe("special_notes (LLM chat, real DB)", () => {- beforeAll(async () => {- sql_init.initializeDb();- await sql_init.dbReady;- });-- describe("createLlmChat", () => {- it("creates an llmChat note with the expected metadata under a monthly parent", () => {- const note = cls.init(() => specialNotes.createLlmChat());-- expect(note.type).toBe("llmChat");- expect(note.mime).toBe("application/json");- expect(JSON.parse(note.getContent() as string)).toEqual({ version: 1, messages: [] });- expect(note.getLabelValue("iconClass")).toBe("bx bx-message-square-dots");- expect(note.hasLabel("keepCurrentHoisting")).toBe(true);-- // It must live (transitively) under the _llmChat hidden subtree.- expect(note.hasAncestor("_llmChat")).toBe(true);-- // The monthly parent must be a book note labelled llmChatMonthNote.- const parent = note.getParentNotes()[0];- expect(parent.type).toBe("book");- expect(parent.hasLabel("llmChatMonthNote")).toBe(true);- });-- it("reuses the same monthly parent for chats created in the same month", () => {- const a = cls.init(() => specialNotes.createLlmChat());- const b = cls.init(() => specialNotes.createLlmChat());-- expect(a.getParentNotes()[0].noteId).toBe(b.getParentNotes()[0].noteId);- });- });-- describe("getMostRecentLlmChat / getRecentLlmChats", () => {- // Self-contained: don't rely on chats created by a sibling describe block- // (the in-memory DB is shared per file, so test order must not matter).- beforeAll(() => {- cls.init(() => specialNotes.createLlmChat());- });-- it("returns the most recently modified chat and a mapped recent list", () => {- const recent = specialNotes.getRecentLlmChats(5);- expect(Array.isArray(recent)).toBe(true);- expect(recent.length).toBeGreaterThan(0);- for (const entry of recent) {- expect(entry).toHaveProperty("noteId");- expect(entry).toHaveProperty("title");- expect(entry).toHaveProperty("dateModified");- }-- const mostRecent = specialNotes.getMostRecentLlmChat();- expect(mostRecent).not.toBeNull();- expect(mostRecent!.type).toBe("llmChat");- // The newest chat in the recent list should match getMostRecentLlmChat.- expect(mostRecent!.noteId).toBe(recent[0].noteId);- });-- it("respects the limit argument", () => {- expect(specialNotes.getRecentLlmChats(1).length).toBeLessThanOrEqual(1);- });- });-- describe("getOrCreateLlmChat", () => {- it("returns an existing chat when one exists", () => {- // Ensure at least one exists.- cls.init(() => specialNotes.createLlmChat());- const result = specialNotes.getOrCreateLlmChat();- expect(result.type).toBe("llmChat");- });-- it("creates a new chat when none exist", () => {- // Delete all existing chats first.- cls.init(() => {- for (const chat of searchService.searchNotes(- "note.type = llmChat",- new SearchContext({ ancestorNoteId: "_llmChat" })- )) {- chat.deleteNote();- }- });- expect(specialNotes.getMostRecentLlmChat()).toBeNull();-- const created = cls.init(() => specialNotes.getOrCreateLlmChat());- expect(created.type).toBe("llmChat");- expect(specialNotes.getMostRecentLlmChat()).not.toBeNull();- });- });-- describe("saveLlmChat", () => {- it("throws when no chat note ID is provided", () => {- expect(() => specialNotes.saveLlmChat(null)).toThrow();- });-- it("throws when the chat note does not exist", () => {- expect(() => specialNotes.saveLlmChat("doesNotExist123")).toThrow();- });-- it("clones the chat to the chat home and removes the hidden-subtree parent branch", () => {- const chat = cls.init(() => specialNotes.createLlmChat());- expect(chat.hasAncestor("_hidden")).toBe(true);-- const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- expect(result.success).toBe(true);- expect(result.branchId).toBeTruthy();-- // After saving, the chat should no longer hang off the hidden subtree.- const liveParents = chat.getParentBranches().filter((b) => !b.isDeleted);- expect(liveParents.length).toBeGreaterThan(0);- const stillHidden = liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"));- expect(stillHidden).toBe(false);-- // The clone produced a resolvable branch.- const branch = becca.getBranch(result.branchId!);- expect(branch).toBeTruthy();- });- });-- describe("getLlmChatHome branches (via saveLlmChat)", () => {- afterEach(() => vi.restoreAllMocks());-- it("throws when there is no workspace note", () => {- vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(null as any);- const chat = cls.init(() => specialNotes.createLlmChat());-- expect(() => cls.init(() => specialNotes.saveLlmChat(chat.noteId)))- .toThrow(/workspace note/);- });-- // A real workspace note (under root, labelled #workspace) plus two DISTINCT- // child notes used as the clone targets, so each short-circuit operand of- // `#workspaceLlmChatHome || #llmChatHome || workspaceNote` resolves to a- // different note and the chosen target can be asserted unambiguously.- let workspaceId: string;- let workspaceHomeId: string;- let genericHomeId: string;- beforeAll(() => {- cls.init(() => {- const workspace = noteService.createNewNote({- parentNoteId: "root", title: "Workspace", content: "", type: "book"- }).note;- workspace.addLabel("workspace");- workspaceId = workspace.noteId;- workspaceHomeId = noteService.createNewNote({- parentNoteId: workspaceId, title: "Workspace LLM Home", content: "", type: "book"- }).note.noteId;- genericHomeId = noteService.createNewNote({- parentNoteId: workspaceId, title: "Generic LLM Home", content: "", type: "book"- }).note.noteId;- });- });-- function expectClonedUnder(- result: ReturnType<typeof specialNotes.saveLlmChat>,- chat: ReturnType<typeof specialNotes.createLlmChat>,- expectedParentId: string- ) {- expect(result.success).toBe(true);- // The chat was cloned to the chosen target and detached from _hidden.- const branch = becca.getBranch(result.branchId!);- expect(branch).toBeTruthy();- expect(branch!.parentNoteId).toBe(expectedParentId);- const liveParents = chat.getParentBranches().filter((b) => !b.isDeleted);- expect(liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"))).toBe(false);- }-- /**- * Returns a workspace stub backed by the real workspace note but with a- * controllable searchNoteInSubtree, so the three short-circuit operands of- * `#workspaceLlmChatHome || #llmChatHome || workspaceNote` can each be reached- * (the production searchNoteInSubtree is global, so real labels would collide).- */- function workspaceStub(found: Record<string, unknown>) {- const real = becca.getNoteOrThrow(workspaceId);- return new Proxy(real, {- get(target, prop) {- if (prop === "isRoot") return () => false;- if (prop === "searchNoteInSubtree") {- return (query: string) => found[query] ?? null;- }- return (target as any)[prop];- }- });- }-- it("uses the #workspaceLlmChatHome target when present", () => {- vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(- workspaceStub({ "#workspaceLlmChatHome": becca.getNoteOrThrow(workspaceHomeId) }) as any- );-- const chat = cls.init(() => specialNotes.createLlmChat());- const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- expectClonedUnder(result, chat, workspaceHomeId);- });-- it("falls back to #llmChatHome when #workspaceLlmChatHome is absent", () => {- vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(- workspaceStub({ "#llmChatHome": becca.getNoteOrThrow(genericHomeId) }) as any- );-- const chat = cls.init(() => specialNotes.createLlmChat());- const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- // Distinct from the #workspaceLlmChatHome target above.- expectClonedUnder(result, chat, genericHomeId);- });-- it("falls back to the workspace note itself when no chat-home label exists", () => {- vi.spyOn(hoistedNoteService, "getWorkspaceNote")- .mockReturnValue(workspaceStub({}) as any);-- const chat = cls.init(() => specialNotes.createLlmChat());- const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- expectClonedUnder(result, chat, workspaceId);- });- });-- it("starts with at least the seeded chat content available", () => {- expect(countLlmChats()).toBeGreaterThanOrEqual(0);- });-});diff --git a/apps/server/src/services/special_notes.ts b/apps/server/src/services/special_notes.tsdeleted file mode 100644index c899002e58..0000000000--- a/apps/server/src/services/special_notes.ts+++ /dev/null@@ -1,144 +0,0 @@-import { SaveLlmChatResponse } from "@triliumnext/commons";-import { becca, type BNote, date_notes as dateNoteService, date_utils as dateUtils, hoisted_note as hoistedNoteService, note_service as noteService, search as searchService, SearchContext } from "@triliumnext/core";-import { t } from "i18next";--function createLlmChat() {- const { note } = noteService.createNewNote({- parentNoteId: getMonthlyParentNoteId("_llmChat", "llmChat"),- title: `${t("special_notes.llm_chat_prefix")} ${dateUtils.localNowDateTime()}`,- content: JSON.stringify({- version: 1,- messages: []- }),- type: "llmChat",- mime: "application/json"- });-- note.setLabel("iconClass", "bx bx-message-square-dots");- note.setLabel("keepCurrentHoisting");-- return note;-}--/**- * Gets the most recently modified LLM chat note.- * Used by sidebar chat to persist conversation across page refreshes.- * Returns null if no chat exists.- */-function getMostRecentLlmChat() {- // Search for all llmChat notes and return the most recently modified- const results = searchService.searchNotes(- "note.type = llmChat",- new SearchContext({- ancestorNoteId: "_llmChat",- limit: 1,- orderBy: "utcDateModified",- orderDirection: "desc"- })- );-- return results.length > 0 ? results[0] : null;-}--/**- * Gets the most recent LLM chat or creates a new one if none exists.- * Used by sidebar chat for persistent conversations.- */-function getOrCreateLlmChat() {- const existingChat = getMostRecentLlmChat();-- if (existingChat) {- return existingChat;- }-- return createLlmChat();-}--/**- * Gets a list of recent LLM chat notes.- * Used by sidebar chat history popup.- */-function getRecentLlmChats(limit: number = 10) {- const results = searchService.searchNotes(- "note.type = llmChat",- new SearchContext({- ancestorNoteId: "_llmChat",- limit,- orderBy: "utcDateModified",- orderDirection: "desc"- })- );-- return results.map(note => ({- noteId: note.noteId,- title: note.title,- dateModified: note.utcDateModified- }));-}--function getLlmChatHome() {- const workspaceNote = hoistedNoteService.getWorkspaceNote();- if (!workspaceNote) {- throw new Error("Unable to find workspace note");- }-- if (!workspaceNote.isRoot()) {- return workspaceNote.searchNoteInSubtree("#workspaceLlmChatHome") || workspaceNote.searchNoteInSubtree("#llmChatHome") || workspaceNote;- }- const today = dateUtils.localNowDate();-- return workspaceNote.searchNoteInSubtree("#llmChatHome") || dateNoteService.getDayNote(today);--}--function saveLlmChat(llmChatNoteId: string | null) {- if (!llmChatNoteId) {- throw new Error(`Missing chat note ID`);- }-- const llmChatNote = becca.getNote(llmChatNoteId);- if (!llmChatNote) {- throw new Error(`Unable to find LLM chat note ID: ${llmChatNoteId}`);- }-- const llmChatHome = getLlmChatHome();-- const result = llmChatNote.cloneTo(llmChatHome.noteId);-- for (const parentBranch of llmChatNote.getParentBranches()) {- if (parentBranch.parentNote?.hasAncestor("_hidden")) {- parentBranch.markAsDeleted();- }- }-- return result satisfies SaveLlmChatResponse;-}--function getMonthlyParentNoteId(rootNoteId: string, prefix: string) {- const month = dateUtils.localNowDate().substring(0, 7);- const labelName = `${prefix}MonthNote`;-- let monthNote: BNote | null = searchService.findFirstNoteWithQuery(`#${labelName}="${month}"`, new SearchContext({ ancestorNoteId: rootNoteId }));-- if (!monthNote) {- monthNote = noteService.createNewNote({- parentNoteId: rootNoteId,- title: month,- content: "",- isProtected: false,- type: "book"- }).note;-- monthNote.addLabel(labelName, month);- }-- return monthNote.noteId;-}--export default {- createLlmChat,- getMostRecentLlmChat,- getOrCreateLlmChat,- getRecentLlmChats,- saveLlmChat,-};diff --git a/packages/trilium-core/src/routes/api/special_notes.spec.ts b/packages/trilium-core/src/routes/api/special_notes.spec.tsindex 38c312f354..a878a49fb9 100644--- a/packages/trilium-core/src/routes/api/special_notes.spec.ts+++ b/packages/trilium-core/src/routes/api/special_notes.spec.ts@@ -175,6 +175,67 @@ describe("Special notes API (core)", () => {});});++ // Driven through the route table rather than the handlers, so registration+ // and the limit query-param parsing are both covered.+ describe("LLM chats", () => {+ interface RecentChat {+ noteId: string;+ title: string;+ dateModified: string;+ }++ it("creates a chat, then returns it as the most recent one", async () => {+ const created = await api.post<NotePojo>("/api/special-notes/llm-chat");+ expect(created.status).toBe(200);+ expect(created.body.type).toBe("llmChat");++ const recent = await api.get<NotePojo | null>("/api/special-notes/most-recent-llm-chat");+ expect(recent.status).toBe(200);+ expect(recent.body?.noteId).toBe(created.body.noteId);+ });++ it("get-or-create returns the existing chat rather than a new one", async () => {+ const existing = await api.get<NotePojo>("/api/special-notes/most-recent-llm-chat");+ const res = await api.get<NotePojo>("/api/special-notes/get-or-create-llm-chat");+ expect(res.status).toBe(200);+ expect(res.body.noteId).toBe(existing.body.noteId);+ });++ it("lists recent chats, honouring the limit and defaulting it when absent", async () => {+ await api.post<NotePojo>("/api/special-notes/llm-chat");++ const limited = await api.get<RecentChat[]>("/api/special-notes/recent-llm-chats", {+ query: { limit: "1" }+ });+ expect(limited.status).toBe(200);+ expect(limited.body).toHaveLength(1);+ expect(limited.body[0]).toEqual(expect.objectContaining({+ noteId: expect.any(String),+ title: expect.any(String)+ }));++ // No limit, and a non-numeric one, both fall back to the default of 10.+ for (const query of [undefined, { limit: "not-a-number" }]) {+ const res = await api.get<RecentChat[]>("/api/special-notes/recent-llm-chats", { query });+ expect(res.status).toBe(200);+ expect(res.body.length).toBeGreaterThan(0);+ expect(res.body.length).toBeLessThanOrEqual(10);+ }+ });++ it("saves a chat out of the hidden subtree", async () => {+ const created = await api.post<NotePojo>("/api/special-notes/llm-chat");++ const saved = await api.post<CloneResponse>("/api/special-notes/save-llm-chat", {+ body: { llmChatNoteId: created.body.noteId }+ });+ expect(saved.status).toBe(200);+ expect(saved.body.success).toBe(true);+ expect(saved.body.branchId).toBeTruthy();+ });+ });+describe("launchers", () => {it("creates a launcher under a parent and resets it", async () => {const created = await api.post<{ success: boolean; note: NotePojo }>(diff --git a/packages/trilium-core/src/routes/api/special_notes.ts b/packages/trilium-core/src/routes/api/special_notes.tsindex 40bfea5e19..b28689a262 100644--- a/packages/trilium-core/src/routes/api/special_notes.ts+++ b/packages/trilium-core/src/routes/api/special_notes.ts@@ -107,6 +107,29 @@ function createOrUpdateScriptLauncherFromApi(req: Request) {return specialNotesService.createOrUpdateScriptLauncherFromApi(req.body);}+function createLlmChat() {+ return specialNotesService.createLlmChat();+}++function getMostRecentLlmChat() {+ const chat = specialNotesService.getMostRecentLlmChat();+ // Return null explicitly if no chat found (not undefined)+ return chat || null;+}++function getOrCreateLlmChat() {+ return specialNotesService.getOrCreateLlmChat();+}++function getRecentLlmChats(req: Request) {+ const limit = parseInt(req.query.limit as string) || 10;+ return specialNotesService.getRecentLlmChats(limit);+}++function saveLlmChat(req: Request<{ llmChatNoteId: string }>) {+ return specialNotesService.saveLlmChat(req.body?.llmChatNoteId);+}+export default {getInboxNote,getDayNote,@@ -122,5 +145,10 @@ export default {saveSearchNote,createLauncher,resetLauncher,- createOrUpdateScriptLauncherFromApi+ createOrUpdateScriptLauncherFromApi,+ createLlmChat,+ getMostRecentLlmChat,+ getOrCreateLlmChat,+ getRecentLlmChats,+ saveLlmChat};diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex ac2f0be744..1e6841b372 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -232,6 +232,11 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransapiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);+ apiRoute(PST, "/api/special-notes/llm-chat", specialNotesRoute.createLlmChat);+ apiRoute(GET, "/api/special-notes/most-recent-llm-chat", specialNotesRoute.getMostRecentLlmChat);+ apiRoute(GET, "/api/special-notes/get-or-create-llm-chat", specialNotesRoute.getOrCreateLlmChat);+ apiRoute(GET, "/api/special-notes/recent-llm-chats", specialNotesRoute.getRecentLlmChats);+ apiRoute(PST, "/api/special-notes/save-llm-chat", specialNotesRoute.saveLlmChat);apiRoute(PST, "/api/note-map/:noteId/tree", noteMapRoute.getTreeMap);apiRoute(PST, "/api/note-map/:noteId/link", noteMapRoute.getLinkMap);diff --git a/packages/trilium-core/src/services/special_notes.spec.ts b/packages/trilium-core/src/services/special_notes.spec.tsindex 15217e2e4d..97a4b1721f 100644--- a/packages/trilium-core/src/services/special_notes.spec.ts+++ b/packages/trilium-core/src/services/special_notes.spec.ts@@ -1,10 +1,13 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import becca from "../becca/becca.js";import type BNote from "../becca/entities/bnote.js";import attributeService from "./attributes.js";import { getContext } from "./context.js";import hoistedNoteService from "./hoisted_note.js";+import noteService from "./notes.js";+import SearchContext from "./search/search_context.js";+import searchService from "./search/services/search.js";import specialNotes from "./special_notes.js";import { unwrapStringOrBuffer } from "./utils/binary.js";@@ -358,6 +361,158 @@ describe("special_notes (core, real DB)", () => {expect(launcher.noteId).toMatch(/^tb_/);});});+ describe("LLM chat", () => {+ describe("createLlmChat", () => {+ it("creates an llmChat note with the expected metadata under a monthly parent", () => {+ const note = getContext().init(() => specialNotes.createLlmChat());++ expect(note.type).toBe("llmChat");+ expect(note.mime).toBe("application/json");+ expect(JSON.parse(note.getContent() as string)).toEqual({ version: 1, messages: [] });+ expect(note.getLabelValue("iconClass")).toBe("bx bx-message-square-dots");+ expect(note.hasLabel("keepCurrentHoisting")).toBe(true);+ expectUnderHidden(note, "_llmChat");++ // The monthly parent must be a book note labelled llmChatMonthNote.+ const parent = note.getParentNotes()[0];+ expect(parent.type).toBe("book");+ expect(parent.hasLabel("llmChatMonthNote")).toBe(true);+ });++ it("reuses the same monthly parent for chats created in the same month", () => {+ const a = getContext().init(() => specialNotes.createLlmChat());+ const b = getContext().init(() => specialNotes.createLlmChat());++ expect(a.getParentNotes()[0].noteId).toBe(b.getParentNotes()[0].noteId);+ });+ });++ describe("getMostRecentLlmChat / getRecentLlmChats", () => {+ // Self-contained: don't rely on chats created by a sibling describe block+ // (the in-memory DB is shared per file, so test order must not matter).+ beforeAll(() => {+ getContext().init(() => specialNotes.createLlmChat());+ });++ it("returns the most recently modified chat and a mapped recent list", () => {+ const recent = specialNotes.getRecentLlmChats(5);+ expect(recent.length).toBeGreaterThan(0);+ for (const entry of recent) {+ expect(entry).toHaveProperty("noteId");+ expect(entry).toHaveProperty("title");+ expect(entry).toHaveProperty("dateModified");+ }++ const mostRecent = specialNotes.getMostRecentLlmChat();+ // The newest chat in the recent list should match getMostRecentLlmChat.+ expect(mostRecent?.type).toBe("llmChat");+ expect(mostRecent?.noteId).toBe(recent[0].noteId);+ });++ it("respects the limit argument", () => {+ expect(specialNotes.getRecentLlmChats(1).length).toBeLessThanOrEqual(1);+ });+ });++ describe("getOrCreateLlmChat", () => {+ it("returns an existing chat when one exists", () => {+ getContext().init(() => specialNotes.createLlmChat());+ expect(specialNotes.getOrCreateLlmChat().type).toBe("llmChat");+ });++ it("creates a new chat when none exist", () => {+ getContext().init(() => {+ for (const chat of searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({ ancestorNoteId: "_llmChat" })+ )) {+ chat.deleteNote();+ }+ });+ expect(specialNotes.getMostRecentLlmChat()).toBeNull();++ const created = getContext().init(() => specialNotes.getOrCreateLlmChat());+ expect(created.type).toBe("llmChat");+ expect(specialNotes.getMostRecentLlmChat()).not.toBeNull();+ });+ });++ describe("saveLlmChat", () => {+ it("rejects a missing id and an id that resolves to nothing", () => {+ expect(() => specialNotes.saveLlmChat(null)).toThrow();+ expect(() => specialNotes.saveLlmChat("doesNotExist123")).toThrow();+ });++ it("clones the chat to the chat home and removes the hidden-subtree parent branch", () => {+ const chat = getContext().init(() => specialNotes.createLlmChat());+ expect(chat.hasAncestor("_hidden")).toBe(true);++ const result = getContext().init(() => specialNotes.saveLlmChat(chat.noteId));+ expect(result.success).toBe(true);+ expect(result.branchId).toBeTruthy();++ // After saving, the chat no longer hangs off the hidden subtree.+ const liveParents = chat.getParentBranches().filter(b => !b.isDeleted);+ expect(liveParents.length).toBeGreaterThan(0);+ expect(liveParents.some(b => b.parentNote?.hasAncestor("_hidden"))).toBe(false);+ expect(result.branchId && becca.getBranch(result.branchId)).toBeTruthy();+ });+ });++ // Each short-circuit operand of `#workspaceLlmChatHome || #llmChatHome ||+ // workspaceNote` must resolve to a DISTINCT note, so the chosen target can be+ // asserted unambiguously.+ describe("getLlmChatHome branches (via saveLlmChat)", () => {+ let workspaceHomeId: string;+ let genericHomeId: string;+ let fallbackId: string;++ beforeAll(() => {+ getContext().init(() => {+ workspaceHomeId = noteService.createNewNote({+ parentNoteId: "root", title: "Workspace LLM Home", content: "", type: "book"+ }).note.noteId;+ genericHomeId = noteService.createNewNote({+ parentNoteId: "root", title: "Generic LLM Home", content: "", type: "book"+ }).note.noteId;+ });+ // What makeWorkspaceStub proxies, and therefore the last operand.+ fallbackId = becca.getNoteOrThrow("root").getChildNotes()[0].noteId;+ });++ function expectClonedUnder(found: Record<string, unknown>, expectedParentId: string) {+ vi.spyOn(hoistedNoteService, "getWorkspaceNote")+ .mockReturnValue(makeWorkspaceStub(found) as never);++ const chat = getContext().init(() => specialNotes.createLlmChat());+ const result = getContext().init(() => specialNotes.saveLlmChat(chat.noteId));++ expect(result.success).toBe(true);+ expect(result.branchId && becca.getBranch(result.branchId)?.parentNoteId).toBe(expectedParentId);+ const liveParents = chat.getParentBranches().filter(b => !b.isDeleted);+ expect(liveParents.some(b => b.parentNote?.hasAncestor("_hidden"))).toBe(false);+ }++ it("throws when there is no workspace note", () => {+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(null as never);+ const chat = getContext().init(() => specialNotes.createLlmChat());++ expect(() => getContext().init(() => specialNotes.saveLlmChat(chat.noteId)))+ .toThrow(/workspace note/);+ });++ it("prefers #workspaceLlmChatHome, then #llmChatHome, then the workspace note itself", () => {+ expectClonedUnder(+ { "#workspaceLlmChatHome": becca.getNoteOrThrow(workspaceHomeId) },+ workspaceHomeId+ );+ vi.restoreAllMocks();+ expectClonedUnder({ "#llmChatHome": becca.getNoteOrThrow(genericHomeId) }, genericHomeId);+ vi.restoreAllMocks();+ expectClonedUnder({}, fallbackId);+ });+ });+ });});/**diff --git a/packages/trilium-core/src/services/special_notes.ts b/packages/trilium-core/src/services/special_notes.tsindex 03d5ca1f8d..d92ff5d60b 100644--- a/packages/trilium-core/src/services/special_notes.ts+++ b/packages/trilium-core/src/services/special_notes.ts@@ -10,7 +10,7 @@ import SearchContext from "./search/search_context.js";import { LBTPL_NOTE_LAUNCHER, LBTPL_CUSTOM_WIDGET, LBTPL_SPACER, LBTPL_SCRIPT } from "./hidden_subtree.js";import { t } from "i18next";import BNote from '../becca/entities/bnote.js';-import { SaveSearchNoteResponse, SaveSqlConsoleResponse } from "@triliumnext/commons";+import { SaveLlmChatResponse, SaveSearchNoteResponse, SaveSqlConsoleResponse } from "@triliumnext/commons";function getInboxNote(date: string) {const workspaceNote = hoistedNoteService.getWorkspaceNote();@@ -276,6 +276,117 @@ function createOrUpdateScriptLauncherFromApi(opts: { id: string; title: string;return launcherNote;}+/**+ * Gets the most recently modified LLM chat note.+ * Used by sidebar chat to persist conversation across page refreshes.+ * Returns null if no chat exists.+ */+function getMostRecentLlmChat() {+ // Search for all llmChat notes and return the most recently modified+ const results = searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({+ ancestorNoteId: "_llmChat",+ limit: 1,+ orderBy: "utcDateModified",+ orderDirection: "desc"+ })+ );++ return results.length > 0 ? results[0] : null;+}++/**+ * Gets the most recent LLM chat or creates a new one if none exists.+ * Used by sidebar chat for persistent conversations.+ */+function getOrCreateLlmChat() {+ const existingChat = getMostRecentLlmChat();++ if (existingChat) {+ return existingChat;+ }++ return createLlmChat();+}++/**+ * Gets a list of recent LLM chat notes.+ * Used by sidebar chat history popup.+ */+function getRecentLlmChats(limit: number = 10) {+ const results = searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({+ ancestorNoteId: "_llmChat",+ limit,+ orderBy: "utcDateModified",+ orderDirection: "desc"+ })+ );++ return results.map(note => ({+ noteId: note.noteId,+ title: note.title,+ dateModified: note.utcDateModified+ }));+}++function createLlmChat() {+ const { note } = noteService.createNewNote({+ parentNoteId: getMonthlyParentNoteId("_llmChat", "llmChat"),+ title: `${t("special_notes.llm_chat_prefix")} ${dateUtils.localNowDateTime()}`,+ content: JSON.stringify({+ version: 1,+ messages: []+ }),+ type: "llmChat",+ mime: "application/json"+ });++ note.setLabel("iconClass", "bx bx-message-square-dots");+ note.setLabel("keepCurrentHoisting");++ return note;+}++function getLlmChatHome() {+ const workspaceNote = hoistedNoteService.getWorkspaceNote();+ if (!workspaceNote) {+ throw new Error("Unable to find workspace note");+ }++ if (!workspaceNote.isRoot()) {+ return workspaceNote.searchNoteInSubtree("#workspaceLlmChatHome") || workspaceNote.searchNoteInSubtree("#llmChatHome") || workspaceNote;+ }+ const today = dateUtils.localNowDate();++ return workspaceNote.searchNoteInSubtree("#llmChatHome") || dateNoteService.getDayNote(today);+}++function saveLlmChat(llmChatNoteId: string | null) {+ if (!llmChatNoteId) {+ throw new Error(`Missing chat note ID`);+ }++ const llmChatNote = becca.getNote(llmChatNoteId);+ if (!llmChatNote) {+ throw new Error(`Unable to find LLM chat note ID: ${llmChatNoteId}`);+ }++ const llmChatHome = getLlmChatHome();++ const result = llmChatNote.cloneTo(llmChatHome.noteId);++ for (const parentBranch of llmChatNote.getParentBranches()) {+ if (parentBranch.parentNote?.hasAncestor("_hidden")) {+ parentBranch.markAsDeleted();+ }+ }++ return result satisfies SaveLlmChatResponse;+}+export default {getInboxNote,createSqlConsole,@@ -284,5 +395,10 @@ export default {saveSearchNote,createLauncher,resetLauncher,- createOrUpdateScriptLauncherFromApi+ createOrUpdateScriptLauncherFromApi,+ createLlmChat,+ getMostRecentLlmChat,+ getOrCreateLlmChat,+ getRecentLlmChats,+ saveLlmChat};