Skip to content

Build your personal knowledge base with Trilium Notes

test(llm): basic retry functionality

Elian Doran822138f4a621
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index e6c41bd950..7ae886d34a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1808,7 +1808,8 @@
"note_context_disabled": "Click to include current note in context",
"no_provider_message": "No AI provider configured. Add one to start chatting.",
"add_provider": "Add AI Provider",
- "stop": "Stop"
+ "stop": "Stop",
+ "retry": "Retry"
},
"sidebar_chat": {
"title": "AI Chat",
diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsx
index 4fb028726e..96f606bf83 100644
--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx
+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx
@@ -286,8 +286,16 @@ export default function SidebarChat() {
text={t("sidebar_chat.empty_state")}
/>
)}
- {chat.messages.map(msg => (
- <ChatMessage key={msg.id} message={msg} />
+ {chat.messages.map((msg, idx) => (
+ <ChatMessage
+ key={msg.id}
+ message={msg}
+ onRetry={
+ idx === chat.messages.length - 1 && msg.type === "error" && !chat.isStreaming
+ ? chat.retryLast
+ : undefined
+ }
+ />
))}
{chat.isStreaming && chat.streamingThinking && (
<ChatMessage
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
index f37f9abec9..5218d18202 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
@@ -136,6 +136,10 @@
color: var(--danger-text-color, #c00);
}
+.llm-chat-message-error .llm-chat-error-actions {
+ margin-top: 0.5rem;
+}
+
.llm-chat-thinking-card.expandable-card {
width: 100%;
max-width: 100%;
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
index e394d53556..eb3992bca2 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
@@ -6,6 +6,7 @@ import { useMemo } from "preact/hooks";
import { t } from "../../../services/i18n.js";
import utils from "../../../services/utils.js";
+import Button from "../../react/Button.js";
import { ReadOnlyTextContent } from "../text/ReadOnlyText.js";
import { ExpandableCard, ExpandableSection } from "./ExpandableCard.js";
import { type ContentBlock, getMessageText, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";
@@ -39,6 +40,8 @@ function MarkdownContent({ html, isStreaming }: { html: string; isStreaming?: bo
interface Props {
message: StoredMessage;
isStreaming?: boolean;
+ /** When set on an error message, renders a Retry button that re-runs the failed turn. */
+ onRetry?: () => void;
}
type ContentGroup =
@@ -104,7 +107,7 @@ function CitationsSection({ citations }: { citations: LlmCitation[] }) {
);
}
-export default function ChatMessage({ message, isStreaming }: Props) {
+export default function ChatMessage({ message, isStreaming, onRetry }: Props) {
const isError = message.type === "error";
const isThinking = message.type === "thinking";
const textContent = typeof message.content === "string" ? message.content : getMessageText(message.content);
@@ -160,6 +163,16 @@ export default function ChatMessage({ message, isStreaming }: Props) {
{message.citations && message.citations.length > 0 && (
<CitationsSection citations={message.citations} />
)}
+ {isError && onRetry && (
+ <div className="llm-chat-error-actions">
+ <Button
+ text={t("llm_chat.retry")}
+ icon="bx-revision"
+ size="small"
+ onClick={onRetry}
+ />
+ </div>
+ )}
</div>
<div className={`llm-chat-footer llm-chat-footer-${message.role}`}>
<span
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
index a192c8521b..bde73bc09a 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
@@ -62,8 +62,16 @@ export default function LlmChat({ note, ntxId, noteContext }: TypeWidgetProps) {
text={t("llm_chat.empty_state")}
/>
)}
- {chat.messages.map(msg => (
- <ChatMessage key={msg.id} message={msg} />
+ {chat.messages.map((msg, idx) => (
+ <ChatMessage
+ key={msg.id}
+ message={msg}
+ onRetry={
+ idx === chat.messages.length - 1 && msg.type === "error" && !chat.isStreaming
+ ? chat.retryLast
+ : undefined
+ }
+ />
))}
{chat.isStreaming && chat.streamingThinking && (
<ChatMessage
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 6abe534a2e..30579c5a59 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -65,6 +65,8 @@ export interface UseLlmChatReturn {
refreshModels: () => void;
/** Stop the current generation */
stopStreaming: () => void;
+ /** Re-run the last turn after a failed response (drops the trailing error message) */
+ retryLast: () => void;
}
export function useLlmChat(
@@ -218,22 +220,13 @@ export function useLlmChat(
setLastPromptTokens(0);
}, [setMessages]);
- const handleSubmit = useCallback(async (e: Event) => {
- e.preventDefault();
- if (!input.trim() || isStreaming) return;
-
+ /**
+ * Run a streaming completion against `conversation` — the full ordered message
+ * list to send to the model and to use as the base for finalized/error results.
+ */
+ const runStream = useCallback(async (conversation: StoredMessage[]) => {
setPendingCitations([]);
-
- const userMessage: StoredMessage = {
- id: randomString(),
- role: "user",
- content: input.trim(),
- createdAt: new Date().toISOString()
- };
-
- const newMessages = [...messages, userMessage];
- setMessagesInternal(newMessages);
- setInput("");
+ setMessagesInternal(conversation);
setIsStreaming(true);
setStreamingContent("");
setStreamingBlocks([]);
@@ -255,7 +248,7 @@ export function useLlmChat(
return block as ContentBlock & { type: "text" };
}
- const apiMessages: LlmMessage[] = newMessages.map(m => ({
+ const apiMessages: LlmMessage[] = conversation.map(m => ({
role: m.role,
content: typeof m.content === "string" ? m.content : m.content
.filter((b): b is ContentBlock & { type: "text" } => b.type === "text")
@@ -315,7 +308,7 @@ export function useLlmChat(
}
if (finalNewMessages.length > 0) {
- setMessages([...newMessages, ...finalNewMessages]);
+ setMessages([...conversation, ...finalNewMessages]);
}
setStreamingContent("");
@@ -387,7 +380,7 @@ export function useLlmChat(
createdAt: new Date().toISOString(),
type: "error"
};
- const finalMessages = [...newMessages, errorMessage];
+ const finalMessages = [...conversation, errorMessage];
setMessages(finalMessages);
setStreamingContent("");
setStreamingBlocks([]);
@@ -408,7 +401,28 @@ export function useLlmChat(
throw e;
}
});
- }, [input, isStreaming, messages, selectedModel, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages]);
+ }, [selectedModel, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages]);
+
+ const handleSubmit = useCallback(async (e: Event) => {
+ e.preventDefault();
+ if (!input.trim() || isStreaming) return;
+
+ const userMessage: StoredMessage = {
+ id: randomString(),
+ role: "user",
+ content: input.trim(),
+ createdAt: new Date().toISOString()
+ };
+ setInput("");
+ await runStream([...messages, userMessage]);
+ }, [input, isStreaming, messages, runStream]);
+
+ /** Re-run the last turn after a failed response, dropping the trailing error message. */
+ const retryLast = useCallback(async () => {
+ if (isStreaming) return;
+ if (messages[messages.length - 1]?.type !== "error") return;
+ await runStream(messages.slice(0, -1));
+ }, [isStreaming, messages, runStream]);
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -463,6 +477,7 @@ export function useLlmChat(
getContent,
clearMessages,
refreshModels,
- stopStreaming
+ stopStreaming,
+ retryLast
};
}