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(sidebar-chat): start a new chat after deleting the open one
Elian Dorancd6f75457343
diff --git a/apps/client/src/services/date_notes.spec.ts b/apps/client/src/services/date_notes.spec.tsindex c31a4e2305..10fc183f19 100644--- a/apps/client/src/services/date_notes.spec.ts+++ b/apps/client/src/services/date_notes.spec.ts@@ -189,16 +189,6 @@ describe("date_notes", () => {expect(result).toBe(note);});- it("getOrCreateLlmChat resolves the note", async () => {- const note = buildNote({ title: "Persistent chat" });- server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;-- const result = await dateNotes.getOrCreateLlmChat();-- expect(server.get).toHaveBeenCalledWith("special-notes/get-or-create-llm-chat");- expect(result).toBe(note);- });-it("getRecentLlmChats uses the default limit and returns the list", async () => {const chats = [{ noteId: "a", title: "A", dateModified: "2025-05-29" }];server.get = vi.fn(async () => chats) as typeof server.get;diff --git a/apps/client/src/services/date_notes.ts b/apps/client/src/services/date_notes.tsindex 2718d84f64..5baad4d58f 100644--- a/apps/client/src/services/date_notes.ts+++ b/apps/client/src/services/date_notes.ts@@ -123,18 +123,6 @@ async function getMostRecentLlmChat() {return await froca.getNote(note.noteId);}-/**- * 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 getOrCreateLlmChat() {- const note = await server.get<FNoteRow>("special-notes/get-or-create-llm-chat");-- await ws.waitForMaxKnownEntityChangeId();-- return await froca.getNote(note.noteId);-}-export interface RecentLlmChat {noteId: string;title: string;@@ -163,6 +151,5 @@ export default {createSearchNote,createLlmChat,getMostRecentLlmChat,- getOrCreateLlmChat,getRecentLlmChats};diff --git a/apps/client/src/widgets/sidebar/SidebarChat.spec.tsx b/apps/client/src/widgets/sidebar/SidebarChat.spec.tsxnew file mode 100644index 0000000000..e04ef0f892--- /dev/null+++ b/apps/client/src/widgets/sidebar/SidebarChat.spec.tsx@@ -0,0 +1,113 @@+import type { ComponentChildren } from "preact";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";++/** The chat notes on the server, most recently modified first. */+let serverChats: string[] = [];+let createdCount = 0;++vi.mock("../../services/date_notes.js", () => ({+ default: {+ getMostRecentLlmChat: vi.fn(async () => serverChats.length ? { noteId: serverChats[0] } : null),+ createLlmChat: vi.fn(async () => createChat()),+ getRecentLlmChats: vi.fn(async () => [])+ }+}));+vi.mock("../../services/server.js", () => ({+ default: {+ get: vi.fn(async () => ({ content: JSON.stringify({ version: 1, messages: [] }) })),+ put: vi.fn(async () => undefined),+ post: vi.fn(async () => ({})),+ remove: vi.fn(async (url: string) => {+ serverChats = serverChats.filter(noteId => !url.startsWith(`notes/${noteId}?`));+ })+ }+}));+vi.mock("../../services/dialog.js", () => ({ default: { confirm: vi.fn(async () => true), prompt: vi.fn() } }));+vi.mock("../../services/ws.js", () => ({ default: {} }));+vi.mock("../../components/app_context.js", () => ({ default: {} }));++const fakeChat = {+ messages: [],+ hasInputText: true,+ pendingAttachments: [],+ isStreaming: false,+ getInput: vi.fn(() => "Hello"),+ setInput: vi.fn(),+ getContent: vi.fn(() => ({ version: 1, messages: [] })),+ loadFromContent: vi.fn(),+ clearMessages: vi.fn(),+ setContextNoteId: vi.fn(),+ setChatNoteId: vi.fn((noteId: string | undefined) => { fakeChat.chatNoteId = noteId; }),+ chatNoteId: undefined as string | undefined,+ /** The chat note the message was sent to. */+ submittedTo: undefined as string | undefined,+ handleSubmit: vi.fn(async () => { fakeChat.submittedTo = fakeChat.chatNoteId; })+};++vi.mock("../type_widgets/llm_chat/useLlmChat.js", () => ({ useLlmChat: () => fakeChat }));+vi.mock("../type_widgets/llm_chat/chat_context_menu.js", () => ({ useChatContextMenu: vi.fn() }));+vi.mock("../type_widgets/llm_chat/chat_highlights.js", () => ({ useChatHighlights: () => ({ highlightMenuItems: [] }) }));+vi.mock("../type_widgets/llm_chat/ChatMessageList.js", () => ({ default: () => null }));+vi.mock("../type_widgets/llm_chat/ChatReadOnlyNotice.js", () => ({ default: () => null }));+vi.mock("../type_widgets/llm_chat/ChatInputBar.js", () => ({+ default: ({ onSubmit }: { onSubmit: (e: Event) => void }) => <form className="chat-input" onSubmit={onSubmit} />+}));+vi.mock("../react/hooks.js", () => ({+ useActiveNoteContext: () => ({ noteId: null, note: null }),+ useNote: () => null,+ useNoteProperty: () => undefined,+ useNoteLabelBoolean: () => [ false ],+ useSpacedUpdate: () => ({ scheduleUpdate: vi.fn(), updateNowIfNecessary: async () => undefined })+}));+vi.mock("../react/ActionButton.js", () => ({+ default: ({ icon, onClick }: { icon: string; onClick: (e: MouseEvent) => void }) => <button data-icon={icon} onClick={onClick} />+}));+vi.mock("../react/Dropdown.js", () => ({+ default: ({ children }: { children: ComponentChildren }) => <div>{children}</div>+}));+vi.mock("../react/FormList.js", () => ({+ FormListItem: ({ icon, onClick, children }: { icon?: string; onClick?: () => void; children: ComponentChildren }) =>+ <li data-icon={icon} onClick={onClick}>{children}</li>,+ FormDropdownDivider: () => null+}));+vi.mock("./RightPanelWidget.js", () => ({+ default: ({ buttons, children }: { buttons: ComponentChildren; children: ComponentChildren }) => <div>{buttons}{children}</div>+}));++import SidebarChat from "./SidebarChat";++describe("SidebarChat", () => {+ beforeEach(() => {+ serverChats = [ "chatOpen", "chatOlder" ];+ createdCount = 0;+ fakeChat.chatNoteId = undefined;+ fakeChat.submittedTo = undefined;+ });++ it("sends the first message after deleting the open chat to a new chat, not to an older one", async () => {+ const container = renderInto(<SidebarChat />);+ await vi.waitFor(() => expect(fakeChat.chatNoteId).toBe("chatOpen"));++ const deleteItem = container.querySelector<HTMLLIElement>("li[data-icon='bx bx-trash']");+ expect(deleteItem).not.toBeNull();+ deleteItem?.click();+ await vi.waitFor(() => expect(fakeChat.chatNoteId).toBeUndefined());+ expect(serverChats).toEqual([ "chatOlder" ]);++ const form = container.querySelector("form.chat-input");+ expect(form).not.toBeNull();+ form?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ await vi.waitFor(() => expect(fakeChat.handleSubmit).toHaveBeenCalled());++ expect(fakeChat.submittedTo).toBe("chatNew1");+ expect(serverChats).toEqual([ "chatNew1", "chatOlder" ]);+ });+});++function createChat() {+ const noteId = `chatNew${++createdCount}`;+ serverChats.unshift(noteId);+ return { noteId };+}diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsxindex b5861dac26..61eb2befc1 100644--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx@@ -149,7 +149,7 @@ export default function SidebarChat() {let noteId = chatNoteId;if (!noteId) {try {- const note = await dateNoteService.getOrCreateLlmChat();+ const note = await dateNoteService.createLlmChat();if (note) {setChatNoteId(note.noteId);noteId = note.noteId;diff --git a/packages/trilium-core/src/routes/api/special_notes.spec.ts b/packages/trilium-core/src/routes/api/special_notes.spec.tsindex a878a49fb9..e8350fc9c2 100644--- a/packages/trilium-core/src/routes/api/special_notes.spec.ts+++ b/packages/trilium-core/src/routes/api/special_notes.spec.ts@@ -195,13 +195,6 @@ describe("Special notes API (core)", () => {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");diff --git a/packages/trilium-core/src/routes/api/special_notes.ts b/packages/trilium-core/src/routes/api/special_notes.tsindex 44390a48ce..474fae1763 100644--- a/packages/trilium-core/src/routes/api/special_notes.ts+++ b/packages/trilium-core/src/routes/api/special_notes.ts@@ -121,10 +121,6 @@ function getMostRecentLlmChat() {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);@@ -153,7 +149,6 @@ export default {createOrUpdateScriptLauncherFromApi,createLlmChat,getMostRecentLlmChat,- getOrCreateLlmChat,getRecentLlmChats,saveLlmChat};diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 197d1ed892..fca9a74bb4 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -280,7 +280,6 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransapiRoute(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);diff --git a/packages/trilium-core/src/services/special_notes.spec.ts b/packages/trilium-core/src/services/special_notes.spec.tsindex 84ed7a1130..8345614fc1 100644--- a/packages/trilium-core/src/services/special_notes.spec.ts+++ b/packages/trilium-core/src/services/special_notes.spec.ts@@ -6,8 +6,6 @@ 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";@@ -507,29 +505,6 @@ describe("special_notes (core, real DB)", () => {});});- 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();diff --git a/packages/trilium-core/src/services/special_notes.ts b/packages/trilium-core/src/services/special_notes.tsindex f5179d9c88..d200c18a9a 100644--- a/packages/trilium-core/src/services/special_notes.ts+++ b/packages/trilium-core/src/services/special_notes.ts@@ -329,20 +329,6 @@ function getMostRecentLlmChat() {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.@@ -432,7 +418,6 @@ export default {createOrUpdateScriptLauncherFromApi,createLlmChat,getMostRecentLlmChat,- getOrCreateLlmChat,getRecentLlmChats,saveLlmChat};