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): redesign sidebar to work on a single conversation
Elian Dorand2fd1362c045
diff --git a/apps/client/src/services/date_notes.ts b/apps/client/src/services/date_notes.tsindex e056ac6888..cad14d39fc 100644--- a/apps/client/src/services/date_notes.ts+++ b/apps/client/src/services/date_notes.ts@@ -84,8 +84,8 @@ async function createSearchNote(opts = {}) {return await froca.getNote(note.noteId);}-async function createLlmChat(sourceNoteId?: string) {- const note = await server.post<FNoteRow>("special-notes/llm-chat", { sourceNoteId });+async function createLlmChat() {+ const note = await server.post<FNoteRow>("special-notes/llm-chat");await ws.waitForMaxKnownEntityChangeId();@@ -93,11 +93,11 @@ async function createLlmChat(sourceNoteId?: string) {}/**- * Finds an existing LLM chat linked to the given note, without creating one.- * Returns null if no chat exists for this note.+ * Gets the most recently modified LLM chat.+ * Returns null if no chat exists.*/-async function findLlmChatForNote(noteId: string) {- const note = await server.get<FNoteRow | null>(`special-notes/find-llm-chat-for-note/${noteId}`);+async function getMostRecentLlmChat() {+ const note = await server.get<FNoteRow | null>("special-notes/most-recent-llm-chat");if (!note) {return null;@@ -109,11 +109,11 @@ async function findLlmChatForNote(noteId: string) {}/**- * 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.+ * Gets the most recent LLM chat, or creates a new one if none exists.+ * Used by sidebar chat for persistent conversations across page refreshes.*/-async function getOrCreateLlmChatForNote(noteId: string) {- const note = await server.get<FNoteRow>(`special-notes/llm-chat-for-note/${noteId}`);+async function getOrCreateLlmChat() {+ const note = await server.get<FNoteRow>("special-notes/get-or-create-llm-chat");await ws.waitForMaxKnownEntityChangeId();@@ -132,6 +132,6 @@ export default {createSqlConsole,createSearchNote,createLlmChat,- findLlmChatForNote,- getOrCreateLlmChatForNote+ getMostRecentLlmChat,+ getOrCreateLlmChat};diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsxindex ffa911f035..3007bc066f 100644--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx@@ -7,7 +7,6 @@ import { getAvailableModels, streamChatCompletion } from "../../services/llm_chaimport server from "../../services/server.js";import { randomString } from "../../services/utils.js";import ActionButton from "../react/ActionButton.js";-import { useActiveNoteContext } from "../react/hooks.js";import ChatMessage from "../type_widgets/llm_chat/ChatMessage.js";import RightPanelWidget from "./RightPanelWidget.js";import "./SidebarChat.css";@@ -47,11 +46,10 @@ interface ModelOption extends LlmModelInfo {/*** Sidebar chat widget that appears in the right panel.- * Uses a hidden LLM chat note for persistence, with 1:1 mapping to the active note.+ * Uses a hidden LLM chat note for persistence across all notes.+ * The same chat persists when switching between notes.*/export default function SidebarChat() {- const { note: activeNote } = useActiveNoteContext();- const [sourceNoteId, setSourceNoteId] = useState<string | null>(null);const [chatNoteId, setChatNoteId] = useState<string | null>(null);const [messages, setMessages] = useState<StoredMessage[]>([]);const [input, setInput] = useState("");@@ -68,19 +66,16 @@ export default function SidebarChat() {const textareaRef = useRef<HTMLTextAreaElement>(null);const saveTimeoutRef = useRef<ReturnType<typeof setTimeout>>();- // Load existing chat for a note (without creating one)- const loadExistingChatForNote = useCallback(async (noteId: string) => {+ // Load the most recent chat on mount+ const loadMostRecentChat = useCallback(async () => {try {- // First, check if a chat already exists for this note- const existingChat = await dateNoteService.findLlmChatForNote(noteId);-- setSourceNoteId(noteId);+ const existingChat = await dateNoteService.getMostRecentLlmChat();if (existingChat) {setChatNoteId(existingChat.noteId);await loadChatContent(existingChat.noteId);} else {- // No existing chat - just track the source note, don't create yet+ // No existing chat - will create on first messagesetChatNoteId(null);setMessages([]);}@@ -95,12 +90,8 @@ export default function SidebarChat() {return chatNoteId;}- if (!sourceNoteId) {- return null;- }-try {- const note = await dateNoteService.getOrCreateLlmChatForNote(sourceNoteId);+ const note = await dateNoteService.getOrCreateLlmChat();if (note) {setChatNoteId(note.noteId);return note.noteId;@@ -109,19 +100,12 @@ export default function SidebarChat() {console.error("Failed to create sidebar chat:", err);}return null;- }, [chatNoteId, sourceNoteId]);+ }, [chatNoteId]);- // Track when active note changes and load existing chat+ // Load the most recent chat on mountuseEffect(() => {- if (!activeNote) return;-- const noteId = activeNote.noteId;- // Don't switch if we're already on this note- if (noteId === sourceNoteId) return;-- // Load existing chat for the new note (don't create)- loadExistingChatForNote(noteId);- }, [activeNote, sourceNoteId, loadExistingChatForNote]);+ loadMostRecentChat();+ }, [loadMostRecentChat]);// Fetch available models on mountuseEffect(() => {@@ -336,31 +320,32 @@ export default function SidebarChat() {}, [handleSubmit]);const handleNewChat = useCallback(async () => {- if (!activeNote) return;- // Clear messages for a fresh start with the same note- setMessages([]);- // Save cleared state- if (chatNoteId) {- await saveChat([]);+ // Create a fresh new chat+ try {+ const note = await dateNoteService.createLlmChat();+ if (note) {+ setChatNoteId(note.noteId);+ setMessages([]);+ }+ } catch (err) {+ console.error("Failed to create new chat:", err);}- }, [activeNote, chatNoteId, saveChat]);+ }, []);const handleSaveChat = useCallback(async () => {if (!chatNoteId) return;try {await server.post("special-notes/save-llm-chat", { llmChatNoteId: chatNoteId });- // Clear the current chat after saving (note link is preserved)- setMessages([]);- // Force reload to get a fresh chat for this note- if (activeNote) {- setSourceNoteId(null);- setChatNoteId(null);- loadExistingChatForNote(activeNote.noteId);+ // Create a new empty chat after saving+ const note = await dateNoteService.createLlmChat();+ if (note) {+ setChatNoteId(note.noteId);+ setMessages([]);}} catch (err) {console.error("Failed to save chat to permanent location:", err);}- }, [chatNoteId, activeNote, loadExistingChatForNote]);+ }, [chatNoteId]);return (<RightPanelWidgetdiff --git a/apps/server/src/routes/api/special_notes.ts b/apps/server/src/routes/api/special_notes.tsindex db21db8872..efcc4b93de 100644--- a/apps/server/src/routes/api/special_notes.ts+++ b/apps/server/src/routes/api/special_notes.ts@@ -86,19 +86,18 @@ function createSearchNote(req: Request) {return specialNotesService.createSearchNote(searchString, ancestorNoteId);}-function createLlmChat(req: Request) {- const sourceNoteId = req.body.sourceNoteId;- return specialNotesService.createLlmChat(sourceNoteId);+function createLlmChat() {+ return specialNotesService.createLlmChat();}-function findLlmChatForNote(req: Request<{ noteId: string }>) {- const chat = specialNotesService.findLlmChatForNote(req.params.noteId);+function getMostRecentLlmChat() {+ const chat = specialNotesService.getMostRecentLlmChat();// Return null explicitly if no chat found (not undefined)return chat || null;}-function getOrCreateLlmChatForNote(req: Request<{ noteId: string }>) {- return specialNotesService.getOrCreateLlmChatForNote(req.params.noteId);+function getOrCreateLlmChat() {+ return specialNotesService.getOrCreateLlmChat();}function saveLlmChat(req: Request) {@@ -139,8 +138,8 @@ export default {createSearchNote,saveSearchNote,createLlmChat,- findLlmChatForNote,- getOrCreateLlmChatForNote,+ getMostRecentLlmChat,+ getOrCreateLlmChat,saveLlmChat,createLauncher,resetLauncher,diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex b95443be64..cf19ce24e4 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -293,8 +293,8 @@ 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(GET, "/api/special-notes/most-recent-llm-chat", specialNotesRoute.getMostRecentLlmChat);+ apiRoute(GET, "/api/special-notes/get-or-create-llm-chat", specialNotesRoute.getOrCreateLlmChat);apiRoute(PST, "/api/special-notes/save-llm-chat", specialNotesRoute.saveLlmChat);apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);diff --git a/apps/server/src/services/special_notes.ts b/apps/server/src/services/special_notes.tsindex f5c251fb65..7a090b667d 100644--- a/apps/server/src/services/special_notes.ts+++ b/apps/server/src/services/special_notes.ts@@ -123,13 +123,10 @@ function saveSearchNote(searchNoteId: string) {return result satisfies SaveSearchNoteResponse;}-function createLlmChat(sourceNoteId?: string) {- const sourceNote = sourceNoteId ? becca.getNote(sourceNoteId) : null;- const titleSuffix = sourceNote ? sourceNote.title : dateUtils.localNowDateTime();-+function createLlmChat() {const { note } = noteService.createNewNote({parentNoteId: getMonthlyParentNoteId("_llmChat", "llmChat"),- title: `${t("special_notes.llm_chat_prefix")} ${titleSuffix}`,+ title: `${t("special_notes.llm_chat_prefix")} ${dateUtils.localNowDateTime()}`,content: JSON.stringify({version: 1,messages: []@@ -141,39 +138,41 @@ function createLlmChat(sourceNoteId?: string) {note.setLabel("iconClass", "bx bx-message-square-dots");note.setLabel("keepCurrentHoisting");- // Link to source note if provided- if (sourceNoteId) {- note.setRelation("sourceNote", sourceNoteId);- }-return note;}/**- * 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.+ * 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 getOrCreateLlmChatForNote(sourceNoteId: string) {- // Search for existing chat with this source note relation- const existingChat = findLlmChatForNote(sourceNoteId);-- if (existingChat) {- return existingChat;- }+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: "note.utcDateModified",+ orderDirection: "desc"+ })+ );- // Create new chat linked to this note- return createLlmChat(sourceNoteId);+ return results.length > 0 ? results[0] : null;}/**- * Finds an existing LLM chat linked to the given note, without creating one.- * Returns null if no chat exists for this note.+ * Gets the most recent LLM chat or creates a new one if none exists.+ * Used by sidebar chat for persistent conversations.*/-function findLlmChatForNote(sourceNoteId: string) {- return searchService.findFirstNoteWithQuery(- `~sourceNote.noteId="${sourceNoteId}"`,- new SearchContext({ ancestorNoteId: "_llmChat" })- );+function getOrCreateLlmChat() {+ const existingChat = getMostRecentLlmChat();++ if (existingChat) {+ return existingChat;+ }++ return createLlmChat();}function getLlmChatHome() {@@ -370,8 +369,8 @@ export default {createSearchNote,saveSearchNote,createLlmChat,- findLlmChatForNote,- getOrCreateLlmChatForNote,+ getMostRecentLlmChat,+ getOrCreateLlmChat,saveLlmChat,createLauncher,resetLauncher,