Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): add stop generation button

Tomáš Adámekdc40f6b530f1
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.ts
index fa0a0279d3..cd6ab3e63f 100644
--- a/apps/client/src/services/llm_chat.ts
+++ b/apps/client/src/services/llm_chat.ts
@@ -27,7 +27,8 @@ export interface StreamCallbacks {
export async function streamChatCompletion(
messages: LlmMessage[],
config: LlmChatConfig,
- callbacks: StreamCallbacks
+ callbacks: StreamCallbacks,
+ abortSignal?: AbortSignal
): Promise<void> {
const headers = await server.getHeaders();
@@ -37,7 +38,8 @@ export async function streamChatCompletion(
...headers,
"Content-Type": "application/json"
} as HeadersInit,
- body: JSON.stringify({ messages, config })
+ body: JSON.stringify({ messages, config }),
+ signal: abortSignal
});
if (!response.ok) {
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 9605212f6e..cb1f825157 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1660,7 +1660,8 @@
"note_context_enabled": "Click to disable note context: {{title}}",
"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"
+ "add_provider": "Add AI Provider",
+ "stop": "Stop"
},
"sidebar_chat": {
"title": "AI Chat",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
index 4599e6a511..07adaacf3c 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
@@ -48,6 +48,10 @@
opacity: 0.4;
}
+.llm-chat-stop-btn {
+ color: var(--danger-color, #dc3545);
+}
+
/* Model selector */
.llm-chat-model-selector {
display: flex;
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index 6491a595b0..b4515d2bb4 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -228,11 +228,11 @@ export default function ChatInputBar({
)}
</div>
<ActionButton
- icon={chat.isStreaming ? "bx bx-loader-alt bx-spin" : "bx bx-send"}
- text={chat.isStreaming ? t("llm_chat.sending") : t("llm_chat.send")}
- onClick={handleSubmit}
- disabled={chat.isStreaming || !chat.input.trim()}
- className="llm-chat-send-btn"
+ icon={chat.isStreaming ? "bx bx-stop" : "bx bx-send"}
+ text={chat.isStreaming ? t("llm_chat.stop") : t("llm_chat.send")}
+ onClick={chat.isStreaming ? chat.stopStreaming : handleSubmit}
+ disabled={!chat.isStreaming && !chat.input.trim()}
+ className={`llm-chat-send-btn ${chat.isStreaming ? "llm-chat-stop-btn" : ""}`}
/>
</div>
</form>
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 63cbf4bbf4..b481a2e93a 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -62,6 +62,8 @@ export interface UseLlmChatReturn {
clearMessages: () => void;
/** Refresh the provider/models list */
refreshModels: () => void;
+ /** Stop the current generation */
+ stopStreaming: () => void;
}
export function useLlmChat(
@@ -89,6 +91,7 @@ export function useLlmChat(
const [isCheckingProvider, setIsCheckingProvider] = useState<boolean>(true);
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const abortControllerRef = useRef<AbortController | null>(null);
// Refs to get fresh values in getContent (avoids stale closures)
const messagesRef = useRef(messages);
@@ -251,6 +254,9 @@ export function useLlmChat(
streamOptions.enableExtendedThinking = enableExtendedThinking;
}
+ const abortController = new AbortController();
+ abortControllerRef.current = abortController;
+
await streamChatCompletion(
apiMessages,
streamOptions,
@@ -353,9 +359,44 @@ export function useLlmChat(
setStreamingThinking("");
setPendingCitations([]);
setIsStreaming(false);
+ abortControllerRef.current = null;
+ }
+ },
+ abortController.signal
+ ).catch((e) => {
+ // AbortError is expected when user stops generation
+ if (e instanceof DOMException && e.name === "AbortError") {
+ // Finalize whatever we have so far
+ const finalNewMessages: StoredMessage[] = [];
+ if (thinkingContent) {
+ finalNewMessages.push({
+ id: randomString(),
+ role: "assistant",
+ content: thinkingContent,
+ createdAt: new Date().toISOString(),
+ type: "thinking"
+ });
+ }
+ if (contentBlocks.length > 0) {
+ finalNewMessages.push({
+ id: randomString(),
+ role: "assistant",
+ content: contentBlocks,
+ createdAt: new Date().toISOString(),
+ citations: citations.length > 0 ? citations : undefined
+ });
+ }
+ if (finalNewMessages.length > 0) {
+ setMessages([...newMessages, ...finalNewMessages]);
}
+ setStreamingContent("");
+ setStreamingBlocks([]);
+ setStreamingThinking("");
+ setPendingCitations([]);
+ setIsStreaming(false);
+ abortControllerRef.current = null;
}
- );
+ });
}, [input, isStreaming, messages, selectedModel, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages]);
const handleKeyDown = useCallback((e: KeyboardEvent) => {
@@ -365,6 +406,13 @@ export function useLlmChat(
}
}, [handleSubmit]);
+ /** Stop the current generation by aborting the SSE connection. */
+ const stopStreaming = useCallback(() => {
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort();
+ }
+ }, []);
+
return {
// State
messages,
@@ -402,6 +450,7 @@ export function useLlmChat(
loadFromContent,
getContent,
clearMessages,
- refreshModels
+ refreshModels,
+ stopStreaming
};
}