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
fix(llm): chat note created for every note navigated to
Elian Doran9fa2e940d6d8
diff --git a/apps/client/src/services/date_notes.ts b/apps/client/src/services/date_notes.tsindex 09ff1e8ca5..e056ac6888 100644--- a/apps/client/src/services/date_notes.ts+++ b/apps/client/src/services/date_notes.ts@@ -92,6 +92,22 @@ async function createLlmChat(sourceNoteId?: string) {return await froca.getNote(note.noteId);}+/**+ * Finds an existing LLM chat linked to the given note, without creating one.+ * Returns null if no chat exists for this note.+ */+async function findLlmChatForNote(noteId: string) {+ const note = await server.get<FNoteRow | null>(`special-notes/find-llm-chat-for-note/${noteId}`);++ if (!note) {+ return null;+ }++ await ws.waitForMaxKnownEntityChangeId();++ return await froca.getNote(note.noteId);+}+/*** Gets an existing LLM chat linked to the given note, or creates a new one.* Used by sidebar chat to maintain 1:1 mapping between notes and their chats.@@ -116,5 +132,6 @@ export default {createSqlConsole,createSearchNote,createLlmChat,+ findLlmChatForNote,getOrCreateLlmChatForNote};diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsxindex 13b5772efa..b6f53d4520 100644--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx@@ -71,55 +71,83 @@ export default function SidebarChat() {const textareaRef = useRef<HTMLTextAreaElement>(null);const saveTimeoutRef = useRef<ReturnType<typeof setTimeout>>();- // Initialize chat for a specific note- const initializeChatForNote = useCallback(async (noteId: string) => {+ // Load existing chat for a note (without creating one)+ const loadExistingChatForNote = useCallback(async (noteId: string) => {try {- const note = await dateNoteService.getOrCreateLlmChatForNote(noteId);+ // First, check if a chat already exists for this note+ const existingChat = await dateNoteService.findLlmChatForNote(noteId);++ setSourceNoteId(noteId);++ if (existingChat) {+ setChatNoteId(existingChat.noteId);+ await loadChatContent(existingChat.noteId);+ } else {+ // No existing chat - just track the source note, don't create yet+ setChatNoteId(null);+ setMessages([]);+ }+ } catch (err) {+ console.error("Failed to load sidebar chat:", err);+ }+ }, []);++ // Create chat note on demand (when user sends first message)+ const ensureChatNoteExists = useCallback(async (): Promise<string | null> => {+ if (chatNoteId) {+ return chatNoteId;+ }++ if (!sourceNoteId) {+ return null;+ }++ try {+ const note = await dateNoteService.getOrCreateLlmChatForNote(sourceNoteId);if (note) {- setSourceNoteId(noteId);setChatNoteId(note.noteId);- // Load existing messages if any- await loadChatContent(note.noteId);+ return note.noteId;}} catch (err) {- console.error("Failed to initialize sidebar chat:", err);+ console.error("Failed to create sidebar chat:", err);}- }, []);+ return null;+ }, [chatNoteId, sourceNoteId]);- // Track when active note changes and load/create corresponding chat+ // Track when active note changes and load existing chatuseEffect(() => {if (!visible || !activeNote) return;const noteId = activeNote.noteId;- // Don't switch chats if we're already on this note's chat+ // Don't switch if we're already on this noteif (noteId === sourceNoteId) return;- // Load or create chat for the new note- initializeChatForNote(noteId);- }, [activeNote, visible, sourceNoteId, initializeChatForNote]);+ // Load existing chat for the new note (don't create)+ loadExistingChatForNote(noteId);+ }, [activeNote, visible, sourceNoteId, loadExistingChatForNote]);// Listen for toggle eventuseTriliumEvent("toggleSidebarChat", useCallback(() => {setVisible(v => {const newValue = !v;if (newValue && activeNote) {- initializeChatForNote(activeNote.noteId);+ loadExistingChatForNote(activeNote.noteId);}return newValue;});- }, [activeNote, initializeChatForNote]));+ }, [activeNote, loadExistingChatForNote]));- // Listen for open event (always opens, creates chat if needed)+ // Listen for open event (always opens)useTriliumEvent("openSidebarChat", useCallback(() => {setVisible(true);if (activeNote) {- initializeChatForNote(activeNote.noteId);+ loadExistingChatForNote(activeNote.noteId);}// Ensure right pane is visibleif (!options.is("rightPaneVisible")) {appContext.triggerEvent("toggleRightPane", {});}- }, [activeNote, initializeChatForNote]));+ }, [activeNote, loadExistingChatForNote]));// Fetch available models on mountuseEffect(() => {@@ -195,6 +223,13 @@ export default function SidebarChat() {e.preventDefault();if (!input.trim() || isStreaming) return;+ // Ensure chat note exists before sending (lazy creation)+ const noteId = await ensureChatNoteExists();+ if (!noteId) {+ console.error("Cannot send message: no chat note available");+ return;+ }+setToolActivity(null);setPendingCitations([]);@@ -317,7 +352,7 @@ export default function SidebarChat() {}});- }, [input, isStreaming, messages, selectedModel, enableWebSearch, enableNoteTools, saveChat]);+ }, [input, isStreaming, messages, selectedModel, enableWebSearch, enableNoteTools, saveChat, ensureChatNoteExists]);const handleKeyDown = useCallback((e: KeyboardEvent) => {if (e.key === "Enter" && !e.shiftKey) {@@ -346,12 +381,12 @@ export default function SidebarChat() {if (activeNote) {setSourceNoteId(null);setChatNoteId(null);- initializeChatForNote(activeNote.noteId);+ loadExistingChatForNote(activeNote.noteId);}} catch (err) {console.error("Failed to save chat to permanent location:", err);}- }, [chatNoteId, activeNote, initializeChatForNote]);+ }, [chatNoteId, activeNote, loadExistingChatForNote]);if (!visible) {return null;diff --git a/apps/server/src/routes/api/special_notes.ts b/apps/server/src/routes/api/special_notes.tsindex 09f0215244..db21db8872 100644--- a/apps/server/src/routes/api/special_notes.ts+++ b/apps/server/src/routes/api/special_notes.ts@@ -91,6 +91,12 @@ function createLlmChat(req: Request) {return specialNotesService.createLlmChat(sourceNoteId);}+function findLlmChatForNote(req: Request<{ noteId: string }>) {+ const chat = specialNotesService.findLlmChatForNote(req.params.noteId);+ // Return null explicitly if no chat found (not undefined)+ return chat || null;+}+function getOrCreateLlmChatForNote(req: Request<{ noteId: string }>) {return specialNotesService.getOrCreateLlmChatForNote(req.params.noteId);}@@ -133,6 +139,7 @@ export default {createSearchNote,saveSearchNote,createLlmChat,+ findLlmChatForNote,getOrCreateLlmChatForNote,saveLlmChat,createLauncher,diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 9c7b7d052b..b95443be64 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -293,6 +293,7 @@ function register(app: express.Application) {apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);apiRoute(PST, "/api/special-notes/llm-chat", specialNotesRoute.createLlmChat);+ apiRoute(GET, "/api/special-notes/find-llm-chat-for-note/:noteId", specialNotesRoute.findLlmChatForNote);apiRoute(GET, "/api/special-notes/llm-chat-for-note/:noteId", specialNotesRoute.getOrCreateLlmChatForNote);apiRoute(PST, "/api/special-notes/save-llm-chat", specialNotesRoute.saveLlmChat);apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);diff --git a/apps/server/src/services/special_notes.ts b/apps/server/src/services/special_notes.tsindex 0d95a48652..f5c251fb65 100644--- a/apps/server/src/services/special_notes.ts+++ b/apps/server/src/services/special_notes.ts@@ -155,10 +155,7 @@ function createLlmChat(sourceNoteId?: string) {*/function getOrCreateLlmChatForNote(sourceNoteId: string) {// Search for existing chat with this source note relation- const existingChat = searchService.findFirstNoteWithQuery(- `~sourceNote.noteId="${sourceNoteId}"`,- new SearchContext({ ancestorNoteId: "_llmChat" })- );+ const existingChat = findLlmChatForNote(sourceNoteId);if (existingChat) {return existingChat;@@ -168,6 +165,17 @@ function getOrCreateLlmChatForNote(sourceNoteId: string) {return createLlmChat(sourceNoteId);}+/**+ * Finds an existing LLM chat linked to the given note, without creating one.+ * Returns null if no chat exists for this note.+ */+function findLlmChatForNote(sourceNoteId: string) {+ return searchService.findFirstNoteWithQuery(+ `~sourceNote.noteId="${sourceNoteId}"`,+ new SearchContext({ ancestorNoteId: "_llmChat" })+ );+}+function getLlmChatHome() {const workspaceNote = hoistedNoteService.getWorkspaceNote();if (!workspaceNote) {@@ -362,6 +370,7 @@ export default {createSearchNote,saveSearchNote,createLlmChat,+ findLlmChatForNote,getOrCreateLlmChatForNote,saveLlmChat,createLauncher,