Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: add a way to regenerate the last reply

Adorian Doran05eef58d3f58
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 17f2b90d16..d255476201 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2083,6 +2083,7 @@
"copy_message": "Copy message",
"save_to_subnote": "Save to sub-note",
"save_to_subnote_failed": "Failed to create a note from the message.",
+ "regenerate": "Regenerate",
"delete_message": "Delete message",
"delete_message_confirm": "Delete this message? This operation cannot be undone.",
"attach_file": "Attach image, PDF, or text file",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.ts
index 9b0f4eef09..3157ba8adc 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.ts
@@ -8,6 +8,7 @@ import toast from "../../../services/toast.js";
import { canCopyMessage, copyMessageToClipboard } from "./chat_copy.js";
import { canDeleteMessage, removeMessage } from "./chat_delete.js";
import { buildQuoteMarkdown } from "./chat_quote.js";
+import { canRegenerate } from "./chat_regenerate.js";
import { canSaveToSubNote, saveMessageToSubNote } from "./chat_save.js";
import { getMessageText } from "./llm_chat_types.js";
import type { UseLlmChatReturn } from "./useLlmChat.js";
@@ -41,7 +42,8 @@ export interface ChatContextMenuOptions {
/**
* The right-click menu over an AI chat's message timeline. Owns the single `contextmenu` listener and
* builds the menu for the message under the cursor: with a text selection — Copy and Quote; with none
- * — Copy message, Save to a sub-note (note chats only) and Delete. `contextMenuItems` lets another
+ * — Copy message, Save to a sub-note (note chats only), Regenerate (last reply only) and Delete.
+ * `contextMenuItems` lets another
* concern (currently highlights) inject its own items next to the selection commands. Bails to the
* native menu when nothing applies.
*
@@ -61,6 +63,8 @@ export function useChatContextMenu({ chat, noteContext, contextMenuItems }: Chat
setMessagesRef.current = chat.setMessages;
const appendToInputRef = useRef(chat.appendToInput);
appendToInputRef.current = chat.appendToInput;
+ const regenerateLastReplyRef = useRef(chat.regenerateLastReply);
+ regenerateLastReplyRef.current = chat.regenerateLastReply;
// Present for note chats (a real note in a tab), undefined for the right-pane sidebar chat —
// gates "Save to sub-note" (note chats only) and is the new note's parent.
const noteContextRef = useRef(noteContext);
@@ -129,6 +133,13 @@ export function useChatContextMenu({ chat, noteContext, contextMenuItems }: Chat
handler: () => void saveMessageToSubNote(parentNotePath, messageMarkdown)
});
}
+ if (canRegenerate(hasSelection, message, messagesRef.current, streaming)) {
+ items.push({
+ title: t("llm_chat.regenerate"),
+ uiIcon: "bx bx-revision",
+ handler: () => void regenerateLastReplyRef.current()
+ });
+ }
if (canDeleteMessage(hasSelection, message, streaming)) {
items.push({
title: t("llm_chat.delete_message"),
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_regenerate.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_regenerate.spec.ts
new file mode 100644
index 0000000000..fdbcc3f459
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_regenerate.spec.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+
+import { canRegenerate, conversationForRegenerate } from "./chat_regenerate.js";
+import type { StoredMessage } from "./llm_chat_types.js";
+
+function msg(id: string, role: StoredMessage["role"]): StoredMessage {
+ return { id, role, content: "x", createdAt: "2026-01-01T00:00:00.000Z" };
+}
+
+describe("canRegenerate", () => {
+ const convo = [msg("u1", "user"), msg("a1", "assistant")];
+
+ it("offers the command on the last assistant reply", () => {
+ expect(canRegenerate(false, convo[1], convo, false)).toBe(true);
+ });
+
+ it("hides it on a non-last message", () => {
+ expect(canRegenerate(false, convo[0], convo, false)).toBe(false);
+ });
+
+ it("hides it when the last message is not an assistant reply", () => {
+ const ending = [msg("a1", "assistant"), msg("u1", "user")];
+ expect(canRegenerate(false, ending[1], ending, false)).toBe(false);
+ });
+
+ it("hides it with a selection or while streaming", () => {
+ expect(canRegenerate(true, convo[1], convo, false)).toBe(false);
+ expect(canRegenerate(false, convo[1], convo, true)).toBe(false);
+ });
+
+ it("hides it when there is no user turn to run from", () => {
+ const noUser = [msg("a1", "assistant")];
+ expect(canRegenerate(false, noUser[0], noUser, false)).toBe(false);
+ });
+});
+
+describe("conversationForRegenerate", () => {
+ it("keeps everything up to and including the last user message", () => {
+ const messages = [msg("u1", "user"), msg("a1", "assistant"), msg("u2", "user"), msg("t2", "assistant"), msg("a2", "assistant")];
+ expect(conversationForRegenerate(messages).map(m => m.id)).toEqual(["u1", "a1", "u2"]);
+ });
+
+ it("returns null when there is no user message", () => {
+ expect(conversationForRegenerate([msg("a1", "assistant")])).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_regenerate.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_regenerate.ts
new file mode 100644
index 0000000000..eafdb3c4e4
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_regenerate.ts
@@ -0,0 +1,22 @@
+import type { StoredMessage } from "./llm_chat_types.js";
+
+/**
+ * Whether the "Regenerate" command should be offered for a right-clicked message: only with no text
+ * selection, not mid-stream, and only for the conversation's last message when it's an assistant reply
+ * (there must be a preceding user turn to re-run from).
+ */
+export function canRegenerate(hasSelection: boolean, message: StoredMessage | undefined, messages: StoredMessage[], isStreaming: boolean): boolean {
+ if (hasSelection || isStreaming || message?.role !== "assistant") return false;
+ const last = messages[messages.length - 1];
+ return last?.id === message.id && messages.some(m => m.role === "user");
+}
+
+/**
+ * The conversation to re-run when regenerating: everything up to and including the last user message,
+ * dropping the reply that followed it (its text and any separate "thinking" message). Returns null if
+ * there's no user message to run from.
+ */
+export function conversationForRegenerate(messages: StoredMessage[]): StoredMessage[] | null {
+ const lastUserIndex = messages.map(m => m.role).lastIndexOf("user");
+ return lastUserIndex < 0 ? null : messages.slice(0, lastUserIndex + 1);
+}
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 7cd7e77544..5d0080bb1a 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -6,6 +6,7 @@ import { getAvailableModels, streamChatCompletion } from "../../../services/llm_
import { randomString } from "../../../services/utils.js";
import { useTriliumEvent } from "../../react/hooks.js";
import { stripQuoteSources } from "./chat_quote.js";
+import { conversationForRegenerate } from "./chat_regenerate.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";
@@ -150,6 +151,8 @@ export interface UseLlmChatReturn {
stopStreaming: () => void;
/** Re-run the last turn after a failed response (drops the trailing error message) */
retryLast: () => void;
+ /** Regenerate the last reply: re-run from the last user message, dropping the reply that followed */
+ regenerateLastReply: () => void;
}
export function useLlmChat(
@@ -781,6 +784,15 @@ export function useLlmChat(
await runStream(messages.slice(0, -1));
}, [isStreaming, messages, runStream]);
+ /** Regenerate the last reply: re-run from the last user message, dropping the reply that followed. */
+ const regenerateLastReply = useCallback(async () => {
+ if (isStreaming) return;
+ const conversation = conversationForRegenerate(messages);
+ if (!conversation) return;
+ pendingScrollRef.current = "anchor";
+ await runStream(conversation);
+ }, [isStreaming, messages, runStream]);
+
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
@@ -865,6 +877,7 @@ export function useLlmChat(
clearMessages,
refreshModels,
stopStreaming,
- retryLast
+ retryLast,
+ regenerateLastReply
};
}