Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: allow the user to delete messages

Adorian Doran4362c367f643
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index cffd99298f..fb7697af13 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2081,6 +2081,8 @@
"copy_message": "Copy message",
"save_to_subnote": "Save to sub-note",
"save_to_subnote_failed": "Failed to create a note from the message.",
+ "delete_message": "Delete message",
+ "delete_message_confirm": "Delete this message? This operation cannot be undone.",
"attach_file": "Attach image, PDF, or text file",
"remove_attachment": "Remove attachment",
"attachment_upload_failed": "Failed to upload \"{{name}}\".",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_delete.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_delete.spec.ts
new file mode 100644
index 0000000000..e9c71a022d
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_delete.spec.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+
+import { canDeleteMessage, removeMessage } from "./chat_delete.js";
+import type { StoredMessage } from "./llm_chat_types.js";
+
+function message(id: string): StoredMessage {
+ return { id, role: "assistant", content: "text", createdAt: "2026-01-01T00:00:00.000Z" };
+}
+
+describe("canDeleteMessage", () => {
+ it("offers the command for a real message with no selection and no stream", () => {
+ expect(canDeleteMessage(false, message("m1"), false)).toBe(true);
+ });
+
+ it("hides the command when text is selected", () => {
+ expect(canDeleteMessage(true, message("m1"), false)).toBe(false);
+ });
+
+ it("hides the command when there is no message", () => {
+ expect(canDeleteMessage(false, undefined, false)).toBe(false);
+ });
+
+ it("hides the command while a reply is streaming", () => {
+ expect(canDeleteMessage(false, message("m1"), true)).toBe(false);
+ });
+});
+
+describe("removeMessage", () => {
+ it("removes only the matching message, preserving the rest in order", () => {
+ const messages = [message("a"), message("b"), message("c")];
+ expect(removeMessage(messages, "b").map(m => m.id)).toEqual(["a", "c"]);
+ });
+
+ it("returns the list unchanged when the id isn't present", () => {
+ const messages = [message("a"), message("b")];
+ expect(removeMessage(messages, "missing").map(m => m.id)).toEqual(["a", "b"]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_delete.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_delete.ts
new file mode 100644
index 0000000000..db6f9aad28
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_delete.ts
@@ -0,0 +1,16 @@
+import type { StoredMessage } from "./llm_chat_types.js";
+
+/**
+ * Whether the "Delete message" command should be offered for a right-clicked message: only with no
+ * active text selection (a selection means the selection commands apply), only for a real message,
+ * and never mid-stream — the in-flight reply is finalized from a pre-stream snapshot, which would
+ * resurrect a message deleted while it runs.
+ */
+export function canDeleteMessage(hasSelection: boolean, message: StoredMessage | undefined, isStreaming: boolean): boolean {
+ return !isStreaming && !hasSelection && !!message;
+}
+
+/** Remove the message with `messageId` from the conversation, leaving the rest in order. */
+export function removeMessage(messages: StoredMessage[], messageId: string): StoredMessage[] {
+ return messages.filter(message => message.id !== messageId);
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts
index 13a0c39ec4..41dde14cc7 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts
@@ -4,10 +4,12 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preac
import type NoteContext from "../../../components/note_context.js";
import contextMenu, { type MenuItem } from "../../../menus/context_menu.js";
+import dialog from "../../../services/dialog.js";
import { t } from "../../../services/i18n.js";
import toast from "../../../services/toast.js";
import { randomString } from "../../../services/utils.js";
import { canCopyMessage, copyMessageToClipboard } from "./chat_copy.js";
+import { canDeleteMessage, removeMessage } from "./chat_delete.js";
import { createAnchorFromSelection, resolveAnchorRange } from "./chat_highlights_anchor.js";
import { buildQuoteMarkdown } from "./chat_quote.js";
import { canSaveToSubNote, saveMessageToSubNote } from "./chat_save.js";
@@ -124,6 +126,12 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte
}));
}, []);
+ const confirmAndDeleteMessage = useCallback(async (messageId: string) => {
+ if (await dialog.confirm(t("llm_chat.delete_message_confirm"))) {
+ setMessagesRef.current(removeMessage(messagesRef.current, messageId));
+ }
+ }, []);
+
const scrollToHighlight = useCallback((anchorId: string) => {
// Reuse the range resolved by the most recent recompute rather than re-walking the DOM; every
// listed highlight has a cached entry (the list is built from the same resolved set).
@@ -133,10 +141,10 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte
}, []);
// Right-click menu over the timeline. With a text selection: Copy, Quote, and Add/Remove
- // highlight. With no selection: Copy the whole message, and Save it to a sub-note (note chats
- // only). Because preventing the default menu drops the browser's own Copy, we provide it here.
- // Bails (leaving the native menu) when there's nothing to offer. Copy stays available while a
- // reply streams; only the message-mutating add/remove are suppressed then.
+ // highlight. With no selection: Copy the whole message, Save it to a sub-note (note chats only),
+ // and Delete it. Because preventing the default menu drops the browser's own Copy, we provide it
+ // here. Bails (leaving the native menu) when there's nothing to offer. Copy stays available while
+ // a reply streams; the message-mutating add/remove/delete are suppressed then.
useEffect(() => {
const container = scrollContainerRef.current;
if (!container) return;
@@ -199,6 +207,13 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte
handler: () => void saveMessageToSubNote(parentNotePath, messageMarkdown)
});
}
+ if (canDeleteMessage(hasSelection, message, streaming)) {
+ items.push({
+ title: t("llm_chat.delete_message"),
+ uiIcon: "bx bx-trash",
+ handler: () => void confirmAndDeleteMessage(messageId)
+ });
+ }
if (items.length === 0) return; // nothing to do → leave the native menu
e.preventDefault();
@@ -207,7 +222,7 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte
container.addEventListener("contextmenu", onContextMenu);
return () => container.removeEventListener("contextmenu", onContextMenu);
- }, [scrollContainerRef, addHighlight, removeHighlight]);
+ }, [scrollContainerRef, addHighlight, removeHighlight, confirmAndDeleteMessage]);
// Publish the list for the sidebar widget.
useEffect(() => {
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.spec.ts
new file mode 100644
index 0000000000..c43578c9a4
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.spec.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+
+import { trimToFirstUserMessage } from "./llm_chat_types.js";
+
+describe("trimToFirstUserMessage", () => {
+ const u = { role: "user", id: "u" };
+ const a = { role: "assistant", id: "a" };
+
+ it("leaves a conversation that already starts with a user message unchanged", () => {
+ const messages = [u, a, { ...u, id: "u2" }];
+ expect(trimToFirstUserMessage(messages)).toBe(messages);
+ });
+
+ it("drops leading assistant turns so the first message is a user turn", () => {
+ expect(trimToFirstUserMessage([a, { ...a, id: "a2" }, u, a]).map(m => m.id)).toEqual(["u", "a"]);
+ });
+
+ it("leaves a conversation with no user message untouched", () => {
+ const messages = [a, { ...a, id: "a2" }];
+ expect(trimToFirstUserMessage(messages)).toBe(messages);
+ });
+
+ it("returns an empty list unchanged", () => {
+ expect(trimToFirstUserMessage([])).toEqual([]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
index 2531f7fa66..4a7c8b5cc2 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
@@ -86,6 +86,16 @@ export function getMessageText(content: string | ContentBlock[]): string {
.join("");
}
+/**
+ * Drop leading messages until the first user turn, so the conversation sent to the LLM starts with a
+ * user message. Some providers (e.g. Anthropic) reject a leading assistant turn, which can happen
+ * after the first user message is deleted. A conversation with no user message is left untouched.
+ */
+export function trimToFirstUserMessage<T extends { role: string }>(messages: T[]): T[] {
+ const firstUser = messages.findIndex(m => m.role === "user");
+ return firstUser <= 0 ? messages : messages.slice(firstUser);
+}
+
/**
* Extract tool calls from message content blocks.
*/
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index 41a3332243..d7e3035afc 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { getAvailableModels, streamChatCompletion } from "../../../services/llm_chat.js";
import { randomString } from "../../../services/utils.js";
import { useTriliumEvent } from "../../react/hooks.js";
-import type { ContentBlock, FileBlock, ImageBlock, LlmChatContent, StoredMessage, TextFileBlock } from "./llm_chat_types.js";
+import { type ContentBlock, type FileBlock, type ImageBlock, type LlmChatContent, type StoredMessage, type TextFileBlock, trimToFirstUserMessage } from "./llm_chat_types.js";
import { useSmoothStreaming } from "./useSmoothStreaming.js";
/** A user-supplied attachment waiting to be sent with the next message. */
@@ -497,7 +497,7 @@ export function useLlmChat(
return block as ContentBlock & { type: "text" };
}
- const apiMessages: LlmMessage[] = conversation.map(m => ({
+ const apiMessages: LlmMessage[] = trimToFirstUserMessage(conversation).map(m => ({
role: m.role,
content: flattenToApiContent(m.content)
}));